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 backtab(&mut self, _: &Backtab, 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(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7713        }
 7714        drop(chunk_by);
 7715        if !revert_changes.is_empty() {
 7716            self.transact(window, cx, |editor, window, cx| {
 7717                editor.revert(revert_changes, window, cx);
 7718            });
 7719        }
 7720    }
 7721
 7722    pub fn open_active_item_in_terminal(
 7723        &mut self,
 7724        _: &OpenInTerminal,
 7725        window: &mut Window,
 7726        cx: &mut Context<Self>,
 7727    ) {
 7728        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7729            let project_path = buffer.read(cx).project_path(cx)?;
 7730            let project = self.project.as_ref()?.read(cx);
 7731            let entry = project.entry_for_path(&project_path, cx)?;
 7732            let parent = match &entry.canonical_path {
 7733                Some(canonical_path) => canonical_path.to_path_buf(),
 7734                None => project.absolute_path(&project_path, cx)?,
 7735            }
 7736            .parent()?
 7737            .to_path_buf();
 7738            Some(parent)
 7739        }) {
 7740            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7741        }
 7742    }
 7743
 7744    pub fn prepare_restore_change(
 7745        &self,
 7746        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7747        hunk: &MultiBufferDiffHunk,
 7748        cx: &mut App,
 7749    ) -> Option<()> {
 7750        let buffer = self.buffer.read(cx);
 7751        let diff = buffer.diff_for(hunk.buffer_id)?;
 7752        let buffer = buffer.buffer(hunk.buffer_id)?;
 7753        let buffer = buffer.read(cx);
 7754        let original_text = diff
 7755            .read(cx)
 7756            .base_text()
 7757            .as_ref()?
 7758            .as_rope()
 7759            .slice(hunk.diff_base_byte_range.clone());
 7760        let buffer_snapshot = buffer.snapshot();
 7761        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7762        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7763            probe
 7764                .0
 7765                .start
 7766                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7767                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7768        }) {
 7769            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7770            Some(())
 7771        } else {
 7772            None
 7773        }
 7774    }
 7775
 7776    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7777        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7778    }
 7779
 7780    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7781        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7782    }
 7783
 7784    fn manipulate_lines<Fn>(
 7785        &mut self,
 7786        window: &mut Window,
 7787        cx: &mut Context<Self>,
 7788        mut callback: Fn,
 7789    ) where
 7790        Fn: FnMut(&mut Vec<&str>),
 7791    {
 7792        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7793        let buffer = self.buffer.read(cx).snapshot(cx);
 7794
 7795        let mut edits = Vec::new();
 7796
 7797        let selections = self.selections.all::<Point>(cx);
 7798        let mut selections = selections.iter().peekable();
 7799        let mut contiguous_row_selections = Vec::new();
 7800        let mut new_selections = Vec::new();
 7801        let mut added_lines = 0;
 7802        let mut removed_lines = 0;
 7803
 7804        while let Some(selection) = selections.next() {
 7805            let (start_row, end_row) = consume_contiguous_rows(
 7806                &mut contiguous_row_selections,
 7807                selection,
 7808                &display_map,
 7809                &mut selections,
 7810            );
 7811
 7812            let start_point = Point::new(start_row.0, 0);
 7813            let end_point = Point::new(
 7814                end_row.previous_row().0,
 7815                buffer.line_len(end_row.previous_row()),
 7816            );
 7817            let text = buffer
 7818                .text_for_range(start_point..end_point)
 7819                .collect::<String>();
 7820
 7821            let mut lines = text.split('\n').collect_vec();
 7822
 7823            let lines_before = lines.len();
 7824            callback(&mut lines);
 7825            let lines_after = lines.len();
 7826
 7827            edits.push((start_point..end_point, lines.join("\n")));
 7828
 7829            // Selections must change based on added and removed line count
 7830            let start_row =
 7831                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7832            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7833            new_selections.push(Selection {
 7834                id: selection.id,
 7835                start: start_row,
 7836                end: end_row,
 7837                goal: SelectionGoal::None,
 7838                reversed: selection.reversed,
 7839            });
 7840
 7841            if lines_after > lines_before {
 7842                added_lines += lines_after - lines_before;
 7843            } else if lines_before > lines_after {
 7844                removed_lines += lines_before - lines_after;
 7845            }
 7846        }
 7847
 7848        self.transact(window, cx, |this, window, cx| {
 7849            let buffer = this.buffer.update(cx, |buffer, cx| {
 7850                buffer.edit(edits, None, cx);
 7851                buffer.snapshot(cx)
 7852            });
 7853
 7854            // Recalculate offsets on newly edited buffer
 7855            let new_selections = new_selections
 7856                .iter()
 7857                .map(|s| {
 7858                    let start_point = Point::new(s.start.0, 0);
 7859                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7860                    Selection {
 7861                        id: s.id,
 7862                        start: buffer.point_to_offset(start_point),
 7863                        end: buffer.point_to_offset(end_point),
 7864                        goal: s.goal,
 7865                        reversed: s.reversed,
 7866                    }
 7867                })
 7868                .collect();
 7869
 7870            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7871                s.select(new_selections);
 7872            });
 7873
 7874            this.request_autoscroll(Autoscroll::fit(), cx);
 7875        });
 7876    }
 7877
 7878    pub fn convert_to_upper_case(
 7879        &mut self,
 7880        _: &ConvertToUpperCase,
 7881        window: &mut Window,
 7882        cx: &mut Context<Self>,
 7883    ) {
 7884        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7885    }
 7886
 7887    pub fn convert_to_lower_case(
 7888        &mut self,
 7889        _: &ConvertToLowerCase,
 7890        window: &mut Window,
 7891        cx: &mut Context<Self>,
 7892    ) {
 7893        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7894    }
 7895
 7896    pub fn convert_to_title_case(
 7897        &mut self,
 7898        _: &ConvertToTitleCase,
 7899        window: &mut Window,
 7900        cx: &mut Context<Self>,
 7901    ) {
 7902        self.manipulate_text(window, cx, |text| {
 7903            text.split('\n')
 7904                .map(|line| line.to_case(Case::Title))
 7905                .join("\n")
 7906        })
 7907    }
 7908
 7909    pub fn convert_to_snake_case(
 7910        &mut self,
 7911        _: &ConvertToSnakeCase,
 7912        window: &mut Window,
 7913        cx: &mut Context<Self>,
 7914    ) {
 7915        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7916    }
 7917
 7918    pub fn convert_to_kebab_case(
 7919        &mut self,
 7920        _: &ConvertToKebabCase,
 7921        window: &mut Window,
 7922        cx: &mut Context<Self>,
 7923    ) {
 7924        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7925    }
 7926
 7927    pub fn convert_to_upper_camel_case(
 7928        &mut self,
 7929        _: &ConvertToUpperCamelCase,
 7930        window: &mut Window,
 7931        cx: &mut Context<Self>,
 7932    ) {
 7933        self.manipulate_text(window, cx, |text| {
 7934            text.split('\n')
 7935                .map(|line| line.to_case(Case::UpperCamel))
 7936                .join("\n")
 7937        })
 7938    }
 7939
 7940    pub fn convert_to_lower_camel_case(
 7941        &mut self,
 7942        _: &ConvertToLowerCamelCase,
 7943        window: &mut Window,
 7944        cx: &mut Context<Self>,
 7945    ) {
 7946        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7947    }
 7948
 7949    pub fn convert_to_opposite_case(
 7950        &mut self,
 7951        _: &ConvertToOppositeCase,
 7952        window: &mut Window,
 7953        cx: &mut Context<Self>,
 7954    ) {
 7955        self.manipulate_text(window, cx, |text| {
 7956            text.chars()
 7957                .fold(String::with_capacity(text.len()), |mut t, c| {
 7958                    if c.is_uppercase() {
 7959                        t.extend(c.to_lowercase());
 7960                    } else {
 7961                        t.extend(c.to_uppercase());
 7962                    }
 7963                    t
 7964                })
 7965        })
 7966    }
 7967
 7968    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7969    where
 7970        Fn: FnMut(&str) -> String,
 7971    {
 7972        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7973        let buffer = self.buffer.read(cx).snapshot(cx);
 7974
 7975        let mut new_selections = Vec::new();
 7976        let mut edits = Vec::new();
 7977        let mut selection_adjustment = 0i32;
 7978
 7979        for selection in self.selections.all::<usize>(cx) {
 7980            let selection_is_empty = selection.is_empty();
 7981
 7982            let (start, end) = if selection_is_empty {
 7983                let word_range = movement::surrounding_word(
 7984                    &display_map,
 7985                    selection.start.to_display_point(&display_map),
 7986                );
 7987                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7988                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7989                (start, end)
 7990            } else {
 7991                (selection.start, selection.end)
 7992            };
 7993
 7994            let text = buffer.text_for_range(start..end).collect::<String>();
 7995            let old_length = text.len() as i32;
 7996            let text = callback(&text);
 7997
 7998            new_selections.push(Selection {
 7999                start: (start as i32 - selection_adjustment) as usize,
 8000                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8001                goal: SelectionGoal::None,
 8002                ..selection
 8003            });
 8004
 8005            selection_adjustment += old_length - text.len() as i32;
 8006
 8007            edits.push((start..end, text));
 8008        }
 8009
 8010        self.transact(window, cx, |this, window, cx| {
 8011            this.buffer.update(cx, |buffer, cx| {
 8012                buffer.edit(edits, None, cx);
 8013            });
 8014
 8015            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8016                s.select(new_selections);
 8017            });
 8018
 8019            this.request_autoscroll(Autoscroll::fit(), cx);
 8020        });
 8021    }
 8022
 8023    pub fn duplicate(
 8024        &mut self,
 8025        upwards: bool,
 8026        whole_lines: bool,
 8027        window: &mut Window,
 8028        cx: &mut Context<Self>,
 8029    ) {
 8030        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8031        let buffer = &display_map.buffer_snapshot;
 8032        let selections = self.selections.all::<Point>(cx);
 8033
 8034        let mut edits = Vec::new();
 8035        let mut selections_iter = selections.iter().peekable();
 8036        while let Some(selection) = selections_iter.next() {
 8037            let mut rows = selection.spanned_rows(false, &display_map);
 8038            // duplicate line-wise
 8039            if whole_lines || selection.start == selection.end {
 8040                // Avoid duplicating the same lines twice.
 8041                while let Some(next_selection) = selections_iter.peek() {
 8042                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8043                    if next_rows.start < rows.end {
 8044                        rows.end = next_rows.end;
 8045                        selections_iter.next().unwrap();
 8046                    } else {
 8047                        break;
 8048                    }
 8049                }
 8050
 8051                // Copy the text from the selected row region and splice it either at the start
 8052                // or end of the region.
 8053                let start = Point::new(rows.start.0, 0);
 8054                let end = Point::new(
 8055                    rows.end.previous_row().0,
 8056                    buffer.line_len(rows.end.previous_row()),
 8057                );
 8058                let text = buffer
 8059                    .text_for_range(start..end)
 8060                    .chain(Some("\n"))
 8061                    .collect::<String>();
 8062                let insert_location = if upwards {
 8063                    Point::new(rows.end.0, 0)
 8064                } else {
 8065                    start
 8066                };
 8067                edits.push((insert_location..insert_location, text));
 8068            } else {
 8069                // duplicate character-wise
 8070                let start = selection.start;
 8071                let end = selection.end;
 8072                let text = buffer.text_for_range(start..end).collect::<String>();
 8073                edits.push((selection.end..selection.end, text));
 8074            }
 8075        }
 8076
 8077        self.transact(window, cx, |this, _, cx| {
 8078            this.buffer.update(cx, |buffer, cx| {
 8079                buffer.edit(edits, None, cx);
 8080            });
 8081
 8082            this.request_autoscroll(Autoscroll::fit(), cx);
 8083        });
 8084    }
 8085
 8086    pub fn duplicate_line_up(
 8087        &mut self,
 8088        _: &DuplicateLineUp,
 8089        window: &mut Window,
 8090        cx: &mut Context<Self>,
 8091    ) {
 8092        self.duplicate(true, true, window, cx);
 8093    }
 8094
 8095    pub fn duplicate_line_down(
 8096        &mut self,
 8097        _: &DuplicateLineDown,
 8098        window: &mut Window,
 8099        cx: &mut Context<Self>,
 8100    ) {
 8101        self.duplicate(false, true, window, cx);
 8102    }
 8103
 8104    pub fn duplicate_selection(
 8105        &mut self,
 8106        _: &DuplicateSelection,
 8107        window: &mut Window,
 8108        cx: &mut Context<Self>,
 8109    ) {
 8110        self.duplicate(false, false, window, cx);
 8111    }
 8112
 8113    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8114        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8115        let buffer = self.buffer.read(cx).snapshot(cx);
 8116
 8117        let mut edits = Vec::new();
 8118        let mut unfold_ranges = Vec::new();
 8119        let mut refold_creases = Vec::new();
 8120
 8121        let selections = self.selections.all::<Point>(cx);
 8122        let mut selections = selections.iter().peekable();
 8123        let mut contiguous_row_selections = Vec::new();
 8124        let mut new_selections = Vec::new();
 8125
 8126        while let Some(selection) = selections.next() {
 8127            // Find all the selections that span a contiguous row range
 8128            let (start_row, end_row) = consume_contiguous_rows(
 8129                &mut contiguous_row_selections,
 8130                selection,
 8131                &display_map,
 8132                &mut selections,
 8133            );
 8134
 8135            // Move the text spanned by the row range to be before the line preceding the row range
 8136            if start_row.0 > 0 {
 8137                let range_to_move = Point::new(
 8138                    start_row.previous_row().0,
 8139                    buffer.line_len(start_row.previous_row()),
 8140                )
 8141                    ..Point::new(
 8142                        end_row.previous_row().0,
 8143                        buffer.line_len(end_row.previous_row()),
 8144                    );
 8145                let insertion_point = display_map
 8146                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8147                    .0;
 8148
 8149                // Don't move lines across excerpts
 8150                if buffer
 8151                    .excerpt_containing(insertion_point..range_to_move.end)
 8152                    .is_some()
 8153                {
 8154                    let text = buffer
 8155                        .text_for_range(range_to_move.clone())
 8156                        .flat_map(|s| s.chars())
 8157                        .skip(1)
 8158                        .chain(['\n'])
 8159                        .collect::<String>();
 8160
 8161                    edits.push((
 8162                        buffer.anchor_after(range_to_move.start)
 8163                            ..buffer.anchor_before(range_to_move.end),
 8164                        String::new(),
 8165                    ));
 8166                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8167                    edits.push((insertion_anchor..insertion_anchor, text));
 8168
 8169                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8170
 8171                    // Move selections up
 8172                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8173                        |mut selection| {
 8174                            selection.start.row -= row_delta;
 8175                            selection.end.row -= row_delta;
 8176                            selection
 8177                        },
 8178                    ));
 8179
 8180                    // Move folds up
 8181                    unfold_ranges.push(range_to_move.clone());
 8182                    for fold in display_map.folds_in_range(
 8183                        buffer.anchor_before(range_to_move.start)
 8184                            ..buffer.anchor_after(range_to_move.end),
 8185                    ) {
 8186                        let mut start = fold.range.start.to_point(&buffer);
 8187                        let mut end = fold.range.end.to_point(&buffer);
 8188                        start.row -= row_delta;
 8189                        end.row -= row_delta;
 8190                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8191                    }
 8192                }
 8193            }
 8194
 8195            // If we didn't move line(s), preserve the existing selections
 8196            new_selections.append(&mut contiguous_row_selections);
 8197        }
 8198
 8199        self.transact(window, cx, |this, window, cx| {
 8200            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8201            this.buffer.update(cx, |buffer, cx| {
 8202                for (range, text) in edits {
 8203                    buffer.edit([(range, text)], None, cx);
 8204                }
 8205            });
 8206            this.fold_creases(refold_creases, true, window, cx);
 8207            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8208                s.select(new_selections);
 8209            })
 8210        });
 8211    }
 8212
 8213    pub fn move_line_down(
 8214        &mut self,
 8215        _: &MoveLineDown,
 8216        window: &mut Window,
 8217        cx: &mut Context<Self>,
 8218    ) {
 8219        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8220        let buffer = self.buffer.read(cx).snapshot(cx);
 8221
 8222        let mut edits = Vec::new();
 8223        let mut unfold_ranges = Vec::new();
 8224        let mut refold_creases = Vec::new();
 8225
 8226        let selections = self.selections.all::<Point>(cx);
 8227        let mut selections = selections.iter().peekable();
 8228        let mut contiguous_row_selections = Vec::new();
 8229        let mut new_selections = Vec::new();
 8230
 8231        while let Some(selection) = selections.next() {
 8232            // Find all the selections that span a contiguous row range
 8233            let (start_row, end_row) = consume_contiguous_rows(
 8234                &mut contiguous_row_selections,
 8235                selection,
 8236                &display_map,
 8237                &mut selections,
 8238            );
 8239
 8240            // Move the text spanned by the row range to be after the last line of the row range
 8241            if end_row.0 <= buffer.max_point().row {
 8242                let range_to_move =
 8243                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8244                let insertion_point = display_map
 8245                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8246                    .0;
 8247
 8248                // Don't move lines across excerpt boundaries
 8249                if buffer
 8250                    .excerpt_containing(range_to_move.start..insertion_point)
 8251                    .is_some()
 8252                {
 8253                    let mut text = String::from("\n");
 8254                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8255                    text.pop(); // Drop trailing newline
 8256                    edits.push((
 8257                        buffer.anchor_after(range_to_move.start)
 8258                            ..buffer.anchor_before(range_to_move.end),
 8259                        String::new(),
 8260                    ));
 8261                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8262                    edits.push((insertion_anchor..insertion_anchor, text));
 8263
 8264                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8265
 8266                    // Move selections down
 8267                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8268                        |mut selection| {
 8269                            selection.start.row += row_delta;
 8270                            selection.end.row += row_delta;
 8271                            selection
 8272                        },
 8273                    ));
 8274
 8275                    // Move folds down
 8276                    unfold_ranges.push(range_to_move.clone());
 8277                    for fold in display_map.folds_in_range(
 8278                        buffer.anchor_before(range_to_move.start)
 8279                            ..buffer.anchor_after(range_to_move.end),
 8280                    ) {
 8281                        let mut start = fold.range.start.to_point(&buffer);
 8282                        let mut end = fold.range.end.to_point(&buffer);
 8283                        start.row += row_delta;
 8284                        end.row += row_delta;
 8285                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8286                    }
 8287                }
 8288            }
 8289
 8290            // If we didn't move line(s), preserve the existing selections
 8291            new_selections.append(&mut contiguous_row_selections);
 8292        }
 8293
 8294        self.transact(window, cx, |this, window, cx| {
 8295            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8296            this.buffer.update(cx, |buffer, cx| {
 8297                for (range, text) in edits {
 8298                    buffer.edit([(range, text)], None, cx);
 8299                }
 8300            });
 8301            this.fold_creases(refold_creases, true, window, cx);
 8302            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8303                s.select(new_selections)
 8304            });
 8305        });
 8306    }
 8307
 8308    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8309        let text_layout_details = &self.text_layout_details(window);
 8310        self.transact(window, cx, |this, window, cx| {
 8311            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8312                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8313                let line_mode = s.line_mode;
 8314                s.move_with(|display_map, selection| {
 8315                    if !selection.is_empty() || line_mode {
 8316                        return;
 8317                    }
 8318
 8319                    let mut head = selection.head();
 8320                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8321                    if head.column() == display_map.line_len(head.row()) {
 8322                        transpose_offset = display_map
 8323                            .buffer_snapshot
 8324                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8325                    }
 8326
 8327                    if transpose_offset == 0 {
 8328                        return;
 8329                    }
 8330
 8331                    *head.column_mut() += 1;
 8332                    head = display_map.clip_point(head, Bias::Right);
 8333                    let goal = SelectionGoal::HorizontalPosition(
 8334                        display_map
 8335                            .x_for_display_point(head, text_layout_details)
 8336                            .into(),
 8337                    );
 8338                    selection.collapse_to(head, goal);
 8339
 8340                    let transpose_start = display_map
 8341                        .buffer_snapshot
 8342                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8343                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8344                        let transpose_end = display_map
 8345                            .buffer_snapshot
 8346                            .clip_offset(transpose_offset + 1, Bias::Right);
 8347                        if let Some(ch) =
 8348                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8349                        {
 8350                            edits.push((transpose_start..transpose_offset, String::new()));
 8351                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8352                        }
 8353                    }
 8354                });
 8355                edits
 8356            });
 8357            this.buffer
 8358                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8359            let selections = this.selections.all::<usize>(cx);
 8360            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8361                s.select(selections);
 8362            });
 8363        });
 8364    }
 8365
 8366    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8367        self.rewrap_impl(IsVimMode::No, cx)
 8368    }
 8369
 8370    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8371        let buffer = self.buffer.read(cx).snapshot(cx);
 8372        let selections = self.selections.all::<Point>(cx);
 8373        let mut selections = selections.iter().peekable();
 8374
 8375        let mut edits = Vec::new();
 8376        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8377
 8378        while let Some(selection) = selections.next() {
 8379            let mut start_row = selection.start.row;
 8380            let mut end_row = selection.end.row;
 8381
 8382            // Skip selections that overlap with a range that has already been rewrapped.
 8383            let selection_range = start_row..end_row;
 8384            if rewrapped_row_ranges
 8385                .iter()
 8386                .any(|range| range.overlaps(&selection_range))
 8387            {
 8388                continue;
 8389            }
 8390
 8391            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8392
 8393            // Since not all lines in the selection may be at the same indent
 8394            // level, choose the indent size that is the most common between all
 8395            // of the lines.
 8396            //
 8397            // If there is a tie, we use the deepest indent.
 8398            let (indent_size, indent_end) = {
 8399                let mut indent_size_occurrences = HashMap::default();
 8400                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8401
 8402                for row in start_row..=end_row {
 8403                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8404                    rows_by_indent_size.entry(indent).or_default().push(row);
 8405                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8406                }
 8407
 8408                let indent_size = indent_size_occurrences
 8409                    .into_iter()
 8410                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8411                    .map(|(indent, _)| indent)
 8412                    .unwrap_or_default();
 8413                let row = rows_by_indent_size[&indent_size][0];
 8414                let indent_end = Point::new(row, indent_size.len);
 8415
 8416                (indent_size, indent_end)
 8417            };
 8418
 8419            let mut line_prefix = indent_size.chars().collect::<String>();
 8420
 8421            let mut inside_comment = false;
 8422            if let Some(comment_prefix) =
 8423                buffer
 8424                    .language_scope_at(selection.head())
 8425                    .and_then(|language| {
 8426                        language
 8427                            .line_comment_prefixes()
 8428                            .iter()
 8429                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8430                            .cloned()
 8431                    })
 8432            {
 8433                line_prefix.push_str(&comment_prefix);
 8434                inside_comment = true;
 8435            }
 8436
 8437            let language_settings = buffer.settings_at(selection.head(), cx);
 8438            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8439                RewrapBehavior::InComments => inside_comment,
 8440                RewrapBehavior::InSelections => !selection.is_empty(),
 8441                RewrapBehavior::Anywhere => true,
 8442            };
 8443
 8444            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8445            if !should_rewrap {
 8446                continue;
 8447            }
 8448
 8449            if selection.is_empty() {
 8450                'expand_upwards: while start_row > 0 {
 8451                    let prev_row = start_row - 1;
 8452                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8453                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8454                    {
 8455                        start_row = prev_row;
 8456                    } else {
 8457                        break 'expand_upwards;
 8458                    }
 8459                }
 8460
 8461                'expand_downwards: while end_row < buffer.max_point().row {
 8462                    let next_row = end_row + 1;
 8463                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8464                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8465                    {
 8466                        end_row = next_row;
 8467                    } else {
 8468                        break 'expand_downwards;
 8469                    }
 8470                }
 8471            }
 8472
 8473            let start = Point::new(start_row, 0);
 8474            let start_offset = start.to_offset(&buffer);
 8475            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8476            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8477            let Some(lines_without_prefixes) = selection_text
 8478                .lines()
 8479                .map(|line| {
 8480                    line.strip_prefix(&line_prefix)
 8481                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8482                        .ok_or_else(|| {
 8483                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8484                        })
 8485                })
 8486                .collect::<Result<Vec<_>, _>>()
 8487                .log_err()
 8488            else {
 8489                continue;
 8490            };
 8491
 8492            let wrap_column = buffer
 8493                .settings_at(Point::new(start_row, 0), cx)
 8494                .preferred_line_length as usize;
 8495            let wrapped_text = wrap_with_prefix(
 8496                line_prefix,
 8497                lines_without_prefixes.join(" "),
 8498                wrap_column,
 8499                tab_size,
 8500            );
 8501
 8502            // TODO: should always use char-based diff while still supporting cursor behavior that
 8503            // matches vim.
 8504            let mut diff_options = DiffOptions::default();
 8505            if is_vim_mode == IsVimMode::Yes {
 8506                diff_options.max_word_diff_len = 0;
 8507                diff_options.max_word_diff_line_count = 0;
 8508            } else {
 8509                diff_options.max_word_diff_len = usize::MAX;
 8510                diff_options.max_word_diff_line_count = usize::MAX;
 8511            }
 8512
 8513            for (old_range, new_text) in
 8514                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8515            {
 8516                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8517                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8518                edits.push((edit_start..edit_end, new_text));
 8519            }
 8520
 8521            rewrapped_row_ranges.push(start_row..=end_row);
 8522        }
 8523
 8524        self.buffer
 8525            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8526    }
 8527
 8528    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8529        let mut text = String::new();
 8530        let buffer = self.buffer.read(cx).snapshot(cx);
 8531        let mut selections = self.selections.all::<Point>(cx);
 8532        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8533        {
 8534            let max_point = buffer.max_point();
 8535            let mut is_first = true;
 8536            for selection in &mut selections {
 8537                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8538                if is_entire_line {
 8539                    selection.start = Point::new(selection.start.row, 0);
 8540                    if !selection.is_empty() && selection.end.column == 0 {
 8541                        selection.end = cmp::min(max_point, selection.end);
 8542                    } else {
 8543                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8544                    }
 8545                    selection.goal = SelectionGoal::None;
 8546                }
 8547                if is_first {
 8548                    is_first = false;
 8549                } else {
 8550                    text += "\n";
 8551                }
 8552                let mut len = 0;
 8553                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8554                    text.push_str(chunk);
 8555                    len += chunk.len();
 8556                }
 8557                clipboard_selections.push(ClipboardSelection {
 8558                    len,
 8559                    is_entire_line,
 8560                    start_column: selection.start.column,
 8561                });
 8562            }
 8563        }
 8564
 8565        self.transact(window, cx, |this, window, cx| {
 8566            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8567                s.select(selections);
 8568            });
 8569            this.insert("", window, cx);
 8570        });
 8571        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8572    }
 8573
 8574    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8575        let item = self.cut_common(window, cx);
 8576        cx.write_to_clipboard(item);
 8577    }
 8578
 8579    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8580        self.change_selections(None, window, cx, |s| {
 8581            s.move_with(|snapshot, sel| {
 8582                if sel.is_empty() {
 8583                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8584                }
 8585            });
 8586        });
 8587        let item = self.cut_common(window, cx);
 8588        cx.set_global(KillRing(item))
 8589    }
 8590
 8591    pub fn kill_ring_yank(
 8592        &mut self,
 8593        _: &KillRingYank,
 8594        window: &mut Window,
 8595        cx: &mut Context<Self>,
 8596    ) {
 8597        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8598            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8599                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8600            } else {
 8601                return;
 8602            }
 8603        } else {
 8604            return;
 8605        };
 8606        self.do_paste(&text, metadata, false, window, cx);
 8607    }
 8608
 8609    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8610        let selections = self.selections.all::<Point>(cx);
 8611        let buffer = self.buffer.read(cx).read(cx);
 8612        let mut text = String::new();
 8613
 8614        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8615        {
 8616            let max_point = buffer.max_point();
 8617            let mut is_first = true;
 8618            for selection in selections.iter() {
 8619                let mut start = selection.start;
 8620                let mut end = selection.end;
 8621                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8622                if is_entire_line {
 8623                    start = Point::new(start.row, 0);
 8624                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8625                }
 8626                if is_first {
 8627                    is_first = false;
 8628                } else {
 8629                    text += "\n";
 8630                }
 8631                let mut len = 0;
 8632                for chunk in buffer.text_for_range(start..end) {
 8633                    text.push_str(chunk);
 8634                    len += chunk.len();
 8635                }
 8636                clipboard_selections.push(ClipboardSelection {
 8637                    len,
 8638                    is_entire_line,
 8639                    start_column: start.column,
 8640                });
 8641            }
 8642        }
 8643
 8644        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8645            text,
 8646            clipboard_selections,
 8647        ));
 8648    }
 8649
 8650    pub fn do_paste(
 8651        &mut self,
 8652        text: &String,
 8653        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8654        handle_entire_lines: bool,
 8655        window: &mut Window,
 8656        cx: &mut Context<Self>,
 8657    ) {
 8658        if self.read_only(cx) {
 8659            return;
 8660        }
 8661
 8662        let clipboard_text = Cow::Borrowed(text);
 8663
 8664        self.transact(window, cx, |this, window, cx| {
 8665            if let Some(mut clipboard_selections) = clipboard_selections {
 8666                let old_selections = this.selections.all::<usize>(cx);
 8667                let all_selections_were_entire_line =
 8668                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8669                let first_selection_start_column =
 8670                    clipboard_selections.first().map(|s| s.start_column);
 8671                if clipboard_selections.len() != old_selections.len() {
 8672                    clipboard_selections.drain(..);
 8673                }
 8674                let cursor_offset = this.selections.last::<usize>(cx).head();
 8675                let mut auto_indent_on_paste = true;
 8676
 8677                this.buffer.update(cx, |buffer, cx| {
 8678                    let snapshot = buffer.read(cx);
 8679                    auto_indent_on_paste =
 8680                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8681
 8682                    let mut start_offset = 0;
 8683                    let mut edits = Vec::new();
 8684                    let mut original_start_columns = Vec::new();
 8685                    for (ix, selection) in old_selections.iter().enumerate() {
 8686                        let to_insert;
 8687                        let entire_line;
 8688                        let original_start_column;
 8689                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8690                            let end_offset = start_offset + clipboard_selection.len;
 8691                            to_insert = &clipboard_text[start_offset..end_offset];
 8692                            entire_line = clipboard_selection.is_entire_line;
 8693                            start_offset = end_offset + 1;
 8694                            original_start_column = Some(clipboard_selection.start_column);
 8695                        } else {
 8696                            to_insert = clipboard_text.as_str();
 8697                            entire_line = all_selections_were_entire_line;
 8698                            original_start_column = first_selection_start_column
 8699                        }
 8700
 8701                        // If the corresponding selection was empty when this slice of the
 8702                        // clipboard text was written, then the entire line containing the
 8703                        // selection was copied. If this selection is also currently empty,
 8704                        // then paste the line before the current line of the buffer.
 8705                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8706                            let column = selection.start.to_point(&snapshot).column as usize;
 8707                            let line_start = selection.start - column;
 8708                            line_start..line_start
 8709                        } else {
 8710                            selection.range()
 8711                        };
 8712
 8713                        edits.push((range, to_insert));
 8714                        original_start_columns.extend(original_start_column);
 8715                    }
 8716                    drop(snapshot);
 8717
 8718                    buffer.edit(
 8719                        edits,
 8720                        if auto_indent_on_paste {
 8721                            Some(AutoindentMode::Block {
 8722                                original_start_columns,
 8723                            })
 8724                        } else {
 8725                            None
 8726                        },
 8727                        cx,
 8728                    );
 8729                });
 8730
 8731                let selections = this.selections.all::<usize>(cx);
 8732                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8733                    s.select(selections)
 8734                });
 8735            } else {
 8736                this.insert(&clipboard_text, window, cx);
 8737            }
 8738        });
 8739    }
 8740
 8741    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8742        if let Some(item) = cx.read_from_clipboard() {
 8743            let entries = item.entries();
 8744
 8745            match entries.first() {
 8746                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8747                // of all the pasted entries.
 8748                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8749                    .do_paste(
 8750                        clipboard_string.text(),
 8751                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8752                        true,
 8753                        window,
 8754                        cx,
 8755                    ),
 8756                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8757            }
 8758        }
 8759    }
 8760
 8761    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8762        if self.read_only(cx) {
 8763            return;
 8764        }
 8765
 8766        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8767            if let Some((selections, _)) =
 8768                self.selection_history.transaction(transaction_id).cloned()
 8769            {
 8770                self.change_selections(None, window, cx, |s| {
 8771                    s.select_anchors(selections.to_vec());
 8772                });
 8773            }
 8774            self.request_autoscroll(Autoscroll::fit(), cx);
 8775            self.unmark_text(window, cx);
 8776            self.refresh_inline_completion(true, false, window, cx);
 8777            cx.emit(EditorEvent::Edited { transaction_id });
 8778            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8779        }
 8780    }
 8781
 8782    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8783        if self.read_only(cx) {
 8784            return;
 8785        }
 8786
 8787        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8788            if let Some((_, Some(selections))) =
 8789                self.selection_history.transaction(transaction_id).cloned()
 8790            {
 8791                self.change_selections(None, window, cx, |s| {
 8792                    s.select_anchors(selections.to_vec());
 8793                });
 8794            }
 8795            self.request_autoscroll(Autoscroll::fit(), cx);
 8796            self.unmark_text(window, cx);
 8797            self.refresh_inline_completion(true, false, window, cx);
 8798            cx.emit(EditorEvent::Edited { transaction_id });
 8799        }
 8800    }
 8801
 8802    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8803        self.buffer
 8804            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8805    }
 8806
 8807    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8808        self.buffer
 8809            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8810    }
 8811
 8812    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8813        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8814            let line_mode = s.line_mode;
 8815            s.move_with(|map, selection| {
 8816                let cursor = if selection.is_empty() && !line_mode {
 8817                    movement::left(map, selection.start)
 8818                } else {
 8819                    selection.start
 8820                };
 8821                selection.collapse_to(cursor, SelectionGoal::None);
 8822            });
 8823        })
 8824    }
 8825
 8826    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8827        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8828            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8829        })
 8830    }
 8831
 8832    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8833        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8834            let line_mode = s.line_mode;
 8835            s.move_with(|map, selection| {
 8836                let cursor = if selection.is_empty() && !line_mode {
 8837                    movement::right(map, selection.end)
 8838                } else {
 8839                    selection.end
 8840                };
 8841                selection.collapse_to(cursor, SelectionGoal::None)
 8842            });
 8843        })
 8844    }
 8845
 8846    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8847        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8848            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8849        })
 8850    }
 8851
 8852    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8853        if self.take_rename(true, window, cx).is_some() {
 8854            return;
 8855        }
 8856
 8857        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8858            cx.propagate();
 8859            return;
 8860        }
 8861
 8862        let text_layout_details = &self.text_layout_details(window);
 8863        let selection_count = self.selections.count();
 8864        let first_selection = self.selections.first_anchor();
 8865
 8866        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8867            let line_mode = s.line_mode;
 8868            s.move_with(|map, selection| {
 8869                if !selection.is_empty() && !line_mode {
 8870                    selection.goal = SelectionGoal::None;
 8871                }
 8872                let (cursor, goal) = movement::up(
 8873                    map,
 8874                    selection.start,
 8875                    selection.goal,
 8876                    false,
 8877                    text_layout_details,
 8878                );
 8879                selection.collapse_to(cursor, goal);
 8880            });
 8881        });
 8882
 8883        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8884        {
 8885            cx.propagate();
 8886        }
 8887    }
 8888
 8889    pub fn move_up_by_lines(
 8890        &mut self,
 8891        action: &MoveUpByLines,
 8892        window: &mut Window,
 8893        cx: &mut Context<Self>,
 8894    ) {
 8895        if self.take_rename(true, window, cx).is_some() {
 8896            return;
 8897        }
 8898
 8899        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8900            cx.propagate();
 8901            return;
 8902        }
 8903
 8904        let text_layout_details = &self.text_layout_details(window);
 8905
 8906        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8907            let line_mode = s.line_mode;
 8908            s.move_with(|map, selection| {
 8909                if !selection.is_empty() && !line_mode {
 8910                    selection.goal = SelectionGoal::None;
 8911                }
 8912                let (cursor, goal) = movement::up_by_rows(
 8913                    map,
 8914                    selection.start,
 8915                    action.lines,
 8916                    selection.goal,
 8917                    false,
 8918                    text_layout_details,
 8919                );
 8920                selection.collapse_to(cursor, goal);
 8921            });
 8922        })
 8923    }
 8924
 8925    pub fn move_down_by_lines(
 8926        &mut self,
 8927        action: &MoveDownByLines,
 8928        window: &mut Window,
 8929        cx: &mut Context<Self>,
 8930    ) {
 8931        if self.take_rename(true, window, cx).is_some() {
 8932            return;
 8933        }
 8934
 8935        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8936            cx.propagate();
 8937            return;
 8938        }
 8939
 8940        let text_layout_details = &self.text_layout_details(window);
 8941
 8942        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8943            let line_mode = s.line_mode;
 8944            s.move_with(|map, selection| {
 8945                if !selection.is_empty() && !line_mode {
 8946                    selection.goal = SelectionGoal::None;
 8947                }
 8948                let (cursor, goal) = movement::down_by_rows(
 8949                    map,
 8950                    selection.start,
 8951                    action.lines,
 8952                    selection.goal,
 8953                    false,
 8954                    text_layout_details,
 8955                );
 8956                selection.collapse_to(cursor, goal);
 8957            });
 8958        })
 8959    }
 8960
 8961    pub fn select_down_by_lines(
 8962        &mut self,
 8963        action: &SelectDownByLines,
 8964        window: &mut Window,
 8965        cx: &mut Context<Self>,
 8966    ) {
 8967        let text_layout_details = &self.text_layout_details(window);
 8968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8969            s.move_heads_with(|map, head, goal| {
 8970                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8971            })
 8972        })
 8973    }
 8974
 8975    pub fn select_up_by_lines(
 8976        &mut self,
 8977        action: &SelectUpByLines,
 8978        window: &mut Window,
 8979        cx: &mut Context<Self>,
 8980    ) {
 8981        let text_layout_details = &self.text_layout_details(window);
 8982        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8983            s.move_heads_with(|map, head, goal| {
 8984                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8985            })
 8986        })
 8987    }
 8988
 8989    pub fn select_page_up(
 8990        &mut self,
 8991        _: &SelectPageUp,
 8992        window: &mut Window,
 8993        cx: &mut Context<Self>,
 8994    ) {
 8995        let Some(row_count) = self.visible_row_count() else {
 8996            return;
 8997        };
 8998
 8999        let text_layout_details = &self.text_layout_details(window);
 9000
 9001        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9002            s.move_heads_with(|map, head, goal| {
 9003                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9004            })
 9005        })
 9006    }
 9007
 9008    pub fn move_page_up(
 9009        &mut self,
 9010        action: &MovePageUp,
 9011        window: &mut Window,
 9012        cx: &mut Context<Self>,
 9013    ) {
 9014        if self.take_rename(true, window, cx).is_some() {
 9015            return;
 9016        }
 9017
 9018        if self
 9019            .context_menu
 9020            .borrow_mut()
 9021            .as_mut()
 9022            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9023            .unwrap_or(false)
 9024        {
 9025            return;
 9026        }
 9027
 9028        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9029            cx.propagate();
 9030            return;
 9031        }
 9032
 9033        let Some(row_count) = self.visible_row_count() else {
 9034            return;
 9035        };
 9036
 9037        let autoscroll = if action.center_cursor {
 9038            Autoscroll::center()
 9039        } else {
 9040            Autoscroll::fit()
 9041        };
 9042
 9043        let text_layout_details = &self.text_layout_details(window);
 9044
 9045        self.change_selections(Some(autoscroll), window, cx, |s| {
 9046            let line_mode = s.line_mode;
 9047            s.move_with(|map, selection| {
 9048                if !selection.is_empty() && !line_mode {
 9049                    selection.goal = SelectionGoal::None;
 9050                }
 9051                let (cursor, goal) = movement::up_by_rows(
 9052                    map,
 9053                    selection.end,
 9054                    row_count,
 9055                    selection.goal,
 9056                    false,
 9057                    text_layout_details,
 9058                );
 9059                selection.collapse_to(cursor, goal);
 9060            });
 9061        });
 9062    }
 9063
 9064    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9065        let text_layout_details = &self.text_layout_details(window);
 9066        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9067            s.move_heads_with(|map, head, goal| {
 9068                movement::up(map, head, goal, false, text_layout_details)
 9069            })
 9070        })
 9071    }
 9072
 9073    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9074        self.take_rename(true, window, cx);
 9075
 9076        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9077            cx.propagate();
 9078            return;
 9079        }
 9080
 9081        let text_layout_details = &self.text_layout_details(window);
 9082        let selection_count = self.selections.count();
 9083        let first_selection = self.selections.first_anchor();
 9084
 9085        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9086            let line_mode = s.line_mode;
 9087            s.move_with(|map, selection| {
 9088                if !selection.is_empty() && !line_mode {
 9089                    selection.goal = SelectionGoal::None;
 9090                }
 9091                let (cursor, goal) = movement::down(
 9092                    map,
 9093                    selection.end,
 9094                    selection.goal,
 9095                    false,
 9096                    text_layout_details,
 9097                );
 9098                selection.collapse_to(cursor, goal);
 9099            });
 9100        });
 9101
 9102        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9103        {
 9104            cx.propagate();
 9105        }
 9106    }
 9107
 9108    pub fn select_page_down(
 9109        &mut self,
 9110        _: &SelectPageDown,
 9111        window: &mut Window,
 9112        cx: &mut Context<Self>,
 9113    ) {
 9114        let Some(row_count) = self.visible_row_count() else {
 9115            return;
 9116        };
 9117
 9118        let text_layout_details = &self.text_layout_details(window);
 9119
 9120        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9121            s.move_heads_with(|map, head, goal| {
 9122                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9123            })
 9124        })
 9125    }
 9126
 9127    pub fn move_page_down(
 9128        &mut self,
 9129        action: &MovePageDown,
 9130        window: &mut Window,
 9131        cx: &mut Context<Self>,
 9132    ) {
 9133        if self.take_rename(true, window, cx).is_some() {
 9134            return;
 9135        }
 9136
 9137        if self
 9138            .context_menu
 9139            .borrow_mut()
 9140            .as_mut()
 9141            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9142            .unwrap_or(false)
 9143        {
 9144            return;
 9145        }
 9146
 9147        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9148            cx.propagate();
 9149            return;
 9150        }
 9151
 9152        let Some(row_count) = self.visible_row_count() else {
 9153            return;
 9154        };
 9155
 9156        let autoscroll = if action.center_cursor {
 9157            Autoscroll::center()
 9158        } else {
 9159            Autoscroll::fit()
 9160        };
 9161
 9162        let text_layout_details = &self.text_layout_details(window);
 9163        self.change_selections(Some(autoscroll), window, cx, |s| {
 9164            let line_mode = s.line_mode;
 9165            s.move_with(|map, selection| {
 9166                if !selection.is_empty() && !line_mode {
 9167                    selection.goal = SelectionGoal::None;
 9168                }
 9169                let (cursor, goal) = movement::down_by_rows(
 9170                    map,
 9171                    selection.end,
 9172                    row_count,
 9173                    selection.goal,
 9174                    false,
 9175                    text_layout_details,
 9176                );
 9177                selection.collapse_to(cursor, goal);
 9178            });
 9179        });
 9180    }
 9181
 9182    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9183        let text_layout_details = &self.text_layout_details(window);
 9184        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9185            s.move_heads_with(|map, head, goal| {
 9186                movement::down(map, head, goal, false, text_layout_details)
 9187            })
 9188        });
 9189    }
 9190
 9191    pub fn context_menu_first(
 9192        &mut self,
 9193        _: &ContextMenuFirst,
 9194        _window: &mut Window,
 9195        cx: &mut Context<Self>,
 9196    ) {
 9197        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9198            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9199        }
 9200    }
 9201
 9202    pub fn context_menu_prev(
 9203        &mut self,
 9204        _: &ContextMenuPrevious,
 9205        _window: &mut Window,
 9206        cx: &mut Context<Self>,
 9207    ) {
 9208        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9209            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9210        }
 9211    }
 9212
 9213    pub fn context_menu_next(
 9214        &mut self,
 9215        _: &ContextMenuNext,
 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_next(self.completion_provider.as_deref(), cx);
 9221        }
 9222    }
 9223
 9224    pub fn context_menu_last(
 9225        &mut self,
 9226        _: &ContextMenuLast,
 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_last(self.completion_provider.as_deref(), cx);
 9232        }
 9233    }
 9234
 9235    pub fn move_to_previous_word_start(
 9236        &mut self,
 9237        _: &MoveToPreviousWordStart,
 9238        window: &mut Window,
 9239        cx: &mut Context<Self>,
 9240    ) {
 9241        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9242            s.move_cursors_with(|map, head, _| {
 9243                (
 9244                    movement::previous_word_start(map, head),
 9245                    SelectionGoal::None,
 9246                )
 9247            });
 9248        })
 9249    }
 9250
 9251    pub fn move_to_previous_subword_start(
 9252        &mut self,
 9253        _: &MoveToPreviousSubwordStart,
 9254        window: &mut Window,
 9255        cx: &mut Context<Self>,
 9256    ) {
 9257        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9258            s.move_cursors_with(|map, head, _| {
 9259                (
 9260                    movement::previous_subword_start(map, head),
 9261                    SelectionGoal::None,
 9262                )
 9263            });
 9264        })
 9265    }
 9266
 9267    pub fn select_to_previous_word_start(
 9268        &mut self,
 9269        _: &SelectToPreviousWordStart,
 9270        window: &mut Window,
 9271        cx: &mut Context<Self>,
 9272    ) {
 9273        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9274            s.move_heads_with(|map, head, _| {
 9275                (
 9276                    movement::previous_word_start(map, head),
 9277                    SelectionGoal::None,
 9278                )
 9279            });
 9280        })
 9281    }
 9282
 9283    pub fn select_to_previous_subword_start(
 9284        &mut self,
 9285        _: &SelectToPreviousSubwordStart,
 9286        window: &mut Window,
 9287        cx: &mut Context<Self>,
 9288    ) {
 9289        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9290            s.move_heads_with(|map, head, _| {
 9291                (
 9292                    movement::previous_subword_start(map, head),
 9293                    SelectionGoal::None,
 9294                )
 9295            });
 9296        })
 9297    }
 9298
 9299    pub fn delete_to_previous_word_start(
 9300        &mut self,
 9301        action: &DeleteToPreviousWordStart,
 9302        window: &mut Window,
 9303        cx: &mut Context<Self>,
 9304    ) {
 9305        self.transact(window, cx, |this, window, cx| {
 9306            this.select_autoclose_pair(window, cx);
 9307            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9308                let line_mode = s.line_mode;
 9309                s.move_with(|map, selection| {
 9310                    if selection.is_empty() && !line_mode {
 9311                        let cursor = if action.ignore_newlines {
 9312                            movement::previous_word_start(map, selection.head())
 9313                        } else {
 9314                            movement::previous_word_start_or_newline(map, selection.head())
 9315                        };
 9316                        selection.set_head(cursor, SelectionGoal::None);
 9317                    }
 9318                });
 9319            });
 9320            this.insert("", window, cx);
 9321        });
 9322    }
 9323
 9324    pub fn delete_to_previous_subword_start(
 9325        &mut self,
 9326        _: &DeleteToPreviousSubwordStart,
 9327        window: &mut Window,
 9328        cx: &mut Context<Self>,
 9329    ) {
 9330        self.transact(window, cx, |this, window, cx| {
 9331            this.select_autoclose_pair(window, cx);
 9332            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9333                let line_mode = s.line_mode;
 9334                s.move_with(|map, selection| {
 9335                    if selection.is_empty() && !line_mode {
 9336                        let cursor = movement::previous_subword_start(map, selection.head());
 9337                        selection.set_head(cursor, SelectionGoal::None);
 9338                    }
 9339                });
 9340            });
 9341            this.insert("", window, cx);
 9342        });
 9343    }
 9344
 9345    pub fn move_to_next_word_end(
 9346        &mut self,
 9347        _: &MoveToNextWordEnd,
 9348        window: &mut Window,
 9349        cx: &mut Context<Self>,
 9350    ) {
 9351        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9352            s.move_cursors_with(|map, head, _| {
 9353                (movement::next_word_end(map, head), SelectionGoal::None)
 9354            });
 9355        })
 9356    }
 9357
 9358    pub fn move_to_next_subword_end(
 9359        &mut self,
 9360        _: &MoveToNextSubwordEnd,
 9361        window: &mut Window,
 9362        cx: &mut Context<Self>,
 9363    ) {
 9364        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9365            s.move_cursors_with(|map, head, _| {
 9366                (movement::next_subword_end(map, head), SelectionGoal::None)
 9367            });
 9368        })
 9369    }
 9370
 9371    pub fn select_to_next_word_end(
 9372        &mut self,
 9373        _: &SelectToNextWordEnd,
 9374        window: &mut Window,
 9375        cx: &mut Context<Self>,
 9376    ) {
 9377        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9378            s.move_heads_with(|map, head, _| {
 9379                (movement::next_word_end(map, head), SelectionGoal::None)
 9380            });
 9381        })
 9382    }
 9383
 9384    pub fn select_to_next_subword_end(
 9385        &mut self,
 9386        _: &SelectToNextSubwordEnd,
 9387        window: &mut Window,
 9388        cx: &mut Context<Self>,
 9389    ) {
 9390        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9391            s.move_heads_with(|map, head, _| {
 9392                (movement::next_subword_end(map, head), SelectionGoal::None)
 9393            });
 9394        })
 9395    }
 9396
 9397    pub fn delete_to_next_word_end(
 9398        &mut self,
 9399        action: &DeleteToNextWordEnd,
 9400        window: &mut Window,
 9401        cx: &mut Context<Self>,
 9402    ) {
 9403        self.transact(window, cx, |this, window, cx| {
 9404            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9405                let line_mode = s.line_mode;
 9406                s.move_with(|map, selection| {
 9407                    if selection.is_empty() && !line_mode {
 9408                        let cursor = if action.ignore_newlines {
 9409                            movement::next_word_end(map, selection.head())
 9410                        } else {
 9411                            movement::next_word_end_or_newline(map, selection.head())
 9412                        };
 9413                        selection.set_head(cursor, SelectionGoal::None);
 9414                    }
 9415                });
 9416            });
 9417            this.insert("", window, cx);
 9418        });
 9419    }
 9420
 9421    pub fn delete_to_next_subword_end(
 9422        &mut self,
 9423        _: &DeleteToNextSubwordEnd,
 9424        window: &mut Window,
 9425        cx: &mut Context<Self>,
 9426    ) {
 9427        self.transact(window, cx, |this, window, cx| {
 9428            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9429                s.move_with(|map, selection| {
 9430                    if selection.is_empty() {
 9431                        let cursor = movement::next_subword_end(map, selection.head());
 9432                        selection.set_head(cursor, SelectionGoal::None);
 9433                    }
 9434                });
 9435            });
 9436            this.insert("", window, cx);
 9437        });
 9438    }
 9439
 9440    pub fn move_to_beginning_of_line(
 9441        &mut self,
 9442        action: &MoveToBeginningOfLine,
 9443        window: &mut Window,
 9444        cx: &mut Context<Self>,
 9445    ) {
 9446        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9447            s.move_cursors_with(|map, head, _| {
 9448                (
 9449                    movement::indented_line_beginning(
 9450                        map,
 9451                        head,
 9452                        action.stop_at_soft_wraps,
 9453                        action.stop_at_indent,
 9454                    ),
 9455                    SelectionGoal::None,
 9456                )
 9457            });
 9458        })
 9459    }
 9460
 9461    pub fn select_to_beginning_of_line(
 9462        &mut self,
 9463        action: &SelectToBeginningOfLine,
 9464        window: &mut Window,
 9465        cx: &mut Context<Self>,
 9466    ) {
 9467        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9468            s.move_heads_with(|map, head, _| {
 9469                (
 9470                    movement::indented_line_beginning(
 9471                        map,
 9472                        head,
 9473                        action.stop_at_soft_wraps,
 9474                        action.stop_at_indent,
 9475                    ),
 9476                    SelectionGoal::None,
 9477                )
 9478            });
 9479        });
 9480    }
 9481
 9482    pub fn delete_to_beginning_of_line(
 9483        &mut self,
 9484        _: &DeleteToBeginningOfLine,
 9485        window: &mut Window,
 9486        cx: &mut Context<Self>,
 9487    ) {
 9488        self.transact(window, cx, |this, window, cx| {
 9489            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9490                s.move_with(|_, selection| {
 9491                    selection.reversed = true;
 9492                });
 9493            });
 9494
 9495            this.select_to_beginning_of_line(
 9496                &SelectToBeginningOfLine {
 9497                    stop_at_soft_wraps: false,
 9498                    stop_at_indent: false,
 9499                },
 9500                window,
 9501                cx,
 9502            );
 9503            this.backspace(&Backspace, window, cx);
 9504        });
 9505    }
 9506
 9507    pub fn move_to_end_of_line(
 9508        &mut self,
 9509        action: &MoveToEndOfLine,
 9510        window: &mut Window,
 9511        cx: &mut Context<Self>,
 9512    ) {
 9513        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9514            s.move_cursors_with(|map, head, _| {
 9515                (
 9516                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9517                    SelectionGoal::None,
 9518                )
 9519            });
 9520        })
 9521    }
 9522
 9523    pub fn select_to_end_of_line(
 9524        &mut self,
 9525        action: &SelectToEndOfLine,
 9526        window: &mut Window,
 9527        cx: &mut Context<Self>,
 9528    ) {
 9529        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9530            s.move_heads_with(|map, head, _| {
 9531                (
 9532                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9533                    SelectionGoal::None,
 9534                )
 9535            });
 9536        })
 9537    }
 9538
 9539    pub fn delete_to_end_of_line(
 9540        &mut self,
 9541        _: &DeleteToEndOfLine,
 9542        window: &mut Window,
 9543        cx: &mut Context<Self>,
 9544    ) {
 9545        self.transact(window, cx, |this, window, cx| {
 9546            this.select_to_end_of_line(
 9547                &SelectToEndOfLine {
 9548                    stop_at_soft_wraps: false,
 9549                },
 9550                window,
 9551                cx,
 9552            );
 9553            this.delete(&Delete, window, cx);
 9554        });
 9555    }
 9556
 9557    pub fn cut_to_end_of_line(
 9558        &mut self,
 9559        _: &CutToEndOfLine,
 9560        window: &mut Window,
 9561        cx: &mut Context<Self>,
 9562    ) {
 9563        self.transact(window, cx, |this, window, cx| {
 9564            this.select_to_end_of_line(
 9565                &SelectToEndOfLine {
 9566                    stop_at_soft_wraps: false,
 9567                },
 9568                window,
 9569                cx,
 9570            );
 9571            this.cut(&Cut, window, cx);
 9572        });
 9573    }
 9574
 9575    pub fn move_to_start_of_paragraph(
 9576        &mut self,
 9577        _: &MoveToStartOfParagraph,
 9578        window: &mut Window,
 9579        cx: &mut Context<Self>,
 9580    ) {
 9581        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9582            cx.propagate();
 9583            return;
 9584        }
 9585
 9586        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9587            s.move_with(|map, selection| {
 9588                selection.collapse_to(
 9589                    movement::start_of_paragraph(map, selection.head(), 1),
 9590                    SelectionGoal::None,
 9591                )
 9592            });
 9593        })
 9594    }
 9595
 9596    pub fn move_to_end_of_paragraph(
 9597        &mut self,
 9598        _: &MoveToEndOfParagraph,
 9599        window: &mut Window,
 9600        cx: &mut Context<Self>,
 9601    ) {
 9602        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9603            cx.propagate();
 9604            return;
 9605        }
 9606
 9607        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9608            s.move_with(|map, selection| {
 9609                selection.collapse_to(
 9610                    movement::end_of_paragraph(map, selection.head(), 1),
 9611                    SelectionGoal::None,
 9612                )
 9613            });
 9614        })
 9615    }
 9616
 9617    pub fn select_to_start_of_paragraph(
 9618        &mut self,
 9619        _: &SelectToStartOfParagraph,
 9620        window: &mut Window,
 9621        cx: &mut Context<Self>,
 9622    ) {
 9623        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9624            cx.propagate();
 9625            return;
 9626        }
 9627
 9628        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9629            s.move_heads_with(|map, head, _| {
 9630                (
 9631                    movement::start_of_paragraph(map, head, 1),
 9632                    SelectionGoal::None,
 9633                )
 9634            });
 9635        })
 9636    }
 9637
 9638    pub fn select_to_end_of_paragraph(
 9639        &mut self,
 9640        _: &SelectToEndOfParagraph,
 9641        window: &mut Window,
 9642        cx: &mut Context<Self>,
 9643    ) {
 9644        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9645            cx.propagate();
 9646            return;
 9647        }
 9648
 9649        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9650            s.move_heads_with(|map, head, _| {
 9651                (
 9652                    movement::end_of_paragraph(map, head, 1),
 9653                    SelectionGoal::None,
 9654                )
 9655            });
 9656        })
 9657    }
 9658
 9659    pub fn move_to_start_of_excerpt(
 9660        &mut self,
 9661        _: &MoveToStartOfExcerpt,
 9662        window: &mut Window,
 9663        cx: &mut Context<Self>,
 9664    ) {
 9665        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9666            cx.propagate();
 9667            return;
 9668        }
 9669
 9670        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9671            s.move_with(|map, selection| {
 9672                selection.collapse_to(
 9673                    movement::start_of_excerpt(
 9674                        map,
 9675                        selection.head(),
 9676                        workspace::searchable::Direction::Prev,
 9677                    ),
 9678                    SelectionGoal::None,
 9679                )
 9680            });
 9681        })
 9682    }
 9683
 9684    pub fn move_to_end_of_excerpt(
 9685        &mut self,
 9686        _: &MoveToEndOfExcerpt,
 9687        window: &mut Window,
 9688        cx: &mut Context<Self>,
 9689    ) {
 9690        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9691            cx.propagate();
 9692            return;
 9693        }
 9694
 9695        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9696            s.move_with(|map, selection| {
 9697                selection.collapse_to(
 9698                    movement::end_of_excerpt(
 9699                        map,
 9700                        selection.head(),
 9701                        workspace::searchable::Direction::Next,
 9702                    ),
 9703                    SelectionGoal::None,
 9704                )
 9705            });
 9706        })
 9707    }
 9708
 9709    pub fn select_to_start_of_excerpt(
 9710        &mut self,
 9711        _: &SelectToStartOfExcerpt,
 9712        window: &mut Window,
 9713        cx: &mut Context<Self>,
 9714    ) {
 9715        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9716            cx.propagate();
 9717            return;
 9718        }
 9719
 9720        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9721            s.move_heads_with(|map, head, _| {
 9722                (
 9723                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9724                    SelectionGoal::None,
 9725                )
 9726            });
 9727        })
 9728    }
 9729
 9730    pub fn select_to_end_of_excerpt(
 9731        &mut self,
 9732        _: &SelectToEndOfExcerpt,
 9733        window: &mut Window,
 9734        cx: &mut Context<Self>,
 9735    ) {
 9736        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9737            cx.propagate();
 9738            return;
 9739        }
 9740
 9741        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9742            s.move_heads_with(|map, head, _| {
 9743                (
 9744                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9745                    SelectionGoal::None,
 9746                )
 9747            });
 9748        })
 9749    }
 9750
 9751    pub fn move_to_beginning(
 9752        &mut self,
 9753        _: &MoveToBeginning,
 9754        window: &mut Window,
 9755        cx: &mut Context<Self>,
 9756    ) {
 9757        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9758            cx.propagate();
 9759            return;
 9760        }
 9761
 9762        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9763            s.select_ranges(vec![0..0]);
 9764        });
 9765    }
 9766
 9767    pub fn select_to_beginning(
 9768        &mut self,
 9769        _: &SelectToBeginning,
 9770        window: &mut Window,
 9771        cx: &mut Context<Self>,
 9772    ) {
 9773        let mut selection = self.selections.last::<Point>(cx);
 9774        selection.set_head(Point::zero(), SelectionGoal::None);
 9775
 9776        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9777            s.select(vec![selection]);
 9778        });
 9779    }
 9780
 9781    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9782        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9783            cx.propagate();
 9784            return;
 9785        }
 9786
 9787        let cursor = self.buffer.read(cx).read(cx).len();
 9788        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9789            s.select_ranges(vec![cursor..cursor])
 9790        });
 9791    }
 9792
 9793    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9794        self.nav_history = nav_history;
 9795    }
 9796
 9797    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9798        self.nav_history.as_ref()
 9799    }
 9800
 9801    fn push_to_nav_history(
 9802        &mut self,
 9803        cursor_anchor: Anchor,
 9804        new_position: Option<Point>,
 9805        cx: &mut Context<Self>,
 9806    ) {
 9807        if let Some(nav_history) = self.nav_history.as_mut() {
 9808            let buffer = self.buffer.read(cx).read(cx);
 9809            let cursor_position = cursor_anchor.to_point(&buffer);
 9810            let scroll_state = self.scroll_manager.anchor();
 9811            let scroll_top_row = scroll_state.top_row(&buffer);
 9812            drop(buffer);
 9813
 9814            if let Some(new_position) = new_position {
 9815                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9816                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9817                    return;
 9818                }
 9819            }
 9820
 9821            nav_history.push(
 9822                Some(NavigationData {
 9823                    cursor_anchor,
 9824                    cursor_position,
 9825                    scroll_anchor: scroll_state,
 9826                    scroll_top_row,
 9827                }),
 9828                cx,
 9829            );
 9830        }
 9831    }
 9832
 9833    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9834        let buffer = self.buffer.read(cx).snapshot(cx);
 9835        let mut selection = self.selections.first::<usize>(cx);
 9836        selection.set_head(buffer.len(), SelectionGoal::None);
 9837        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9838            s.select(vec![selection]);
 9839        });
 9840    }
 9841
 9842    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9843        let end = self.buffer.read(cx).read(cx).len();
 9844        self.change_selections(None, window, cx, |s| {
 9845            s.select_ranges(vec![0..end]);
 9846        });
 9847    }
 9848
 9849    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9850        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9851        let mut selections = self.selections.all::<Point>(cx);
 9852        let max_point = display_map.buffer_snapshot.max_point();
 9853        for selection in &mut selections {
 9854            let rows = selection.spanned_rows(true, &display_map);
 9855            selection.start = Point::new(rows.start.0, 0);
 9856            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9857            selection.reversed = false;
 9858        }
 9859        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9860            s.select(selections);
 9861        });
 9862    }
 9863
 9864    pub fn split_selection_into_lines(
 9865        &mut self,
 9866        _: &SplitSelectionIntoLines,
 9867        window: &mut Window,
 9868        cx: &mut Context<Self>,
 9869    ) {
 9870        let selections = self
 9871            .selections
 9872            .all::<Point>(cx)
 9873            .into_iter()
 9874            .map(|selection| selection.start..selection.end)
 9875            .collect::<Vec<_>>();
 9876        self.unfold_ranges(&selections, true, true, cx);
 9877
 9878        let mut new_selection_ranges = Vec::new();
 9879        {
 9880            let buffer = self.buffer.read(cx).read(cx);
 9881            for selection in selections {
 9882                for row in selection.start.row..selection.end.row {
 9883                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9884                    new_selection_ranges.push(cursor..cursor);
 9885                }
 9886
 9887                let is_multiline_selection = selection.start.row != selection.end.row;
 9888                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9889                // so this action feels more ergonomic when paired with other selection operations
 9890                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9891                if !should_skip_last {
 9892                    new_selection_ranges.push(selection.end..selection.end);
 9893                }
 9894            }
 9895        }
 9896        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9897            s.select_ranges(new_selection_ranges);
 9898        });
 9899    }
 9900
 9901    pub fn add_selection_above(
 9902        &mut self,
 9903        _: &AddSelectionAbove,
 9904        window: &mut Window,
 9905        cx: &mut Context<Self>,
 9906    ) {
 9907        self.add_selection(true, window, cx);
 9908    }
 9909
 9910    pub fn add_selection_below(
 9911        &mut self,
 9912        _: &AddSelectionBelow,
 9913        window: &mut Window,
 9914        cx: &mut Context<Self>,
 9915    ) {
 9916        self.add_selection(false, window, cx);
 9917    }
 9918
 9919    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9920        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9921        let mut selections = self.selections.all::<Point>(cx);
 9922        let text_layout_details = self.text_layout_details(window);
 9923        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9924            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9925            let range = oldest_selection.display_range(&display_map).sorted();
 9926
 9927            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9928            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9929            let positions = start_x.min(end_x)..start_x.max(end_x);
 9930
 9931            selections.clear();
 9932            let mut stack = Vec::new();
 9933            for row in range.start.row().0..=range.end.row().0 {
 9934                if let Some(selection) = self.selections.build_columnar_selection(
 9935                    &display_map,
 9936                    DisplayRow(row),
 9937                    &positions,
 9938                    oldest_selection.reversed,
 9939                    &text_layout_details,
 9940                ) {
 9941                    stack.push(selection.id);
 9942                    selections.push(selection);
 9943                }
 9944            }
 9945
 9946            if above {
 9947                stack.reverse();
 9948            }
 9949
 9950            AddSelectionsState { above, stack }
 9951        });
 9952
 9953        let last_added_selection = *state.stack.last().unwrap();
 9954        let mut new_selections = Vec::new();
 9955        if above == state.above {
 9956            let end_row = if above {
 9957                DisplayRow(0)
 9958            } else {
 9959                display_map.max_point().row()
 9960            };
 9961
 9962            'outer: for selection in selections {
 9963                if selection.id == last_added_selection {
 9964                    let range = selection.display_range(&display_map).sorted();
 9965                    debug_assert_eq!(range.start.row(), range.end.row());
 9966                    let mut row = range.start.row();
 9967                    let positions =
 9968                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9969                            px(start)..px(end)
 9970                        } else {
 9971                            let start_x =
 9972                                display_map.x_for_display_point(range.start, &text_layout_details);
 9973                            let end_x =
 9974                                display_map.x_for_display_point(range.end, &text_layout_details);
 9975                            start_x.min(end_x)..start_x.max(end_x)
 9976                        };
 9977
 9978                    while row != end_row {
 9979                        if above {
 9980                            row.0 -= 1;
 9981                        } else {
 9982                            row.0 += 1;
 9983                        }
 9984
 9985                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9986                            &display_map,
 9987                            row,
 9988                            &positions,
 9989                            selection.reversed,
 9990                            &text_layout_details,
 9991                        ) {
 9992                            state.stack.push(new_selection.id);
 9993                            if above {
 9994                                new_selections.push(new_selection);
 9995                                new_selections.push(selection);
 9996                            } else {
 9997                                new_selections.push(selection);
 9998                                new_selections.push(new_selection);
 9999                            }
10000
10001                            continue 'outer;
10002                        }
10003                    }
10004                }
10005
10006                new_selections.push(selection);
10007            }
10008        } else {
10009            new_selections = selections;
10010            new_selections.retain(|s| s.id != last_added_selection);
10011            state.stack.pop();
10012        }
10013
10014        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10015            s.select(new_selections);
10016        });
10017        if state.stack.len() > 1 {
10018            self.add_selections_state = Some(state);
10019        }
10020    }
10021
10022    pub fn select_next_match_internal(
10023        &mut self,
10024        display_map: &DisplaySnapshot,
10025        replace_newest: bool,
10026        autoscroll: Option<Autoscroll>,
10027        window: &mut Window,
10028        cx: &mut Context<Self>,
10029    ) -> Result<()> {
10030        fn select_next_match_ranges(
10031            this: &mut Editor,
10032            range: Range<usize>,
10033            replace_newest: bool,
10034            auto_scroll: Option<Autoscroll>,
10035            window: &mut Window,
10036            cx: &mut Context<Editor>,
10037        ) {
10038            this.unfold_ranges(&[range.clone()], false, true, cx);
10039            this.change_selections(auto_scroll, window, cx, |s| {
10040                if replace_newest {
10041                    s.delete(s.newest_anchor().id);
10042                }
10043                s.insert_range(range.clone());
10044            });
10045        }
10046
10047        let buffer = &display_map.buffer_snapshot;
10048        let mut selections = self.selections.all::<usize>(cx);
10049        if let Some(mut select_next_state) = self.select_next_state.take() {
10050            let query = &select_next_state.query;
10051            if !select_next_state.done {
10052                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10053                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10054                let mut next_selected_range = None;
10055
10056                let bytes_after_last_selection =
10057                    buffer.bytes_in_range(last_selection.end..buffer.len());
10058                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10059                let query_matches = query
10060                    .stream_find_iter(bytes_after_last_selection)
10061                    .map(|result| (last_selection.end, result))
10062                    .chain(
10063                        query
10064                            .stream_find_iter(bytes_before_first_selection)
10065                            .map(|result| (0, result)),
10066                    );
10067
10068                for (start_offset, query_match) in query_matches {
10069                    let query_match = query_match.unwrap(); // can only fail due to I/O
10070                    let offset_range =
10071                        start_offset + query_match.start()..start_offset + query_match.end();
10072                    let display_range = offset_range.start.to_display_point(display_map)
10073                        ..offset_range.end.to_display_point(display_map);
10074
10075                    if !select_next_state.wordwise
10076                        || (!movement::is_inside_word(display_map, display_range.start)
10077                            && !movement::is_inside_word(display_map, display_range.end))
10078                    {
10079                        // TODO: This is n^2, because we might check all the selections
10080                        if !selections
10081                            .iter()
10082                            .any(|selection| selection.range().overlaps(&offset_range))
10083                        {
10084                            next_selected_range = Some(offset_range);
10085                            break;
10086                        }
10087                    }
10088                }
10089
10090                if let Some(next_selected_range) = next_selected_range {
10091                    select_next_match_ranges(
10092                        self,
10093                        next_selected_range,
10094                        replace_newest,
10095                        autoscroll,
10096                        window,
10097                        cx,
10098                    );
10099                } else {
10100                    select_next_state.done = true;
10101                }
10102            }
10103
10104            self.select_next_state = Some(select_next_state);
10105        } else {
10106            let mut only_carets = true;
10107            let mut same_text_selected = true;
10108            let mut selected_text = None;
10109
10110            let mut selections_iter = selections.iter().peekable();
10111            while let Some(selection) = selections_iter.next() {
10112                if selection.start != selection.end {
10113                    only_carets = false;
10114                }
10115
10116                if same_text_selected {
10117                    if selected_text.is_none() {
10118                        selected_text =
10119                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10120                    }
10121
10122                    if let Some(next_selection) = selections_iter.peek() {
10123                        if next_selection.range().len() == selection.range().len() {
10124                            let next_selected_text = buffer
10125                                .text_for_range(next_selection.range())
10126                                .collect::<String>();
10127                            if Some(next_selected_text) != selected_text {
10128                                same_text_selected = false;
10129                                selected_text = None;
10130                            }
10131                        } else {
10132                            same_text_selected = false;
10133                            selected_text = None;
10134                        }
10135                    }
10136                }
10137            }
10138
10139            if only_carets {
10140                for selection in &mut selections {
10141                    let word_range = movement::surrounding_word(
10142                        display_map,
10143                        selection.start.to_display_point(display_map),
10144                    );
10145                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10146                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10147                    selection.goal = SelectionGoal::None;
10148                    selection.reversed = false;
10149                    select_next_match_ranges(
10150                        self,
10151                        selection.start..selection.end,
10152                        replace_newest,
10153                        autoscroll,
10154                        window,
10155                        cx,
10156                    );
10157                }
10158
10159                if selections.len() == 1 {
10160                    let selection = selections
10161                        .last()
10162                        .expect("ensured that there's only one selection");
10163                    let query = buffer
10164                        .text_for_range(selection.start..selection.end)
10165                        .collect::<String>();
10166                    let is_empty = query.is_empty();
10167                    let select_state = SelectNextState {
10168                        query: AhoCorasick::new(&[query])?,
10169                        wordwise: true,
10170                        done: is_empty,
10171                    };
10172                    self.select_next_state = Some(select_state);
10173                } else {
10174                    self.select_next_state = None;
10175                }
10176            } else if let Some(selected_text) = selected_text {
10177                self.select_next_state = Some(SelectNextState {
10178                    query: AhoCorasick::new(&[selected_text])?,
10179                    wordwise: false,
10180                    done: false,
10181                });
10182                self.select_next_match_internal(
10183                    display_map,
10184                    replace_newest,
10185                    autoscroll,
10186                    window,
10187                    cx,
10188                )?;
10189            }
10190        }
10191        Ok(())
10192    }
10193
10194    pub fn select_all_matches(
10195        &mut self,
10196        _action: &SelectAllMatches,
10197        window: &mut Window,
10198        cx: &mut Context<Self>,
10199    ) -> Result<()> {
10200        self.push_to_selection_history();
10201        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10202
10203        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10204        let Some(select_next_state) = self.select_next_state.as_mut() else {
10205            return Ok(());
10206        };
10207        if select_next_state.done {
10208            return Ok(());
10209        }
10210
10211        let mut new_selections = self.selections.all::<usize>(cx);
10212
10213        let buffer = &display_map.buffer_snapshot;
10214        let query_matches = select_next_state
10215            .query
10216            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10217
10218        for query_match in query_matches {
10219            let query_match = query_match.unwrap(); // can only fail due to I/O
10220            let offset_range = query_match.start()..query_match.end();
10221            let display_range = offset_range.start.to_display_point(&display_map)
10222                ..offset_range.end.to_display_point(&display_map);
10223
10224            if !select_next_state.wordwise
10225                || (!movement::is_inside_word(&display_map, display_range.start)
10226                    && !movement::is_inside_word(&display_map, display_range.end))
10227            {
10228                self.selections.change_with(cx, |selections| {
10229                    new_selections.push(Selection {
10230                        id: selections.new_selection_id(),
10231                        start: offset_range.start,
10232                        end: offset_range.end,
10233                        reversed: false,
10234                        goal: SelectionGoal::None,
10235                    });
10236                });
10237            }
10238        }
10239
10240        new_selections.sort_by_key(|selection| selection.start);
10241        let mut ix = 0;
10242        while ix + 1 < new_selections.len() {
10243            let current_selection = &new_selections[ix];
10244            let next_selection = &new_selections[ix + 1];
10245            if current_selection.range().overlaps(&next_selection.range()) {
10246                if current_selection.id < next_selection.id {
10247                    new_selections.remove(ix + 1);
10248                } else {
10249                    new_selections.remove(ix);
10250                }
10251            } else {
10252                ix += 1;
10253            }
10254        }
10255
10256        let reversed = self.selections.oldest::<usize>(cx).reversed;
10257
10258        for selection in new_selections.iter_mut() {
10259            selection.reversed = reversed;
10260        }
10261
10262        select_next_state.done = true;
10263        self.unfold_ranges(
10264            &new_selections
10265                .iter()
10266                .map(|selection| selection.range())
10267                .collect::<Vec<_>>(),
10268            false,
10269            false,
10270            cx,
10271        );
10272        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10273            selections.select(new_selections)
10274        });
10275
10276        Ok(())
10277    }
10278
10279    pub fn select_next(
10280        &mut self,
10281        action: &SelectNext,
10282        window: &mut Window,
10283        cx: &mut Context<Self>,
10284    ) -> Result<()> {
10285        self.push_to_selection_history();
10286        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10287        self.select_next_match_internal(
10288            &display_map,
10289            action.replace_newest,
10290            Some(Autoscroll::newest()),
10291            window,
10292            cx,
10293        )?;
10294        Ok(())
10295    }
10296
10297    pub fn select_previous(
10298        &mut self,
10299        action: &SelectPrevious,
10300        window: &mut Window,
10301        cx: &mut Context<Self>,
10302    ) -> Result<()> {
10303        self.push_to_selection_history();
10304        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10305        let buffer = &display_map.buffer_snapshot;
10306        let mut selections = self.selections.all::<usize>(cx);
10307        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10308            let query = &select_prev_state.query;
10309            if !select_prev_state.done {
10310                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10311                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10312                let mut next_selected_range = None;
10313                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10314                let bytes_before_last_selection =
10315                    buffer.reversed_bytes_in_range(0..last_selection.start);
10316                let bytes_after_first_selection =
10317                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10318                let query_matches = query
10319                    .stream_find_iter(bytes_before_last_selection)
10320                    .map(|result| (last_selection.start, result))
10321                    .chain(
10322                        query
10323                            .stream_find_iter(bytes_after_first_selection)
10324                            .map(|result| (buffer.len(), result)),
10325                    );
10326                for (end_offset, query_match) in query_matches {
10327                    let query_match = query_match.unwrap(); // can only fail due to I/O
10328                    let offset_range =
10329                        end_offset - query_match.end()..end_offset - query_match.start();
10330                    let display_range = offset_range.start.to_display_point(&display_map)
10331                        ..offset_range.end.to_display_point(&display_map);
10332
10333                    if !select_prev_state.wordwise
10334                        || (!movement::is_inside_word(&display_map, display_range.start)
10335                            && !movement::is_inside_word(&display_map, display_range.end))
10336                    {
10337                        next_selected_range = Some(offset_range);
10338                        break;
10339                    }
10340                }
10341
10342                if let Some(next_selected_range) = next_selected_range {
10343                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10344                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10345                        if action.replace_newest {
10346                            s.delete(s.newest_anchor().id);
10347                        }
10348                        s.insert_range(next_selected_range);
10349                    });
10350                } else {
10351                    select_prev_state.done = true;
10352                }
10353            }
10354
10355            self.select_prev_state = Some(select_prev_state);
10356        } else {
10357            let mut only_carets = true;
10358            let mut same_text_selected = true;
10359            let mut selected_text = None;
10360
10361            let mut selections_iter = selections.iter().peekable();
10362            while let Some(selection) = selections_iter.next() {
10363                if selection.start != selection.end {
10364                    only_carets = false;
10365                }
10366
10367                if same_text_selected {
10368                    if selected_text.is_none() {
10369                        selected_text =
10370                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10371                    }
10372
10373                    if let Some(next_selection) = selections_iter.peek() {
10374                        if next_selection.range().len() == selection.range().len() {
10375                            let next_selected_text = buffer
10376                                .text_for_range(next_selection.range())
10377                                .collect::<String>();
10378                            if Some(next_selected_text) != selected_text {
10379                                same_text_selected = false;
10380                                selected_text = None;
10381                            }
10382                        } else {
10383                            same_text_selected = false;
10384                            selected_text = None;
10385                        }
10386                    }
10387                }
10388            }
10389
10390            if only_carets {
10391                for selection in &mut selections {
10392                    let word_range = movement::surrounding_word(
10393                        &display_map,
10394                        selection.start.to_display_point(&display_map),
10395                    );
10396                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10397                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10398                    selection.goal = SelectionGoal::None;
10399                    selection.reversed = false;
10400                }
10401                if selections.len() == 1 {
10402                    let selection = selections
10403                        .last()
10404                        .expect("ensured that there's only one selection");
10405                    let query = buffer
10406                        .text_for_range(selection.start..selection.end)
10407                        .collect::<String>();
10408                    let is_empty = query.is_empty();
10409                    let select_state = SelectNextState {
10410                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10411                        wordwise: true,
10412                        done: is_empty,
10413                    };
10414                    self.select_prev_state = Some(select_state);
10415                } else {
10416                    self.select_prev_state = None;
10417                }
10418
10419                self.unfold_ranges(
10420                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10421                    false,
10422                    true,
10423                    cx,
10424                );
10425                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10426                    s.select(selections);
10427                });
10428            } else if let Some(selected_text) = selected_text {
10429                self.select_prev_state = Some(SelectNextState {
10430                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10431                    wordwise: false,
10432                    done: false,
10433                });
10434                self.select_previous(action, window, cx)?;
10435            }
10436        }
10437        Ok(())
10438    }
10439
10440    pub fn toggle_comments(
10441        &mut self,
10442        action: &ToggleComments,
10443        window: &mut Window,
10444        cx: &mut Context<Self>,
10445    ) {
10446        if self.read_only(cx) {
10447            return;
10448        }
10449        let text_layout_details = &self.text_layout_details(window);
10450        self.transact(window, cx, |this, window, cx| {
10451            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10452            let mut edits = Vec::new();
10453            let mut selection_edit_ranges = Vec::new();
10454            let mut last_toggled_row = None;
10455            let snapshot = this.buffer.read(cx).read(cx);
10456            let empty_str: Arc<str> = Arc::default();
10457            let mut suffixes_inserted = Vec::new();
10458            let ignore_indent = action.ignore_indent;
10459
10460            fn comment_prefix_range(
10461                snapshot: &MultiBufferSnapshot,
10462                row: MultiBufferRow,
10463                comment_prefix: &str,
10464                comment_prefix_whitespace: &str,
10465                ignore_indent: bool,
10466            ) -> Range<Point> {
10467                let indent_size = if ignore_indent {
10468                    0
10469                } else {
10470                    snapshot.indent_size_for_line(row).len
10471                };
10472
10473                let start = Point::new(row.0, indent_size);
10474
10475                let mut line_bytes = snapshot
10476                    .bytes_in_range(start..snapshot.max_point())
10477                    .flatten()
10478                    .copied();
10479
10480                // If this line currently begins with the line comment prefix, then record
10481                // the range containing the prefix.
10482                if line_bytes
10483                    .by_ref()
10484                    .take(comment_prefix.len())
10485                    .eq(comment_prefix.bytes())
10486                {
10487                    // Include any whitespace that matches the comment prefix.
10488                    let matching_whitespace_len = line_bytes
10489                        .zip(comment_prefix_whitespace.bytes())
10490                        .take_while(|(a, b)| a == b)
10491                        .count() as u32;
10492                    let end = Point::new(
10493                        start.row,
10494                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10495                    );
10496                    start..end
10497                } else {
10498                    start..start
10499                }
10500            }
10501
10502            fn comment_suffix_range(
10503                snapshot: &MultiBufferSnapshot,
10504                row: MultiBufferRow,
10505                comment_suffix: &str,
10506                comment_suffix_has_leading_space: bool,
10507            ) -> Range<Point> {
10508                let end = Point::new(row.0, snapshot.line_len(row));
10509                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10510
10511                let mut line_end_bytes = snapshot
10512                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10513                    .flatten()
10514                    .copied();
10515
10516                let leading_space_len = if suffix_start_column > 0
10517                    && line_end_bytes.next() == Some(b' ')
10518                    && comment_suffix_has_leading_space
10519                {
10520                    1
10521                } else {
10522                    0
10523                };
10524
10525                // If this line currently begins with the line comment prefix, then record
10526                // the range containing the prefix.
10527                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10528                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10529                    start..end
10530                } else {
10531                    end..end
10532                }
10533            }
10534
10535            // TODO: Handle selections that cross excerpts
10536            for selection in &mut selections {
10537                let start_column = snapshot
10538                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10539                    .len;
10540                let language = if let Some(language) =
10541                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10542                {
10543                    language
10544                } else {
10545                    continue;
10546                };
10547
10548                selection_edit_ranges.clear();
10549
10550                // If multiple selections contain a given row, avoid processing that
10551                // row more than once.
10552                let mut start_row = MultiBufferRow(selection.start.row);
10553                if last_toggled_row == Some(start_row) {
10554                    start_row = start_row.next_row();
10555                }
10556                let end_row =
10557                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10558                        MultiBufferRow(selection.end.row - 1)
10559                    } else {
10560                        MultiBufferRow(selection.end.row)
10561                    };
10562                last_toggled_row = Some(end_row);
10563
10564                if start_row > end_row {
10565                    continue;
10566                }
10567
10568                // If the language has line comments, toggle those.
10569                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10570
10571                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10572                if ignore_indent {
10573                    full_comment_prefixes = full_comment_prefixes
10574                        .into_iter()
10575                        .map(|s| Arc::from(s.trim_end()))
10576                        .collect();
10577                }
10578
10579                if !full_comment_prefixes.is_empty() {
10580                    let first_prefix = full_comment_prefixes
10581                        .first()
10582                        .expect("prefixes is non-empty");
10583                    let prefix_trimmed_lengths = full_comment_prefixes
10584                        .iter()
10585                        .map(|p| p.trim_end_matches(' ').len())
10586                        .collect::<SmallVec<[usize; 4]>>();
10587
10588                    let mut all_selection_lines_are_comments = true;
10589
10590                    for row in start_row.0..=end_row.0 {
10591                        let row = MultiBufferRow(row);
10592                        if start_row < end_row && snapshot.is_line_blank(row) {
10593                            continue;
10594                        }
10595
10596                        let prefix_range = full_comment_prefixes
10597                            .iter()
10598                            .zip(prefix_trimmed_lengths.iter().copied())
10599                            .map(|(prefix, trimmed_prefix_len)| {
10600                                comment_prefix_range(
10601                                    snapshot.deref(),
10602                                    row,
10603                                    &prefix[..trimmed_prefix_len],
10604                                    &prefix[trimmed_prefix_len..],
10605                                    ignore_indent,
10606                                )
10607                            })
10608                            .max_by_key(|range| range.end.column - range.start.column)
10609                            .expect("prefixes is non-empty");
10610
10611                        if prefix_range.is_empty() {
10612                            all_selection_lines_are_comments = false;
10613                        }
10614
10615                        selection_edit_ranges.push(prefix_range);
10616                    }
10617
10618                    if all_selection_lines_are_comments {
10619                        edits.extend(
10620                            selection_edit_ranges
10621                                .iter()
10622                                .cloned()
10623                                .map(|range| (range, empty_str.clone())),
10624                        );
10625                    } else {
10626                        let min_column = selection_edit_ranges
10627                            .iter()
10628                            .map(|range| range.start.column)
10629                            .min()
10630                            .unwrap_or(0);
10631                        edits.extend(selection_edit_ranges.iter().map(|range| {
10632                            let position = Point::new(range.start.row, min_column);
10633                            (position..position, first_prefix.clone())
10634                        }));
10635                    }
10636                } else if let Some((full_comment_prefix, comment_suffix)) =
10637                    language.block_comment_delimiters()
10638                {
10639                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10640                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10641                    let prefix_range = comment_prefix_range(
10642                        snapshot.deref(),
10643                        start_row,
10644                        comment_prefix,
10645                        comment_prefix_whitespace,
10646                        ignore_indent,
10647                    );
10648                    let suffix_range = comment_suffix_range(
10649                        snapshot.deref(),
10650                        end_row,
10651                        comment_suffix.trim_start_matches(' '),
10652                        comment_suffix.starts_with(' '),
10653                    );
10654
10655                    if prefix_range.is_empty() || suffix_range.is_empty() {
10656                        edits.push((
10657                            prefix_range.start..prefix_range.start,
10658                            full_comment_prefix.clone(),
10659                        ));
10660                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10661                        suffixes_inserted.push((end_row, comment_suffix.len()));
10662                    } else {
10663                        edits.push((prefix_range, empty_str.clone()));
10664                        edits.push((suffix_range, empty_str.clone()));
10665                    }
10666                } else {
10667                    continue;
10668                }
10669            }
10670
10671            drop(snapshot);
10672            this.buffer.update(cx, |buffer, cx| {
10673                buffer.edit(edits, None, cx);
10674            });
10675
10676            // Adjust selections so that they end before any comment suffixes that
10677            // were inserted.
10678            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10679            let mut selections = this.selections.all::<Point>(cx);
10680            let snapshot = this.buffer.read(cx).read(cx);
10681            for selection in &mut selections {
10682                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10683                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10684                        Ordering::Less => {
10685                            suffixes_inserted.next();
10686                            continue;
10687                        }
10688                        Ordering::Greater => break,
10689                        Ordering::Equal => {
10690                            if selection.end.column == snapshot.line_len(row) {
10691                                if selection.is_empty() {
10692                                    selection.start.column -= suffix_len as u32;
10693                                }
10694                                selection.end.column -= suffix_len as u32;
10695                            }
10696                            break;
10697                        }
10698                    }
10699                }
10700            }
10701
10702            drop(snapshot);
10703            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10704                s.select(selections)
10705            });
10706
10707            let selections = this.selections.all::<Point>(cx);
10708            let selections_on_single_row = selections.windows(2).all(|selections| {
10709                selections[0].start.row == selections[1].start.row
10710                    && selections[0].end.row == selections[1].end.row
10711                    && selections[0].start.row == selections[0].end.row
10712            });
10713            let selections_selecting = selections
10714                .iter()
10715                .any(|selection| selection.start != selection.end);
10716            let advance_downwards = action.advance_downwards
10717                && selections_on_single_row
10718                && !selections_selecting
10719                && !matches!(this.mode, EditorMode::SingleLine { .. });
10720
10721            if advance_downwards {
10722                let snapshot = this.buffer.read(cx).snapshot(cx);
10723
10724                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10725                    s.move_cursors_with(|display_snapshot, display_point, _| {
10726                        let mut point = display_point.to_point(display_snapshot);
10727                        point.row += 1;
10728                        point = snapshot.clip_point(point, Bias::Left);
10729                        let display_point = point.to_display_point(display_snapshot);
10730                        let goal = SelectionGoal::HorizontalPosition(
10731                            display_snapshot
10732                                .x_for_display_point(display_point, text_layout_details)
10733                                .into(),
10734                        );
10735                        (display_point, goal)
10736                    })
10737                });
10738            }
10739        });
10740    }
10741
10742    pub fn select_enclosing_symbol(
10743        &mut self,
10744        _: &SelectEnclosingSymbol,
10745        window: &mut Window,
10746        cx: &mut Context<Self>,
10747    ) {
10748        let buffer = self.buffer.read(cx).snapshot(cx);
10749        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10750
10751        fn update_selection(
10752            selection: &Selection<usize>,
10753            buffer_snap: &MultiBufferSnapshot,
10754        ) -> Option<Selection<usize>> {
10755            let cursor = selection.head();
10756            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10757            for symbol in symbols.iter().rev() {
10758                let start = symbol.range.start.to_offset(buffer_snap);
10759                let end = symbol.range.end.to_offset(buffer_snap);
10760                let new_range = start..end;
10761                if start < selection.start || end > selection.end {
10762                    return Some(Selection {
10763                        id: selection.id,
10764                        start: new_range.start,
10765                        end: new_range.end,
10766                        goal: SelectionGoal::None,
10767                        reversed: selection.reversed,
10768                    });
10769                }
10770            }
10771            None
10772        }
10773
10774        let mut selected_larger_symbol = false;
10775        let new_selections = old_selections
10776            .iter()
10777            .map(|selection| match update_selection(selection, &buffer) {
10778                Some(new_selection) => {
10779                    if new_selection.range() != selection.range() {
10780                        selected_larger_symbol = true;
10781                    }
10782                    new_selection
10783                }
10784                None => selection.clone(),
10785            })
10786            .collect::<Vec<_>>();
10787
10788        if selected_larger_symbol {
10789            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10790                s.select(new_selections);
10791            });
10792        }
10793    }
10794
10795    pub fn select_larger_syntax_node(
10796        &mut self,
10797        _: &SelectLargerSyntaxNode,
10798        window: &mut Window,
10799        cx: &mut Context<Self>,
10800    ) {
10801        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10802        let buffer = self.buffer.read(cx).snapshot(cx);
10803        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10804
10805        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10806        let mut selected_larger_node = false;
10807        let new_selections = old_selections
10808            .iter()
10809            .map(|selection| {
10810                let old_range = selection.start..selection.end;
10811                let mut new_range = old_range.clone();
10812                let mut new_node = None;
10813                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10814                {
10815                    new_node = Some(node);
10816                    new_range = match containing_range {
10817                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10818                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10819                    };
10820                    if !display_map.intersects_fold(new_range.start)
10821                        && !display_map.intersects_fold(new_range.end)
10822                    {
10823                        break;
10824                    }
10825                }
10826
10827                if let Some(node) = new_node {
10828                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10829                    // nodes. Parent and grandparent are also logged because this operation will not
10830                    // visit nodes that have the same range as their parent.
10831                    log::info!("Node: {node:?}");
10832                    let parent = node.parent();
10833                    log::info!("Parent: {parent:?}");
10834                    let grandparent = parent.and_then(|x| x.parent());
10835                    log::info!("Grandparent: {grandparent:?}");
10836                }
10837
10838                selected_larger_node |= new_range != old_range;
10839                Selection {
10840                    id: selection.id,
10841                    start: new_range.start,
10842                    end: new_range.end,
10843                    goal: SelectionGoal::None,
10844                    reversed: selection.reversed,
10845                }
10846            })
10847            .collect::<Vec<_>>();
10848
10849        if selected_larger_node {
10850            stack.push(old_selections);
10851            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10852                s.select(new_selections);
10853            });
10854        }
10855        self.select_larger_syntax_node_stack = stack;
10856    }
10857
10858    pub fn select_smaller_syntax_node(
10859        &mut self,
10860        _: &SelectSmallerSyntaxNode,
10861        window: &mut Window,
10862        cx: &mut Context<Self>,
10863    ) {
10864        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10865        if let Some(selections) = stack.pop() {
10866            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10867                s.select(selections.to_vec());
10868            });
10869        }
10870        self.select_larger_syntax_node_stack = stack;
10871    }
10872
10873    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10874        if !EditorSettings::get_global(cx).gutter.runnables {
10875            self.clear_tasks();
10876            return Task::ready(());
10877        }
10878        let project = self.project.as_ref().map(Entity::downgrade);
10879        cx.spawn_in(window, |this, mut cx| async move {
10880            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10881            let Some(project) = project.and_then(|p| p.upgrade()) else {
10882                return;
10883            };
10884            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10885                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10886            }) else {
10887                return;
10888            };
10889
10890            let hide_runnables = project
10891                .update(&mut cx, |project, cx| {
10892                    // Do not display any test indicators in non-dev server remote projects.
10893                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10894                })
10895                .unwrap_or(true);
10896            if hide_runnables {
10897                return;
10898            }
10899            let new_rows =
10900                cx.background_spawn({
10901                    let snapshot = display_snapshot.clone();
10902                    async move {
10903                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10904                    }
10905                })
10906                    .await;
10907
10908            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10909            this.update(&mut cx, |this, _| {
10910                this.clear_tasks();
10911                for (key, value) in rows {
10912                    this.insert_tasks(key, value);
10913                }
10914            })
10915            .ok();
10916        })
10917    }
10918    fn fetch_runnable_ranges(
10919        snapshot: &DisplaySnapshot,
10920        range: Range<Anchor>,
10921    ) -> Vec<language::RunnableRange> {
10922        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10923    }
10924
10925    fn runnable_rows(
10926        project: Entity<Project>,
10927        snapshot: DisplaySnapshot,
10928        runnable_ranges: Vec<RunnableRange>,
10929        mut cx: AsyncWindowContext,
10930    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10931        runnable_ranges
10932            .into_iter()
10933            .filter_map(|mut runnable| {
10934                let tasks = cx
10935                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10936                    .ok()?;
10937                if tasks.is_empty() {
10938                    return None;
10939                }
10940
10941                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10942
10943                let row = snapshot
10944                    .buffer_snapshot
10945                    .buffer_line_for_row(MultiBufferRow(point.row))?
10946                    .1
10947                    .start
10948                    .row;
10949
10950                let context_range =
10951                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10952                Some((
10953                    (runnable.buffer_id, row),
10954                    RunnableTasks {
10955                        templates: tasks,
10956                        offset: snapshot
10957                            .buffer_snapshot
10958                            .anchor_before(runnable.run_range.start),
10959                        context_range,
10960                        column: point.column,
10961                        extra_variables: runnable.extra_captures,
10962                    },
10963                ))
10964            })
10965            .collect()
10966    }
10967
10968    fn templates_with_tags(
10969        project: &Entity<Project>,
10970        runnable: &mut Runnable,
10971        cx: &mut App,
10972    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10973        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10974            let (worktree_id, file) = project
10975                .buffer_for_id(runnable.buffer, cx)
10976                .and_then(|buffer| buffer.read(cx).file())
10977                .map(|file| (file.worktree_id(cx), file.clone()))
10978                .unzip();
10979
10980            (
10981                project.task_store().read(cx).task_inventory().cloned(),
10982                worktree_id,
10983                file,
10984            )
10985        });
10986
10987        let tags = mem::take(&mut runnable.tags);
10988        let mut tags: Vec<_> = tags
10989            .into_iter()
10990            .flat_map(|tag| {
10991                let tag = tag.0.clone();
10992                inventory
10993                    .as_ref()
10994                    .into_iter()
10995                    .flat_map(|inventory| {
10996                        inventory.read(cx).list_tasks(
10997                            file.clone(),
10998                            Some(runnable.language.clone()),
10999                            worktree_id,
11000                            cx,
11001                        )
11002                    })
11003                    .filter(move |(_, template)| {
11004                        template.tags.iter().any(|source_tag| source_tag == &tag)
11005                    })
11006            })
11007            .sorted_by_key(|(kind, _)| kind.to_owned())
11008            .collect();
11009        if let Some((leading_tag_source, _)) = tags.first() {
11010            // Strongest source wins; if we have worktree tag binding, prefer that to
11011            // global and language bindings;
11012            // if we have a global binding, prefer that to language binding.
11013            let first_mismatch = tags
11014                .iter()
11015                .position(|(tag_source, _)| tag_source != leading_tag_source);
11016            if let Some(index) = first_mismatch {
11017                tags.truncate(index);
11018            }
11019        }
11020
11021        tags
11022    }
11023
11024    pub fn move_to_enclosing_bracket(
11025        &mut self,
11026        _: &MoveToEnclosingBracket,
11027        window: &mut Window,
11028        cx: &mut Context<Self>,
11029    ) {
11030        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11031            s.move_offsets_with(|snapshot, selection| {
11032                let Some(enclosing_bracket_ranges) =
11033                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11034                else {
11035                    return;
11036                };
11037
11038                let mut best_length = usize::MAX;
11039                let mut best_inside = false;
11040                let mut best_in_bracket_range = false;
11041                let mut best_destination = None;
11042                for (open, close) in enclosing_bracket_ranges {
11043                    let close = close.to_inclusive();
11044                    let length = close.end() - open.start;
11045                    let inside = selection.start >= open.end && selection.end <= *close.start();
11046                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11047                        || close.contains(&selection.head());
11048
11049                    // If best is next to a bracket and current isn't, skip
11050                    if !in_bracket_range && best_in_bracket_range {
11051                        continue;
11052                    }
11053
11054                    // Prefer smaller lengths unless best is inside and current isn't
11055                    if length > best_length && (best_inside || !inside) {
11056                        continue;
11057                    }
11058
11059                    best_length = length;
11060                    best_inside = inside;
11061                    best_in_bracket_range = in_bracket_range;
11062                    best_destination = Some(
11063                        if close.contains(&selection.start) && close.contains(&selection.end) {
11064                            if inside {
11065                                open.end
11066                            } else {
11067                                open.start
11068                            }
11069                        } else if inside {
11070                            *close.start()
11071                        } else {
11072                            *close.end()
11073                        },
11074                    );
11075                }
11076
11077                if let Some(destination) = best_destination {
11078                    selection.collapse_to(destination, SelectionGoal::None);
11079                }
11080            })
11081        });
11082    }
11083
11084    pub fn undo_selection(
11085        &mut self,
11086        _: &UndoSelection,
11087        window: &mut Window,
11088        cx: &mut Context<Self>,
11089    ) {
11090        self.end_selection(window, cx);
11091        self.selection_history.mode = SelectionHistoryMode::Undoing;
11092        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11093            self.change_selections(None, window, cx, |s| {
11094                s.select_anchors(entry.selections.to_vec())
11095            });
11096            self.select_next_state = entry.select_next_state;
11097            self.select_prev_state = entry.select_prev_state;
11098            self.add_selections_state = entry.add_selections_state;
11099            self.request_autoscroll(Autoscroll::newest(), cx);
11100        }
11101        self.selection_history.mode = SelectionHistoryMode::Normal;
11102    }
11103
11104    pub fn redo_selection(
11105        &mut self,
11106        _: &RedoSelection,
11107        window: &mut Window,
11108        cx: &mut Context<Self>,
11109    ) {
11110        self.end_selection(window, cx);
11111        self.selection_history.mode = SelectionHistoryMode::Redoing;
11112        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11113            self.change_selections(None, window, cx, |s| {
11114                s.select_anchors(entry.selections.to_vec())
11115            });
11116            self.select_next_state = entry.select_next_state;
11117            self.select_prev_state = entry.select_prev_state;
11118            self.add_selections_state = entry.add_selections_state;
11119            self.request_autoscroll(Autoscroll::newest(), cx);
11120        }
11121        self.selection_history.mode = SelectionHistoryMode::Normal;
11122    }
11123
11124    pub fn expand_excerpts(
11125        &mut self,
11126        action: &ExpandExcerpts,
11127        _: &mut Window,
11128        cx: &mut Context<Self>,
11129    ) {
11130        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11131    }
11132
11133    pub fn expand_excerpts_down(
11134        &mut self,
11135        action: &ExpandExcerptsDown,
11136        _: &mut Window,
11137        cx: &mut Context<Self>,
11138    ) {
11139        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11140    }
11141
11142    pub fn expand_excerpts_up(
11143        &mut self,
11144        action: &ExpandExcerptsUp,
11145        _: &mut Window,
11146        cx: &mut Context<Self>,
11147    ) {
11148        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11149    }
11150
11151    pub fn expand_excerpts_for_direction(
11152        &mut self,
11153        lines: u32,
11154        direction: ExpandExcerptDirection,
11155
11156        cx: &mut Context<Self>,
11157    ) {
11158        let selections = self.selections.disjoint_anchors();
11159
11160        let lines = if lines == 0 {
11161            EditorSettings::get_global(cx).expand_excerpt_lines
11162        } else {
11163            lines
11164        };
11165
11166        self.buffer.update(cx, |buffer, cx| {
11167            let snapshot = buffer.snapshot(cx);
11168            let mut excerpt_ids = selections
11169                .iter()
11170                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11171                .collect::<Vec<_>>();
11172            excerpt_ids.sort();
11173            excerpt_ids.dedup();
11174            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11175        })
11176    }
11177
11178    pub fn expand_excerpt(
11179        &mut self,
11180        excerpt: ExcerptId,
11181        direction: ExpandExcerptDirection,
11182        cx: &mut Context<Self>,
11183    ) {
11184        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11185        self.buffer.update(cx, |buffer, cx| {
11186            buffer.expand_excerpts([excerpt], lines, direction, cx)
11187        })
11188    }
11189
11190    pub fn go_to_singleton_buffer_point(
11191        &mut self,
11192        point: Point,
11193        window: &mut Window,
11194        cx: &mut Context<Self>,
11195    ) {
11196        self.go_to_singleton_buffer_range(point..point, window, cx);
11197    }
11198
11199    pub fn go_to_singleton_buffer_range(
11200        &mut self,
11201        range: Range<Point>,
11202        window: &mut Window,
11203        cx: &mut Context<Self>,
11204    ) {
11205        let multibuffer = self.buffer().read(cx);
11206        let Some(buffer) = multibuffer.as_singleton() else {
11207            return;
11208        };
11209        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11210            return;
11211        };
11212        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11213            return;
11214        };
11215        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11216            s.select_anchor_ranges([start..end])
11217        });
11218    }
11219
11220    fn go_to_diagnostic(
11221        &mut self,
11222        _: &GoToDiagnostic,
11223        window: &mut Window,
11224        cx: &mut Context<Self>,
11225    ) {
11226        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11227    }
11228
11229    fn go_to_prev_diagnostic(
11230        &mut self,
11231        _: &GoToPreviousDiagnostic,
11232        window: &mut Window,
11233        cx: &mut Context<Self>,
11234    ) {
11235        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11236    }
11237
11238    pub fn go_to_diagnostic_impl(
11239        &mut self,
11240        direction: Direction,
11241        window: &mut Window,
11242        cx: &mut Context<Self>,
11243    ) {
11244        let buffer = self.buffer.read(cx).snapshot(cx);
11245        let selection = self.selections.newest::<usize>(cx);
11246
11247        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11248        if direction == Direction::Next {
11249            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11250                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11251                    return;
11252                };
11253                self.activate_diagnostics(
11254                    buffer_id,
11255                    popover.local_diagnostic.diagnostic.group_id,
11256                    window,
11257                    cx,
11258                );
11259                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11260                    let primary_range_start = active_diagnostics.primary_range.start;
11261                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11262                        let mut new_selection = s.newest_anchor().clone();
11263                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11264                        s.select_anchors(vec![new_selection.clone()]);
11265                    });
11266                    self.refresh_inline_completion(false, true, window, cx);
11267                }
11268                return;
11269            }
11270        }
11271
11272        let active_group_id = self
11273            .active_diagnostics
11274            .as_ref()
11275            .map(|active_group| active_group.group_id);
11276        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11277            active_diagnostics
11278                .primary_range
11279                .to_offset(&buffer)
11280                .to_inclusive()
11281        });
11282        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11283            if active_primary_range.contains(&selection.head()) {
11284                *active_primary_range.start()
11285            } else {
11286                selection.head()
11287            }
11288        } else {
11289            selection.head()
11290        };
11291
11292        let snapshot = self.snapshot(window, cx);
11293        let primary_diagnostics_before = buffer
11294            .diagnostics_in_range::<usize>(0..search_start)
11295            .filter(|entry| entry.diagnostic.is_primary)
11296            .filter(|entry| entry.range.start != entry.range.end)
11297            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11298            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11299            .collect::<Vec<_>>();
11300        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11301            primary_diagnostics_before
11302                .iter()
11303                .position(|entry| entry.diagnostic.group_id == active_group_id)
11304        });
11305
11306        let primary_diagnostics_after = buffer
11307            .diagnostics_in_range::<usize>(search_start..buffer.len())
11308            .filter(|entry| entry.diagnostic.is_primary)
11309            .filter(|entry| entry.range.start != entry.range.end)
11310            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11311            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11312            .collect::<Vec<_>>();
11313        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11314            primary_diagnostics_after
11315                .iter()
11316                .enumerate()
11317                .rev()
11318                .find_map(|(i, entry)| {
11319                    if entry.diagnostic.group_id == active_group_id {
11320                        Some(i)
11321                    } else {
11322                        None
11323                    }
11324                })
11325        });
11326
11327        let next_primary_diagnostic = match direction {
11328            Direction::Prev => primary_diagnostics_before
11329                .iter()
11330                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11331                .rev()
11332                .next(),
11333            Direction::Next => primary_diagnostics_after
11334                .iter()
11335                .skip(
11336                    last_same_group_diagnostic_after
11337                        .map(|index| index + 1)
11338                        .unwrap_or(0),
11339                )
11340                .next(),
11341        };
11342
11343        // Cycle around to the start of the buffer, potentially moving back to the start of
11344        // the currently active diagnostic.
11345        let cycle_around = || match direction {
11346            Direction::Prev => primary_diagnostics_after
11347                .iter()
11348                .rev()
11349                .chain(primary_diagnostics_before.iter().rev())
11350                .next(),
11351            Direction::Next => primary_diagnostics_before
11352                .iter()
11353                .chain(primary_diagnostics_after.iter())
11354                .next(),
11355        };
11356
11357        if let Some((primary_range, group_id)) = next_primary_diagnostic
11358            .or_else(cycle_around)
11359            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11360        {
11361            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11362                return;
11363            };
11364            self.activate_diagnostics(buffer_id, group_id, window, cx);
11365            if self.active_diagnostics.is_some() {
11366                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11367                    s.select(vec![Selection {
11368                        id: selection.id,
11369                        start: primary_range.start,
11370                        end: primary_range.start,
11371                        reversed: false,
11372                        goal: SelectionGoal::None,
11373                    }]);
11374                });
11375                self.refresh_inline_completion(false, true, window, cx);
11376            }
11377        }
11378    }
11379
11380    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11381        let snapshot = self.snapshot(window, cx);
11382        let selection = self.selections.newest::<Point>(cx);
11383        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11384    }
11385
11386    fn go_to_hunk_after_position(
11387        &mut self,
11388        snapshot: &EditorSnapshot,
11389        position: Point,
11390        window: &mut Window,
11391        cx: &mut Context<Editor>,
11392    ) -> Option<MultiBufferDiffHunk> {
11393        let mut hunk = snapshot
11394            .buffer_snapshot
11395            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11396            .find(|hunk| hunk.row_range.start.0 > position.row);
11397        if hunk.is_none() {
11398            hunk = snapshot
11399                .buffer_snapshot
11400                .diff_hunks_in_range(Point::zero()..position)
11401                .find(|hunk| hunk.row_range.end.0 < position.row)
11402        }
11403        if let Some(hunk) = &hunk {
11404            let destination = Point::new(hunk.row_range.start.0, 0);
11405            self.unfold_ranges(&[destination..destination], false, false, cx);
11406            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11407                s.select_ranges(vec![destination..destination]);
11408            });
11409        }
11410
11411        hunk
11412    }
11413
11414    fn go_to_prev_hunk(
11415        &mut self,
11416        _: &GoToPreviousHunk,
11417        window: &mut Window,
11418        cx: &mut Context<Self>,
11419    ) {
11420        let snapshot = self.snapshot(window, cx);
11421        let selection = self.selections.newest::<Point>(cx);
11422        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11423    }
11424
11425    fn go_to_hunk_before_position(
11426        &mut self,
11427        snapshot: &EditorSnapshot,
11428        position: Point,
11429        window: &mut Window,
11430        cx: &mut Context<Editor>,
11431    ) -> Option<MultiBufferDiffHunk> {
11432        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11433        if hunk.is_none() {
11434            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11435        }
11436        if let Some(hunk) = &hunk {
11437            let destination = Point::new(hunk.row_range.start.0, 0);
11438            self.unfold_ranges(&[destination..destination], false, false, cx);
11439            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11440                s.select_ranges(vec![destination..destination]);
11441            });
11442        }
11443
11444        hunk
11445    }
11446
11447    pub fn go_to_definition(
11448        &mut self,
11449        _: &GoToDefinition,
11450        window: &mut Window,
11451        cx: &mut Context<Self>,
11452    ) -> Task<Result<Navigated>> {
11453        let definition =
11454            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11455        cx.spawn_in(window, |editor, mut cx| async move {
11456            if definition.await? == Navigated::Yes {
11457                return Ok(Navigated::Yes);
11458            }
11459            match editor.update_in(&mut cx, |editor, window, cx| {
11460                editor.find_all_references(&FindAllReferences, window, cx)
11461            })? {
11462                Some(references) => references.await,
11463                None => Ok(Navigated::No),
11464            }
11465        })
11466    }
11467
11468    pub fn go_to_declaration(
11469        &mut self,
11470        _: &GoToDeclaration,
11471        window: &mut Window,
11472        cx: &mut Context<Self>,
11473    ) -> Task<Result<Navigated>> {
11474        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11475    }
11476
11477    pub fn go_to_declaration_split(
11478        &mut self,
11479        _: &GoToDeclaration,
11480        window: &mut Window,
11481        cx: &mut Context<Self>,
11482    ) -> Task<Result<Navigated>> {
11483        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11484    }
11485
11486    pub fn go_to_implementation(
11487        &mut self,
11488        _: &GoToImplementation,
11489        window: &mut Window,
11490        cx: &mut Context<Self>,
11491    ) -> Task<Result<Navigated>> {
11492        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11493    }
11494
11495    pub fn go_to_implementation_split(
11496        &mut self,
11497        _: &GoToImplementationSplit,
11498        window: &mut Window,
11499        cx: &mut Context<Self>,
11500    ) -> Task<Result<Navigated>> {
11501        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11502    }
11503
11504    pub fn go_to_type_definition(
11505        &mut self,
11506        _: &GoToTypeDefinition,
11507        window: &mut Window,
11508        cx: &mut Context<Self>,
11509    ) -> Task<Result<Navigated>> {
11510        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11511    }
11512
11513    pub fn go_to_definition_split(
11514        &mut self,
11515        _: &GoToDefinitionSplit,
11516        window: &mut Window,
11517        cx: &mut Context<Self>,
11518    ) -> Task<Result<Navigated>> {
11519        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11520    }
11521
11522    pub fn go_to_type_definition_split(
11523        &mut self,
11524        _: &GoToTypeDefinitionSplit,
11525        window: &mut Window,
11526        cx: &mut Context<Self>,
11527    ) -> Task<Result<Navigated>> {
11528        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11529    }
11530
11531    fn go_to_definition_of_kind(
11532        &mut self,
11533        kind: GotoDefinitionKind,
11534        split: bool,
11535        window: &mut Window,
11536        cx: &mut Context<Self>,
11537    ) -> Task<Result<Navigated>> {
11538        let Some(provider) = self.semantics_provider.clone() else {
11539            return Task::ready(Ok(Navigated::No));
11540        };
11541        let head = self.selections.newest::<usize>(cx).head();
11542        let buffer = self.buffer.read(cx);
11543        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11544            text_anchor
11545        } else {
11546            return Task::ready(Ok(Navigated::No));
11547        };
11548
11549        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11550            return Task::ready(Ok(Navigated::No));
11551        };
11552
11553        cx.spawn_in(window, |editor, mut cx| async move {
11554            let definitions = definitions.await?;
11555            let navigated = editor
11556                .update_in(&mut cx, |editor, window, cx| {
11557                    editor.navigate_to_hover_links(
11558                        Some(kind),
11559                        definitions
11560                            .into_iter()
11561                            .filter(|location| {
11562                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11563                            })
11564                            .map(HoverLink::Text)
11565                            .collect::<Vec<_>>(),
11566                        split,
11567                        window,
11568                        cx,
11569                    )
11570                })?
11571                .await?;
11572            anyhow::Ok(navigated)
11573        })
11574    }
11575
11576    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11577        let selection = self.selections.newest_anchor();
11578        let head = selection.head();
11579        let tail = selection.tail();
11580
11581        let Some((buffer, start_position)) =
11582            self.buffer.read(cx).text_anchor_for_position(head, cx)
11583        else {
11584            return;
11585        };
11586
11587        let end_position = if head != tail {
11588            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11589                return;
11590            };
11591            Some(pos)
11592        } else {
11593            None
11594        };
11595
11596        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11597            let url = if let Some(end_pos) = end_position {
11598                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11599            } else {
11600                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11601            };
11602
11603            if let Some(url) = url {
11604                editor.update(&mut cx, |_, cx| {
11605                    cx.open_url(&url);
11606                })
11607            } else {
11608                Ok(())
11609            }
11610        });
11611
11612        url_finder.detach();
11613    }
11614
11615    pub fn open_selected_filename(
11616        &mut self,
11617        _: &OpenSelectedFilename,
11618        window: &mut Window,
11619        cx: &mut Context<Self>,
11620    ) {
11621        let Some(workspace) = self.workspace() else {
11622            return;
11623        };
11624
11625        let position = self.selections.newest_anchor().head();
11626
11627        let Some((buffer, buffer_position)) =
11628            self.buffer.read(cx).text_anchor_for_position(position, cx)
11629        else {
11630            return;
11631        };
11632
11633        let project = self.project.clone();
11634
11635        cx.spawn_in(window, |_, mut cx| async move {
11636            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11637
11638            if let Some((_, path)) = result {
11639                workspace
11640                    .update_in(&mut cx, |workspace, window, cx| {
11641                        workspace.open_resolved_path(path, window, cx)
11642                    })?
11643                    .await?;
11644            }
11645            anyhow::Ok(())
11646        })
11647        .detach();
11648    }
11649
11650    pub(crate) fn navigate_to_hover_links(
11651        &mut self,
11652        kind: Option<GotoDefinitionKind>,
11653        mut definitions: Vec<HoverLink>,
11654        split: bool,
11655        window: &mut Window,
11656        cx: &mut Context<Editor>,
11657    ) -> Task<Result<Navigated>> {
11658        // If there is one definition, just open it directly
11659        if definitions.len() == 1 {
11660            let definition = definitions.pop().unwrap();
11661
11662            enum TargetTaskResult {
11663                Location(Option<Location>),
11664                AlreadyNavigated,
11665            }
11666
11667            let target_task = match definition {
11668                HoverLink::Text(link) => {
11669                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11670                }
11671                HoverLink::InlayHint(lsp_location, server_id) => {
11672                    let computation =
11673                        self.compute_target_location(lsp_location, server_id, window, cx);
11674                    cx.background_spawn(async move {
11675                        let location = computation.await?;
11676                        Ok(TargetTaskResult::Location(location))
11677                    })
11678                }
11679                HoverLink::Url(url) => {
11680                    cx.open_url(&url);
11681                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11682                }
11683                HoverLink::File(path) => {
11684                    if let Some(workspace) = self.workspace() {
11685                        cx.spawn_in(window, |_, mut cx| async move {
11686                            workspace
11687                                .update_in(&mut cx, |workspace, window, cx| {
11688                                    workspace.open_resolved_path(path, window, cx)
11689                                })?
11690                                .await
11691                                .map(|_| TargetTaskResult::AlreadyNavigated)
11692                        })
11693                    } else {
11694                        Task::ready(Ok(TargetTaskResult::Location(None)))
11695                    }
11696                }
11697            };
11698            cx.spawn_in(window, |editor, mut cx| async move {
11699                let target = match target_task.await.context("target resolution task")? {
11700                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11701                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11702                    TargetTaskResult::Location(Some(target)) => target,
11703                };
11704
11705                editor.update_in(&mut cx, |editor, window, cx| {
11706                    let Some(workspace) = editor.workspace() else {
11707                        return Navigated::No;
11708                    };
11709                    let pane = workspace.read(cx).active_pane().clone();
11710
11711                    let range = target.range.to_point(target.buffer.read(cx));
11712                    let range = editor.range_for_match(&range);
11713                    let range = collapse_multiline_range(range);
11714
11715                    if !split
11716                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11717                    {
11718                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11719                    } else {
11720                        window.defer(cx, move |window, cx| {
11721                            let target_editor: Entity<Self> =
11722                                workspace.update(cx, |workspace, cx| {
11723                                    let pane = if split {
11724                                        workspace.adjacent_pane(window, cx)
11725                                    } else {
11726                                        workspace.active_pane().clone()
11727                                    };
11728
11729                                    workspace.open_project_item(
11730                                        pane,
11731                                        target.buffer.clone(),
11732                                        true,
11733                                        true,
11734                                        window,
11735                                        cx,
11736                                    )
11737                                });
11738                            target_editor.update(cx, |target_editor, cx| {
11739                                // When selecting a definition in a different buffer, disable the nav history
11740                                // to avoid creating a history entry at the previous cursor location.
11741                                pane.update(cx, |pane, _| pane.disable_history());
11742                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11743                                pane.update(cx, |pane, _| pane.enable_history());
11744                            });
11745                        });
11746                    }
11747                    Navigated::Yes
11748                })
11749            })
11750        } else if !definitions.is_empty() {
11751            cx.spawn_in(window, |editor, mut cx| async move {
11752                let (title, location_tasks, workspace) = editor
11753                    .update_in(&mut cx, |editor, window, cx| {
11754                        let tab_kind = match kind {
11755                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11756                            _ => "Definitions",
11757                        };
11758                        let title = definitions
11759                            .iter()
11760                            .find_map(|definition| match definition {
11761                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11762                                    let buffer = origin.buffer.read(cx);
11763                                    format!(
11764                                        "{} for {}",
11765                                        tab_kind,
11766                                        buffer
11767                                            .text_for_range(origin.range.clone())
11768                                            .collect::<String>()
11769                                    )
11770                                }),
11771                                HoverLink::InlayHint(_, _) => None,
11772                                HoverLink::Url(_) => None,
11773                                HoverLink::File(_) => None,
11774                            })
11775                            .unwrap_or(tab_kind.to_string());
11776                        let location_tasks = definitions
11777                            .into_iter()
11778                            .map(|definition| match definition {
11779                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11780                                HoverLink::InlayHint(lsp_location, server_id) => editor
11781                                    .compute_target_location(lsp_location, server_id, window, cx),
11782                                HoverLink::Url(_) => Task::ready(Ok(None)),
11783                                HoverLink::File(_) => Task::ready(Ok(None)),
11784                            })
11785                            .collect::<Vec<_>>();
11786                        (title, location_tasks, editor.workspace().clone())
11787                    })
11788                    .context("location tasks preparation")?;
11789
11790                let locations = future::join_all(location_tasks)
11791                    .await
11792                    .into_iter()
11793                    .filter_map(|location| location.transpose())
11794                    .collect::<Result<_>>()
11795                    .context("location tasks")?;
11796
11797                let Some(workspace) = workspace else {
11798                    return Ok(Navigated::No);
11799                };
11800                let opened = workspace
11801                    .update_in(&mut cx, |workspace, window, cx| {
11802                        Self::open_locations_in_multibuffer(
11803                            workspace,
11804                            locations,
11805                            title,
11806                            split,
11807                            MultibufferSelectionMode::First,
11808                            window,
11809                            cx,
11810                        )
11811                    })
11812                    .ok();
11813
11814                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11815            })
11816        } else {
11817            Task::ready(Ok(Navigated::No))
11818        }
11819    }
11820
11821    fn compute_target_location(
11822        &self,
11823        lsp_location: lsp::Location,
11824        server_id: LanguageServerId,
11825        window: &mut Window,
11826        cx: &mut Context<Self>,
11827    ) -> Task<anyhow::Result<Option<Location>>> {
11828        let Some(project) = self.project.clone() else {
11829            return Task::ready(Ok(None));
11830        };
11831
11832        cx.spawn_in(window, move |editor, mut cx| async move {
11833            let location_task = editor.update(&mut cx, |_, cx| {
11834                project.update(cx, |project, cx| {
11835                    let language_server_name = project
11836                        .language_server_statuses(cx)
11837                        .find(|(id, _)| server_id == *id)
11838                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11839                    language_server_name.map(|language_server_name| {
11840                        project.open_local_buffer_via_lsp(
11841                            lsp_location.uri.clone(),
11842                            server_id,
11843                            language_server_name,
11844                            cx,
11845                        )
11846                    })
11847                })
11848            })?;
11849            let location = match location_task {
11850                Some(task) => Some({
11851                    let target_buffer_handle = task.await.context("open local buffer")?;
11852                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11853                        let target_start = target_buffer
11854                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11855                        let target_end = target_buffer
11856                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11857                        target_buffer.anchor_after(target_start)
11858                            ..target_buffer.anchor_before(target_end)
11859                    })?;
11860                    Location {
11861                        buffer: target_buffer_handle,
11862                        range,
11863                    }
11864                }),
11865                None => None,
11866            };
11867            Ok(location)
11868        })
11869    }
11870
11871    pub fn find_all_references(
11872        &mut self,
11873        _: &FindAllReferences,
11874        window: &mut Window,
11875        cx: &mut Context<Self>,
11876    ) -> Option<Task<Result<Navigated>>> {
11877        let selection = self.selections.newest::<usize>(cx);
11878        let multi_buffer = self.buffer.read(cx);
11879        let head = selection.head();
11880
11881        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11882        let head_anchor = multi_buffer_snapshot.anchor_at(
11883            head,
11884            if head < selection.tail() {
11885                Bias::Right
11886            } else {
11887                Bias::Left
11888            },
11889        );
11890
11891        match self
11892            .find_all_references_task_sources
11893            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11894        {
11895            Ok(_) => {
11896                log::info!(
11897                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11898                );
11899                return None;
11900            }
11901            Err(i) => {
11902                self.find_all_references_task_sources.insert(i, head_anchor);
11903            }
11904        }
11905
11906        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11907        let workspace = self.workspace()?;
11908        let project = workspace.read(cx).project().clone();
11909        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11910        Some(cx.spawn_in(window, |editor, mut cx| async move {
11911            let _cleanup = defer({
11912                let mut cx = cx.clone();
11913                move || {
11914                    let _ = editor.update(&mut cx, |editor, _| {
11915                        if let Ok(i) =
11916                            editor
11917                                .find_all_references_task_sources
11918                                .binary_search_by(|anchor| {
11919                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11920                                })
11921                        {
11922                            editor.find_all_references_task_sources.remove(i);
11923                        }
11924                    });
11925                }
11926            });
11927
11928            let locations = references.await?;
11929            if locations.is_empty() {
11930                return anyhow::Ok(Navigated::No);
11931            }
11932
11933            workspace.update_in(&mut cx, |workspace, window, cx| {
11934                let title = locations
11935                    .first()
11936                    .as_ref()
11937                    .map(|location| {
11938                        let buffer = location.buffer.read(cx);
11939                        format!(
11940                            "References to `{}`",
11941                            buffer
11942                                .text_for_range(location.range.clone())
11943                                .collect::<String>()
11944                        )
11945                    })
11946                    .unwrap();
11947                Self::open_locations_in_multibuffer(
11948                    workspace,
11949                    locations,
11950                    title,
11951                    false,
11952                    MultibufferSelectionMode::First,
11953                    window,
11954                    cx,
11955                );
11956                Navigated::Yes
11957            })
11958        }))
11959    }
11960
11961    /// Opens a multibuffer with the given project locations in it
11962    pub fn open_locations_in_multibuffer(
11963        workspace: &mut Workspace,
11964        mut locations: Vec<Location>,
11965        title: String,
11966        split: bool,
11967        multibuffer_selection_mode: MultibufferSelectionMode,
11968        window: &mut Window,
11969        cx: &mut Context<Workspace>,
11970    ) {
11971        // If there are multiple definitions, open them in a multibuffer
11972        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11973        let mut locations = locations.into_iter().peekable();
11974        let mut ranges = Vec::new();
11975        let capability = workspace.project().read(cx).capability();
11976
11977        let excerpt_buffer = cx.new(|cx| {
11978            let mut multibuffer = MultiBuffer::new(capability);
11979            while let Some(location) = locations.next() {
11980                let buffer = location.buffer.read(cx);
11981                let mut ranges_for_buffer = Vec::new();
11982                let range = location.range.to_offset(buffer);
11983                ranges_for_buffer.push(range.clone());
11984
11985                while let Some(next_location) = locations.peek() {
11986                    if next_location.buffer == location.buffer {
11987                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11988                        locations.next();
11989                    } else {
11990                        break;
11991                    }
11992                }
11993
11994                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11995                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11996                    location.buffer.clone(),
11997                    ranges_for_buffer,
11998                    DEFAULT_MULTIBUFFER_CONTEXT,
11999                    cx,
12000                ))
12001            }
12002
12003            multibuffer.with_title(title)
12004        });
12005
12006        let editor = cx.new(|cx| {
12007            Editor::for_multibuffer(
12008                excerpt_buffer,
12009                Some(workspace.project().clone()),
12010                true,
12011                window,
12012                cx,
12013            )
12014        });
12015        editor.update(cx, |editor, cx| {
12016            match multibuffer_selection_mode {
12017                MultibufferSelectionMode::First => {
12018                    if let Some(first_range) = ranges.first() {
12019                        editor.change_selections(None, window, cx, |selections| {
12020                            selections.clear_disjoint();
12021                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12022                        });
12023                    }
12024                    editor.highlight_background::<Self>(
12025                        &ranges,
12026                        |theme| theme.editor_highlighted_line_background,
12027                        cx,
12028                    );
12029                }
12030                MultibufferSelectionMode::All => {
12031                    editor.change_selections(None, window, cx, |selections| {
12032                        selections.clear_disjoint();
12033                        selections.select_anchor_ranges(ranges);
12034                    });
12035                }
12036            }
12037            editor.register_buffers_with_language_servers(cx);
12038        });
12039
12040        let item = Box::new(editor);
12041        let item_id = item.item_id();
12042
12043        if split {
12044            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12045        } else {
12046            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12047                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12048                    pane.close_current_preview_item(window, cx)
12049                } else {
12050                    None
12051                }
12052            });
12053            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12054        }
12055        workspace.active_pane().update(cx, |pane, cx| {
12056            pane.set_preview_item_id(Some(item_id), cx);
12057        });
12058    }
12059
12060    pub fn rename(
12061        &mut self,
12062        _: &Rename,
12063        window: &mut Window,
12064        cx: &mut Context<Self>,
12065    ) -> Option<Task<Result<()>>> {
12066        use language::ToOffset as _;
12067
12068        let provider = self.semantics_provider.clone()?;
12069        let selection = self.selections.newest_anchor().clone();
12070        let (cursor_buffer, cursor_buffer_position) = self
12071            .buffer
12072            .read(cx)
12073            .text_anchor_for_position(selection.head(), cx)?;
12074        let (tail_buffer, cursor_buffer_position_end) = self
12075            .buffer
12076            .read(cx)
12077            .text_anchor_for_position(selection.tail(), cx)?;
12078        if tail_buffer != cursor_buffer {
12079            return None;
12080        }
12081
12082        let snapshot = cursor_buffer.read(cx).snapshot();
12083        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12084        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12085        let prepare_rename = provider
12086            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12087            .unwrap_or_else(|| Task::ready(Ok(None)));
12088        drop(snapshot);
12089
12090        Some(cx.spawn_in(window, |this, mut cx| async move {
12091            let rename_range = if let Some(range) = prepare_rename.await? {
12092                Some(range)
12093            } else {
12094                this.update(&mut cx, |this, cx| {
12095                    let buffer = this.buffer.read(cx).snapshot(cx);
12096                    let mut buffer_highlights = this
12097                        .document_highlights_for_position(selection.head(), &buffer)
12098                        .filter(|highlight| {
12099                            highlight.start.excerpt_id == selection.head().excerpt_id
12100                                && highlight.end.excerpt_id == selection.head().excerpt_id
12101                        });
12102                    buffer_highlights
12103                        .next()
12104                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12105                })?
12106            };
12107            if let Some(rename_range) = rename_range {
12108                this.update_in(&mut cx, |this, window, cx| {
12109                    let snapshot = cursor_buffer.read(cx).snapshot();
12110                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12111                    let cursor_offset_in_rename_range =
12112                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12113                    let cursor_offset_in_rename_range_end =
12114                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12115
12116                    this.take_rename(false, window, cx);
12117                    let buffer = this.buffer.read(cx).read(cx);
12118                    let cursor_offset = selection.head().to_offset(&buffer);
12119                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12120                    let rename_end = rename_start + rename_buffer_range.len();
12121                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12122                    let mut old_highlight_id = None;
12123                    let old_name: Arc<str> = buffer
12124                        .chunks(rename_start..rename_end, true)
12125                        .map(|chunk| {
12126                            if old_highlight_id.is_none() {
12127                                old_highlight_id = chunk.syntax_highlight_id;
12128                            }
12129                            chunk.text
12130                        })
12131                        .collect::<String>()
12132                        .into();
12133
12134                    drop(buffer);
12135
12136                    // Position the selection in the rename editor so that it matches the current selection.
12137                    this.show_local_selections = false;
12138                    let rename_editor = cx.new(|cx| {
12139                        let mut editor = Editor::single_line(window, cx);
12140                        editor.buffer.update(cx, |buffer, cx| {
12141                            buffer.edit([(0..0, old_name.clone())], None, cx)
12142                        });
12143                        let rename_selection_range = match cursor_offset_in_rename_range
12144                            .cmp(&cursor_offset_in_rename_range_end)
12145                        {
12146                            Ordering::Equal => {
12147                                editor.select_all(&SelectAll, window, cx);
12148                                return editor;
12149                            }
12150                            Ordering::Less => {
12151                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12152                            }
12153                            Ordering::Greater => {
12154                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12155                            }
12156                        };
12157                        if rename_selection_range.end > old_name.len() {
12158                            editor.select_all(&SelectAll, window, cx);
12159                        } else {
12160                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12161                                s.select_ranges([rename_selection_range]);
12162                            });
12163                        }
12164                        editor
12165                    });
12166                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12167                        if e == &EditorEvent::Focused {
12168                            cx.emit(EditorEvent::FocusedIn)
12169                        }
12170                    })
12171                    .detach();
12172
12173                    let write_highlights =
12174                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12175                    let read_highlights =
12176                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12177                    let ranges = write_highlights
12178                        .iter()
12179                        .flat_map(|(_, ranges)| ranges.iter())
12180                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12181                        .cloned()
12182                        .collect();
12183
12184                    this.highlight_text::<Rename>(
12185                        ranges,
12186                        HighlightStyle {
12187                            fade_out: Some(0.6),
12188                            ..Default::default()
12189                        },
12190                        cx,
12191                    );
12192                    let rename_focus_handle = rename_editor.focus_handle(cx);
12193                    window.focus(&rename_focus_handle);
12194                    let block_id = this.insert_blocks(
12195                        [BlockProperties {
12196                            style: BlockStyle::Flex,
12197                            placement: BlockPlacement::Below(range.start),
12198                            height: 1,
12199                            render: Arc::new({
12200                                let rename_editor = rename_editor.clone();
12201                                move |cx: &mut BlockContext| {
12202                                    let mut text_style = cx.editor_style.text.clone();
12203                                    if let Some(highlight_style) = old_highlight_id
12204                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12205                                    {
12206                                        text_style = text_style.highlight(highlight_style);
12207                                    }
12208                                    div()
12209                                        .block_mouse_down()
12210                                        .pl(cx.anchor_x)
12211                                        .child(EditorElement::new(
12212                                            &rename_editor,
12213                                            EditorStyle {
12214                                                background: cx.theme().system().transparent,
12215                                                local_player: cx.editor_style.local_player,
12216                                                text: text_style,
12217                                                scrollbar_width: cx.editor_style.scrollbar_width,
12218                                                syntax: cx.editor_style.syntax.clone(),
12219                                                status: cx.editor_style.status.clone(),
12220                                                inlay_hints_style: HighlightStyle {
12221                                                    font_weight: Some(FontWeight::BOLD),
12222                                                    ..make_inlay_hints_style(cx.app)
12223                                                },
12224                                                inline_completion_styles: make_suggestion_styles(
12225                                                    cx.app,
12226                                                ),
12227                                                ..EditorStyle::default()
12228                                            },
12229                                        ))
12230                                        .into_any_element()
12231                                }
12232                            }),
12233                            priority: 0,
12234                        }],
12235                        Some(Autoscroll::fit()),
12236                        cx,
12237                    )[0];
12238                    this.pending_rename = Some(RenameState {
12239                        range,
12240                        old_name,
12241                        editor: rename_editor,
12242                        block_id,
12243                    });
12244                })?;
12245            }
12246
12247            Ok(())
12248        }))
12249    }
12250
12251    pub fn confirm_rename(
12252        &mut self,
12253        _: &ConfirmRename,
12254        window: &mut Window,
12255        cx: &mut Context<Self>,
12256    ) -> Option<Task<Result<()>>> {
12257        let rename = self.take_rename(false, window, cx)?;
12258        let workspace = self.workspace()?.downgrade();
12259        let (buffer, start) = self
12260            .buffer
12261            .read(cx)
12262            .text_anchor_for_position(rename.range.start, cx)?;
12263        let (end_buffer, _) = self
12264            .buffer
12265            .read(cx)
12266            .text_anchor_for_position(rename.range.end, cx)?;
12267        if buffer != end_buffer {
12268            return None;
12269        }
12270
12271        let old_name = rename.old_name;
12272        let new_name = rename.editor.read(cx).text(cx);
12273
12274        let rename = self.semantics_provider.as_ref()?.perform_rename(
12275            &buffer,
12276            start,
12277            new_name.clone(),
12278            cx,
12279        )?;
12280
12281        Some(cx.spawn_in(window, |editor, mut cx| async move {
12282            let project_transaction = rename.await?;
12283            Self::open_project_transaction(
12284                &editor,
12285                workspace,
12286                project_transaction,
12287                format!("Rename: {}{}", old_name, new_name),
12288                cx.clone(),
12289            )
12290            .await?;
12291
12292            editor.update(&mut cx, |editor, cx| {
12293                editor.refresh_document_highlights(cx);
12294            })?;
12295            Ok(())
12296        }))
12297    }
12298
12299    fn take_rename(
12300        &mut self,
12301        moving_cursor: bool,
12302        window: &mut Window,
12303        cx: &mut Context<Self>,
12304    ) -> Option<RenameState> {
12305        let rename = self.pending_rename.take()?;
12306        if rename.editor.focus_handle(cx).is_focused(window) {
12307            window.focus(&self.focus_handle);
12308        }
12309
12310        self.remove_blocks(
12311            [rename.block_id].into_iter().collect(),
12312            Some(Autoscroll::fit()),
12313            cx,
12314        );
12315        self.clear_highlights::<Rename>(cx);
12316        self.show_local_selections = true;
12317
12318        if moving_cursor {
12319            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12320                editor.selections.newest::<usize>(cx).head()
12321            });
12322
12323            // Update the selection to match the position of the selection inside
12324            // the rename editor.
12325            let snapshot = self.buffer.read(cx).read(cx);
12326            let rename_range = rename.range.to_offset(&snapshot);
12327            let cursor_in_editor = snapshot
12328                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12329                .min(rename_range.end);
12330            drop(snapshot);
12331
12332            self.change_selections(None, window, cx, |s| {
12333                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12334            });
12335        } else {
12336            self.refresh_document_highlights(cx);
12337        }
12338
12339        Some(rename)
12340    }
12341
12342    pub fn pending_rename(&self) -> Option<&RenameState> {
12343        self.pending_rename.as_ref()
12344    }
12345
12346    fn format(
12347        &mut self,
12348        _: &Format,
12349        window: &mut Window,
12350        cx: &mut Context<Self>,
12351    ) -> Option<Task<Result<()>>> {
12352        let project = match &self.project {
12353            Some(project) => project.clone(),
12354            None => return None,
12355        };
12356
12357        Some(self.perform_format(
12358            project,
12359            FormatTrigger::Manual,
12360            FormatTarget::Buffers,
12361            window,
12362            cx,
12363        ))
12364    }
12365
12366    fn format_selections(
12367        &mut self,
12368        _: &FormatSelections,
12369        window: &mut Window,
12370        cx: &mut Context<Self>,
12371    ) -> Option<Task<Result<()>>> {
12372        let project = match &self.project {
12373            Some(project) => project.clone(),
12374            None => return None,
12375        };
12376
12377        let ranges = self
12378            .selections
12379            .all_adjusted(cx)
12380            .into_iter()
12381            .map(|selection| selection.range())
12382            .collect_vec();
12383
12384        Some(self.perform_format(
12385            project,
12386            FormatTrigger::Manual,
12387            FormatTarget::Ranges(ranges),
12388            window,
12389            cx,
12390        ))
12391    }
12392
12393    fn perform_format(
12394        &mut self,
12395        project: Entity<Project>,
12396        trigger: FormatTrigger,
12397        target: FormatTarget,
12398        window: &mut Window,
12399        cx: &mut Context<Self>,
12400    ) -> Task<Result<()>> {
12401        let buffer = self.buffer.clone();
12402        let (buffers, target) = match target {
12403            FormatTarget::Buffers => {
12404                let mut buffers = buffer.read(cx).all_buffers();
12405                if trigger == FormatTrigger::Save {
12406                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12407                }
12408                (buffers, LspFormatTarget::Buffers)
12409            }
12410            FormatTarget::Ranges(selection_ranges) => {
12411                let multi_buffer = buffer.read(cx);
12412                let snapshot = multi_buffer.read(cx);
12413                let mut buffers = HashSet::default();
12414                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12415                    BTreeMap::new();
12416                for selection_range in selection_ranges {
12417                    for (buffer, buffer_range, _) in
12418                        snapshot.range_to_buffer_ranges(selection_range)
12419                    {
12420                        let buffer_id = buffer.remote_id();
12421                        let start = buffer.anchor_before(buffer_range.start);
12422                        let end = buffer.anchor_after(buffer_range.end);
12423                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12424                        buffer_id_to_ranges
12425                            .entry(buffer_id)
12426                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12427                            .or_insert_with(|| vec![start..end]);
12428                    }
12429                }
12430                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12431            }
12432        };
12433
12434        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12435        let format = project.update(cx, |project, cx| {
12436            project.format(buffers, target, true, trigger, cx)
12437        });
12438
12439        cx.spawn_in(window, |_, mut cx| async move {
12440            let transaction = futures::select_biased! {
12441                () = timeout => {
12442                    log::warn!("timed out waiting for formatting");
12443                    None
12444                }
12445                transaction = format.log_err().fuse() => transaction,
12446            };
12447
12448            buffer
12449                .update(&mut cx, |buffer, cx| {
12450                    if let Some(transaction) = transaction {
12451                        if !buffer.is_singleton() {
12452                            buffer.push_transaction(&transaction.0, cx);
12453                        }
12454                    }
12455
12456                    cx.notify();
12457                })
12458                .ok();
12459
12460            Ok(())
12461        })
12462    }
12463
12464    fn restart_language_server(
12465        &mut self,
12466        _: &RestartLanguageServer,
12467        _: &mut Window,
12468        cx: &mut Context<Self>,
12469    ) {
12470        if let Some(project) = self.project.clone() {
12471            self.buffer.update(cx, |multi_buffer, cx| {
12472                project.update(cx, |project, cx| {
12473                    project.restart_language_servers_for_buffers(
12474                        multi_buffer.all_buffers().into_iter().collect(),
12475                        cx,
12476                    );
12477                });
12478            })
12479        }
12480    }
12481
12482    fn cancel_language_server_work(
12483        workspace: &mut Workspace,
12484        _: &actions::CancelLanguageServerWork,
12485        _: &mut Window,
12486        cx: &mut Context<Workspace>,
12487    ) {
12488        let project = workspace.project();
12489        let buffers = workspace
12490            .active_item(cx)
12491            .and_then(|item| item.act_as::<Editor>(cx))
12492            .map_or(HashSet::default(), |editor| {
12493                editor.read(cx).buffer.read(cx).all_buffers()
12494            });
12495        project.update(cx, |project, cx| {
12496            project.cancel_language_server_work_for_buffers(buffers, cx);
12497        });
12498    }
12499
12500    fn show_character_palette(
12501        &mut self,
12502        _: &ShowCharacterPalette,
12503        window: &mut Window,
12504        _: &mut Context<Self>,
12505    ) {
12506        window.show_character_palette();
12507    }
12508
12509    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12510        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12511            let buffer = self.buffer.read(cx).snapshot(cx);
12512            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12513            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12514            let is_valid = buffer
12515                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12516                .any(|entry| {
12517                    entry.diagnostic.is_primary
12518                        && !entry.range.is_empty()
12519                        && entry.range.start == primary_range_start
12520                        && entry.diagnostic.message == active_diagnostics.primary_message
12521                });
12522
12523            if is_valid != active_diagnostics.is_valid {
12524                active_diagnostics.is_valid = is_valid;
12525                let mut new_styles = HashMap::default();
12526                for (block_id, diagnostic) in &active_diagnostics.blocks {
12527                    new_styles.insert(
12528                        *block_id,
12529                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12530                    );
12531                }
12532                self.display_map.update(cx, |display_map, _cx| {
12533                    display_map.replace_blocks(new_styles)
12534                });
12535            }
12536        }
12537    }
12538
12539    fn activate_diagnostics(
12540        &mut self,
12541        buffer_id: BufferId,
12542        group_id: usize,
12543        window: &mut Window,
12544        cx: &mut Context<Self>,
12545    ) {
12546        self.dismiss_diagnostics(cx);
12547        let snapshot = self.snapshot(window, cx);
12548        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12549            let buffer = self.buffer.read(cx).snapshot(cx);
12550
12551            let mut primary_range = None;
12552            let mut primary_message = None;
12553            let diagnostic_group = buffer
12554                .diagnostic_group(buffer_id, group_id)
12555                .filter_map(|entry| {
12556                    let start = entry.range.start;
12557                    let end = entry.range.end;
12558                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12559                        && (start.row == end.row
12560                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12561                    {
12562                        return None;
12563                    }
12564                    if entry.diagnostic.is_primary {
12565                        primary_range = Some(entry.range.clone());
12566                        primary_message = Some(entry.diagnostic.message.clone());
12567                    }
12568                    Some(entry)
12569                })
12570                .collect::<Vec<_>>();
12571            let primary_range = primary_range?;
12572            let primary_message = primary_message?;
12573
12574            let blocks = display_map
12575                .insert_blocks(
12576                    diagnostic_group.iter().map(|entry| {
12577                        let diagnostic = entry.diagnostic.clone();
12578                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12579                        BlockProperties {
12580                            style: BlockStyle::Fixed,
12581                            placement: BlockPlacement::Below(
12582                                buffer.anchor_after(entry.range.start),
12583                            ),
12584                            height: message_height,
12585                            render: diagnostic_block_renderer(diagnostic, None, true, true),
12586                            priority: 0,
12587                        }
12588                    }),
12589                    cx,
12590                )
12591                .into_iter()
12592                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12593                .collect();
12594
12595            Some(ActiveDiagnosticGroup {
12596                primary_range: buffer.anchor_before(primary_range.start)
12597                    ..buffer.anchor_after(primary_range.end),
12598                primary_message,
12599                group_id,
12600                blocks,
12601                is_valid: true,
12602            })
12603        });
12604    }
12605
12606    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12607        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12608            self.display_map.update(cx, |display_map, cx| {
12609                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12610            });
12611            cx.notify();
12612        }
12613    }
12614
12615    /// Disable inline diagnostics rendering for this editor.
12616    pub fn disable_inline_diagnostics(&mut self) {
12617        self.inline_diagnostics_enabled = false;
12618        self.inline_diagnostics_update = Task::ready(());
12619        self.inline_diagnostics.clear();
12620    }
12621
12622    pub fn inline_diagnostics_enabled(&self) -> bool {
12623        self.inline_diagnostics_enabled
12624    }
12625
12626    pub fn show_inline_diagnostics(&self) -> bool {
12627        self.show_inline_diagnostics
12628    }
12629
12630    pub fn toggle_inline_diagnostics(
12631        &mut self,
12632        _: &ToggleInlineDiagnostics,
12633        window: &mut Window,
12634        cx: &mut Context<'_, Editor>,
12635    ) {
12636        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12637        self.refresh_inline_diagnostics(false, window, cx);
12638    }
12639
12640    fn refresh_inline_diagnostics(
12641        &mut self,
12642        debounce: bool,
12643        window: &mut Window,
12644        cx: &mut Context<Self>,
12645    ) {
12646        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12647            self.inline_diagnostics_update = Task::ready(());
12648            self.inline_diagnostics.clear();
12649            return;
12650        }
12651
12652        let debounce_ms = ProjectSettings::get_global(cx)
12653            .diagnostics
12654            .inline
12655            .update_debounce_ms;
12656        let debounce = if debounce && debounce_ms > 0 {
12657            Some(Duration::from_millis(debounce_ms))
12658        } else {
12659            None
12660        };
12661        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12662            if let Some(debounce) = debounce {
12663                cx.background_executor().timer(debounce).await;
12664            }
12665            let Some(snapshot) = editor
12666                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12667                .ok()
12668            else {
12669                return;
12670            };
12671
12672            let new_inline_diagnostics = cx
12673                .background_spawn(async move {
12674                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12675                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12676                        let message = diagnostic_entry
12677                            .diagnostic
12678                            .message
12679                            .split_once('\n')
12680                            .map(|(line, _)| line)
12681                            .map(SharedString::new)
12682                            .unwrap_or_else(|| {
12683                                SharedString::from(diagnostic_entry.diagnostic.message)
12684                            });
12685                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12686                        let (Ok(i) | Err(i)) = inline_diagnostics
12687                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12688                        inline_diagnostics.insert(
12689                            i,
12690                            (
12691                                start_anchor,
12692                                InlineDiagnostic {
12693                                    message,
12694                                    group_id: diagnostic_entry.diagnostic.group_id,
12695                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12696                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12697                                    severity: diagnostic_entry.diagnostic.severity,
12698                                },
12699                            ),
12700                        );
12701                    }
12702                    inline_diagnostics
12703                })
12704                .await;
12705
12706            editor
12707                .update(&mut cx, |editor, cx| {
12708                    editor.inline_diagnostics = new_inline_diagnostics;
12709                    cx.notify();
12710                })
12711                .ok();
12712        });
12713    }
12714
12715    pub fn set_selections_from_remote(
12716        &mut self,
12717        selections: Vec<Selection<Anchor>>,
12718        pending_selection: Option<Selection<Anchor>>,
12719        window: &mut Window,
12720        cx: &mut Context<Self>,
12721    ) {
12722        let old_cursor_position = self.selections.newest_anchor().head();
12723        self.selections.change_with(cx, |s| {
12724            s.select_anchors(selections);
12725            if let Some(pending_selection) = pending_selection {
12726                s.set_pending(pending_selection, SelectMode::Character);
12727            } else {
12728                s.clear_pending();
12729            }
12730        });
12731        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12732    }
12733
12734    fn push_to_selection_history(&mut self) {
12735        self.selection_history.push(SelectionHistoryEntry {
12736            selections: self.selections.disjoint_anchors(),
12737            select_next_state: self.select_next_state.clone(),
12738            select_prev_state: self.select_prev_state.clone(),
12739            add_selections_state: self.add_selections_state.clone(),
12740        });
12741    }
12742
12743    pub fn transact(
12744        &mut self,
12745        window: &mut Window,
12746        cx: &mut Context<Self>,
12747        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12748    ) -> Option<TransactionId> {
12749        self.start_transaction_at(Instant::now(), window, cx);
12750        update(self, window, cx);
12751        self.end_transaction_at(Instant::now(), cx)
12752    }
12753
12754    pub fn start_transaction_at(
12755        &mut self,
12756        now: Instant,
12757        window: &mut Window,
12758        cx: &mut Context<Self>,
12759    ) {
12760        self.end_selection(window, cx);
12761        if let Some(tx_id) = self
12762            .buffer
12763            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12764        {
12765            self.selection_history
12766                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12767            cx.emit(EditorEvent::TransactionBegun {
12768                transaction_id: tx_id,
12769            })
12770        }
12771    }
12772
12773    pub fn end_transaction_at(
12774        &mut self,
12775        now: Instant,
12776        cx: &mut Context<Self>,
12777    ) -> Option<TransactionId> {
12778        if let Some(transaction_id) = self
12779            .buffer
12780            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12781        {
12782            if let Some((_, end_selections)) =
12783                self.selection_history.transaction_mut(transaction_id)
12784            {
12785                *end_selections = Some(self.selections.disjoint_anchors());
12786            } else {
12787                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12788            }
12789
12790            cx.emit(EditorEvent::Edited { transaction_id });
12791            Some(transaction_id)
12792        } else {
12793            None
12794        }
12795    }
12796
12797    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12798        if self.selection_mark_mode {
12799            self.change_selections(None, window, cx, |s| {
12800                s.move_with(|_, sel| {
12801                    sel.collapse_to(sel.head(), SelectionGoal::None);
12802                });
12803            })
12804        }
12805        self.selection_mark_mode = true;
12806        cx.notify();
12807    }
12808
12809    pub fn swap_selection_ends(
12810        &mut self,
12811        _: &actions::SwapSelectionEnds,
12812        window: &mut Window,
12813        cx: &mut Context<Self>,
12814    ) {
12815        self.change_selections(None, window, cx, |s| {
12816            s.move_with(|_, sel| {
12817                if sel.start != sel.end {
12818                    sel.reversed = !sel.reversed
12819                }
12820            });
12821        });
12822        self.request_autoscroll(Autoscroll::newest(), cx);
12823        cx.notify();
12824    }
12825
12826    pub fn toggle_fold(
12827        &mut self,
12828        _: &actions::ToggleFold,
12829        window: &mut Window,
12830        cx: &mut Context<Self>,
12831    ) {
12832        if self.is_singleton(cx) {
12833            let selection = self.selections.newest::<Point>(cx);
12834
12835            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12836            let range = if selection.is_empty() {
12837                let point = selection.head().to_display_point(&display_map);
12838                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12839                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12840                    .to_point(&display_map);
12841                start..end
12842            } else {
12843                selection.range()
12844            };
12845            if display_map.folds_in_range(range).next().is_some() {
12846                self.unfold_lines(&Default::default(), window, cx)
12847            } else {
12848                self.fold(&Default::default(), window, cx)
12849            }
12850        } else {
12851            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12852            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12853                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12854                .map(|(snapshot, _, _)| snapshot.remote_id())
12855                .collect();
12856
12857            for buffer_id in buffer_ids {
12858                if self.is_buffer_folded(buffer_id, cx) {
12859                    self.unfold_buffer(buffer_id, cx);
12860                } else {
12861                    self.fold_buffer(buffer_id, cx);
12862                }
12863            }
12864        }
12865    }
12866
12867    pub fn toggle_fold_recursive(
12868        &mut self,
12869        _: &actions::ToggleFoldRecursive,
12870        window: &mut Window,
12871        cx: &mut Context<Self>,
12872    ) {
12873        let selection = self.selections.newest::<Point>(cx);
12874
12875        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12876        let range = if selection.is_empty() {
12877            let point = selection.head().to_display_point(&display_map);
12878            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12879            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12880                .to_point(&display_map);
12881            start..end
12882        } else {
12883            selection.range()
12884        };
12885        if display_map.folds_in_range(range).next().is_some() {
12886            self.unfold_recursive(&Default::default(), window, cx)
12887        } else {
12888            self.fold_recursive(&Default::default(), window, cx)
12889        }
12890    }
12891
12892    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12893        if self.is_singleton(cx) {
12894            let mut to_fold = Vec::new();
12895            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12896            let selections = self.selections.all_adjusted(cx);
12897
12898            for selection in selections {
12899                let range = selection.range().sorted();
12900                let buffer_start_row = range.start.row;
12901
12902                if range.start.row != range.end.row {
12903                    let mut found = false;
12904                    let mut row = range.start.row;
12905                    while row <= range.end.row {
12906                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12907                        {
12908                            found = true;
12909                            row = crease.range().end.row + 1;
12910                            to_fold.push(crease);
12911                        } else {
12912                            row += 1
12913                        }
12914                    }
12915                    if found {
12916                        continue;
12917                    }
12918                }
12919
12920                for row in (0..=range.start.row).rev() {
12921                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12922                        if crease.range().end.row >= buffer_start_row {
12923                            to_fold.push(crease);
12924                            if row <= range.start.row {
12925                                break;
12926                            }
12927                        }
12928                    }
12929                }
12930            }
12931
12932            self.fold_creases(to_fold, true, window, cx);
12933        } else {
12934            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12935
12936            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12937                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12938                .map(|(snapshot, _, _)| snapshot.remote_id())
12939                .collect();
12940            for buffer_id in buffer_ids {
12941                self.fold_buffer(buffer_id, cx);
12942            }
12943        }
12944    }
12945
12946    fn fold_at_level(
12947        &mut self,
12948        fold_at: &FoldAtLevel,
12949        window: &mut Window,
12950        cx: &mut Context<Self>,
12951    ) {
12952        if !self.buffer.read(cx).is_singleton() {
12953            return;
12954        }
12955
12956        let fold_at_level = fold_at.0;
12957        let snapshot = self.buffer.read(cx).snapshot(cx);
12958        let mut to_fold = Vec::new();
12959        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12960
12961        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12962            while start_row < end_row {
12963                match self
12964                    .snapshot(window, cx)
12965                    .crease_for_buffer_row(MultiBufferRow(start_row))
12966                {
12967                    Some(crease) => {
12968                        let nested_start_row = crease.range().start.row + 1;
12969                        let nested_end_row = crease.range().end.row;
12970
12971                        if current_level < fold_at_level {
12972                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12973                        } else if current_level == fold_at_level {
12974                            to_fold.push(crease);
12975                        }
12976
12977                        start_row = nested_end_row + 1;
12978                    }
12979                    None => start_row += 1,
12980                }
12981            }
12982        }
12983
12984        self.fold_creases(to_fold, true, window, cx);
12985    }
12986
12987    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12988        if self.buffer.read(cx).is_singleton() {
12989            let mut fold_ranges = Vec::new();
12990            let snapshot = self.buffer.read(cx).snapshot(cx);
12991
12992            for row in 0..snapshot.max_row().0 {
12993                if let Some(foldable_range) = self
12994                    .snapshot(window, cx)
12995                    .crease_for_buffer_row(MultiBufferRow(row))
12996                {
12997                    fold_ranges.push(foldable_range);
12998                }
12999            }
13000
13001            self.fold_creases(fold_ranges, true, window, cx);
13002        } else {
13003            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13004                editor
13005                    .update_in(&mut cx, |editor, _, cx| {
13006                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13007                            editor.fold_buffer(buffer_id, cx);
13008                        }
13009                    })
13010                    .ok();
13011            });
13012        }
13013    }
13014
13015    pub fn fold_function_bodies(
13016        &mut self,
13017        _: &actions::FoldFunctionBodies,
13018        window: &mut Window,
13019        cx: &mut Context<Self>,
13020    ) {
13021        let snapshot = self.buffer.read(cx).snapshot(cx);
13022
13023        let ranges = snapshot
13024            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13025            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13026            .collect::<Vec<_>>();
13027
13028        let creases = ranges
13029            .into_iter()
13030            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13031            .collect();
13032
13033        self.fold_creases(creases, true, window, cx);
13034    }
13035
13036    pub fn fold_recursive(
13037        &mut self,
13038        _: &actions::FoldRecursive,
13039        window: &mut Window,
13040        cx: &mut Context<Self>,
13041    ) {
13042        let mut to_fold = Vec::new();
13043        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13044        let selections = self.selections.all_adjusted(cx);
13045
13046        for selection in selections {
13047            let range = selection.range().sorted();
13048            let buffer_start_row = range.start.row;
13049
13050            if range.start.row != range.end.row {
13051                let mut found = false;
13052                for row in range.start.row..=range.end.row {
13053                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13054                        found = true;
13055                        to_fold.push(crease);
13056                    }
13057                }
13058                if found {
13059                    continue;
13060                }
13061            }
13062
13063            for row in (0..=range.start.row).rev() {
13064                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13065                    if crease.range().end.row >= buffer_start_row {
13066                        to_fold.push(crease);
13067                    } else {
13068                        break;
13069                    }
13070                }
13071            }
13072        }
13073
13074        self.fold_creases(to_fold, true, window, cx);
13075    }
13076
13077    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13078        let buffer_row = fold_at.buffer_row;
13079        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13080
13081        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13082            let autoscroll = self
13083                .selections
13084                .all::<Point>(cx)
13085                .iter()
13086                .any(|selection| crease.range().overlaps(&selection.range()));
13087
13088            self.fold_creases(vec![crease], autoscroll, window, cx);
13089        }
13090    }
13091
13092    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13093        if self.is_singleton(cx) {
13094            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13095            let buffer = &display_map.buffer_snapshot;
13096            let selections = self.selections.all::<Point>(cx);
13097            let ranges = selections
13098                .iter()
13099                .map(|s| {
13100                    let range = s.display_range(&display_map).sorted();
13101                    let mut start = range.start.to_point(&display_map);
13102                    let mut end = range.end.to_point(&display_map);
13103                    start.column = 0;
13104                    end.column = buffer.line_len(MultiBufferRow(end.row));
13105                    start..end
13106                })
13107                .collect::<Vec<_>>();
13108
13109            self.unfold_ranges(&ranges, true, true, cx);
13110        } else {
13111            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13112            let buffer_ids: HashSet<_> = multi_buffer_snapshot
13113                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13114                .map(|(snapshot, _, _)| snapshot.remote_id())
13115                .collect();
13116            for buffer_id in buffer_ids {
13117                self.unfold_buffer(buffer_id, cx);
13118            }
13119        }
13120    }
13121
13122    pub fn unfold_recursive(
13123        &mut self,
13124        _: &UnfoldRecursive,
13125        _window: &mut Window,
13126        cx: &mut Context<Self>,
13127    ) {
13128        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13129        let selections = self.selections.all::<Point>(cx);
13130        let ranges = selections
13131            .iter()
13132            .map(|s| {
13133                let mut range = s.display_range(&display_map).sorted();
13134                *range.start.column_mut() = 0;
13135                *range.end.column_mut() = display_map.line_len(range.end.row());
13136                let start = range.start.to_point(&display_map);
13137                let end = range.end.to_point(&display_map);
13138                start..end
13139            })
13140            .collect::<Vec<_>>();
13141
13142        self.unfold_ranges(&ranges, true, true, cx);
13143    }
13144
13145    pub fn unfold_at(
13146        &mut self,
13147        unfold_at: &UnfoldAt,
13148        _window: &mut Window,
13149        cx: &mut Context<Self>,
13150    ) {
13151        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13152
13153        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13154            ..Point::new(
13155                unfold_at.buffer_row.0,
13156                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13157            );
13158
13159        let autoscroll = self
13160            .selections
13161            .all::<Point>(cx)
13162            .iter()
13163            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13164
13165        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13166    }
13167
13168    pub fn unfold_all(
13169        &mut self,
13170        _: &actions::UnfoldAll,
13171        _window: &mut Window,
13172        cx: &mut Context<Self>,
13173    ) {
13174        if self.buffer.read(cx).is_singleton() {
13175            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13176            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13177        } else {
13178            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13179                editor
13180                    .update(&mut cx, |editor, cx| {
13181                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13182                            editor.unfold_buffer(buffer_id, cx);
13183                        }
13184                    })
13185                    .ok();
13186            });
13187        }
13188    }
13189
13190    pub fn fold_selected_ranges(
13191        &mut self,
13192        _: &FoldSelectedRanges,
13193        window: &mut Window,
13194        cx: &mut Context<Self>,
13195    ) {
13196        let selections = self.selections.all::<Point>(cx);
13197        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13198        let line_mode = self.selections.line_mode;
13199        let ranges = selections
13200            .into_iter()
13201            .map(|s| {
13202                if line_mode {
13203                    let start = Point::new(s.start.row, 0);
13204                    let end = Point::new(
13205                        s.end.row,
13206                        display_map
13207                            .buffer_snapshot
13208                            .line_len(MultiBufferRow(s.end.row)),
13209                    );
13210                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13211                } else {
13212                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13213                }
13214            })
13215            .collect::<Vec<_>>();
13216        self.fold_creases(ranges, true, window, cx);
13217    }
13218
13219    pub fn fold_ranges<T: ToOffset + Clone>(
13220        &mut self,
13221        ranges: Vec<Range<T>>,
13222        auto_scroll: bool,
13223        window: &mut Window,
13224        cx: &mut Context<Self>,
13225    ) {
13226        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13227        let ranges = ranges
13228            .into_iter()
13229            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13230            .collect::<Vec<_>>();
13231        self.fold_creases(ranges, auto_scroll, window, cx);
13232    }
13233
13234    pub fn fold_creases<T: ToOffset + Clone>(
13235        &mut self,
13236        creases: Vec<Crease<T>>,
13237        auto_scroll: bool,
13238        window: &mut Window,
13239        cx: &mut Context<Self>,
13240    ) {
13241        if creases.is_empty() {
13242            return;
13243        }
13244
13245        let mut buffers_affected = HashSet::default();
13246        let multi_buffer = self.buffer().read(cx);
13247        for crease in &creases {
13248            if let Some((_, buffer, _)) =
13249                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13250            {
13251                buffers_affected.insert(buffer.read(cx).remote_id());
13252            };
13253        }
13254
13255        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13256
13257        if auto_scroll {
13258            self.request_autoscroll(Autoscroll::fit(), cx);
13259        }
13260
13261        cx.notify();
13262
13263        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13264            // Clear diagnostics block when folding a range that contains it.
13265            let snapshot = self.snapshot(window, cx);
13266            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13267                drop(snapshot);
13268                self.active_diagnostics = Some(active_diagnostics);
13269                self.dismiss_diagnostics(cx);
13270            } else {
13271                self.active_diagnostics = Some(active_diagnostics);
13272            }
13273        }
13274
13275        self.scrollbar_marker_state.dirty = true;
13276    }
13277
13278    /// Removes any folds whose ranges intersect any of the given ranges.
13279    pub fn unfold_ranges<T: ToOffset + Clone>(
13280        &mut self,
13281        ranges: &[Range<T>],
13282        inclusive: bool,
13283        auto_scroll: bool,
13284        cx: &mut Context<Self>,
13285    ) {
13286        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13287            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13288        });
13289    }
13290
13291    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13292        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13293            return;
13294        }
13295        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13296        self.display_map
13297            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13298        cx.emit(EditorEvent::BufferFoldToggled {
13299            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13300            folded: true,
13301        });
13302        cx.notify();
13303    }
13304
13305    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13306        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13307            return;
13308        }
13309        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13310        self.display_map.update(cx, |display_map, cx| {
13311            display_map.unfold_buffer(buffer_id, cx);
13312        });
13313        cx.emit(EditorEvent::BufferFoldToggled {
13314            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13315            folded: false,
13316        });
13317        cx.notify();
13318    }
13319
13320    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13321        self.display_map.read(cx).is_buffer_folded(buffer)
13322    }
13323
13324    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13325        self.display_map.read(cx).folded_buffers()
13326    }
13327
13328    /// Removes any folds with the given ranges.
13329    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13330        &mut self,
13331        ranges: &[Range<T>],
13332        type_id: TypeId,
13333        auto_scroll: bool,
13334        cx: &mut Context<Self>,
13335    ) {
13336        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13337            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13338        });
13339    }
13340
13341    fn remove_folds_with<T: ToOffset + Clone>(
13342        &mut self,
13343        ranges: &[Range<T>],
13344        auto_scroll: bool,
13345        cx: &mut Context<Self>,
13346        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13347    ) {
13348        if ranges.is_empty() {
13349            return;
13350        }
13351
13352        let mut buffers_affected = HashSet::default();
13353        let multi_buffer = self.buffer().read(cx);
13354        for range in ranges {
13355            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13356                buffers_affected.insert(buffer.read(cx).remote_id());
13357            };
13358        }
13359
13360        self.display_map.update(cx, update);
13361
13362        if auto_scroll {
13363            self.request_autoscroll(Autoscroll::fit(), cx);
13364        }
13365
13366        cx.notify();
13367        self.scrollbar_marker_state.dirty = true;
13368        self.active_indent_guides_state.dirty = true;
13369    }
13370
13371    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13372        self.display_map.read(cx).fold_placeholder.clone()
13373    }
13374
13375    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13376        self.buffer.update(cx, |buffer, cx| {
13377            buffer.set_all_diff_hunks_expanded(cx);
13378        });
13379    }
13380
13381    pub fn expand_all_diff_hunks(
13382        &mut self,
13383        _: &ExpandAllDiffHunks,
13384        _window: &mut Window,
13385        cx: &mut Context<Self>,
13386    ) {
13387        self.buffer.update(cx, |buffer, cx| {
13388            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13389        });
13390    }
13391
13392    pub fn toggle_selected_diff_hunks(
13393        &mut self,
13394        _: &ToggleSelectedDiffHunks,
13395        _window: &mut Window,
13396        cx: &mut Context<Self>,
13397    ) {
13398        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13399        self.toggle_diff_hunks_in_ranges(ranges, cx);
13400    }
13401
13402    pub fn diff_hunks_in_ranges<'a>(
13403        &'a self,
13404        ranges: &'a [Range<Anchor>],
13405        buffer: &'a MultiBufferSnapshot,
13406    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13407        ranges.iter().flat_map(move |range| {
13408            let end_excerpt_id = range.end.excerpt_id;
13409            let range = range.to_point(buffer);
13410            let mut peek_end = range.end;
13411            if range.end.row < buffer.max_row().0 {
13412                peek_end = Point::new(range.end.row + 1, 0);
13413            }
13414            buffer
13415                .diff_hunks_in_range(range.start..peek_end)
13416                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13417        })
13418    }
13419
13420    pub fn has_stageable_diff_hunks_in_ranges(
13421        &self,
13422        ranges: &[Range<Anchor>],
13423        snapshot: &MultiBufferSnapshot,
13424    ) -> bool {
13425        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13426        hunks.any(|hunk| hunk.secondary_status != DiffHunkSecondaryStatus::None)
13427    }
13428
13429    pub fn toggle_staged_selected_diff_hunks(
13430        &mut self,
13431        _: &::git::ToggleStaged,
13432        _window: &mut Window,
13433        cx: &mut Context<Self>,
13434    ) {
13435        let snapshot = self.buffer.read(cx).snapshot(cx);
13436        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13437        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13438        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13439    }
13440
13441    pub fn stage_and_next(
13442        &mut self,
13443        _: &::git::StageAndNext,
13444        window: &mut Window,
13445        cx: &mut Context<Self>,
13446    ) {
13447        self.do_stage_or_unstage_and_next(true, window, cx);
13448    }
13449
13450    pub fn unstage_and_next(
13451        &mut self,
13452        _: &::git::UnstageAndNext,
13453        window: &mut Window,
13454        cx: &mut Context<Self>,
13455    ) {
13456        self.do_stage_or_unstage_and_next(false, window, cx);
13457    }
13458
13459    pub fn stage_or_unstage_diff_hunks(
13460        &mut self,
13461        stage: bool,
13462        ranges: &[Range<Anchor>],
13463        cx: &mut Context<Self>,
13464    ) {
13465        let snapshot = self.buffer.read(cx).snapshot(cx);
13466        let Some(project) = &self.project else {
13467            return;
13468        };
13469
13470        let chunk_by = self
13471            .diff_hunks_in_ranges(&ranges, &snapshot)
13472            .chunk_by(|hunk| hunk.buffer_id);
13473        for (buffer_id, hunks) in &chunk_by {
13474            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13475        }
13476    }
13477
13478    fn do_stage_or_unstage_and_next(
13479        &mut self,
13480        stage: bool,
13481        window: &mut Window,
13482        cx: &mut Context<Self>,
13483    ) {
13484        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13485        if ranges.iter().any(|range| range.start != range.end) {
13486            self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13487            return;
13488        }
13489
13490        if !self.buffer().read(cx).is_singleton() {
13491            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13492                if buffer.read(cx).is_empty() {
13493                    let buffer = buffer.read(cx);
13494                    let Some(file) = buffer.file() else {
13495                        return;
13496                    };
13497                    let project_path = project::ProjectPath {
13498                        worktree_id: file.worktree_id(cx),
13499                        path: file.path().clone(),
13500                    };
13501                    let Some(project) = self.project.as_ref() else {
13502                        return;
13503                    };
13504                    let project = project.read(cx);
13505
13506                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13507                        return;
13508                    };
13509
13510                    repo.update(cx, |repo, cx| {
13511                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13512                            return;
13513                        };
13514                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13515                            return;
13516                        };
13517                        if stage && status.status == FileStatus::Untracked {
13518                            repo.stage_entries(vec![repo_path], cx)
13519                                .detach_and_log_err(cx);
13520                            return;
13521                        }
13522                    })
13523                }
13524                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13525                    excerpt_id,
13526                    buffer.read(cx).remote_id(),
13527                    range,
13528                )];
13529                self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13530                let snapshot = self.buffer().read(cx).snapshot(cx);
13531                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13532                if point.row < snapshot.max_row().0 {
13533                    point.row += 1;
13534                    point.column = 0;
13535                    point = snapshot.clip_point(point, Bias::Right);
13536                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13537                        s.select_ranges([point..point]);
13538                    })
13539                }
13540                return;
13541            }
13542        }
13543        self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13544        self.go_to_next_hunk(&Default::default(), window, cx);
13545    }
13546
13547    fn do_stage_or_unstage(
13548        project: &Entity<Project>,
13549        stage: bool,
13550        buffer_id: BufferId,
13551        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13552        snapshot: &MultiBufferSnapshot,
13553        cx: &mut App,
13554    ) {
13555        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13556            log::debug!("no buffer for id");
13557            return;
13558        };
13559        let buffer_snapshot = buffer.read(cx).snapshot();
13560        let file_exists = buffer_snapshot
13561            .file()
13562            .is_some_and(|file| file.disk_state().exists());
13563        let Some((repo, path)) = project
13564            .read(cx)
13565            .repository_and_path_for_buffer_id(buffer_id, cx)
13566        else {
13567            log::debug!("no git repo for buffer id");
13568            return;
13569        };
13570        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13571            log::debug!("no diff for buffer id");
13572            return;
13573        };
13574
13575        let new_index_text = if !stage && diff.is_single_insertion || stage && !file_exists {
13576            log::debug!("removing from index");
13577            None
13578        } else {
13579            diff.new_secondary_text_for_stage_or_unstage(
13580                stage,
13581                hunks.filter_map(|hunk| {
13582                    if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13583                        return None;
13584                    } else if !stage
13585                        && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13586                    {
13587                        return None;
13588                    }
13589                    Some((hunk.buffer_range.clone(), hunk.diff_base_byte_range.clone()))
13590                }),
13591                &buffer_snapshot,
13592                cx,
13593            )
13594        };
13595
13596        if file_exists {
13597            let buffer_store = project.read(cx).buffer_store().clone();
13598            buffer_store
13599                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13600                .detach_and_log_err(cx);
13601        }
13602
13603        cx.background_spawn(
13604            repo.read(cx)
13605                .set_index_text(&path, new_index_text.map(|rope| rope.to_string()))
13606                .log_err(),
13607        )
13608        .detach();
13609    }
13610
13611    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13612        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13613        self.buffer
13614            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13615    }
13616
13617    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13618        self.buffer.update(cx, |buffer, cx| {
13619            let ranges = vec![Anchor::min()..Anchor::max()];
13620            if !buffer.all_diff_hunks_expanded()
13621                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13622            {
13623                buffer.collapse_diff_hunks(ranges, cx);
13624                true
13625            } else {
13626                false
13627            }
13628        })
13629    }
13630
13631    fn toggle_diff_hunks_in_ranges(
13632        &mut self,
13633        ranges: Vec<Range<Anchor>>,
13634        cx: &mut Context<'_, Editor>,
13635    ) {
13636        self.buffer.update(cx, |buffer, cx| {
13637            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13638            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13639        })
13640    }
13641
13642    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13643        self.buffer.update(cx, |buffer, cx| {
13644            let snapshot = buffer.snapshot(cx);
13645            let excerpt_id = range.end.excerpt_id;
13646            let point_range = range.to_point(&snapshot);
13647            let expand = !buffer.single_hunk_is_expanded(range, cx);
13648            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13649        })
13650    }
13651
13652    pub(crate) fn apply_all_diff_hunks(
13653        &mut self,
13654        _: &ApplyAllDiffHunks,
13655        window: &mut Window,
13656        cx: &mut Context<Self>,
13657    ) {
13658        let buffers = self.buffer.read(cx).all_buffers();
13659        for branch_buffer in buffers {
13660            branch_buffer.update(cx, |branch_buffer, cx| {
13661                branch_buffer.merge_into_base(Vec::new(), cx);
13662            });
13663        }
13664
13665        if let Some(project) = self.project.clone() {
13666            self.save(true, project, window, cx).detach_and_log_err(cx);
13667        }
13668    }
13669
13670    pub(crate) fn apply_selected_diff_hunks(
13671        &mut self,
13672        _: &ApplyDiffHunk,
13673        window: &mut Window,
13674        cx: &mut Context<Self>,
13675    ) {
13676        let snapshot = self.snapshot(window, cx);
13677        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13678        let mut ranges_by_buffer = HashMap::default();
13679        self.transact(window, cx, |editor, _window, cx| {
13680            for hunk in hunks {
13681                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13682                    ranges_by_buffer
13683                        .entry(buffer.clone())
13684                        .or_insert_with(Vec::new)
13685                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13686                }
13687            }
13688
13689            for (buffer, ranges) in ranges_by_buffer {
13690                buffer.update(cx, |buffer, cx| {
13691                    buffer.merge_into_base(ranges, cx);
13692                });
13693            }
13694        });
13695
13696        if let Some(project) = self.project.clone() {
13697            self.save(true, project, window, cx).detach_and_log_err(cx);
13698        }
13699    }
13700
13701    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13702        if hovered != self.gutter_hovered {
13703            self.gutter_hovered = hovered;
13704            cx.notify();
13705        }
13706    }
13707
13708    pub fn insert_blocks(
13709        &mut self,
13710        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13711        autoscroll: Option<Autoscroll>,
13712        cx: &mut Context<Self>,
13713    ) -> Vec<CustomBlockId> {
13714        let blocks = self
13715            .display_map
13716            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13717        if let Some(autoscroll) = autoscroll {
13718            self.request_autoscroll(autoscroll, cx);
13719        }
13720        cx.notify();
13721        blocks
13722    }
13723
13724    pub fn resize_blocks(
13725        &mut self,
13726        heights: HashMap<CustomBlockId, u32>,
13727        autoscroll: Option<Autoscroll>,
13728        cx: &mut Context<Self>,
13729    ) {
13730        self.display_map
13731            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13732        if let Some(autoscroll) = autoscroll {
13733            self.request_autoscroll(autoscroll, cx);
13734        }
13735        cx.notify();
13736    }
13737
13738    pub fn replace_blocks(
13739        &mut self,
13740        renderers: HashMap<CustomBlockId, RenderBlock>,
13741        autoscroll: Option<Autoscroll>,
13742        cx: &mut Context<Self>,
13743    ) {
13744        self.display_map
13745            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13746        if let Some(autoscroll) = autoscroll {
13747            self.request_autoscroll(autoscroll, cx);
13748        }
13749        cx.notify();
13750    }
13751
13752    pub fn remove_blocks(
13753        &mut self,
13754        block_ids: HashSet<CustomBlockId>,
13755        autoscroll: Option<Autoscroll>,
13756        cx: &mut Context<Self>,
13757    ) {
13758        self.display_map.update(cx, |display_map, cx| {
13759            display_map.remove_blocks(block_ids, cx)
13760        });
13761        if let Some(autoscroll) = autoscroll {
13762            self.request_autoscroll(autoscroll, cx);
13763        }
13764        cx.notify();
13765    }
13766
13767    pub fn row_for_block(
13768        &self,
13769        block_id: CustomBlockId,
13770        cx: &mut Context<Self>,
13771    ) -> Option<DisplayRow> {
13772        self.display_map
13773            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13774    }
13775
13776    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13777        self.focused_block = Some(focused_block);
13778    }
13779
13780    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13781        self.focused_block.take()
13782    }
13783
13784    pub fn insert_creases(
13785        &mut self,
13786        creases: impl IntoIterator<Item = Crease<Anchor>>,
13787        cx: &mut Context<Self>,
13788    ) -> Vec<CreaseId> {
13789        self.display_map
13790            .update(cx, |map, cx| map.insert_creases(creases, cx))
13791    }
13792
13793    pub fn remove_creases(
13794        &mut self,
13795        ids: impl IntoIterator<Item = CreaseId>,
13796        cx: &mut Context<Self>,
13797    ) {
13798        self.display_map
13799            .update(cx, |map, cx| map.remove_creases(ids, cx));
13800    }
13801
13802    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13803        self.display_map
13804            .update(cx, |map, cx| map.snapshot(cx))
13805            .longest_row()
13806    }
13807
13808    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13809        self.display_map
13810            .update(cx, |map, cx| map.snapshot(cx))
13811            .max_point()
13812    }
13813
13814    pub fn text(&self, cx: &App) -> String {
13815        self.buffer.read(cx).read(cx).text()
13816    }
13817
13818    pub fn is_empty(&self, cx: &App) -> bool {
13819        self.buffer.read(cx).read(cx).is_empty()
13820    }
13821
13822    pub fn text_option(&self, cx: &App) -> Option<String> {
13823        let text = self.text(cx);
13824        let text = text.trim();
13825
13826        if text.is_empty() {
13827            return None;
13828        }
13829
13830        Some(text.to_string())
13831    }
13832
13833    pub fn set_text(
13834        &mut self,
13835        text: impl Into<Arc<str>>,
13836        window: &mut Window,
13837        cx: &mut Context<Self>,
13838    ) {
13839        self.transact(window, cx, |this, _, cx| {
13840            this.buffer
13841                .read(cx)
13842                .as_singleton()
13843                .expect("you can only call set_text on editors for singleton buffers")
13844                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13845        });
13846    }
13847
13848    pub fn display_text(&self, cx: &mut App) -> String {
13849        self.display_map
13850            .update(cx, |map, cx| map.snapshot(cx))
13851            .text()
13852    }
13853
13854    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13855        let mut wrap_guides = smallvec::smallvec![];
13856
13857        if self.show_wrap_guides == Some(false) {
13858            return wrap_guides;
13859        }
13860
13861        let settings = self.buffer.read(cx).settings_at(0, cx);
13862        if settings.show_wrap_guides {
13863            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13864                wrap_guides.push((soft_wrap as usize, true));
13865            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13866                wrap_guides.push((soft_wrap as usize, true));
13867            }
13868            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13869        }
13870
13871        wrap_guides
13872    }
13873
13874    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13875        let settings = self.buffer.read(cx).settings_at(0, cx);
13876        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13877        match mode {
13878            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13879                SoftWrap::None
13880            }
13881            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13882            language_settings::SoftWrap::PreferredLineLength => {
13883                SoftWrap::Column(settings.preferred_line_length)
13884            }
13885            language_settings::SoftWrap::Bounded => {
13886                SoftWrap::Bounded(settings.preferred_line_length)
13887            }
13888        }
13889    }
13890
13891    pub fn set_soft_wrap_mode(
13892        &mut self,
13893        mode: language_settings::SoftWrap,
13894
13895        cx: &mut Context<Self>,
13896    ) {
13897        self.soft_wrap_mode_override = Some(mode);
13898        cx.notify();
13899    }
13900
13901    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13902        self.text_style_refinement = Some(style);
13903    }
13904
13905    /// called by the Element so we know what style we were most recently rendered with.
13906    pub(crate) fn set_style(
13907        &mut self,
13908        style: EditorStyle,
13909        window: &mut Window,
13910        cx: &mut Context<Self>,
13911    ) {
13912        let rem_size = window.rem_size();
13913        self.display_map.update(cx, |map, cx| {
13914            map.set_font(
13915                style.text.font(),
13916                style.text.font_size.to_pixels(rem_size),
13917                cx,
13918            )
13919        });
13920        self.style = Some(style);
13921    }
13922
13923    pub fn style(&self) -> Option<&EditorStyle> {
13924        self.style.as_ref()
13925    }
13926
13927    // Called by the element. This method is not designed to be called outside of the editor
13928    // element's layout code because it does not notify when rewrapping is computed synchronously.
13929    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13930        self.display_map
13931            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13932    }
13933
13934    pub fn set_soft_wrap(&mut self) {
13935        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13936    }
13937
13938    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13939        if self.soft_wrap_mode_override.is_some() {
13940            self.soft_wrap_mode_override.take();
13941        } else {
13942            let soft_wrap = match self.soft_wrap_mode(cx) {
13943                SoftWrap::GitDiff => return,
13944                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13945                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13946                    language_settings::SoftWrap::None
13947                }
13948            };
13949            self.soft_wrap_mode_override = Some(soft_wrap);
13950        }
13951        cx.notify();
13952    }
13953
13954    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13955        let Some(workspace) = self.workspace() else {
13956            return;
13957        };
13958        let fs = workspace.read(cx).app_state().fs.clone();
13959        let current_show = TabBarSettings::get_global(cx).show;
13960        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13961            setting.show = Some(!current_show);
13962        });
13963    }
13964
13965    pub fn toggle_indent_guides(
13966        &mut self,
13967        _: &ToggleIndentGuides,
13968        _: &mut Window,
13969        cx: &mut Context<Self>,
13970    ) {
13971        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13972            self.buffer
13973                .read(cx)
13974                .settings_at(0, cx)
13975                .indent_guides
13976                .enabled
13977        });
13978        self.show_indent_guides = Some(!currently_enabled);
13979        cx.notify();
13980    }
13981
13982    fn should_show_indent_guides(&self) -> Option<bool> {
13983        self.show_indent_guides
13984    }
13985
13986    pub fn toggle_line_numbers(
13987        &mut self,
13988        _: &ToggleLineNumbers,
13989        _: &mut Window,
13990        cx: &mut Context<Self>,
13991    ) {
13992        let mut editor_settings = EditorSettings::get_global(cx).clone();
13993        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13994        EditorSettings::override_global(editor_settings, cx);
13995    }
13996
13997    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13998        self.use_relative_line_numbers
13999            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14000    }
14001
14002    pub fn toggle_relative_line_numbers(
14003        &mut self,
14004        _: &ToggleRelativeLineNumbers,
14005        _: &mut Window,
14006        cx: &mut Context<Self>,
14007    ) {
14008        let is_relative = self.should_use_relative_line_numbers(cx);
14009        self.set_relative_line_number(Some(!is_relative), cx)
14010    }
14011
14012    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14013        self.use_relative_line_numbers = is_relative;
14014        cx.notify();
14015    }
14016
14017    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14018        self.show_gutter = show_gutter;
14019        cx.notify();
14020    }
14021
14022    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14023        self.show_scrollbars = show_scrollbars;
14024        cx.notify();
14025    }
14026
14027    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14028        self.show_line_numbers = Some(show_line_numbers);
14029        cx.notify();
14030    }
14031
14032    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14033        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14034        cx.notify();
14035    }
14036
14037    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14038        self.show_code_actions = Some(show_code_actions);
14039        cx.notify();
14040    }
14041
14042    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14043        self.show_runnables = Some(show_runnables);
14044        cx.notify();
14045    }
14046
14047    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14048        if self.display_map.read(cx).masked != masked {
14049            self.display_map.update(cx, |map, _| map.masked = masked);
14050        }
14051        cx.notify()
14052    }
14053
14054    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14055        self.show_wrap_guides = Some(show_wrap_guides);
14056        cx.notify();
14057    }
14058
14059    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14060        self.show_indent_guides = Some(show_indent_guides);
14061        cx.notify();
14062    }
14063
14064    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14065        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14066            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14067                if let Some(dir) = file.abs_path(cx).parent() {
14068                    return Some(dir.to_owned());
14069                }
14070            }
14071
14072            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14073                return Some(project_path.path.to_path_buf());
14074            }
14075        }
14076
14077        None
14078    }
14079
14080    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14081        self.active_excerpt(cx)?
14082            .1
14083            .read(cx)
14084            .file()
14085            .and_then(|f| f.as_local())
14086    }
14087
14088    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14089        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14090            let buffer = buffer.read(cx);
14091            if let Some(project_path) = buffer.project_path(cx) {
14092                let project = self.project.as_ref()?.read(cx);
14093                project.absolute_path(&project_path, cx)
14094            } else {
14095                buffer
14096                    .file()
14097                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14098            }
14099        })
14100    }
14101
14102    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14103        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14104            let project_path = buffer.read(cx).project_path(cx)?;
14105            let project = self.project.as_ref()?.read(cx);
14106            let entry = project.entry_for_path(&project_path, cx)?;
14107            let path = entry.path.to_path_buf();
14108            Some(path)
14109        })
14110    }
14111
14112    pub fn reveal_in_finder(
14113        &mut self,
14114        _: &RevealInFileManager,
14115        _window: &mut Window,
14116        cx: &mut Context<Self>,
14117    ) {
14118        if let Some(target) = self.target_file(cx) {
14119            cx.reveal_path(&target.abs_path(cx));
14120        }
14121    }
14122
14123    pub fn copy_path(
14124        &mut self,
14125        _: &zed_actions::workspace::CopyPath,
14126        _window: &mut Window,
14127        cx: &mut Context<Self>,
14128    ) {
14129        if let Some(path) = self.target_file_abs_path(cx) {
14130            if let Some(path) = path.to_str() {
14131                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14132            }
14133        }
14134    }
14135
14136    pub fn copy_relative_path(
14137        &mut self,
14138        _: &zed_actions::workspace::CopyRelativePath,
14139        _window: &mut Window,
14140        cx: &mut Context<Self>,
14141    ) {
14142        if let Some(path) = self.target_file_path(cx) {
14143            if let Some(path) = path.to_str() {
14144                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14145            }
14146        }
14147    }
14148
14149    pub fn copy_file_name_without_extension(
14150        &mut self,
14151        _: &CopyFileNameWithoutExtension,
14152        _: &mut Window,
14153        cx: &mut Context<Self>,
14154    ) {
14155        if let Some(file) = self.target_file(cx) {
14156            if let Some(file_stem) = file.path().file_stem() {
14157                if let Some(name) = file_stem.to_str() {
14158                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14159                }
14160            }
14161        }
14162    }
14163
14164    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14165        if let Some(file) = self.target_file(cx) {
14166            if let Some(file_name) = file.path().file_name() {
14167                if let Some(name) = file_name.to_str() {
14168                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14169                }
14170            }
14171        }
14172    }
14173
14174    pub fn toggle_git_blame(
14175        &mut self,
14176        _: &ToggleGitBlame,
14177        window: &mut Window,
14178        cx: &mut Context<Self>,
14179    ) {
14180        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14181
14182        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14183            self.start_git_blame(true, window, cx);
14184        }
14185
14186        cx.notify();
14187    }
14188
14189    pub fn toggle_git_blame_inline(
14190        &mut self,
14191        _: &ToggleGitBlameInline,
14192        window: &mut Window,
14193        cx: &mut Context<Self>,
14194    ) {
14195        self.toggle_git_blame_inline_internal(true, window, cx);
14196        cx.notify();
14197    }
14198
14199    pub fn git_blame_inline_enabled(&self) -> bool {
14200        self.git_blame_inline_enabled
14201    }
14202
14203    pub fn toggle_selection_menu(
14204        &mut self,
14205        _: &ToggleSelectionMenu,
14206        _: &mut Window,
14207        cx: &mut Context<Self>,
14208    ) {
14209        self.show_selection_menu = self
14210            .show_selection_menu
14211            .map(|show_selections_menu| !show_selections_menu)
14212            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14213
14214        cx.notify();
14215    }
14216
14217    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14218        self.show_selection_menu
14219            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14220    }
14221
14222    fn start_git_blame(
14223        &mut self,
14224        user_triggered: bool,
14225        window: &mut Window,
14226        cx: &mut Context<Self>,
14227    ) {
14228        if let Some(project) = self.project.as_ref() {
14229            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14230                return;
14231            };
14232
14233            if buffer.read(cx).file().is_none() {
14234                return;
14235            }
14236
14237            let focused = self.focus_handle(cx).contains_focused(window, cx);
14238
14239            let project = project.clone();
14240            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14241            self.blame_subscription =
14242                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14243            self.blame = Some(blame);
14244        }
14245    }
14246
14247    fn toggle_git_blame_inline_internal(
14248        &mut self,
14249        user_triggered: bool,
14250        window: &mut Window,
14251        cx: &mut Context<Self>,
14252    ) {
14253        if self.git_blame_inline_enabled {
14254            self.git_blame_inline_enabled = false;
14255            self.show_git_blame_inline = false;
14256            self.show_git_blame_inline_delay_task.take();
14257        } else {
14258            self.git_blame_inline_enabled = true;
14259            self.start_git_blame_inline(user_triggered, window, cx);
14260        }
14261
14262        cx.notify();
14263    }
14264
14265    fn start_git_blame_inline(
14266        &mut self,
14267        user_triggered: bool,
14268        window: &mut Window,
14269        cx: &mut Context<Self>,
14270    ) {
14271        self.start_git_blame(user_triggered, window, cx);
14272
14273        if ProjectSettings::get_global(cx)
14274            .git
14275            .inline_blame_delay()
14276            .is_some()
14277        {
14278            self.start_inline_blame_timer(window, cx);
14279        } else {
14280            self.show_git_blame_inline = true
14281        }
14282    }
14283
14284    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14285        self.blame.as_ref()
14286    }
14287
14288    pub fn show_git_blame_gutter(&self) -> bool {
14289        self.show_git_blame_gutter
14290    }
14291
14292    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14293        self.show_git_blame_gutter && self.has_blame_entries(cx)
14294    }
14295
14296    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14297        self.show_git_blame_inline
14298            && (self.focus_handle.is_focused(window)
14299                || self
14300                    .git_blame_inline_tooltip
14301                    .as_ref()
14302                    .and_then(|t| t.upgrade())
14303                    .is_some())
14304            && !self.newest_selection_head_on_empty_line(cx)
14305            && self.has_blame_entries(cx)
14306    }
14307
14308    fn has_blame_entries(&self, cx: &App) -> bool {
14309        self.blame()
14310            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14311    }
14312
14313    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14314        let cursor_anchor = self.selections.newest_anchor().head();
14315
14316        let snapshot = self.buffer.read(cx).snapshot(cx);
14317        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14318
14319        snapshot.line_len(buffer_row) == 0
14320    }
14321
14322    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14323        let buffer_and_selection = maybe!({
14324            let selection = self.selections.newest::<Point>(cx);
14325            let selection_range = selection.range();
14326
14327            let multi_buffer = self.buffer().read(cx);
14328            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14329            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14330
14331            let (buffer, range, _) = if selection.reversed {
14332                buffer_ranges.first()
14333            } else {
14334                buffer_ranges.last()
14335            }?;
14336
14337            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14338                ..text::ToPoint::to_point(&range.end, &buffer).row;
14339            Some((
14340                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14341                selection,
14342            ))
14343        });
14344
14345        let Some((buffer, selection)) = buffer_and_selection else {
14346            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14347        };
14348
14349        let Some(project) = self.project.as_ref() else {
14350            return Task::ready(Err(anyhow!("editor does not have project")));
14351        };
14352
14353        project.update(cx, |project, cx| {
14354            project.get_permalink_to_line(&buffer, selection, cx)
14355        })
14356    }
14357
14358    pub fn copy_permalink_to_line(
14359        &mut self,
14360        _: &CopyPermalinkToLine,
14361        window: &mut Window,
14362        cx: &mut Context<Self>,
14363    ) {
14364        let permalink_task = self.get_permalink_to_line(cx);
14365        let workspace = self.workspace();
14366
14367        cx.spawn_in(window, |_, mut cx| async move {
14368            match permalink_task.await {
14369                Ok(permalink) => {
14370                    cx.update(|_, cx| {
14371                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14372                    })
14373                    .ok();
14374                }
14375                Err(err) => {
14376                    let message = format!("Failed to copy permalink: {err}");
14377
14378                    Err::<(), anyhow::Error>(err).log_err();
14379
14380                    if let Some(workspace) = workspace {
14381                        workspace
14382                            .update_in(&mut cx, |workspace, _, cx| {
14383                                struct CopyPermalinkToLine;
14384
14385                                workspace.show_toast(
14386                                    Toast::new(
14387                                        NotificationId::unique::<CopyPermalinkToLine>(),
14388                                        message,
14389                                    ),
14390                                    cx,
14391                                )
14392                            })
14393                            .ok();
14394                    }
14395                }
14396            }
14397        })
14398        .detach();
14399    }
14400
14401    pub fn copy_file_location(
14402        &mut self,
14403        _: &CopyFileLocation,
14404        _: &mut Window,
14405        cx: &mut Context<Self>,
14406    ) {
14407        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14408        if let Some(file) = self.target_file(cx) {
14409            if let Some(path) = file.path().to_str() {
14410                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14411            }
14412        }
14413    }
14414
14415    pub fn open_permalink_to_line(
14416        &mut self,
14417        _: &OpenPermalinkToLine,
14418        window: &mut Window,
14419        cx: &mut Context<Self>,
14420    ) {
14421        let permalink_task = self.get_permalink_to_line(cx);
14422        let workspace = self.workspace();
14423
14424        cx.spawn_in(window, |_, mut cx| async move {
14425            match permalink_task.await {
14426                Ok(permalink) => {
14427                    cx.update(|_, cx| {
14428                        cx.open_url(permalink.as_ref());
14429                    })
14430                    .ok();
14431                }
14432                Err(err) => {
14433                    let message = format!("Failed to open permalink: {err}");
14434
14435                    Err::<(), anyhow::Error>(err).log_err();
14436
14437                    if let Some(workspace) = workspace {
14438                        workspace
14439                            .update(&mut cx, |workspace, cx| {
14440                                struct OpenPermalinkToLine;
14441
14442                                workspace.show_toast(
14443                                    Toast::new(
14444                                        NotificationId::unique::<OpenPermalinkToLine>(),
14445                                        message,
14446                                    ),
14447                                    cx,
14448                                )
14449                            })
14450                            .ok();
14451                    }
14452                }
14453            }
14454        })
14455        .detach();
14456    }
14457
14458    pub fn insert_uuid_v4(
14459        &mut self,
14460        _: &InsertUuidV4,
14461        window: &mut Window,
14462        cx: &mut Context<Self>,
14463    ) {
14464        self.insert_uuid(UuidVersion::V4, window, cx);
14465    }
14466
14467    pub fn insert_uuid_v7(
14468        &mut self,
14469        _: &InsertUuidV7,
14470        window: &mut Window,
14471        cx: &mut Context<Self>,
14472    ) {
14473        self.insert_uuid(UuidVersion::V7, window, cx);
14474    }
14475
14476    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14477        self.transact(window, cx, |this, window, cx| {
14478            let edits = this
14479                .selections
14480                .all::<Point>(cx)
14481                .into_iter()
14482                .map(|selection| {
14483                    let uuid = match version {
14484                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14485                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14486                    };
14487
14488                    (selection.range(), uuid.to_string())
14489                });
14490            this.edit(edits, cx);
14491            this.refresh_inline_completion(true, false, window, cx);
14492        });
14493    }
14494
14495    pub fn open_selections_in_multibuffer(
14496        &mut self,
14497        _: &OpenSelectionsInMultibuffer,
14498        window: &mut Window,
14499        cx: &mut Context<Self>,
14500    ) {
14501        let multibuffer = self.buffer.read(cx);
14502
14503        let Some(buffer) = multibuffer.as_singleton() else {
14504            return;
14505        };
14506
14507        let Some(workspace) = self.workspace() else {
14508            return;
14509        };
14510
14511        let locations = self
14512            .selections
14513            .disjoint_anchors()
14514            .iter()
14515            .map(|range| Location {
14516                buffer: buffer.clone(),
14517                range: range.start.text_anchor..range.end.text_anchor,
14518            })
14519            .collect::<Vec<_>>();
14520
14521        let title = multibuffer.title(cx).to_string();
14522
14523        cx.spawn_in(window, |_, mut cx| async move {
14524            workspace.update_in(&mut cx, |workspace, window, cx| {
14525                Self::open_locations_in_multibuffer(
14526                    workspace,
14527                    locations,
14528                    format!("Selections for '{title}'"),
14529                    false,
14530                    MultibufferSelectionMode::All,
14531                    window,
14532                    cx,
14533                );
14534            })
14535        })
14536        .detach();
14537    }
14538
14539    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14540    /// last highlight added will be used.
14541    ///
14542    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14543    pub fn highlight_rows<T: 'static>(
14544        &mut self,
14545        range: Range<Anchor>,
14546        color: Hsla,
14547        should_autoscroll: bool,
14548        cx: &mut Context<Self>,
14549    ) {
14550        let snapshot = self.buffer().read(cx).snapshot(cx);
14551        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14552        let ix = row_highlights.binary_search_by(|highlight| {
14553            Ordering::Equal
14554                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14555                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14556        });
14557
14558        if let Err(mut ix) = ix {
14559            let index = post_inc(&mut self.highlight_order);
14560
14561            // If this range intersects with the preceding highlight, then merge it with
14562            // the preceding highlight. Otherwise insert a new highlight.
14563            let mut merged = false;
14564            if ix > 0 {
14565                let prev_highlight = &mut row_highlights[ix - 1];
14566                if prev_highlight
14567                    .range
14568                    .end
14569                    .cmp(&range.start, &snapshot)
14570                    .is_ge()
14571                {
14572                    ix -= 1;
14573                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14574                        prev_highlight.range.end = range.end;
14575                    }
14576                    merged = true;
14577                    prev_highlight.index = index;
14578                    prev_highlight.color = color;
14579                    prev_highlight.should_autoscroll = should_autoscroll;
14580                }
14581            }
14582
14583            if !merged {
14584                row_highlights.insert(
14585                    ix,
14586                    RowHighlight {
14587                        range: range.clone(),
14588                        index,
14589                        color,
14590                        should_autoscroll,
14591                    },
14592                );
14593            }
14594
14595            // If any of the following highlights intersect with this one, merge them.
14596            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14597                let highlight = &row_highlights[ix];
14598                if next_highlight
14599                    .range
14600                    .start
14601                    .cmp(&highlight.range.end, &snapshot)
14602                    .is_le()
14603                {
14604                    if next_highlight
14605                        .range
14606                        .end
14607                        .cmp(&highlight.range.end, &snapshot)
14608                        .is_gt()
14609                    {
14610                        row_highlights[ix].range.end = next_highlight.range.end;
14611                    }
14612                    row_highlights.remove(ix + 1);
14613                } else {
14614                    break;
14615                }
14616            }
14617        }
14618    }
14619
14620    /// Remove any highlighted row ranges of the given type that intersect the
14621    /// given ranges.
14622    pub fn remove_highlighted_rows<T: 'static>(
14623        &mut self,
14624        ranges_to_remove: Vec<Range<Anchor>>,
14625        cx: &mut Context<Self>,
14626    ) {
14627        let snapshot = self.buffer().read(cx).snapshot(cx);
14628        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14629        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14630        row_highlights.retain(|highlight| {
14631            while let Some(range_to_remove) = ranges_to_remove.peek() {
14632                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14633                    Ordering::Less | Ordering::Equal => {
14634                        ranges_to_remove.next();
14635                    }
14636                    Ordering::Greater => {
14637                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14638                            Ordering::Less | Ordering::Equal => {
14639                                return false;
14640                            }
14641                            Ordering::Greater => break,
14642                        }
14643                    }
14644                }
14645            }
14646
14647            true
14648        })
14649    }
14650
14651    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14652    pub fn clear_row_highlights<T: 'static>(&mut self) {
14653        self.highlighted_rows.remove(&TypeId::of::<T>());
14654    }
14655
14656    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14657    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14658        self.highlighted_rows
14659            .get(&TypeId::of::<T>())
14660            .map_or(&[] as &[_], |vec| vec.as_slice())
14661            .iter()
14662            .map(|highlight| (highlight.range.clone(), highlight.color))
14663    }
14664
14665    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14666    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14667    /// Allows to ignore certain kinds of highlights.
14668    pub fn highlighted_display_rows(
14669        &self,
14670        window: &mut Window,
14671        cx: &mut App,
14672    ) -> BTreeMap<DisplayRow, Background> {
14673        let snapshot = self.snapshot(window, cx);
14674        let mut used_highlight_orders = HashMap::default();
14675        self.highlighted_rows
14676            .iter()
14677            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14678            .fold(
14679                BTreeMap::<DisplayRow, Background>::new(),
14680                |mut unique_rows, highlight| {
14681                    let start = highlight.range.start.to_display_point(&snapshot);
14682                    let end = highlight.range.end.to_display_point(&snapshot);
14683                    let start_row = start.row().0;
14684                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14685                        && end.column() == 0
14686                    {
14687                        end.row().0.saturating_sub(1)
14688                    } else {
14689                        end.row().0
14690                    };
14691                    for row in start_row..=end_row {
14692                        let used_index =
14693                            used_highlight_orders.entry(row).or_insert(highlight.index);
14694                        if highlight.index >= *used_index {
14695                            *used_index = highlight.index;
14696                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14697                        }
14698                    }
14699                    unique_rows
14700                },
14701            )
14702    }
14703
14704    pub fn highlighted_display_row_for_autoscroll(
14705        &self,
14706        snapshot: &DisplaySnapshot,
14707    ) -> Option<DisplayRow> {
14708        self.highlighted_rows
14709            .values()
14710            .flat_map(|highlighted_rows| highlighted_rows.iter())
14711            .filter_map(|highlight| {
14712                if highlight.should_autoscroll {
14713                    Some(highlight.range.start.to_display_point(snapshot).row())
14714                } else {
14715                    None
14716                }
14717            })
14718            .min()
14719    }
14720
14721    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14722        self.highlight_background::<SearchWithinRange>(
14723            ranges,
14724            |colors| colors.editor_document_highlight_read_background,
14725            cx,
14726        )
14727    }
14728
14729    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14730        self.breadcrumb_header = Some(new_header);
14731    }
14732
14733    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14734        self.clear_background_highlights::<SearchWithinRange>(cx);
14735    }
14736
14737    pub fn highlight_background<T: 'static>(
14738        &mut self,
14739        ranges: &[Range<Anchor>],
14740        color_fetcher: fn(&ThemeColors) -> Hsla,
14741        cx: &mut Context<Self>,
14742    ) {
14743        self.background_highlights
14744            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14745        self.scrollbar_marker_state.dirty = true;
14746        cx.notify();
14747    }
14748
14749    pub fn clear_background_highlights<T: 'static>(
14750        &mut self,
14751        cx: &mut Context<Self>,
14752    ) -> Option<BackgroundHighlight> {
14753        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14754        if !text_highlights.1.is_empty() {
14755            self.scrollbar_marker_state.dirty = true;
14756            cx.notify();
14757        }
14758        Some(text_highlights)
14759    }
14760
14761    pub fn highlight_gutter<T: 'static>(
14762        &mut self,
14763        ranges: &[Range<Anchor>],
14764        color_fetcher: fn(&App) -> Hsla,
14765        cx: &mut Context<Self>,
14766    ) {
14767        self.gutter_highlights
14768            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14769        cx.notify();
14770    }
14771
14772    pub fn clear_gutter_highlights<T: 'static>(
14773        &mut self,
14774        cx: &mut Context<Self>,
14775    ) -> Option<GutterHighlight> {
14776        cx.notify();
14777        self.gutter_highlights.remove(&TypeId::of::<T>())
14778    }
14779
14780    #[cfg(feature = "test-support")]
14781    pub fn all_text_background_highlights(
14782        &self,
14783        window: &mut Window,
14784        cx: &mut Context<Self>,
14785    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14786        let snapshot = self.snapshot(window, cx);
14787        let buffer = &snapshot.buffer_snapshot;
14788        let start = buffer.anchor_before(0);
14789        let end = buffer.anchor_after(buffer.len());
14790        let theme = cx.theme().colors();
14791        self.background_highlights_in_range(start..end, &snapshot, theme)
14792    }
14793
14794    #[cfg(feature = "test-support")]
14795    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14796        let snapshot = self.buffer().read(cx).snapshot(cx);
14797
14798        let highlights = self
14799            .background_highlights
14800            .get(&TypeId::of::<items::BufferSearchHighlights>());
14801
14802        if let Some((_color, ranges)) = highlights {
14803            ranges
14804                .iter()
14805                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14806                .collect_vec()
14807        } else {
14808            vec![]
14809        }
14810    }
14811
14812    fn document_highlights_for_position<'a>(
14813        &'a self,
14814        position: Anchor,
14815        buffer: &'a MultiBufferSnapshot,
14816    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14817        let read_highlights = self
14818            .background_highlights
14819            .get(&TypeId::of::<DocumentHighlightRead>())
14820            .map(|h| &h.1);
14821        let write_highlights = self
14822            .background_highlights
14823            .get(&TypeId::of::<DocumentHighlightWrite>())
14824            .map(|h| &h.1);
14825        let left_position = position.bias_left(buffer);
14826        let right_position = position.bias_right(buffer);
14827        read_highlights
14828            .into_iter()
14829            .chain(write_highlights)
14830            .flat_map(move |ranges| {
14831                let start_ix = match ranges.binary_search_by(|probe| {
14832                    let cmp = probe.end.cmp(&left_position, buffer);
14833                    if cmp.is_ge() {
14834                        Ordering::Greater
14835                    } else {
14836                        Ordering::Less
14837                    }
14838                }) {
14839                    Ok(i) | Err(i) => i,
14840                };
14841
14842                ranges[start_ix..]
14843                    .iter()
14844                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14845            })
14846    }
14847
14848    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14849        self.background_highlights
14850            .get(&TypeId::of::<T>())
14851            .map_or(false, |(_, highlights)| !highlights.is_empty())
14852    }
14853
14854    pub fn background_highlights_in_range(
14855        &self,
14856        search_range: Range<Anchor>,
14857        display_snapshot: &DisplaySnapshot,
14858        theme: &ThemeColors,
14859    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14860        let mut results = Vec::new();
14861        for (color_fetcher, ranges) in self.background_highlights.values() {
14862            let color = color_fetcher(theme);
14863            let start_ix = match ranges.binary_search_by(|probe| {
14864                let cmp = probe
14865                    .end
14866                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14867                if cmp.is_gt() {
14868                    Ordering::Greater
14869                } else {
14870                    Ordering::Less
14871                }
14872            }) {
14873                Ok(i) | Err(i) => i,
14874            };
14875            for range in &ranges[start_ix..] {
14876                if range
14877                    .start
14878                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14879                    .is_ge()
14880                {
14881                    break;
14882                }
14883
14884                let start = range.start.to_display_point(display_snapshot);
14885                let end = range.end.to_display_point(display_snapshot);
14886                results.push((start..end, color))
14887            }
14888        }
14889        results
14890    }
14891
14892    pub fn background_highlight_row_ranges<T: 'static>(
14893        &self,
14894        search_range: Range<Anchor>,
14895        display_snapshot: &DisplaySnapshot,
14896        count: usize,
14897    ) -> Vec<RangeInclusive<DisplayPoint>> {
14898        let mut results = Vec::new();
14899        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14900            return vec![];
14901        };
14902
14903        let start_ix = match ranges.binary_search_by(|probe| {
14904            let cmp = probe
14905                .end
14906                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14907            if cmp.is_gt() {
14908                Ordering::Greater
14909            } else {
14910                Ordering::Less
14911            }
14912        }) {
14913            Ok(i) | Err(i) => i,
14914        };
14915        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14916            if let (Some(start_display), Some(end_display)) = (start, end) {
14917                results.push(
14918                    start_display.to_display_point(display_snapshot)
14919                        ..=end_display.to_display_point(display_snapshot),
14920                );
14921            }
14922        };
14923        let mut start_row: Option<Point> = None;
14924        let mut end_row: Option<Point> = None;
14925        if ranges.len() > count {
14926            return Vec::new();
14927        }
14928        for range in &ranges[start_ix..] {
14929            if range
14930                .start
14931                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14932                .is_ge()
14933            {
14934                break;
14935            }
14936            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14937            if let Some(current_row) = &end_row {
14938                if end.row == current_row.row {
14939                    continue;
14940                }
14941            }
14942            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14943            if start_row.is_none() {
14944                assert_eq!(end_row, None);
14945                start_row = Some(start);
14946                end_row = Some(end);
14947                continue;
14948            }
14949            if let Some(current_end) = end_row.as_mut() {
14950                if start.row > current_end.row + 1 {
14951                    push_region(start_row, end_row);
14952                    start_row = Some(start);
14953                    end_row = Some(end);
14954                } else {
14955                    // Merge two hunks.
14956                    *current_end = end;
14957                }
14958            } else {
14959                unreachable!();
14960            }
14961        }
14962        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14963        push_region(start_row, end_row);
14964        results
14965    }
14966
14967    pub fn gutter_highlights_in_range(
14968        &self,
14969        search_range: Range<Anchor>,
14970        display_snapshot: &DisplaySnapshot,
14971        cx: &App,
14972    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14973        let mut results = Vec::new();
14974        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14975            let color = color_fetcher(cx);
14976            let start_ix = match ranges.binary_search_by(|probe| {
14977                let cmp = probe
14978                    .end
14979                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14980                if cmp.is_gt() {
14981                    Ordering::Greater
14982                } else {
14983                    Ordering::Less
14984                }
14985            }) {
14986                Ok(i) | Err(i) => i,
14987            };
14988            for range in &ranges[start_ix..] {
14989                if range
14990                    .start
14991                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14992                    .is_ge()
14993                {
14994                    break;
14995                }
14996
14997                let start = range.start.to_display_point(display_snapshot);
14998                let end = range.end.to_display_point(display_snapshot);
14999                results.push((start..end, color))
15000            }
15001        }
15002        results
15003    }
15004
15005    /// Get the text ranges corresponding to the redaction query
15006    pub fn redacted_ranges(
15007        &self,
15008        search_range: Range<Anchor>,
15009        display_snapshot: &DisplaySnapshot,
15010        cx: &App,
15011    ) -> Vec<Range<DisplayPoint>> {
15012        display_snapshot
15013            .buffer_snapshot
15014            .redacted_ranges(search_range, |file| {
15015                if let Some(file) = file {
15016                    file.is_private()
15017                        && EditorSettings::get(
15018                            Some(SettingsLocation {
15019                                worktree_id: file.worktree_id(cx),
15020                                path: file.path().as_ref(),
15021                            }),
15022                            cx,
15023                        )
15024                        .redact_private_values
15025                } else {
15026                    false
15027                }
15028            })
15029            .map(|range| {
15030                range.start.to_display_point(display_snapshot)
15031                    ..range.end.to_display_point(display_snapshot)
15032            })
15033            .collect()
15034    }
15035
15036    pub fn highlight_text<T: 'static>(
15037        &mut self,
15038        ranges: Vec<Range<Anchor>>,
15039        style: HighlightStyle,
15040        cx: &mut Context<Self>,
15041    ) {
15042        self.display_map.update(cx, |map, _| {
15043            map.highlight_text(TypeId::of::<T>(), ranges, style)
15044        });
15045        cx.notify();
15046    }
15047
15048    pub(crate) fn highlight_inlays<T: 'static>(
15049        &mut self,
15050        highlights: Vec<InlayHighlight>,
15051        style: HighlightStyle,
15052        cx: &mut Context<Self>,
15053    ) {
15054        self.display_map.update(cx, |map, _| {
15055            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15056        });
15057        cx.notify();
15058    }
15059
15060    pub fn text_highlights<'a, T: 'static>(
15061        &'a self,
15062        cx: &'a App,
15063    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15064        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15065    }
15066
15067    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15068        let cleared = self
15069            .display_map
15070            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15071        if cleared {
15072            cx.notify();
15073        }
15074    }
15075
15076    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15077        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15078            && self.focus_handle.is_focused(window)
15079    }
15080
15081    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15082        self.show_cursor_when_unfocused = is_enabled;
15083        cx.notify();
15084    }
15085
15086    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15087        cx.notify();
15088    }
15089
15090    fn on_buffer_event(
15091        &mut self,
15092        multibuffer: &Entity<MultiBuffer>,
15093        event: &multi_buffer::Event,
15094        window: &mut Window,
15095        cx: &mut Context<Self>,
15096    ) {
15097        match event {
15098            multi_buffer::Event::Edited {
15099                singleton_buffer_edited,
15100                edited_buffer: buffer_edited,
15101            } => {
15102                self.scrollbar_marker_state.dirty = true;
15103                self.active_indent_guides_state.dirty = true;
15104                self.refresh_active_diagnostics(cx);
15105                self.refresh_code_actions(window, cx);
15106                if self.has_active_inline_completion() {
15107                    self.update_visible_inline_completion(window, cx);
15108                }
15109                if let Some(buffer) = buffer_edited {
15110                    let buffer_id = buffer.read(cx).remote_id();
15111                    if !self.registered_buffers.contains_key(&buffer_id) {
15112                        if let Some(project) = self.project.as_ref() {
15113                            project.update(cx, |project, cx| {
15114                                self.registered_buffers.insert(
15115                                    buffer_id,
15116                                    project.register_buffer_with_language_servers(&buffer, cx),
15117                                );
15118                            })
15119                        }
15120                    }
15121                }
15122                cx.emit(EditorEvent::BufferEdited);
15123                cx.emit(SearchEvent::MatchesInvalidated);
15124                if *singleton_buffer_edited {
15125                    if let Some(project) = &self.project {
15126                        #[allow(clippy::mutable_key_type)]
15127                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15128                            multibuffer
15129                                .all_buffers()
15130                                .into_iter()
15131                                .filter_map(|buffer| {
15132                                    buffer.update(cx, |buffer, cx| {
15133                                        let language = buffer.language()?;
15134                                        let should_discard = project.update(cx, |project, cx| {
15135                                            project.is_local()
15136                                                && !project.has_language_servers_for(buffer, cx)
15137                                        });
15138                                        should_discard.not().then_some(language.clone())
15139                                    })
15140                                })
15141                                .collect::<HashSet<_>>()
15142                        });
15143                        if !languages_affected.is_empty() {
15144                            self.refresh_inlay_hints(
15145                                InlayHintRefreshReason::BufferEdited(languages_affected),
15146                                cx,
15147                            );
15148                        }
15149                    }
15150                }
15151
15152                let Some(project) = &self.project else { return };
15153                let (telemetry, is_via_ssh) = {
15154                    let project = project.read(cx);
15155                    let telemetry = project.client().telemetry().clone();
15156                    let is_via_ssh = project.is_via_ssh();
15157                    (telemetry, is_via_ssh)
15158                };
15159                refresh_linked_ranges(self, window, cx);
15160                telemetry.log_edit_event("editor", is_via_ssh);
15161            }
15162            multi_buffer::Event::ExcerptsAdded {
15163                buffer,
15164                predecessor,
15165                excerpts,
15166            } => {
15167                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15168                let buffer_id = buffer.read(cx).remote_id();
15169                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15170                    if let Some(project) = &self.project {
15171                        get_uncommitted_diff_for_buffer(
15172                            project,
15173                            [buffer.clone()],
15174                            self.buffer.clone(),
15175                            cx,
15176                        )
15177                        .detach();
15178                    }
15179                }
15180                cx.emit(EditorEvent::ExcerptsAdded {
15181                    buffer: buffer.clone(),
15182                    predecessor: *predecessor,
15183                    excerpts: excerpts.clone(),
15184                });
15185                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15186            }
15187            multi_buffer::Event::ExcerptsRemoved { ids } => {
15188                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15189                let buffer = self.buffer.read(cx);
15190                self.registered_buffers
15191                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15192                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15193            }
15194            multi_buffer::Event::ExcerptsEdited { ids } => {
15195                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15196            }
15197            multi_buffer::Event::ExcerptsExpanded { ids } => {
15198                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15199                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15200            }
15201            multi_buffer::Event::Reparsed(buffer_id) => {
15202                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15203
15204                cx.emit(EditorEvent::Reparsed(*buffer_id));
15205            }
15206            multi_buffer::Event::DiffHunksToggled => {
15207                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15208            }
15209            multi_buffer::Event::LanguageChanged(buffer_id) => {
15210                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15211                cx.emit(EditorEvent::Reparsed(*buffer_id));
15212                cx.notify();
15213            }
15214            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15215            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15216            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15217                cx.emit(EditorEvent::TitleChanged)
15218            }
15219            // multi_buffer::Event::DiffBaseChanged => {
15220            //     self.scrollbar_marker_state.dirty = true;
15221            //     cx.emit(EditorEvent::DiffBaseChanged);
15222            //     cx.notify();
15223            // }
15224            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15225            multi_buffer::Event::DiagnosticsUpdated => {
15226                self.refresh_active_diagnostics(cx);
15227                self.refresh_inline_diagnostics(true, window, cx);
15228                self.scrollbar_marker_state.dirty = true;
15229                cx.notify();
15230            }
15231            _ => {}
15232        };
15233    }
15234
15235    fn on_display_map_changed(
15236        &mut self,
15237        _: Entity<DisplayMap>,
15238        _: &mut Window,
15239        cx: &mut Context<Self>,
15240    ) {
15241        cx.notify();
15242    }
15243
15244    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15245        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15246        self.update_edit_prediction_settings(cx);
15247        self.refresh_inline_completion(true, false, window, cx);
15248        self.refresh_inlay_hints(
15249            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15250                self.selections.newest_anchor().head(),
15251                &self.buffer.read(cx).snapshot(cx),
15252                cx,
15253            )),
15254            cx,
15255        );
15256
15257        let old_cursor_shape = self.cursor_shape;
15258
15259        {
15260            let editor_settings = EditorSettings::get_global(cx);
15261            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15262            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15263            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15264        }
15265
15266        if old_cursor_shape != self.cursor_shape {
15267            cx.emit(EditorEvent::CursorShapeChanged);
15268        }
15269
15270        let project_settings = ProjectSettings::get_global(cx);
15271        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15272
15273        if self.mode == EditorMode::Full {
15274            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15275            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15276            if self.show_inline_diagnostics != show_inline_diagnostics {
15277                self.show_inline_diagnostics = show_inline_diagnostics;
15278                self.refresh_inline_diagnostics(false, window, cx);
15279            }
15280
15281            if self.git_blame_inline_enabled != inline_blame_enabled {
15282                self.toggle_git_blame_inline_internal(false, window, cx);
15283            }
15284        }
15285
15286        cx.notify();
15287    }
15288
15289    pub fn set_searchable(&mut self, searchable: bool) {
15290        self.searchable = searchable;
15291    }
15292
15293    pub fn searchable(&self) -> bool {
15294        self.searchable
15295    }
15296
15297    fn open_proposed_changes_editor(
15298        &mut self,
15299        _: &OpenProposedChangesEditor,
15300        window: &mut Window,
15301        cx: &mut Context<Self>,
15302    ) {
15303        let Some(workspace) = self.workspace() else {
15304            cx.propagate();
15305            return;
15306        };
15307
15308        let selections = self.selections.all::<usize>(cx);
15309        let multi_buffer = self.buffer.read(cx);
15310        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15311        let mut new_selections_by_buffer = HashMap::default();
15312        for selection in selections {
15313            for (buffer, range, _) in
15314                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15315            {
15316                let mut range = range.to_point(buffer);
15317                range.start.column = 0;
15318                range.end.column = buffer.line_len(range.end.row);
15319                new_selections_by_buffer
15320                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15321                    .or_insert(Vec::new())
15322                    .push(range)
15323            }
15324        }
15325
15326        let proposed_changes_buffers = new_selections_by_buffer
15327            .into_iter()
15328            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15329            .collect::<Vec<_>>();
15330        let proposed_changes_editor = cx.new(|cx| {
15331            ProposedChangesEditor::new(
15332                "Proposed changes",
15333                proposed_changes_buffers,
15334                self.project.clone(),
15335                window,
15336                cx,
15337            )
15338        });
15339
15340        window.defer(cx, move |window, cx| {
15341            workspace.update(cx, |workspace, cx| {
15342                workspace.active_pane().update(cx, |pane, cx| {
15343                    pane.add_item(
15344                        Box::new(proposed_changes_editor),
15345                        true,
15346                        true,
15347                        None,
15348                        window,
15349                        cx,
15350                    );
15351                });
15352            });
15353        });
15354    }
15355
15356    pub fn open_excerpts_in_split(
15357        &mut self,
15358        _: &OpenExcerptsSplit,
15359        window: &mut Window,
15360        cx: &mut Context<Self>,
15361    ) {
15362        self.open_excerpts_common(None, true, window, cx)
15363    }
15364
15365    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15366        self.open_excerpts_common(None, false, window, cx)
15367    }
15368
15369    fn open_excerpts_common(
15370        &mut self,
15371        jump_data: Option<JumpData>,
15372        split: bool,
15373        window: &mut Window,
15374        cx: &mut Context<Self>,
15375    ) {
15376        let Some(workspace) = self.workspace() else {
15377            cx.propagate();
15378            return;
15379        };
15380
15381        if self.buffer.read(cx).is_singleton() {
15382            cx.propagate();
15383            return;
15384        }
15385
15386        let mut new_selections_by_buffer = HashMap::default();
15387        match &jump_data {
15388            Some(JumpData::MultiBufferPoint {
15389                excerpt_id,
15390                position,
15391                anchor,
15392                line_offset_from_top,
15393            }) => {
15394                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15395                if let Some(buffer) = multi_buffer_snapshot
15396                    .buffer_id_for_excerpt(*excerpt_id)
15397                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15398                {
15399                    let buffer_snapshot = buffer.read(cx).snapshot();
15400                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15401                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15402                    } else {
15403                        buffer_snapshot.clip_point(*position, Bias::Left)
15404                    };
15405                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15406                    new_selections_by_buffer.insert(
15407                        buffer,
15408                        (
15409                            vec![jump_to_offset..jump_to_offset],
15410                            Some(*line_offset_from_top),
15411                        ),
15412                    );
15413                }
15414            }
15415            Some(JumpData::MultiBufferRow {
15416                row,
15417                line_offset_from_top,
15418            }) => {
15419                let point = MultiBufferPoint::new(row.0, 0);
15420                if let Some((buffer, buffer_point, _)) =
15421                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15422                {
15423                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15424                    new_selections_by_buffer
15425                        .entry(buffer)
15426                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15427                        .0
15428                        .push(buffer_offset..buffer_offset)
15429                }
15430            }
15431            None => {
15432                let selections = self.selections.all::<usize>(cx);
15433                let multi_buffer = self.buffer.read(cx);
15434                for selection in selections {
15435                    for (snapshot, range, _, anchor) in multi_buffer
15436                        .snapshot(cx)
15437                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15438                    {
15439                        if let Some(anchor) = anchor {
15440                            // selection is in a deleted hunk
15441                            let Some(buffer_id) = anchor.buffer_id else {
15442                                continue;
15443                            };
15444                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15445                                continue;
15446                            };
15447                            let offset = text::ToOffset::to_offset(
15448                                &anchor.text_anchor,
15449                                &buffer_handle.read(cx).snapshot(),
15450                            );
15451                            let range = offset..offset;
15452                            new_selections_by_buffer
15453                                .entry(buffer_handle)
15454                                .or_insert((Vec::new(), None))
15455                                .0
15456                                .push(range)
15457                        } else {
15458                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15459                            else {
15460                                continue;
15461                            };
15462                            new_selections_by_buffer
15463                                .entry(buffer_handle)
15464                                .or_insert((Vec::new(), None))
15465                                .0
15466                                .push(range)
15467                        }
15468                    }
15469                }
15470            }
15471        }
15472
15473        if new_selections_by_buffer.is_empty() {
15474            return;
15475        }
15476
15477        // We defer the pane interaction because we ourselves are a workspace item
15478        // and activating a new item causes the pane to call a method on us reentrantly,
15479        // which panics if we're on the stack.
15480        window.defer(cx, move |window, cx| {
15481            workspace.update(cx, |workspace, cx| {
15482                let pane = if split {
15483                    workspace.adjacent_pane(window, cx)
15484                } else {
15485                    workspace.active_pane().clone()
15486                };
15487
15488                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15489                    let editor = buffer
15490                        .read(cx)
15491                        .file()
15492                        .is_none()
15493                        .then(|| {
15494                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15495                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15496                            // Instead, we try to activate the existing editor in the pane first.
15497                            let (editor, pane_item_index) =
15498                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15499                                    let editor = item.downcast::<Editor>()?;
15500                                    let singleton_buffer =
15501                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15502                                    if singleton_buffer == buffer {
15503                                        Some((editor, i))
15504                                    } else {
15505                                        None
15506                                    }
15507                                })?;
15508                            pane.update(cx, |pane, cx| {
15509                                pane.activate_item(pane_item_index, true, true, window, cx)
15510                            });
15511                            Some(editor)
15512                        })
15513                        .flatten()
15514                        .unwrap_or_else(|| {
15515                            workspace.open_project_item::<Self>(
15516                                pane.clone(),
15517                                buffer,
15518                                true,
15519                                true,
15520                                window,
15521                                cx,
15522                            )
15523                        });
15524
15525                    editor.update(cx, |editor, cx| {
15526                        let autoscroll = match scroll_offset {
15527                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15528                            None => Autoscroll::newest(),
15529                        };
15530                        let nav_history = editor.nav_history.take();
15531                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15532                            s.select_ranges(ranges);
15533                        });
15534                        editor.nav_history = nav_history;
15535                    });
15536                }
15537            })
15538        });
15539    }
15540
15541    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15542        let snapshot = self.buffer.read(cx).read(cx);
15543        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15544        Some(
15545            ranges
15546                .iter()
15547                .map(move |range| {
15548                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15549                })
15550                .collect(),
15551        )
15552    }
15553
15554    fn selection_replacement_ranges(
15555        &self,
15556        range: Range<OffsetUtf16>,
15557        cx: &mut App,
15558    ) -> Vec<Range<OffsetUtf16>> {
15559        let selections = self.selections.all::<OffsetUtf16>(cx);
15560        let newest_selection = selections
15561            .iter()
15562            .max_by_key(|selection| selection.id)
15563            .unwrap();
15564        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15565        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15566        let snapshot = self.buffer.read(cx).read(cx);
15567        selections
15568            .into_iter()
15569            .map(|mut selection| {
15570                selection.start.0 =
15571                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15572                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15573                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15574                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15575            })
15576            .collect()
15577    }
15578
15579    fn report_editor_event(
15580        &self,
15581        event_type: &'static str,
15582        file_extension: Option<String>,
15583        cx: &App,
15584    ) {
15585        if cfg!(any(test, feature = "test-support")) {
15586            return;
15587        }
15588
15589        let Some(project) = &self.project else { return };
15590
15591        // If None, we are in a file without an extension
15592        let file = self
15593            .buffer
15594            .read(cx)
15595            .as_singleton()
15596            .and_then(|b| b.read(cx).file());
15597        let file_extension = file_extension.or(file
15598            .as_ref()
15599            .and_then(|file| Path::new(file.file_name(cx)).extension())
15600            .and_then(|e| e.to_str())
15601            .map(|a| a.to_string()));
15602
15603        let vim_mode = cx
15604            .global::<SettingsStore>()
15605            .raw_user_settings()
15606            .get("vim_mode")
15607            == Some(&serde_json::Value::Bool(true));
15608
15609        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15610        let copilot_enabled = edit_predictions_provider
15611            == language::language_settings::EditPredictionProvider::Copilot;
15612        let copilot_enabled_for_language = self
15613            .buffer
15614            .read(cx)
15615            .settings_at(0, cx)
15616            .show_edit_predictions;
15617
15618        let project = project.read(cx);
15619        telemetry::event!(
15620            event_type,
15621            file_extension,
15622            vim_mode,
15623            copilot_enabled,
15624            copilot_enabled_for_language,
15625            edit_predictions_provider,
15626            is_via_ssh = project.is_via_ssh(),
15627        );
15628    }
15629
15630    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15631    /// with each line being an array of {text, highlight} objects.
15632    fn copy_highlight_json(
15633        &mut self,
15634        _: &CopyHighlightJson,
15635        window: &mut Window,
15636        cx: &mut Context<Self>,
15637    ) {
15638        #[derive(Serialize)]
15639        struct Chunk<'a> {
15640            text: String,
15641            highlight: Option<&'a str>,
15642        }
15643
15644        let snapshot = self.buffer.read(cx).snapshot(cx);
15645        let range = self
15646            .selected_text_range(false, window, cx)
15647            .and_then(|selection| {
15648                if selection.range.is_empty() {
15649                    None
15650                } else {
15651                    Some(selection.range)
15652                }
15653            })
15654            .unwrap_or_else(|| 0..snapshot.len());
15655
15656        let chunks = snapshot.chunks(range, true);
15657        let mut lines = Vec::new();
15658        let mut line: VecDeque<Chunk> = VecDeque::new();
15659
15660        let Some(style) = self.style.as_ref() else {
15661            return;
15662        };
15663
15664        for chunk in chunks {
15665            let highlight = chunk
15666                .syntax_highlight_id
15667                .and_then(|id| id.name(&style.syntax));
15668            let mut chunk_lines = chunk.text.split('\n').peekable();
15669            while let Some(text) = chunk_lines.next() {
15670                let mut merged_with_last_token = false;
15671                if let Some(last_token) = line.back_mut() {
15672                    if last_token.highlight == highlight {
15673                        last_token.text.push_str(text);
15674                        merged_with_last_token = true;
15675                    }
15676                }
15677
15678                if !merged_with_last_token {
15679                    line.push_back(Chunk {
15680                        text: text.into(),
15681                        highlight,
15682                    });
15683                }
15684
15685                if chunk_lines.peek().is_some() {
15686                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15687                        line.pop_front();
15688                    }
15689                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15690                        line.pop_back();
15691                    }
15692
15693                    lines.push(mem::take(&mut line));
15694                }
15695            }
15696        }
15697
15698        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15699            return;
15700        };
15701        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15702    }
15703
15704    pub fn open_context_menu(
15705        &mut self,
15706        _: &OpenContextMenu,
15707        window: &mut Window,
15708        cx: &mut Context<Self>,
15709    ) {
15710        self.request_autoscroll(Autoscroll::newest(), cx);
15711        let position = self.selections.newest_display(cx).start;
15712        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15713    }
15714
15715    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15716        &self.inlay_hint_cache
15717    }
15718
15719    pub fn replay_insert_event(
15720        &mut self,
15721        text: &str,
15722        relative_utf16_range: Option<Range<isize>>,
15723        window: &mut Window,
15724        cx: &mut Context<Self>,
15725    ) {
15726        if !self.input_enabled {
15727            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15728            return;
15729        }
15730        if let Some(relative_utf16_range) = relative_utf16_range {
15731            let selections = self.selections.all::<OffsetUtf16>(cx);
15732            self.change_selections(None, window, cx, |s| {
15733                let new_ranges = selections.into_iter().map(|range| {
15734                    let start = OffsetUtf16(
15735                        range
15736                            .head()
15737                            .0
15738                            .saturating_add_signed(relative_utf16_range.start),
15739                    );
15740                    let end = OffsetUtf16(
15741                        range
15742                            .head()
15743                            .0
15744                            .saturating_add_signed(relative_utf16_range.end),
15745                    );
15746                    start..end
15747                });
15748                s.select_ranges(new_ranges);
15749            });
15750        }
15751
15752        self.handle_input(text, window, cx);
15753    }
15754
15755    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15756        let Some(provider) = self.semantics_provider.as_ref() else {
15757            return false;
15758        };
15759
15760        let mut supports = false;
15761        self.buffer().update(cx, |this, cx| {
15762            this.for_each_buffer(|buffer| {
15763                supports |= provider.supports_inlay_hints(buffer, cx);
15764            });
15765        });
15766
15767        supports
15768    }
15769
15770    pub fn is_focused(&self, window: &Window) -> bool {
15771        self.focus_handle.is_focused(window)
15772    }
15773
15774    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15775        cx.emit(EditorEvent::Focused);
15776
15777        if let Some(descendant) = self
15778            .last_focused_descendant
15779            .take()
15780            .and_then(|descendant| descendant.upgrade())
15781        {
15782            window.focus(&descendant);
15783        } else {
15784            if let Some(blame) = self.blame.as_ref() {
15785                blame.update(cx, GitBlame::focus)
15786            }
15787
15788            self.blink_manager.update(cx, BlinkManager::enable);
15789            self.show_cursor_names(window, cx);
15790            self.buffer.update(cx, |buffer, cx| {
15791                buffer.finalize_last_transaction(cx);
15792                if self.leader_peer_id.is_none() {
15793                    buffer.set_active_selections(
15794                        &self.selections.disjoint_anchors(),
15795                        self.selections.line_mode,
15796                        self.cursor_shape,
15797                        cx,
15798                    );
15799                }
15800            });
15801        }
15802    }
15803
15804    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15805        cx.emit(EditorEvent::FocusedIn)
15806    }
15807
15808    fn handle_focus_out(
15809        &mut self,
15810        event: FocusOutEvent,
15811        _window: &mut Window,
15812        _cx: &mut Context<Self>,
15813    ) {
15814        if event.blurred != self.focus_handle {
15815            self.last_focused_descendant = Some(event.blurred);
15816        }
15817    }
15818
15819    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15820        self.blink_manager.update(cx, BlinkManager::disable);
15821        self.buffer
15822            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15823
15824        if let Some(blame) = self.blame.as_ref() {
15825            blame.update(cx, GitBlame::blur)
15826        }
15827        if !self.hover_state.focused(window, cx) {
15828            hide_hover(self, cx);
15829        }
15830        if !self
15831            .context_menu
15832            .borrow()
15833            .as_ref()
15834            .is_some_and(|context_menu| context_menu.focused(window, cx))
15835        {
15836            self.hide_context_menu(window, cx);
15837        }
15838        self.discard_inline_completion(false, cx);
15839        cx.emit(EditorEvent::Blurred);
15840        cx.notify();
15841    }
15842
15843    pub fn register_action<A: Action>(
15844        &mut self,
15845        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15846    ) -> Subscription {
15847        let id = self.next_editor_action_id.post_inc();
15848        let listener = Arc::new(listener);
15849        self.editor_actions.borrow_mut().insert(
15850            id,
15851            Box::new(move |window, _| {
15852                let listener = listener.clone();
15853                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15854                    let action = action.downcast_ref().unwrap();
15855                    if phase == DispatchPhase::Bubble {
15856                        listener(action, window, cx)
15857                    }
15858                })
15859            }),
15860        );
15861
15862        let editor_actions = self.editor_actions.clone();
15863        Subscription::new(move || {
15864            editor_actions.borrow_mut().remove(&id);
15865        })
15866    }
15867
15868    pub fn file_header_size(&self) -> u32 {
15869        FILE_HEADER_HEIGHT
15870    }
15871
15872    pub fn revert(
15873        &mut self,
15874        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15875        window: &mut Window,
15876        cx: &mut Context<Self>,
15877    ) {
15878        self.buffer().update(cx, |multi_buffer, cx| {
15879            for (buffer_id, changes) in revert_changes {
15880                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15881                    buffer.update(cx, |buffer, cx| {
15882                        buffer.edit(
15883                            changes.into_iter().map(|(range, text)| {
15884                                (range, text.to_string().map(Arc::<str>::from))
15885                            }),
15886                            None,
15887                            cx,
15888                        );
15889                    });
15890                }
15891            }
15892        });
15893        self.change_selections(None, window, cx, |selections| selections.refresh());
15894    }
15895
15896    pub fn to_pixel_point(
15897        &self,
15898        source: multi_buffer::Anchor,
15899        editor_snapshot: &EditorSnapshot,
15900        window: &mut Window,
15901    ) -> Option<gpui::Point<Pixels>> {
15902        let source_point = source.to_display_point(editor_snapshot);
15903        self.display_to_pixel_point(source_point, editor_snapshot, window)
15904    }
15905
15906    pub fn display_to_pixel_point(
15907        &self,
15908        source: DisplayPoint,
15909        editor_snapshot: &EditorSnapshot,
15910        window: &mut Window,
15911    ) -> Option<gpui::Point<Pixels>> {
15912        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15913        let text_layout_details = self.text_layout_details(window);
15914        let scroll_top = text_layout_details
15915            .scroll_anchor
15916            .scroll_position(editor_snapshot)
15917            .y;
15918
15919        if source.row().as_f32() < scroll_top.floor() {
15920            return None;
15921        }
15922        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15923        let source_y = line_height * (source.row().as_f32() - scroll_top);
15924        Some(gpui::Point::new(source_x, source_y))
15925    }
15926
15927    pub fn has_visible_completions_menu(&self) -> bool {
15928        !self.edit_prediction_preview_is_active()
15929            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15930                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15931            })
15932    }
15933
15934    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15935        self.addons
15936            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15937    }
15938
15939    pub fn unregister_addon<T: Addon>(&mut self) {
15940        self.addons.remove(&std::any::TypeId::of::<T>());
15941    }
15942
15943    pub fn addon<T: Addon>(&self) -> Option<&T> {
15944        let type_id = std::any::TypeId::of::<T>();
15945        self.addons
15946            .get(&type_id)
15947            .and_then(|item| item.to_any().downcast_ref::<T>())
15948    }
15949
15950    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15951        let text_layout_details = self.text_layout_details(window);
15952        let style = &text_layout_details.editor_style;
15953        let font_id = window.text_system().resolve_font(&style.text.font());
15954        let font_size = style.text.font_size.to_pixels(window.rem_size());
15955        let line_height = style.text.line_height_in_pixels(window.rem_size());
15956        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15957
15958        gpui::Size::new(em_width, line_height)
15959    }
15960
15961    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15962        self.load_diff_task.clone()
15963    }
15964
15965    fn read_selections_from_db(
15966        &mut self,
15967        item_id: u64,
15968        workspace_id: WorkspaceId,
15969        window: &mut Window,
15970        cx: &mut Context<Editor>,
15971    ) {
15972        if !self.is_singleton(cx)
15973            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15974        {
15975            return;
15976        }
15977        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15978            return;
15979        };
15980        if selections.is_empty() {
15981            return;
15982        }
15983
15984        let snapshot = self.buffer.read(cx).snapshot(cx);
15985        self.change_selections(None, window, cx, |s| {
15986            s.select_ranges(selections.into_iter().map(|(start, end)| {
15987                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15988            }));
15989        });
15990    }
15991}
15992
15993fn insert_extra_newline_brackets(
15994    buffer: &MultiBufferSnapshot,
15995    range: Range<usize>,
15996    language: &language::LanguageScope,
15997) -> bool {
15998    let leading_whitespace_len = buffer
15999        .reversed_chars_at(range.start)
16000        .take_while(|c| c.is_whitespace() && *c != '\n')
16001        .map(|c| c.len_utf8())
16002        .sum::<usize>();
16003    let trailing_whitespace_len = buffer
16004        .chars_at(range.end)
16005        .take_while(|c| c.is_whitespace() && *c != '\n')
16006        .map(|c| c.len_utf8())
16007        .sum::<usize>();
16008    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16009
16010    language.brackets().any(|(pair, enabled)| {
16011        let pair_start = pair.start.trim_end();
16012        let pair_end = pair.end.trim_start();
16013
16014        enabled
16015            && pair.newline
16016            && buffer.contains_str_at(range.end, pair_end)
16017            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16018    })
16019}
16020
16021fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16022    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16023        [(buffer, range, _)] => (*buffer, range.clone()),
16024        _ => return false,
16025    };
16026    let pair = {
16027        let mut result: Option<BracketMatch> = None;
16028
16029        for pair in buffer
16030            .all_bracket_ranges(range.clone())
16031            .filter(move |pair| {
16032                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16033            })
16034        {
16035            let len = pair.close_range.end - pair.open_range.start;
16036
16037            if let Some(existing) = &result {
16038                let existing_len = existing.close_range.end - existing.open_range.start;
16039                if len > existing_len {
16040                    continue;
16041                }
16042            }
16043
16044            result = Some(pair);
16045        }
16046
16047        result
16048    };
16049    let Some(pair) = pair else {
16050        return false;
16051    };
16052    pair.newline_only
16053        && buffer
16054            .chars_for_range(pair.open_range.end..range.start)
16055            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16056            .all(|c| c.is_whitespace() && c != '\n')
16057}
16058
16059fn get_uncommitted_diff_for_buffer(
16060    project: &Entity<Project>,
16061    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16062    buffer: Entity<MultiBuffer>,
16063    cx: &mut App,
16064) -> Task<()> {
16065    let mut tasks = Vec::new();
16066    project.update(cx, |project, cx| {
16067        for buffer in buffers {
16068            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16069        }
16070    });
16071    cx.spawn(|mut cx| async move {
16072        let diffs = futures::future::join_all(tasks).await;
16073        buffer
16074            .update(&mut cx, |buffer, cx| {
16075                for diff in diffs.into_iter().flatten() {
16076                    buffer.add_diff(diff, cx);
16077                }
16078            })
16079            .ok();
16080    })
16081}
16082
16083fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16084    let tab_size = tab_size.get() as usize;
16085    let mut width = offset;
16086
16087    for ch in text.chars() {
16088        width += if ch == '\t' {
16089            tab_size - (width % tab_size)
16090        } else {
16091            1
16092        };
16093    }
16094
16095    width - offset
16096}
16097
16098#[cfg(test)]
16099mod tests {
16100    use super::*;
16101
16102    #[test]
16103    fn test_string_size_with_expanded_tabs() {
16104        let nz = |val| NonZeroU32::new(val).unwrap();
16105        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16106        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16107        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16108        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16109        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16110        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16111        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16112        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16113    }
16114}
16115
16116/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16117struct WordBreakingTokenizer<'a> {
16118    input: &'a str,
16119}
16120
16121impl<'a> WordBreakingTokenizer<'a> {
16122    fn new(input: &'a str) -> Self {
16123        Self { input }
16124    }
16125}
16126
16127fn is_char_ideographic(ch: char) -> bool {
16128    use unicode_script::Script::*;
16129    use unicode_script::UnicodeScript;
16130    matches!(ch.script(), Han | Tangut | Yi)
16131}
16132
16133fn is_grapheme_ideographic(text: &str) -> bool {
16134    text.chars().any(is_char_ideographic)
16135}
16136
16137fn is_grapheme_whitespace(text: &str) -> bool {
16138    text.chars().any(|x| x.is_whitespace())
16139}
16140
16141fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16142    text.chars().next().map_or(false, |ch| {
16143        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16144    })
16145}
16146
16147#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16148struct WordBreakToken<'a> {
16149    token: &'a str,
16150    grapheme_len: usize,
16151    is_whitespace: bool,
16152}
16153
16154impl<'a> Iterator for WordBreakingTokenizer<'a> {
16155    /// Yields a span, the count of graphemes in the token, and whether it was
16156    /// whitespace. Note that it also breaks at word boundaries.
16157    type Item = WordBreakToken<'a>;
16158
16159    fn next(&mut self) -> Option<Self::Item> {
16160        use unicode_segmentation::UnicodeSegmentation;
16161        if self.input.is_empty() {
16162            return None;
16163        }
16164
16165        let mut iter = self.input.graphemes(true).peekable();
16166        let mut offset = 0;
16167        let mut graphemes = 0;
16168        if let Some(first_grapheme) = iter.next() {
16169            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16170            offset += first_grapheme.len();
16171            graphemes += 1;
16172            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16173                if let Some(grapheme) = iter.peek().copied() {
16174                    if should_stay_with_preceding_ideograph(grapheme) {
16175                        offset += grapheme.len();
16176                        graphemes += 1;
16177                    }
16178                }
16179            } else {
16180                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16181                let mut next_word_bound = words.peek().copied();
16182                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16183                    next_word_bound = words.next();
16184                }
16185                while let Some(grapheme) = iter.peek().copied() {
16186                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16187                        break;
16188                    };
16189                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16190                        break;
16191                    };
16192                    offset += grapheme.len();
16193                    graphemes += 1;
16194                    iter.next();
16195                }
16196            }
16197            let token = &self.input[..offset];
16198            self.input = &self.input[offset..];
16199            if is_whitespace {
16200                Some(WordBreakToken {
16201                    token: " ",
16202                    grapheme_len: 1,
16203                    is_whitespace: true,
16204                })
16205            } else {
16206                Some(WordBreakToken {
16207                    token,
16208                    grapheme_len: graphemes,
16209                    is_whitespace: false,
16210                })
16211            }
16212        } else {
16213            None
16214        }
16215    }
16216}
16217
16218#[test]
16219fn test_word_breaking_tokenizer() {
16220    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16221        ("", &[]),
16222        ("  ", &[(" ", 1, true)]),
16223        ("Ʒ", &[("Ʒ", 1, false)]),
16224        ("Ǽ", &[("Ǽ", 1, false)]),
16225        ("", &[("", 1, false)]),
16226        ("⋑⋑", &[("⋑⋑", 2, false)]),
16227        (
16228            "原理,进而",
16229            &[
16230                ("", 1, false),
16231                ("理,", 2, false),
16232                ("", 1, false),
16233                ("", 1, false),
16234            ],
16235        ),
16236        (
16237            "hello world",
16238            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16239        ),
16240        (
16241            "hello, world",
16242            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16243        ),
16244        (
16245            "  hello world",
16246            &[
16247                (" ", 1, true),
16248                ("hello", 5, false),
16249                (" ", 1, true),
16250                ("world", 5, false),
16251            ],
16252        ),
16253        (
16254            "这是什么 \n 钢笔",
16255            &[
16256                ("", 1, false),
16257                ("", 1, false),
16258                ("", 1, false),
16259                ("", 1, false),
16260                (" ", 1, true),
16261                ("", 1, false),
16262                ("", 1, false),
16263            ],
16264        ),
16265        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16266    ];
16267
16268    for (input, result) in tests {
16269        assert_eq!(
16270            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16271            result
16272                .iter()
16273                .copied()
16274                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16275                    token,
16276                    grapheme_len,
16277                    is_whitespace,
16278                })
16279                .collect::<Vec<_>>()
16280        );
16281    }
16282}
16283
16284fn wrap_with_prefix(
16285    line_prefix: String,
16286    unwrapped_text: String,
16287    wrap_column: usize,
16288    tab_size: NonZeroU32,
16289) -> String {
16290    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16291    let mut wrapped_text = String::new();
16292    let mut current_line = line_prefix.clone();
16293
16294    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16295    let mut current_line_len = line_prefix_len;
16296    for WordBreakToken {
16297        token,
16298        grapheme_len,
16299        is_whitespace,
16300    } in tokenizer
16301    {
16302        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16303            wrapped_text.push_str(current_line.trim_end());
16304            wrapped_text.push('\n');
16305            current_line.truncate(line_prefix.len());
16306            current_line_len = line_prefix_len;
16307            if !is_whitespace {
16308                current_line.push_str(token);
16309                current_line_len += grapheme_len;
16310            }
16311        } else if !is_whitespace {
16312            current_line.push_str(token);
16313            current_line_len += grapheme_len;
16314        } else if current_line_len != line_prefix_len {
16315            current_line.push(' ');
16316            current_line_len += 1;
16317        }
16318    }
16319
16320    if !current_line.is_empty() {
16321        wrapped_text.push_str(&current_line);
16322    }
16323    wrapped_text
16324}
16325
16326#[test]
16327fn test_wrap_with_prefix() {
16328    assert_eq!(
16329        wrap_with_prefix(
16330            "# ".to_string(),
16331            "abcdefg".to_string(),
16332            4,
16333            NonZeroU32::new(4).unwrap()
16334        ),
16335        "# abcdefg"
16336    );
16337    assert_eq!(
16338        wrap_with_prefix(
16339            "".to_string(),
16340            "\thello world".to_string(),
16341            8,
16342            NonZeroU32::new(4).unwrap()
16343        ),
16344        "hello\nworld"
16345    );
16346    assert_eq!(
16347        wrap_with_prefix(
16348            "// ".to_string(),
16349            "xx \nyy zz aa bb cc".to_string(),
16350            12,
16351            NonZeroU32::new(4).unwrap()
16352        ),
16353        "// xx yy zz\n// aa bb cc"
16354    );
16355    assert_eq!(
16356        wrap_with_prefix(
16357            String::new(),
16358            "这是什么 \n 钢笔".to_string(),
16359            3,
16360            NonZeroU32::new(4).unwrap()
16361        ),
16362        "这是什\n么 钢\n"
16363    );
16364}
16365
16366pub trait CollaborationHub {
16367    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16368    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16369    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16370}
16371
16372impl CollaborationHub for Entity<Project> {
16373    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16374        self.read(cx).collaborators()
16375    }
16376
16377    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16378        self.read(cx).user_store().read(cx).participant_indices()
16379    }
16380
16381    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16382        let this = self.read(cx);
16383        let user_ids = this.collaborators().values().map(|c| c.user_id);
16384        this.user_store().read_with(cx, |user_store, cx| {
16385            user_store.participant_names(user_ids, cx)
16386        })
16387    }
16388}
16389
16390pub trait SemanticsProvider {
16391    fn hover(
16392        &self,
16393        buffer: &Entity<Buffer>,
16394        position: text::Anchor,
16395        cx: &mut App,
16396    ) -> Option<Task<Vec<project::Hover>>>;
16397
16398    fn inlay_hints(
16399        &self,
16400        buffer_handle: Entity<Buffer>,
16401        range: Range<text::Anchor>,
16402        cx: &mut App,
16403    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16404
16405    fn resolve_inlay_hint(
16406        &self,
16407        hint: InlayHint,
16408        buffer_handle: Entity<Buffer>,
16409        server_id: LanguageServerId,
16410        cx: &mut App,
16411    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16412
16413    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16414
16415    fn document_highlights(
16416        &self,
16417        buffer: &Entity<Buffer>,
16418        position: text::Anchor,
16419        cx: &mut App,
16420    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16421
16422    fn definitions(
16423        &self,
16424        buffer: &Entity<Buffer>,
16425        position: text::Anchor,
16426        kind: GotoDefinitionKind,
16427        cx: &mut App,
16428    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16429
16430    fn range_for_rename(
16431        &self,
16432        buffer: &Entity<Buffer>,
16433        position: text::Anchor,
16434        cx: &mut App,
16435    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16436
16437    fn perform_rename(
16438        &self,
16439        buffer: &Entity<Buffer>,
16440        position: text::Anchor,
16441        new_name: String,
16442        cx: &mut App,
16443    ) -> Option<Task<Result<ProjectTransaction>>>;
16444}
16445
16446pub trait CompletionProvider {
16447    fn completions(
16448        &self,
16449        buffer: &Entity<Buffer>,
16450        buffer_position: text::Anchor,
16451        trigger: CompletionContext,
16452        window: &mut Window,
16453        cx: &mut Context<Editor>,
16454    ) -> Task<Result<Vec<Completion>>>;
16455
16456    fn resolve_completions(
16457        &self,
16458        buffer: Entity<Buffer>,
16459        completion_indices: Vec<usize>,
16460        completions: Rc<RefCell<Box<[Completion]>>>,
16461        cx: &mut Context<Editor>,
16462    ) -> Task<Result<bool>>;
16463
16464    fn apply_additional_edits_for_completion(
16465        &self,
16466        _buffer: Entity<Buffer>,
16467        _completions: Rc<RefCell<Box<[Completion]>>>,
16468        _completion_index: usize,
16469        _push_to_history: bool,
16470        _cx: &mut Context<Editor>,
16471    ) -> Task<Result<Option<language::Transaction>>> {
16472        Task::ready(Ok(None))
16473    }
16474
16475    fn is_completion_trigger(
16476        &self,
16477        buffer: &Entity<Buffer>,
16478        position: language::Anchor,
16479        text: &str,
16480        trigger_in_words: bool,
16481        cx: &mut Context<Editor>,
16482    ) -> bool;
16483
16484    fn sort_completions(&self) -> bool {
16485        true
16486    }
16487}
16488
16489pub trait CodeActionProvider {
16490    fn id(&self) -> Arc<str>;
16491
16492    fn code_actions(
16493        &self,
16494        buffer: &Entity<Buffer>,
16495        range: Range<text::Anchor>,
16496        window: &mut Window,
16497        cx: &mut App,
16498    ) -> Task<Result<Vec<CodeAction>>>;
16499
16500    fn apply_code_action(
16501        &self,
16502        buffer_handle: Entity<Buffer>,
16503        action: CodeAction,
16504        excerpt_id: ExcerptId,
16505        push_to_history: bool,
16506        window: &mut Window,
16507        cx: &mut App,
16508    ) -> Task<Result<ProjectTransaction>>;
16509}
16510
16511impl CodeActionProvider for Entity<Project> {
16512    fn id(&self) -> Arc<str> {
16513        "project".into()
16514    }
16515
16516    fn code_actions(
16517        &self,
16518        buffer: &Entity<Buffer>,
16519        range: Range<text::Anchor>,
16520        _window: &mut Window,
16521        cx: &mut App,
16522    ) -> Task<Result<Vec<CodeAction>>> {
16523        self.update(cx, |project, cx| {
16524            project.code_actions(buffer, range, None, cx)
16525        })
16526    }
16527
16528    fn apply_code_action(
16529        &self,
16530        buffer_handle: Entity<Buffer>,
16531        action: CodeAction,
16532        _excerpt_id: ExcerptId,
16533        push_to_history: bool,
16534        _window: &mut Window,
16535        cx: &mut App,
16536    ) -> Task<Result<ProjectTransaction>> {
16537        self.update(cx, |project, cx| {
16538            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16539        })
16540    }
16541}
16542
16543fn snippet_completions(
16544    project: &Project,
16545    buffer: &Entity<Buffer>,
16546    buffer_position: text::Anchor,
16547    cx: &mut App,
16548) -> Task<Result<Vec<Completion>>> {
16549    let language = buffer.read(cx).language_at(buffer_position);
16550    let language_name = language.as_ref().map(|language| language.lsp_id());
16551    let snippet_store = project.snippets().read(cx);
16552    let snippets = snippet_store.snippets_for(language_name, cx);
16553
16554    if snippets.is_empty() {
16555        return Task::ready(Ok(vec![]));
16556    }
16557    let snapshot = buffer.read(cx).text_snapshot();
16558    let chars: String = snapshot
16559        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16560        .collect();
16561
16562    let scope = language.map(|language| language.default_scope());
16563    let executor = cx.background_executor().clone();
16564
16565    cx.background_spawn(async move {
16566        let classifier = CharClassifier::new(scope).for_completion(true);
16567        let mut last_word = chars
16568            .chars()
16569            .take_while(|c| classifier.is_word(*c))
16570            .collect::<String>();
16571        last_word = last_word.chars().rev().collect();
16572
16573        if last_word.is_empty() {
16574            return Ok(vec![]);
16575        }
16576
16577        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16578        let to_lsp = |point: &text::Anchor| {
16579            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16580            point_to_lsp(end)
16581        };
16582        let lsp_end = to_lsp(&buffer_position);
16583
16584        let candidates = snippets
16585            .iter()
16586            .enumerate()
16587            .flat_map(|(ix, snippet)| {
16588                snippet
16589                    .prefix
16590                    .iter()
16591                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16592            })
16593            .collect::<Vec<StringMatchCandidate>>();
16594
16595        let mut matches = fuzzy::match_strings(
16596            &candidates,
16597            &last_word,
16598            last_word.chars().any(|c| c.is_uppercase()),
16599            100,
16600            &Default::default(),
16601            executor,
16602        )
16603        .await;
16604
16605        // Remove all candidates where the query's start does not match the start of any word in the candidate
16606        if let Some(query_start) = last_word.chars().next() {
16607            matches.retain(|string_match| {
16608                split_words(&string_match.string).any(|word| {
16609                    // Check that the first codepoint of the word as lowercase matches the first
16610                    // codepoint of the query as lowercase
16611                    word.chars()
16612                        .flat_map(|codepoint| codepoint.to_lowercase())
16613                        .zip(query_start.to_lowercase())
16614                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16615                })
16616            });
16617        }
16618
16619        let matched_strings = matches
16620            .into_iter()
16621            .map(|m| m.string)
16622            .collect::<HashSet<_>>();
16623
16624        let result: Vec<Completion> = snippets
16625            .into_iter()
16626            .filter_map(|snippet| {
16627                let matching_prefix = snippet
16628                    .prefix
16629                    .iter()
16630                    .find(|prefix| matched_strings.contains(*prefix))?;
16631                let start = as_offset - last_word.len();
16632                let start = snapshot.anchor_before(start);
16633                let range = start..buffer_position;
16634                let lsp_start = to_lsp(&start);
16635                let lsp_range = lsp::Range {
16636                    start: lsp_start,
16637                    end: lsp_end,
16638                };
16639                Some(Completion {
16640                    old_range: range,
16641                    new_text: snippet.body.clone(),
16642                    resolved: false,
16643                    label: CodeLabel {
16644                        text: matching_prefix.clone(),
16645                        runs: vec![],
16646                        filter_range: 0..matching_prefix.len(),
16647                    },
16648                    server_id: LanguageServerId(usize::MAX),
16649                    documentation: snippet
16650                        .description
16651                        .clone()
16652                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16653                    lsp_completion: lsp::CompletionItem {
16654                        label: snippet.prefix.first().unwrap().clone(),
16655                        kind: Some(CompletionItemKind::SNIPPET),
16656                        label_details: snippet.description.as_ref().map(|description| {
16657                            lsp::CompletionItemLabelDetails {
16658                                detail: Some(description.clone()),
16659                                description: None,
16660                            }
16661                        }),
16662                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16663                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16664                            lsp::InsertReplaceEdit {
16665                                new_text: snippet.body.clone(),
16666                                insert: lsp_range,
16667                                replace: lsp_range,
16668                            },
16669                        )),
16670                        filter_text: Some(snippet.body.clone()),
16671                        sort_text: Some(char::MAX.to_string()),
16672                        ..Default::default()
16673                    },
16674                    confirm: None,
16675                })
16676            })
16677            .collect();
16678
16679        Ok(result)
16680    })
16681}
16682
16683impl CompletionProvider for Entity<Project> {
16684    fn completions(
16685        &self,
16686        buffer: &Entity<Buffer>,
16687        buffer_position: text::Anchor,
16688        options: CompletionContext,
16689        _window: &mut Window,
16690        cx: &mut Context<Editor>,
16691    ) -> Task<Result<Vec<Completion>>> {
16692        self.update(cx, |project, cx| {
16693            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16694            let project_completions = project.completions(buffer, buffer_position, options, cx);
16695            cx.background_spawn(async move {
16696                let mut completions = project_completions.await?;
16697                let snippets_completions = snippets.await?;
16698                completions.extend(snippets_completions);
16699                Ok(completions)
16700            })
16701        })
16702    }
16703
16704    fn resolve_completions(
16705        &self,
16706        buffer: Entity<Buffer>,
16707        completion_indices: Vec<usize>,
16708        completions: Rc<RefCell<Box<[Completion]>>>,
16709        cx: &mut Context<Editor>,
16710    ) -> Task<Result<bool>> {
16711        self.update(cx, |project, cx| {
16712            project.lsp_store().update(cx, |lsp_store, cx| {
16713                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16714            })
16715        })
16716    }
16717
16718    fn apply_additional_edits_for_completion(
16719        &self,
16720        buffer: Entity<Buffer>,
16721        completions: Rc<RefCell<Box<[Completion]>>>,
16722        completion_index: usize,
16723        push_to_history: bool,
16724        cx: &mut Context<Editor>,
16725    ) -> Task<Result<Option<language::Transaction>>> {
16726        self.update(cx, |project, cx| {
16727            project.lsp_store().update(cx, |lsp_store, cx| {
16728                lsp_store.apply_additional_edits_for_completion(
16729                    buffer,
16730                    completions,
16731                    completion_index,
16732                    push_to_history,
16733                    cx,
16734                )
16735            })
16736        })
16737    }
16738
16739    fn is_completion_trigger(
16740        &self,
16741        buffer: &Entity<Buffer>,
16742        position: language::Anchor,
16743        text: &str,
16744        trigger_in_words: bool,
16745        cx: &mut Context<Editor>,
16746    ) -> bool {
16747        let mut chars = text.chars();
16748        let char = if let Some(char) = chars.next() {
16749            char
16750        } else {
16751            return false;
16752        };
16753        if chars.next().is_some() {
16754            return false;
16755        }
16756
16757        let buffer = buffer.read(cx);
16758        let snapshot = buffer.snapshot();
16759        if !snapshot.settings_at(position, cx).show_completions_on_input {
16760            return false;
16761        }
16762        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16763        if trigger_in_words && classifier.is_word(char) {
16764            return true;
16765        }
16766
16767        buffer.completion_triggers().contains(text)
16768    }
16769}
16770
16771impl SemanticsProvider for Entity<Project> {
16772    fn hover(
16773        &self,
16774        buffer: &Entity<Buffer>,
16775        position: text::Anchor,
16776        cx: &mut App,
16777    ) -> Option<Task<Vec<project::Hover>>> {
16778        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16779    }
16780
16781    fn document_highlights(
16782        &self,
16783        buffer: &Entity<Buffer>,
16784        position: text::Anchor,
16785        cx: &mut App,
16786    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16787        Some(self.update(cx, |project, cx| {
16788            project.document_highlights(buffer, position, cx)
16789        }))
16790    }
16791
16792    fn definitions(
16793        &self,
16794        buffer: &Entity<Buffer>,
16795        position: text::Anchor,
16796        kind: GotoDefinitionKind,
16797        cx: &mut App,
16798    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16799        Some(self.update(cx, |project, cx| match kind {
16800            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16801            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16802            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16803            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16804        }))
16805    }
16806
16807    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16808        // TODO: make this work for remote projects
16809        self.update(cx, |this, cx| {
16810            buffer.update(cx, |buffer, cx| {
16811                this.any_language_server_supports_inlay_hints(buffer, cx)
16812            })
16813        })
16814    }
16815
16816    fn inlay_hints(
16817        &self,
16818        buffer_handle: Entity<Buffer>,
16819        range: Range<text::Anchor>,
16820        cx: &mut App,
16821    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16822        Some(self.update(cx, |project, cx| {
16823            project.inlay_hints(buffer_handle, range, cx)
16824        }))
16825    }
16826
16827    fn resolve_inlay_hint(
16828        &self,
16829        hint: InlayHint,
16830        buffer_handle: Entity<Buffer>,
16831        server_id: LanguageServerId,
16832        cx: &mut App,
16833    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16834        Some(self.update(cx, |project, cx| {
16835            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16836        }))
16837    }
16838
16839    fn range_for_rename(
16840        &self,
16841        buffer: &Entity<Buffer>,
16842        position: text::Anchor,
16843        cx: &mut App,
16844    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16845        Some(self.update(cx, |project, cx| {
16846            let buffer = buffer.clone();
16847            let task = project.prepare_rename(buffer.clone(), position, cx);
16848            cx.spawn(|_, mut cx| async move {
16849                Ok(match task.await? {
16850                    PrepareRenameResponse::Success(range) => Some(range),
16851                    PrepareRenameResponse::InvalidPosition => None,
16852                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16853                        // Fallback on using TreeSitter info to determine identifier range
16854                        buffer.update(&mut cx, |buffer, _| {
16855                            let snapshot = buffer.snapshot();
16856                            let (range, kind) = snapshot.surrounding_word(position);
16857                            if kind != Some(CharKind::Word) {
16858                                return None;
16859                            }
16860                            Some(
16861                                snapshot.anchor_before(range.start)
16862                                    ..snapshot.anchor_after(range.end),
16863                            )
16864                        })?
16865                    }
16866                })
16867            })
16868        }))
16869    }
16870
16871    fn perform_rename(
16872        &self,
16873        buffer: &Entity<Buffer>,
16874        position: text::Anchor,
16875        new_name: String,
16876        cx: &mut App,
16877    ) -> Option<Task<Result<ProjectTransaction>>> {
16878        Some(self.update(cx, |project, cx| {
16879            project.perform_rename(buffer.clone(), position, new_name, cx)
16880        }))
16881    }
16882}
16883
16884fn inlay_hint_settings(
16885    location: Anchor,
16886    snapshot: &MultiBufferSnapshot,
16887    cx: &mut Context<Editor>,
16888) -> InlayHintSettings {
16889    let file = snapshot.file_at(location);
16890    let language = snapshot.language_at(location).map(|l| l.name());
16891    language_settings(language, file, cx).inlay_hints
16892}
16893
16894fn consume_contiguous_rows(
16895    contiguous_row_selections: &mut Vec<Selection<Point>>,
16896    selection: &Selection<Point>,
16897    display_map: &DisplaySnapshot,
16898    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16899) -> (MultiBufferRow, MultiBufferRow) {
16900    contiguous_row_selections.push(selection.clone());
16901    let start_row = MultiBufferRow(selection.start.row);
16902    let mut end_row = ending_row(selection, display_map);
16903
16904    while let Some(next_selection) = selections.peek() {
16905        if next_selection.start.row <= end_row.0 {
16906            end_row = ending_row(next_selection, display_map);
16907            contiguous_row_selections.push(selections.next().unwrap().clone());
16908        } else {
16909            break;
16910        }
16911    }
16912    (start_row, end_row)
16913}
16914
16915fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16916    if next_selection.end.column > 0 || next_selection.is_empty() {
16917        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16918    } else {
16919        MultiBufferRow(next_selection.end.row)
16920    }
16921}
16922
16923impl EditorSnapshot {
16924    pub fn remote_selections_in_range<'a>(
16925        &'a self,
16926        range: &'a Range<Anchor>,
16927        collaboration_hub: &dyn CollaborationHub,
16928        cx: &'a App,
16929    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16930        let participant_names = collaboration_hub.user_names(cx);
16931        let participant_indices = collaboration_hub.user_participant_indices(cx);
16932        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16933        let collaborators_by_replica_id = collaborators_by_peer_id
16934            .iter()
16935            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16936            .collect::<HashMap<_, _>>();
16937        self.buffer_snapshot
16938            .selections_in_range(range, false)
16939            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16940                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16941                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16942                let user_name = participant_names.get(&collaborator.user_id).cloned();
16943                Some(RemoteSelection {
16944                    replica_id,
16945                    selection,
16946                    cursor_shape,
16947                    line_mode,
16948                    participant_index,
16949                    peer_id: collaborator.peer_id,
16950                    user_name,
16951                })
16952            })
16953    }
16954
16955    pub fn hunks_for_ranges(
16956        &self,
16957        ranges: impl Iterator<Item = Range<Point>>,
16958    ) -> Vec<MultiBufferDiffHunk> {
16959        let mut hunks = Vec::new();
16960        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16961            HashMap::default();
16962        for query_range in ranges {
16963            let query_rows =
16964                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16965            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16966                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16967            ) {
16968                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16969                // when the caret is just above or just below the deleted hunk.
16970                let allow_adjacent = hunk.status().is_deleted();
16971                let related_to_selection = if allow_adjacent {
16972                    hunk.row_range.overlaps(&query_rows)
16973                        || hunk.row_range.start == query_rows.end
16974                        || hunk.row_range.end == query_rows.start
16975                } else {
16976                    hunk.row_range.overlaps(&query_rows)
16977                };
16978                if related_to_selection {
16979                    if !processed_buffer_rows
16980                        .entry(hunk.buffer_id)
16981                        .or_default()
16982                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16983                    {
16984                        continue;
16985                    }
16986                    hunks.push(hunk);
16987                }
16988            }
16989        }
16990
16991        hunks
16992    }
16993
16994    fn display_diff_hunks_for_rows<'a>(
16995        &'a self,
16996        display_rows: Range<DisplayRow>,
16997        folded_buffers: &'a HashSet<BufferId>,
16998    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
16999        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17000        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17001
17002        self.buffer_snapshot
17003            .diff_hunks_in_range(buffer_start..buffer_end)
17004            .filter_map(|hunk| {
17005                if folded_buffers.contains(&hunk.buffer_id) {
17006                    return None;
17007                }
17008
17009                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17010                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17011
17012                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17013                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17014
17015                let display_hunk = if hunk_display_start.column() != 0 {
17016                    DisplayDiffHunk::Folded {
17017                        display_row: hunk_display_start.row(),
17018                    }
17019                } else {
17020                    let mut end_row = hunk_display_end.row();
17021                    if hunk_display_end.column() > 0 {
17022                        end_row.0 += 1;
17023                    }
17024                    DisplayDiffHunk::Unfolded {
17025                        status: hunk.status(),
17026                        diff_base_byte_range: hunk.diff_base_byte_range,
17027                        display_row_range: hunk_display_start.row()..end_row,
17028                        multi_buffer_range: Anchor::range_in_buffer(
17029                            hunk.excerpt_id,
17030                            hunk.buffer_id,
17031                            hunk.buffer_range,
17032                        ),
17033                    }
17034                };
17035
17036                Some(display_hunk)
17037            })
17038    }
17039
17040    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17041        self.display_snapshot.buffer_snapshot.language_at(position)
17042    }
17043
17044    pub fn is_focused(&self) -> bool {
17045        self.is_focused
17046    }
17047
17048    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17049        self.placeholder_text.as_ref()
17050    }
17051
17052    pub fn scroll_position(&self) -> gpui::Point<f32> {
17053        self.scroll_anchor.scroll_position(&self.display_snapshot)
17054    }
17055
17056    fn gutter_dimensions(
17057        &self,
17058        font_id: FontId,
17059        font_size: Pixels,
17060        max_line_number_width: Pixels,
17061        cx: &App,
17062    ) -> Option<GutterDimensions> {
17063        if !self.show_gutter {
17064            return None;
17065        }
17066
17067        let descent = cx.text_system().descent(font_id, font_size);
17068        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17069        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17070
17071        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17072            matches!(
17073                ProjectSettings::get_global(cx).git.git_gutter,
17074                Some(GitGutterSetting::TrackedFiles)
17075            )
17076        });
17077        let gutter_settings = EditorSettings::get_global(cx).gutter;
17078        let show_line_numbers = self
17079            .show_line_numbers
17080            .unwrap_or(gutter_settings.line_numbers);
17081        let line_gutter_width = if show_line_numbers {
17082            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17083            let min_width_for_number_on_gutter = em_advance * 4.0;
17084            max_line_number_width.max(min_width_for_number_on_gutter)
17085        } else {
17086            0.0.into()
17087        };
17088
17089        let show_code_actions = self
17090            .show_code_actions
17091            .unwrap_or(gutter_settings.code_actions);
17092
17093        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17094
17095        let git_blame_entries_width =
17096            self.git_blame_gutter_max_author_length
17097                .map(|max_author_length| {
17098                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17099
17100                    /// The number of characters to dedicate to gaps and margins.
17101                    const SPACING_WIDTH: usize = 4;
17102
17103                    let max_char_count = max_author_length
17104                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17105                        + ::git::SHORT_SHA_LENGTH
17106                        + MAX_RELATIVE_TIMESTAMP.len()
17107                        + SPACING_WIDTH;
17108
17109                    em_advance * max_char_count
17110                });
17111
17112        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17113        left_padding += if show_code_actions || show_runnables {
17114            em_width * 3.0
17115        } else if show_git_gutter && show_line_numbers {
17116            em_width * 2.0
17117        } else if show_git_gutter || show_line_numbers {
17118            em_width
17119        } else {
17120            px(0.)
17121        };
17122
17123        let right_padding = if gutter_settings.folds && show_line_numbers {
17124            em_width * 4.0
17125        } else if gutter_settings.folds {
17126            em_width * 3.0
17127        } else if show_line_numbers {
17128            em_width
17129        } else {
17130            px(0.)
17131        };
17132
17133        Some(GutterDimensions {
17134            left_padding,
17135            right_padding,
17136            width: line_gutter_width + left_padding + right_padding,
17137            margin: -descent,
17138            git_blame_entries_width,
17139        })
17140    }
17141
17142    pub fn render_crease_toggle(
17143        &self,
17144        buffer_row: MultiBufferRow,
17145        row_contains_cursor: bool,
17146        editor: Entity<Editor>,
17147        window: &mut Window,
17148        cx: &mut App,
17149    ) -> Option<AnyElement> {
17150        let folded = self.is_line_folded(buffer_row);
17151        let mut is_foldable = false;
17152
17153        if let Some(crease) = self
17154            .crease_snapshot
17155            .query_row(buffer_row, &self.buffer_snapshot)
17156        {
17157            is_foldable = true;
17158            match crease {
17159                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17160                    if let Some(render_toggle) = render_toggle {
17161                        let toggle_callback =
17162                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17163                                if folded {
17164                                    editor.update(cx, |editor, cx| {
17165                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17166                                    });
17167                                } else {
17168                                    editor.update(cx, |editor, cx| {
17169                                        editor.unfold_at(
17170                                            &crate::UnfoldAt { buffer_row },
17171                                            window,
17172                                            cx,
17173                                        )
17174                                    });
17175                                }
17176                            });
17177                        return Some((render_toggle)(
17178                            buffer_row,
17179                            folded,
17180                            toggle_callback,
17181                            window,
17182                            cx,
17183                        ));
17184                    }
17185                }
17186            }
17187        }
17188
17189        is_foldable |= self.starts_indent(buffer_row);
17190
17191        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17192            Some(
17193                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17194                    .toggle_state(folded)
17195                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17196                        if folded {
17197                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17198                        } else {
17199                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17200                        }
17201                    }))
17202                    .into_any_element(),
17203            )
17204        } else {
17205            None
17206        }
17207    }
17208
17209    pub fn render_crease_trailer(
17210        &self,
17211        buffer_row: MultiBufferRow,
17212        window: &mut Window,
17213        cx: &mut App,
17214    ) -> Option<AnyElement> {
17215        let folded = self.is_line_folded(buffer_row);
17216        if let Crease::Inline { render_trailer, .. } = self
17217            .crease_snapshot
17218            .query_row(buffer_row, &self.buffer_snapshot)?
17219        {
17220            let render_trailer = render_trailer.as_ref()?;
17221            Some(render_trailer(buffer_row, folded, window, cx))
17222        } else {
17223            None
17224        }
17225    }
17226}
17227
17228impl Deref for EditorSnapshot {
17229    type Target = DisplaySnapshot;
17230
17231    fn deref(&self) -> &Self::Target {
17232        &self.display_snapshot
17233    }
17234}
17235
17236#[derive(Clone, Debug, PartialEq, Eq)]
17237pub enum EditorEvent {
17238    InputIgnored {
17239        text: Arc<str>,
17240    },
17241    InputHandled {
17242        utf16_range_to_replace: Option<Range<isize>>,
17243        text: Arc<str>,
17244    },
17245    ExcerptsAdded {
17246        buffer: Entity<Buffer>,
17247        predecessor: ExcerptId,
17248        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17249    },
17250    ExcerptsRemoved {
17251        ids: Vec<ExcerptId>,
17252    },
17253    BufferFoldToggled {
17254        ids: Vec<ExcerptId>,
17255        folded: bool,
17256    },
17257    ExcerptsEdited {
17258        ids: Vec<ExcerptId>,
17259    },
17260    ExcerptsExpanded {
17261        ids: Vec<ExcerptId>,
17262    },
17263    BufferEdited,
17264    Edited {
17265        transaction_id: clock::Lamport,
17266    },
17267    Reparsed(BufferId),
17268    Focused,
17269    FocusedIn,
17270    Blurred,
17271    DirtyChanged,
17272    Saved,
17273    TitleChanged,
17274    DiffBaseChanged,
17275    SelectionsChanged {
17276        local: bool,
17277    },
17278    ScrollPositionChanged {
17279        local: bool,
17280        autoscroll: bool,
17281    },
17282    Closed,
17283    TransactionUndone {
17284        transaction_id: clock::Lamport,
17285    },
17286    TransactionBegun {
17287        transaction_id: clock::Lamport,
17288    },
17289    Reloaded,
17290    CursorShapeChanged,
17291}
17292
17293impl EventEmitter<EditorEvent> for Editor {}
17294
17295impl Focusable for Editor {
17296    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17297        self.focus_handle.clone()
17298    }
17299}
17300
17301impl Render for Editor {
17302    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17303        let settings = ThemeSettings::get_global(cx);
17304
17305        let mut text_style = match self.mode {
17306            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17307                color: cx.theme().colors().editor_foreground,
17308                font_family: settings.ui_font.family.clone(),
17309                font_features: settings.ui_font.features.clone(),
17310                font_fallbacks: settings.ui_font.fallbacks.clone(),
17311                font_size: rems(0.875).into(),
17312                font_weight: settings.ui_font.weight,
17313                line_height: relative(settings.buffer_line_height.value()),
17314                ..Default::default()
17315            },
17316            EditorMode::Full => TextStyle {
17317                color: cx.theme().colors().editor_foreground,
17318                font_family: settings.buffer_font.family.clone(),
17319                font_features: settings.buffer_font.features.clone(),
17320                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17321                font_size: settings.buffer_font_size(cx).into(),
17322                font_weight: settings.buffer_font.weight,
17323                line_height: relative(settings.buffer_line_height.value()),
17324                ..Default::default()
17325            },
17326        };
17327        if let Some(text_style_refinement) = &self.text_style_refinement {
17328            text_style.refine(text_style_refinement)
17329        }
17330
17331        let background = match self.mode {
17332            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17333            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17334            EditorMode::Full => cx.theme().colors().editor_background,
17335        };
17336
17337        EditorElement::new(
17338            &cx.entity(),
17339            EditorStyle {
17340                background,
17341                local_player: cx.theme().players().local(),
17342                text: text_style,
17343                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17344                syntax: cx.theme().syntax().clone(),
17345                status: cx.theme().status().clone(),
17346                inlay_hints_style: make_inlay_hints_style(cx),
17347                inline_completion_styles: make_suggestion_styles(cx),
17348                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17349            },
17350        )
17351    }
17352}
17353
17354impl EntityInputHandler for Editor {
17355    fn text_for_range(
17356        &mut self,
17357        range_utf16: Range<usize>,
17358        adjusted_range: &mut Option<Range<usize>>,
17359        _: &mut Window,
17360        cx: &mut Context<Self>,
17361    ) -> Option<String> {
17362        let snapshot = self.buffer.read(cx).read(cx);
17363        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17364        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17365        if (start.0..end.0) != range_utf16 {
17366            adjusted_range.replace(start.0..end.0);
17367        }
17368        Some(snapshot.text_for_range(start..end).collect())
17369    }
17370
17371    fn selected_text_range(
17372        &mut self,
17373        ignore_disabled_input: bool,
17374        _: &mut Window,
17375        cx: &mut Context<Self>,
17376    ) -> Option<UTF16Selection> {
17377        // Prevent the IME menu from appearing when holding down an alphabetic key
17378        // while input is disabled.
17379        if !ignore_disabled_input && !self.input_enabled {
17380            return None;
17381        }
17382
17383        let selection = self.selections.newest::<OffsetUtf16>(cx);
17384        let range = selection.range();
17385
17386        Some(UTF16Selection {
17387            range: range.start.0..range.end.0,
17388            reversed: selection.reversed,
17389        })
17390    }
17391
17392    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17393        let snapshot = self.buffer.read(cx).read(cx);
17394        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17395        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17396    }
17397
17398    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17399        self.clear_highlights::<InputComposition>(cx);
17400        self.ime_transaction.take();
17401    }
17402
17403    fn replace_text_in_range(
17404        &mut self,
17405        range_utf16: Option<Range<usize>>,
17406        text: &str,
17407        window: &mut Window,
17408        cx: &mut Context<Self>,
17409    ) {
17410        if !self.input_enabled {
17411            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17412            return;
17413        }
17414
17415        self.transact(window, cx, |this, window, cx| {
17416            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17417                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17418                Some(this.selection_replacement_ranges(range_utf16, cx))
17419            } else {
17420                this.marked_text_ranges(cx)
17421            };
17422
17423            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17424                let newest_selection_id = this.selections.newest_anchor().id;
17425                this.selections
17426                    .all::<OffsetUtf16>(cx)
17427                    .iter()
17428                    .zip(ranges_to_replace.iter())
17429                    .find_map(|(selection, range)| {
17430                        if selection.id == newest_selection_id {
17431                            Some(
17432                                (range.start.0 as isize - selection.head().0 as isize)
17433                                    ..(range.end.0 as isize - selection.head().0 as isize),
17434                            )
17435                        } else {
17436                            None
17437                        }
17438                    })
17439            });
17440
17441            cx.emit(EditorEvent::InputHandled {
17442                utf16_range_to_replace: range_to_replace,
17443                text: text.into(),
17444            });
17445
17446            if let Some(new_selected_ranges) = new_selected_ranges {
17447                this.change_selections(None, window, cx, |selections| {
17448                    selections.select_ranges(new_selected_ranges)
17449                });
17450                this.backspace(&Default::default(), window, cx);
17451            }
17452
17453            this.handle_input(text, window, cx);
17454        });
17455
17456        if let Some(transaction) = self.ime_transaction {
17457            self.buffer.update(cx, |buffer, cx| {
17458                buffer.group_until_transaction(transaction, cx);
17459            });
17460        }
17461
17462        self.unmark_text(window, cx);
17463    }
17464
17465    fn replace_and_mark_text_in_range(
17466        &mut self,
17467        range_utf16: Option<Range<usize>>,
17468        text: &str,
17469        new_selected_range_utf16: Option<Range<usize>>,
17470        window: &mut Window,
17471        cx: &mut Context<Self>,
17472    ) {
17473        if !self.input_enabled {
17474            return;
17475        }
17476
17477        let transaction = self.transact(window, cx, |this, window, cx| {
17478            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17479                let snapshot = this.buffer.read(cx).read(cx);
17480                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17481                    for marked_range in &mut marked_ranges {
17482                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17483                        marked_range.start.0 += relative_range_utf16.start;
17484                        marked_range.start =
17485                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17486                        marked_range.end =
17487                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17488                    }
17489                }
17490                Some(marked_ranges)
17491            } else if let Some(range_utf16) = range_utf16 {
17492                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17493                Some(this.selection_replacement_ranges(range_utf16, cx))
17494            } else {
17495                None
17496            };
17497
17498            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17499                let newest_selection_id = this.selections.newest_anchor().id;
17500                this.selections
17501                    .all::<OffsetUtf16>(cx)
17502                    .iter()
17503                    .zip(ranges_to_replace.iter())
17504                    .find_map(|(selection, range)| {
17505                        if selection.id == newest_selection_id {
17506                            Some(
17507                                (range.start.0 as isize - selection.head().0 as isize)
17508                                    ..(range.end.0 as isize - selection.head().0 as isize),
17509                            )
17510                        } else {
17511                            None
17512                        }
17513                    })
17514            });
17515
17516            cx.emit(EditorEvent::InputHandled {
17517                utf16_range_to_replace: range_to_replace,
17518                text: text.into(),
17519            });
17520
17521            if let Some(ranges) = ranges_to_replace {
17522                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17523            }
17524
17525            let marked_ranges = {
17526                let snapshot = this.buffer.read(cx).read(cx);
17527                this.selections
17528                    .disjoint_anchors()
17529                    .iter()
17530                    .map(|selection| {
17531                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17532                    })
17533                    .collect::<Vec<_>>()
17534            };
17535
17536            if text.is_empty() {
17537                this.unmark_text(window, cx);
17538            } else {
17539                this.highlight_text::<InputComposition>(
17540                    marked_ranges.clone(),
17541                    HighlightStyle {
17542                        underline: Some(UnderlineStyle {
17543                            thickness: px(1.),
17544                            color: None,
17545                            wavy: false,
17546                        }),
17547                        ..Default::default()
17548                    },
17549                    cx,
17550                );
17551            }
17552
17553            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17554            let use_autoclose = this.use_autoclose;
17555            let use_auto_surround = this.use_auto_surround;
17556            this.set_use_autoclose(false);
17557            this.set_use_auto_surround(false);
17558            this.handle_input(text, window, cx);
17559            this.set_use_autoclose(use_autoclose);
17560            this.set_use_auto_surround(use_auto_surround);
17561
17562            if let Some(new_selected_range) = new_selected_range_utf16 {
17563                let snapshot = this.buffer.read(cx).read(cx);
17564                let new_selected_ranges = marked_ranges
17565                    .into_iter()
17566                    .map(|marked_range| {
17567                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17568                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17569                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17570                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17571                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17572                    })
17573                    .collect::<Vec<_>>();
17574
17575                drop(snapshot);
17576                this.change_selections(None, window, cx, |selections| {
17577                    selections.select_ranges(new_selected_ranges)
17578                });
17579            }
17580        });
17581
17582        self.ime_transaction = self.ime_transaction.or(transaction);
17583        if let Some(transaction) = self.ime_transaction {
17584            self.buffer.update(cx, |buffer, cx| {
17585                buffer.group_until_transaction(transaction, cx);
17586            });
17587        }
17588
17589        if self.text_highlights::<InputComposition>(cx).is_none() {
17590            self.ime_transaction.take();
17591        }
17592    }
17593
17594    fn bounds_for_range(
17595        &mut self,
17596        range_utf16: Range<usize>,
17597        element_bounds: gpui::Bounds<Pixels>,
17598        window: &mut Window,
17599        cx: &mut Context<Self>,
17600    ) -> Option<gpui::Bounds<Pixels>> {
17601        let text_layout_details = self.text_layout_details(window);
17602        let gpui::Size {
17603            width: em_width,
17604            height: line_height,
17605        } = self.character_size(window);
17606
17607        let snapshot = self.snapshot(window, cx);
17608        let scroll_position = snapshot.scroll_position();
17609        let scroll_left = scroll_position.x * em_width;
17610
17611        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17612        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17613            + self.gutter_dimensions.width
17614            + self.gutter_dimensions.margin;
17615        let y = line_height * (start.row().as_f32() - scroll_position.y);
17616
17617        Some(Bounds {
17618            origin: element_bounds.origin + point(x, y),
17619            size: size(em_width, line_height),
17620        })
17621    }
17622
17623    fn character_index_for_point(
17624        &mut self,
17625        point: gpui::Point<Pixels>,
17626        _window: &mut Window,
17627        _cx: &mut Context<Self>,
17628    ) -> Option<usize> {
17629        let position_map = self.last_position_map.as_ref()?;
17630        if !position_map.text_hitbox.contains(&point) {
17631            return None;
17632        }
17633        let display_point = position_map.point_for_position(point).previous_valid;
17634        let anchor = position_map
17635            .snapshot
17636            .display_point_to_anchor(display_point, Bias::Left);
17637        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17638        Some(utf16_offset.0)
17639    }
17640}
17641
17642trait SelectionExt {
17643    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17644    fn spanned_rows(
17645        &self,
17646        include_end_if_at_line_start: bool,
17647        map: &DisplaySnapshot,
17648    ) -> Range<MultiBufferRow>;
17649}
17650
17651impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17652    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17653        let start = self
17654            .start
17655            .to_point(&map.buffer_snapshot)
17656            .to_display_point(map);
17657        let end = self
17658            .end
17659            .to_point(&map.buffer_snapshot)
17660            .to_display_point(map);
17661        if self.reversed {
17662            end..start
17663        } else {
17664            start..end
17665        }
17666    }
17667
17668    fn spanned_rows(
17669        &self,
17670        include_end_if_at_line_start: bool,
17671        map: &DisplaySnapshot,
17672    ) -> Range<MultiBufferRow> {
17673        let start = self.start.to_point(&map.buffer_snapshot);
17674        let mut end = self.end.to_point(&map.buffer_snapshot);
17675        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17676            end.row -= 1;
17677        }
17678
17679        let buffer_start = map.prev_line_boundary(start).0;
17680        let buffer_end = map.next_line_boundary(end).0;
17681        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17682    }
17683}
17684
17685impl<T: InvalidationRegion> InvalidationStack<T> {
17686    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17687    where
17688        S: Clone + ToOffset,
17689    {
17690        while let Some(region) = self.last() {
17691            let all_selections_inside_invalidation_ranges =
17692                if selections.len() == region.ranges().len() {
17693                    selections
17694                        .iter()
17695                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17696                        .all(|(selection, invalidation_range)| {
17697                            let head = selection.head().to_offset(buffer);
17698                            invalidation_range.start <= head && invalidation_range.end >= head
17699                        })
17700                } else {
17701                    false
17702                };
17703
17704            if all_selections_inside_invalidation_ranges {
17705                break;
17706            } else {
17707                self.pop();
17708            }
17709        }
17710    }
17711}
17712
17713impl<T> Default for InvalidationStack<T> {
17714    fn default() -> Self {
17715        Self(Default::default())
17716    }
17717}
17718
17719impl<T> Deref for InvalidationStack<T> {
17720    type Target = Vec<T>;
17721
17722    fn deref(&self) -> &Self::Target {
17723        &self.0
17724    }
17725}
17726
17727impl<T> DerefMut for InvalidationStack<T> {
17728    fn deref_mut(&mut self) -> &mut Self::Target {
17729        &mut self.0
17730    }
17731}
17732
17733impl InvalidationRegion for SnippetState {
17734    fn ranges(&self) -> &[Range<Anchor>] {
17735        &self.ranges[self.active_index]
17736    }
17737}
17738
17739pub fn diagnostic_block_renderer(
17740    diagnostic: Diagnostic,
17741    max_message_rows: Option<u8>,
17742    allow_closing: bool,
17743    _is_valid: bool,
17744) -> RenderBlock {
17745    let (text_without_backticks, code_ranges) =
17746        highlight_diagnostic_message(&diagnostic, max_message_rows);
17747
17748    Arc::new(move |cx: &mut BlockContext| {
17749        let group_id: SharedString = cx.block_id.to_string().into();
17750
17751        let mut text_style = cx.window.text_style().clone();
17752        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17753        let theme_settings = ThemeSettings::get_global(cx);
17754        text_style.font_family = theme_settings.buffer_font.family.clone();
17755        text_style.font_style = theme_settings.buffer_font.style;
17756        text_style.font_features = theme_settings.buffer_font.features.clone();
17757        text_style.font_weight = theme_settings.buffer_font.weight;
17758
17759        let multi_line_diagnostic = diagnostic.message.contains('\n');
17760
17761        let buttons = |diagnostic: &Diagnostic| {
17762            if multi_line_diagnostic {
17763                v_flex()
17764            } else {
17765                h_flex()
17766            }
17767            .when(allow_closing, |div| {
17768                div.children(diagnostic.is_primary.then(|| {
17769                    IconButton::new("close-block", IconName::XCircle)
17770                        .icon_color(Color::Muted)
17771                        .size(ButtonSize::Compact)
17772                        .style(ButtonStyle::Transparent)
17773                        .visible_on_hover(group_id.clone())
17774                        .on_click(move |_click, window, cx| {
17775                            window.dispatch_action(Box::new(Cancel), cx)
17776                        })
17777                        .tooltip(|window, cx| {
17778                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17779                        })
17780                }))
17781            })
17782            .child(
17783                IconButton::new("copy-block", IconName::Copy)
17784                    .icon_color(Color::Muted)
17785                    .size(ButtonSize::Compact)
17786                    .style(ButtonStyle::Transparent)
17787                    .visible_on_hover(group_id.clone())
17788                    .on_click({
17789                        let message = diagnostic.message.clone();
17790                        move |_click, _, cx| {
17791                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17792                        }
17793                    })
17794                    .tooltip(Tooltip::text("Copy diagnostic message")),
17795            )
17796        };
17797
17798        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17799            AvailableSpace::min_size(),
17800            cx.window,
17801            cx.app,
17802        );
17803
17804        h_flex()
17805            .id(cx.block_id)
17806            .group(group_id.clone())
17807            .relative()
17808            .size_full()
17809            .block_mouse_down()
17810            .pl(cx.gutter_dimensions.width)
17811            .w(cx.max_width - cx.gutter_dimensions.full_width())
17812            .child(
17813                div()
17814                    .flex()
17815                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17816                    .flex_shrink(),
17817            )
17818            .child(buttons(&diagnostic))
17819            .child(div().flex().flex_shrink_0().child(
17820                StyledText::new(text_without_backticks.clone()).with_highlights(
17821                    &text_style,
17822                    code_ranges.iter().map(|range| {
17823                        (
17824                            range.clone(),
17825                            HighlightStyle {
17826                                font_weight: Some(FontWeight::BOLD),
17827                                ..Default::default()
17828                            },
17829                        )
17830                    }),
17831                ),
17832            ))
17833            .into_any_element()
17834    })
17835}
17836
17837fn inline_completion_edit_text(
17838    current_snapshot: &BufferSnapshot,
17839    edits: &[(Range<Anchor>, String)],
17840    edit_preview: &EditPreview,
17841    include_deletions: bool,
17842    cx: &App,
17843) -> HighlightedText {
17844    let edits = edits
17845        .iter()
17846        .map(|(anchor, text)| {
17847            (
17848                anchor.start.text_anchor..anchor.end.text_anchor,
17849                text.clone(),
17850            )
17851        })
17852        .collect::<Vec<_>>();
17853
17854    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17855}
17856
17857pub fn highlight_diagnostic_message(
17858    diagnostic: &Diagnostic,
17859    mut max_message_rows: Option<u8>,
17860) -> (SharedString, Vec<Range<usize>>) {
17861    let mut text_without_backticks = String::new();
17862    let mut code_ranges = Vec::new();
17863
17864    if let Some(source) = &diagnostic.source {
17865        text_without_backticks.push_str(source);
17866        code_ranges.push(0..source.len());
17867        text_without_backticks.push_str(": ");
17868    }
17869
17870    let mut prev_offset = 0;
17871    let mut in_code_block = false;
17872    let has_row_limit = max_message_rows.is_some();
17873    let mut newline_indices = diagnostic
17874        .message
17875        .match_indices('\n')
17876        .filter(|_| has_row_limit)
17877        .map(|(ix, _)| ix)
17878        .fuse()
17879        .peekable();
17880
17881    for (quote_ix, _) in diagnostic
17882        .message
17883        .match_indices('`')
17884        .chain([(diagnostic.message.len(), "")])
17885    {
17886        let mut first_newline_ix = None;
17887        let mut last_newline_ix = None;
17888        while let Some(newline_ix) = newline_indices.peek() {
17889            if *newline_ix < quote_ix {
17890                if first_newline_ix.is_none() {
17891                    first_newline_ix = Some(*newline_ix);
17892                }
17893                last_newline_ix = Some(*newline_ix);
17894
17895                if let Some(rows_left) = &mut max_message_rows {
17896                    if *rows_left == 0 {
17897                        break;
17898                    } else {
17899                        *rows_left -= 1;
17900                    }
17901                }
17902                let _ = newline_indices.next();
17903            } else {
17904                break;
17905            }
17906        }
17907        let prev_len = text_without_backticks.len();
17908        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17909        text_without_backticks.push_str(new_text);
17910        if in_code_block {
17911            code_ranges.push(prev_len..text_without_backticks.len());
17912        }
17913        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17914        in_code_block = !in_code_block;
17915        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17916            text_without_backticks.push_str("...");
17917            break;
17918        }
17919    }
17920
17921    (text_without_backticks.into(), code_ranges)
17922}
17923
17924fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17925    match severity {
17926        DiagnosticSeverity::ERROR => colors.error,
17927        DiagnosticSeverity::WARNING => colors.warning,
17928        DiagnosticSeverity::INFORMATION => colors.info,
17929        DiagnosticSeverity::HINT => colors.info,
17930        _ => colors.ignored,
17931    }
17932}
17933
17934pub fn styled_runs_for_code_label<'a>(
17935    label: &'a CodeLabel,
17936    syntax_theme: &'a theme::SyntaxTheme,
17937) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17938    let fade_out = HighlightStyle {
17939        fade_out: Some(0.35),
17940        ..Default::default()
17941    };
17942
17943    let mut prev_end = label.filter_range.end;
17944    label
17945        .runs
17946        .iter()
17947        .enumerate()
17948        .flat_map(move |(ix, (range, highlight_id))| {
17949            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17950                style
17951            } else {
17952                return Default::default();
17953            };
17954            let mut muted_style = style;
17955            muted_style.highlight(fade_out);
17956
17957            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17958            if range.start >= label.filter_range.end {
17959                if range.start > prev_end {
17960                    runs.push((prev_end..range.start, fade_out));
17961                }
17962                runs.push((range.clone(), muted_style));
17963            } else if range.end <= label.filter_range.end {
17964                runs.push((range.clone(), style));
17965            } else {
17966                runs.push((range.start..label.filter_range.end, style));
17967                runs.push((label.filter_range.end..range.end, muted_style));
17968            }
17969            prev_end = cmp::max(prev_end, range.end);
17970
17971            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17972                runs.push((prev_end..label.text.len(), fade_out));
17973            }
17974
17975            runs
17976        })
17977}
17978
17979pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17980    let mut prev_index = 0;
17981    let mut prev_codepoint: Option<char> = None;
17982    text.char_indices()
17983        .chain([(text.len(), '\0')])
17984        .filter_map(move |(index, codepoint)| {
17985            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17986            let is_boundary = index == text.len()
17987                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17988                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17989            if is_boundary {
17990                let chunk = &text[prev_index..index];
17991                prev_index = index;
17992                Some(chunk)
17993            } else {
17994                None
17995            }
17996        })
17997}
17998
17999pub trait RangeToAnchorExt: Sized {
18000    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18001
18002    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18003        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18004        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18005    }
18006}
18007
18008impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18009    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18010        let start_offset = self.start.to_offset(snapshot);
18011        let end_offset = self.end.to_offset(snapshot);
18012        if start_offset == end_offset {
18013            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18014        } else {
18015            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18016        }
18017    }
18018}
18019
18020pub trait RowExt {
18021    fn as_f32(&self) -> f32;
18022
18023    fn next_row(&self) -> Self;
18024
18025    fn previous_row(&self) -> Self;
18026
18027    fn minus(&self, other: Self) -> u32;
18028}
18029
18030impl RowExt for DisplayRow {
18031    fn as_f32(&self) -> f32 {
18032        self.0 as f32
18033    }
18034
18035    fn next_row(&self) -> Self {
18036        Self(self.0 + 1)
18037    }
18038
18039    fn previous_row(&self) -> Self {
18040        Self(self.0.saturating_sub(1))
18041    }
18042
18043    fn minus(&self, other: Self) -> u32 {
18044        self.0 - other.0
18045    }
18046}
18047
18048impl RowExt for MultiBufferRow {
18049    fn as_f32(&self) -> f32 {
18050        self.0 as f32
18051    }
18052
18053    fn next_row(&self) -> Self {
18054        Self(self.0 + 1)
18055    }
18056
18057    fn previous_row(&self) -> Self {
18058        Self(self.0.saturating_sub(1))
18059    }
18060
18061    fn minus(&self, other: Self) -> u32 {
18062        self.0 - other.0
18063    }
18064}
18065
18066trait RowRangeExt {
18067    type Row;
18068
18069    fn len(&self) -> usize;
18070
18071    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18072}
18073
18074impl RowRangeExt for Range<MultiBufferRow> {
18075    type Row = MultiBufferRow;
18076
18077    fn len(&self) -> usize {
18078        (self.end.0 - self.start.0) as usize
18079    }
18080
18081    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18082        (self.start.0..self.end.0).map(MultiBufferRow)
18083    }
18084}
18085
18086impl RowRangeExt for Range<DisplayRow> {
18087    type Row = DisplayRow;
18088
18089    fn len(&self) -> usize {
18090        (self.end.0 - self.start.0) as usize
18091    }
18092
18093    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18094        (self.start.0..self.end.0).map(DisplayRow)
18095    }
18096}
18097
18098/// If select range has more than one line, we
18099/// just point the cursor to range.start.
18100fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18101    if range.start.row == range.end.row {
18102        range
18103    } else {
18104        range.start..range.start
18105    }
18106}
18107pub struct KillRing(ClipboardItem);
18108impl Global for KillRing {}
18109
18110const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18111
18112fn all_edits_insertions_or_deletions(
18113    edits: &Vec<(Range<Anchor>, String)>,
18114    snapshot: &MultiBufferSnapshot,
18115) -> bool {
18116    let mut all_insertions = true;
18117    let mut all_deletions = true;
18118
18119    for (range, new_text) in edits.iter() {
18120        let range_is_empty = range.to_offset(&snapshot).is_empty();
18121        let text_is_empty = new_text.is_empty();
18122
18123        if range_is_empty != text_is_empty {
18124            if range_is_empty {
18125                all_deletions = false;
18126            } else {
18127                all_insertions = false;
18128            }
18129        } else {
18130            return false;
18131        }
18132
18133        if !all_insertions && !all_deletions {
18134            return false;
18135        }
18136    }
18137    all_insertions || all_deletions
18138}