editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::{DiffHunkSecondaryStatus, DiffHunkStatus};
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::{status::FileStatus, Restore};
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
   89    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  106    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  107    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  124    LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  208
  209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  211
  212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  213    alt: true,
  214    shift: true,
  215    control: false,
  216    platform: false,
  217    function: false,
  218};
  219
  220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  221pub enum InlayId {
  222    InlineCompletion(usize),
  223    Hint(usize),
  224}
  225
  226impl InlayId {
  227    fn id(&self) -> usize {
  228        match self {
  229            Self::InlineCompletion(id) => *id,
  230            Self::Hint(id) => *id,
  231        }
  232    }
  233}
  234
  235enum DocumentHighlightRead {}
  236enum DocumentHighlightWrite {}
  237enum InputComposition {}
  238enum SelectedTextHighlight {}
  239
  240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  241pub enum Navigated {
  242    Yes,
  243    No,
  244}
  245
  246impl Navigated {
  247    pub fn from_bool(yes: bool) -> Navigated {
  248        if yes {
  249            Navigated::Yes
  250        } else {
  251            Navigated::No
  252        }
  253    }
  254}
  255
  256#[derive(Debug, Clone, PartialEq, Eq)]
  257enum DisplayDiffHunk {
  258    Folded {
  259        display_row: DisplayRow,
  260    },
  261    Unfolded {
  262        diff_base_byte_range: Range<usize>,
  263        display_row_range: Range<DisplayRow>,
  264        multi_buffer_range: Range<Anchor>,
  265        status: DiffHunkStatus,
  266    },
  267}
  268
  269pub fn init_settings(cx: &mut App) {
  270    EditorSettings::register(cx);
  271}
  272
  273pub fn init(cx: &mut App) {
  274    init_settings(cx);
  275
  276    workspace::register_project_item::<Editor>(cx);
  277    workspace::FollowableViewRegistry::register::<Editor>(cx);
  278    workspace::register_serializable_item::<Editor>(cx);
  279
  280    cx.observe_new(
  281        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  282            workspace.register_action(Editor::new_file);
  283            workspace.register_action(Editor::new_file_vertical);
  284            workspace.register_action(Editor::new_file_horizontal);
  285            workspace.register_action(Editor::cancel_language_server_work);
  286        },
  287    )
  288    .detach();
  289
  290    cx.on_action(move |_: &workspace::NewFile, cx| {
  291        let app_state = workspace::AppState::global(cx);
  292        if let Some(app_state) = app_state.upgrade() {
  293            workspace::open_new(
  294                Default::default(),
  295                app_state,
  296                cx,
  297                |workspace, window, cx| {
  298                    Editor::new_file(workspace, &Default::default(), window, cx)
  299                },
  300            )
  301            .detach();
  302        }
  303    });
  304    cx.on_action(move |_: &workspace::NewWindow, cx| {
  305        let app_state = workspace::AppState::global(cx);
  306        if let Some(app_state) = app_state.upgrade() {
  307            workspace::open_new(
  308                Default::default(),
  309                app_state,
  310                cx,
  311                |workspace, window, cx| {
  312                    cx.activate(true);
  313                    Editor::new_file(workspace, &Default::default(), window, cx)
  314                },
  315            )
  316            .detach();
  317        }
  318    });
  319}
  320
  321pub struct SearchWithinRange;
  322
  323trait InvalidationRegion {
  324    fn ranges(&self) -> &[Range<Anchor>];
  325}
  326
  327#[derive(Clone, Debug, PartialEq)]
  328pub enum SelectPhase {
  329    Begin {
  330        position: DisplayPoint,
  331        add: bool,
  332        click_count: usize,
  333    },
  334    BeginColumnar {
  335        position: DisplayPoint,
  336        reset: bool,
  337        goal_column: u32,
  338    },
  339    Extend {
  340        position: DisplayPoint,
  341        click_count: usize,
  342    },
  343    Update {
  344        position: DisplayPoint,
  345        goal_column: u32,
  346        scroll_delta: gpui::Point<f32>,
  347    },
  348    End,
  349}
  350
  351#[derive(Clone, Debug)]
  352pub enum SelectMode {
  353    Character,
  354    Word(Range<Anchor>),
  355    Line(Range<Anchor>),
  356    All,
  357}
  358
  359#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  360pub enum EditorMode {
  361    SingleLine { auto_width: bool },
  362    AutoHeight { max_lines: usize },
  363    Full,
  364}
  365
  366#[derive(Copy, Clone, Debug)]
  367pub enum SoftWrap {
  368    /// Prefer not to wrap at all.
  369    ///
  370    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  371    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  372    GitDiff,
  373    /// Prefer a single line generally, unless an overly long line is encountered.
  374    None,
  375    /// Soft wrap lines that exceed the editor width.
  376    EditorWidth,
  377    /// Soft wrap lines at the preferred line length.
  378    Column(u32),
  379    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  380    Bounded(u32),
  381}
  382
  383#[derive(Clone)]
  384pub struct EditorStyle {
  385    pub background: Hsla,
  386    pub local_player: PlayerColor,
  387    pub text: TextStyle,
  388    pub scrollbar_width: Pixels,
  389    pub syntax: Arc<SyntaxTheme>,
  390    pub status: StatusColors,
  391    pub inlay_hints_style: HighlightStyle,
  392    pub inline_completion_styles: InlineCompletionStyles,
  393    pub unnecessary_code_fade: f32,
  394}
  395
  396impl Default for EditorStyle {
  397    fn default() -> Self {
  398        Self {
  399            background: Hsla::default(),
  400            local_player: PlayerColor::default(),
  401            text: TextStyle::default(),
  402            scrollbar_width: Pixels::default(),
  403            syntax: Default::default(),
  404            // HACK: Status colors don't have a real default.
  405            // We should look into removing the status colors from the editor
  406            // style and retrieve them directly from the theme.
  407            status: StatusColors::dark(),
  408            inlay_hints_style: HighlightStyle::default(),
  409            inline_completion_styles: InlineCompletionStyles {
  410                insertion: HighlightStyle::default(),
  411                whitespace: HighlightStyle::default(),
  412            },
  413            unnecessary_code_fade: Default::default(),
  414        }
  415    }
  416}
  417
  418pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  419    let show_background = language_settings::language_settings(None, None, cx)
  420        .inlay_hints
  421        .show_background;
  422
  423    HighlightStyle {
  424        color: Some(cx.theme().status().hint),
  425        background_color: show_background.then(|| cx.theme().status().hint_background),
  426        ..HighlightStyle::default()
  427    }
  428}
  429
  430pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  431    InlineCompletionStyles {
  432        insertion: HighlightStyle {
  433            color: Some(cx.theme().status().predictive),
  434            ..HighlightStyle::default()
  435        },
  436        whitespace: HighlightStyle {
  437            background_color: Some(cx.theme().status().created_background),
  438            ..HighlightStyle::default()
  439        },
  440    }
  441}
  442
  443type CompletionId = usize;
  444
  445pub(crate) enum EditDisplayMode {
  446    TabAccept,
  447    DiffPopover,
  448    Inline,
  449}
  450
  451enum InlineCompletion {
  452    Edit {
  453        edits: Vec<(Range<Anchor>, String)>,
  454        edit_preview: Option<EditPreview>,
  455        display_mode: EditDisplayMode,
  456        snapshot: BufferSnapshot,
  457    },
  458    Move {
  459        target: Anchor,
  460        snapshot: BufferSnapshot,
  461    },
  462}
  463
  464struct InlineCompletionState {
  465    inlay_ids: Vec<InlayId>,
  466    completion: InlineCompletion,
  467    completion_id: Option<SharedString>,
  468    invalidation_range: Range<Anchor>,
  469}
  470
  471enum EditPredictionSettings {
  472    Disabled,
  473    Enabled {
  474        show_in_menu: bool,
  475        preview_requires_modifier: bool,
  476    },
  477}
  478
  479enum InlineCompletionHighlight {}
  480
  481#[derive(Debug, Clone)]
  482struct InlineDiagnostic {
  483    message: SharedString,
  484    group_id: usize,
  485    is_primary: bool,
  486    start: Point,
  487    severity: DiagnosticSeverity,
  488}
  489
  490pub enum MenuInlineCompletionsPolicy {
  491    Never,
  492    ByProvider,
  493}
  494
  495pub enum EditPredictionPreview {
  496    /// Modifier is not pressed
  497    Inactive { released_too_fast: bool },
  498    /// Modifier pressed
  499    Active {
  500        since: Instant,
  501        previous_scroll_position: Option<ScrollAnchor>,
  502    },
  503}
  504
  505impl EditPredictionPreview {
  506    pub fn released_too_fast(&self) -> bool {
  507        match self {
  508            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  509            EditPredictionPreview::Active { .. } => false,
  510        }
  511    }
  512
  513    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  514        if let EditPredictionPreview::Active {
  515            previous_scroll_position,
  516            ..
  517        } = self
  518        {
  519            *previous_scroll_position = scroll_position;
  520        }
  521    }
  522}
  523
  524#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  525struct EditorActionId(usize);
  526
  527impl EditorActionId {
  528    pub fn post_inc(&mut self) -> Self {
  529        let answer = self.0;
  530
  531        *self = Self(answer + 1);
  532
  533        Self(answer)
  534    }
  535}
  536
  537// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  538// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  539
  540type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  541type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  542
  543#[derive(Default)]
  544struct ScrollbarMarkerState {
  545    scrollbar_size: Size<Pixels>,
  546    dirty: bool,
  547    markers: Arc<[PaintQuad]>,
  548    pending_refresh: Option<Task<Result<()>>>,
  549}
  550
  551impl ScrollbarMarkerState {
  552    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  553        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  554    }
  555}
  556
  557#[derive(Clone, Debug)]
  558struct RunnableTasks {
  559    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  560    offset: multi_buffer::Anchor,
  561    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  562    column: u32,
  563    // Values of all named captures, including those starting with '_'
  564    extra_variables: HashMap<String, String>,
  565    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  566    context_range: Range<BufferOffset>,
  567}
  568
  569impl RunnableTasks {
  570    fn resolve<'a>(
  571        &'a self,
  572        cx: &'a task::TaskContext,
  573    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  574        self.templates.iter().filter_map(|(kind, template)| {
  575            template
  576                .resolve_task(&kind.to_id_base(), cx)
  577                .map(|task| (kind.clone(), task))
  578        })
  579    }
  580}
  581
  582#[derive(Clone)]
  583struct ResolvedTasks {
  584    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  585    position: Anchor,
  586}
  587#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  588struct BufferOffset(usize);
  589
  590// Addons allow storing per-editor state in other crates (e.g. Vim)
  591pub trait Addon: 'static {
  592    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  593
  594    fn render_buffer_header_controls(
  595        &self,
  596        _: &ExcerptInfo,
  597        _: &Window,
  598        _: &App,
  599    ) -> Option<AnyElement> {
  600        None
  601    }
  602
  603    fn to_any(&self) -> &dyn std::any::Any;
  604}
  605
  606#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  607pub enum IsVimMode {
  608    Yes,
  609    No,
  610}
  611
  612/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  613///
  614/// See the [module level documentation](self) for more information.
  615pub struct Editor {
  616    focus_handle: FocusHandle,
  617    last_focused_descendant: Option<WeakFocusHandle>,
  618    /// The text buffer being edited
  619    buffer: Entity<MultiBuffer>,
  620    /// Map of how text in the buffer should be displayed.
  621    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  622    pub display_map: Entity<DisplayMap>,
  623    pub selections: SelectionsCollection,
  624    pub scroll_manager: ScrollManager,
  625    /// When inline assist editors are linked, they all render cursors because
  626    /// typing enters text into each of them, even the ones that aren't focused.
  627    pub(crate) show_cursor_when_unfocused: bool,
  628    columnar_selection_tail: Option<Anchor>,
  629    add_selections_state: Option<AddSelectionsState>,
  630    select_next_state: Option<SelectNextState>,
  631    select_prev_state: Option<SelectNextState>,
  632    selection_history: SelectionHistory,
  633    autoclose_regions: Vec<AutocloseRegion>,
  634    snippet_stack: InvalidationStack<SnippetState>,
  635    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  636    ime_transaction: Option<TransactionId>,
  637    active_diagnostics: Option<ActiveDiagnosticGroup>,
  638    show_inline_diagnostics: bool,
  639    inline_diagnostics_update: Task<()>,
  640    inline_diagnostics_enabled: bool,
  641    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  642    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  643
  644    // TODO: make this a access method
  645    pub project: Option<Entity<Project>>,
  646    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  647    completion_provider: Option<Box<dyn CompletionProvider>>,
  648    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  649    blink_manager: Entity<BlinkManager>,
  650    show_cursor_names: bool,
  651    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  652    pub show_local_selections: bool,
  653    mode: EditorMode,
  654    show_breadcrumbs: bool,
  655    show_gutter: bool,
  656    show_scrollbars: bool,
  657    show_line_numbers: Option<bool>,
  658    use_relative_line_numbers: Option<bool>,
  659    show_git_diff_gutter: Option<bool>,
  660    show_code_actions: Option<bool>,
  661    show_runnables: Option<bool>,
  662    show_wrap_guides: Option<bool>,
  663    show_indent_guides: Option<bool>,
  664    placeholder_text: Option<Arc<str>>,
  665    highlight_order: usize,
  666    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  667    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  668    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  669    scrollbar_marker_state: ScrollbarMarkerState,
  670    active_indent_guides_state: ActiveIndentGuidesState,
  671    nav_history: Option<ItemNavHistory>,
  672    context_menu: RefCell<Option<CodeContextMenu>>,
  673    mouse_context_menu: Option<MouseContextMenu>,
  674    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  675    signature_help_state: SignatureHelpState,
  676    auto_signature_help: Option<bool>,
  677    find_all_references_task_sources: Vec<Anchor>,
  678    next_completion_id: CompletionId,
  679    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  680    code_actions_task: Option<Task<Result<()>>>,
  681    selection_highlight_task: Option<Task<()>>,
  682    document_highlights_task: Option<Task<()>>,
  683    linked_editing_range_task: Option<Task<Option<()>>>,
  684    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  685    pending_rename: Option<RenameState>,
  686    searchable: bool,
  687    cursor_shape: CursorShape,
  688    current_line_highlight: Option<CurrentLineHighlight>,
  689    collapse_matches: bool,
  690    autoindent_mode: Option<AutoindentMode>,
  691    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  692    input_enabled: bool,
  693    use_modal_editing: bool,
  694    read_only: bool,
  695    leader_peer_id: Option<PeerId>,
  696    remote_id: Option<ViewId>,
  697    hover_state: HoverState,
  698    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  699    gutter_hovered: bool,
  700    hovered_link_state: Option<HoveredLinkState>,
  701    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  702    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  703    active_inline_completion: Option<InlineCompletionState>,
  704    /// Used to prevent flickering as the user types while the menu is open
  705    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  706    edit_prediction_settings: EditPredictionSettings,
  707    inline_completions_hidden_for_vim_mode: bool,
  708    show_inline_completions_override: Option<bool>,
  709    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  710    edit_prediction_preview: EditPredictionPreview,
  711    edit_prediction_indent_conflict: bool,
  712    edit_prediction_requires_modifier_in_indent_conflict: bool,
  713    inlay_hint_cache: InlayHintCache,
  714    next_inlay_id: usize,
  715    _subscriptions: Vec<Subscription>,
  716    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  717    gutter_dimensions: GutterDimensions,
  718    style: Option<EditorStyle>,
  719    text_style_refinement: Option<TextStyleRefinement>,
  720    next_editor_action_id: EditorActionId,
  721    editor_actions:
  722        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  723    use_autoclose: bool,
  724    use_auto_surround: bool,
  725    auto_replace_emoji_shortcode: bool,
  726    show_git_blame_gutter: bool,
  727    show_git_blame_inline: bool,
  728    show_git_blame_inline_delay_task: Option<Task<()>>,
  729    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  730    git_blame_inline_enabled: bool,
  731    serialize_dirty_buffers: bool,
  732    show_selection_menu: Option<bool>,
  733    blame: Option<Entity<GitBlame>>,
  734    blame_subscription: Option<Subscription>,
  735    custom_context_menu: Option<
  736        Box<
  737            dyn 'static
  738                + Fn(
  739                    &mut Self,
  740                    DisplayPoint,
  741                    &mut Window,
  742                    &mut Context<Self>,
  743                ) -> Option<Entity<ui::ContextMenu>>,
  744        >,
  745    >,
  746    last_bounds: Option<Bounds<Pixels>>,
  747    last_position_map: Option<Rc<PositionMap>>,
  748    expect_bounds_change: Option<Bounds<Pixels>>,
  749    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  750    tasks_update_task: Option<Task<()>>,
  751    in_project_search: bool,
  752    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  753    breadcrumb_header: Option<String>,
  754    focused_block: Option<FocusedBlock>,
  755    next_scroll_position: NextScrollCursorCenterTopBottom,
  756    addons: HashMap<TypeId, Box<dyn Addon>>,
  757    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  758    load_diff_task: Option<Shared<Task<()>>>,
  759    selection_mark_mode: bool,
  760    toggle_fold_multiple_buffers: Task<()>,
  761    _scroll_cursor_center_top_bottom_task: Task<()>,
  762    serialize_selections: Task<()>,
  763}
  764
  765#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  766enum NextScrollCursorCenterTopBottom {
  767    #[default]
  768    Center,
  769    Top,
  770    Bottom,
  771}
  772
  773impl NextScrollCursorCenterTopBottom {
  774    fn next(&self) -> Self {
  775        match self {
  776            Self::Center => Self::Top,
  777            Self::Top => Self::Bottom,
  778            Self::Bottom => Self::Center,
  779        }
  780    }
  781}
  782
  783#[derive(Clone)]
  784pub struct EditorSnapshot {
  785    pub mode: EditorMode,
  786    show_gutter: bool,
  787    show_line_numbers: Option<bool>,
  788    show_git_diff_gutter: Option<bool>,
  789    show_code_actions: Option<bool>,
  790    show_runnables: Option<bool>,
  791    git_blame_gutter_max_author_length: Option<usize>,
  792    pub display_snapshot: DisplaySnapshot,
  793    pub placeholder_text: Option<Arc<str>>,
  794    is_focused: bool,
  795    scroll_anchor: ScrollAnchor,
  796    ongoing_scroll: OngoingScroll,
  797    current_line_highlight: CurrentLineHighlight,
  798    gutter_hovered: bool,
  799}
  800
  801const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  802
  803#[derive(Default, Debug, Clone, Copy)]
  804pub struct GutterDimensions {
  805    pub left_padding: Pixels,
  806    pub right_padding: Pixels,
  807    pub width: Pixels,
  808    pub margin: Pixels,
  809    pub git_blame_entries_width: Option<Pixels>,
  810}
  811
  812impl GutterDimensions {
  813    /// The full width of the space taken up by the gutter.
  814    pub fn full_width(&self) -> Pixels {
  815        self.margin + self.width
  816    }
  817
  818    /// The width of the space reserved for the fold indicators,
  819    /// use alongside 'justify_end' and `gutter_width` to
  820    /// right align content with the line numbers
  821    pub fn fold_area_width(&self) -> Pixels {
  822        self.margin + self.right_padding
  823    }
  824}
  825
  826#[derive(Debug)]
  827pub struct RemoteSelection {
  828    pub replica_id: ReplicaId,
  829    pub selection: Selection<Anchor>,
  830    pub cursor_shape: CursorShape,
  831    pub peer_id: PeerId,
  832    pub line_mode: bool,
  833    pub participant_index: Option<ParticipantIndex>,
  834    pub user_name: Option<SharedString>,
  835}
  836
  837#[derive(Clone, Debug)]
  838struct SelectionHistoryEntry {
  839    selections: Arc<[Selection<Anchor>]>,
  840    select_next_state: Option<SelectNextState>,
  841    select_prev_state: Option<SelectNextState>,
  842    add_selections_state: Option<AddSelectionsState>,
  843}
  844
  845enum SelectionHistoryMode {
  846    Normal,
  847    Undoing,
  848    Redoing,
  849}
  850
  851#[derive(Clone, PartialEq, Eq, Hash)]
  852struct HoveredCursor {
  853    replica_id: u16,
  854    selection_id: usize,
  855}
  856
  857impl Default for SelectionHistoryMode {
  858    fn default() -> Self {
  859        Self::Normal
  860    }
  861}
  862
  863#[derive(Default)]
  864struct SelectionHistory {
  865    #[allow(clippy::type_complexity)]
  866    selections_by_transaction:
  867        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  868    mode: SelectionHistoryMode,
  869    undo_stack: VecDeque<SelectionHistoryEntry>,
  870    redo_stack: VecDeque<SelectionHistoryEntry>,
  871}
  872
  873impl SelectionHistory {
  874    fn insert_transaction(
  875        &mut self,
  876        transaction_id: TransactionId,
  877        selections: Arc<[Selection<Anchor>]>,
  878    ) {
  879        self.selections_by_transaction
  880            .insert(transaction_id, (selections, None));
  881    }
  882
  883    #[allow(clippy::type_complexity)]
  884    fn transaction(
  885        &self,
  886        transaction_id: TransactionId,
  887    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  888        self.selections_by_transaction.get(&transaction_id)
  889    }
  890
  891    #[allow(clippy::type_complexity)]
  892    fn transaction_mut(
  893        &mut self,
  894        transaction_id: TransactionId,
  895    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  896        self.selections_by_transaction.get_mut(&transaction_id)
  897    }
  898
  899    fn push(&mut self, entry: SelectionHistoryEntry) {
  900        if !entry.selections.is_empty() {
  901            match self.mode {
  902                SelectionHistoryMode::Normal => {
  903                    self.push_undo(entry);
  904                    self.redo_stack.clear();
  905                }
  906                SelectionHistoryMode::Undoing => self.push_redo(entry),
  907                SelectionHistoryMode::Redoing => self.push_undo(entry),
  908            }
  909        }
  910    }
  911
  912    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  913        if self
  914            .undo_stack
  915            .back()
  916            .map_or(true, |e| e.selections != entry.selections)
  917        {
  918            self.undo_stack.push_back(entry);
  919            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  920                self.undo_stack.pop_front();
  921            }
  922        }
  923    }
  924
  925    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  926        if self
  927            .redo_stack
  928            .back()
  929            .map_or(true, |e| e.selections != entry.selections)
  930        {
  931            self.redo_stack.push_back(entry);
  932            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  933                self.redo_stack.pop_front();
  934            }
  935        }
  936    }
  937}
  938
  939struct RowHighlight {
  940    index: usize,
  941    range: Range<Anchor>,
  942    color: Hsla,
  943    should_autoscroll: bool,
  944}
  945
  946#[derive(Clone, Debug)]
  947struct AddSelectionsState {
  948    above: bool,
  949    stack: Vec<usize>,
  950}
  951
  952#[derive(Clone)]
  953struct SelectNextState {
  954    query: AhoCorasick,
  955    wordwise: bool,
  956    done: bool,
  957}
  958
  959impl std::fmt::Debug for SelectNextState {
  960    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  961        f.debug_struct(std::any::type_name::<Self>())
  962            .field("wordwise", &self.wordwise)
  963            .field("done", &self.done)
  964            .finish()
  965    }
  966}
  967
  968#[derive(Debug)]
  969struct AutocloseRegion {
  970    selection_id: usize,
  971    range: Range<Anchor>,
  972    pair: BracketPair,
  973}
  974
  975#[derive(Debug)]
  976struct SnippetState {
  977    ranges: Vec<Vec<Range<Anchor>>>,
  978    active_index: usize,
  979    choices: Vec<Option<Vec<String>>>,
  980}
  981
  982#[doc(hidden)]
  983pub struct RenameState {
  984    pub range: Range<Anchor>,
  985    pub old_name: Arc<str>,
  986    pub editor: Entity<Editor>,
  987    block_id: CustomBlockId,
  988}
  989
  990struct InvalidationStack<T>(Vec<T>);
  991
  992struct RegisteredInlineCompletionProvider {
  993    provider: Arc<dyn InlineCompletionProviderHandle>,
  994    _subscription: Subscription,
  995}
  996
  997#[derive(Debug)]
  998struct ActiveDiagnosticGroup {
  999    primary_range: Range<Anchor>,
 1000    primary_message: String,
 1001    group_id: usize,
 1002    blocks: HashMap<CustomBlockId, Diagnostic>,
 1003    is_valid: bool,
 1004}
 1005
 1006#[derive(Serialize, Deserialize, Clone, Debug)]
 1007pub struct ClipboardSelection {
 1008    /// The number of bytes in this selection.
 1009    pub len: usize,
 1010    /// Whether this was a full-line selection.
 1011    pub is_entire_line: bool,
 1012    /// The column where this selection originally started.
 1013    pub start_column: u32,
 1014}
 1015
 1016#[derive(Debug)]
 1017pub(crate) struct NavigationData {
 1018    cursor_anchor: Anchor,
 1019    cursor_position: Point,
 1020    scroll_anchor: ScrollAnchor,
 1021    scroll_top_row: u32,
 1022}
 1023
 1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1025pub enum GotoDefinitionKind {
 1026    Symbol,
 1027    Declaration,
 1028    Type,
 1029    Implementation,
 1030}
 1031
 1032#[derive(Debug, Clone)]
 1033enum InlayHintRefreshReason {
 1034    Toggle(bool),
 1035    SettingsChange(InlayHintSettings),
 1036    NewLinesShown,
 1037    BufferEdited(HashSet<Arc<Language>>),
 1038    RefreshRequested,
 1039    ExcerptsRemoved(Vec<ExcerptId>),
 1040}
 1041
 1042impl InlayHintRefreshReason {
 1043    fn description(&self) -> &'static str {
 1044        match self {
 1045            Self::Toggle(_) => "toggle",
 1046            Self::SettingsChange(_) => "settings change",
 1047            Self::NewLinesShown => "new lines shown",
 1048            Self::BufferEdited(_) => "buffer edited",
 1049            Self::RefreshRequested => "refresh requested",
 1050            Self::ExcerptsRemoved(_) => "excerpts removed",
 1051        }
 1052    }
 1053}
 1054
 1055pub enum FormatTarget {
 1056    Buffers,
 1057    Ranges(Vec<Range<MultiBufferPoint>>),
 1058}
 1059
 1060pub(crate) struct FocusedBlock {
 1061    id: BlockId,
 1062    focus_handle: WeakFocusHandle,
 1063}
 1064
 1065#[derive(Clone)]
 1066enum JumpData {
 1067    MultiBufferRow {
 1068        row: MultiBufferRow,
 1069        line_offset_from_top: u32,
 1070    },
 1071    MultiBufferPoint {
 1072        excerpt_id: ExcerptId,
 1073        position: Point,
 1074        anchor: text::Anchor,
 1075        line_offset_from_top: u32,
 1076    },
 1077}
 1078
 1079pub enum MultibufferSelectionMode {
 1080    First,
 1081    All,
 1082}
 1083
 1084impl Editor {
 1085    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1086        let buffer = cx.new(|cx| Buffer::local("", cx));
 1087        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1088        Self::new(
 1089            EditorMode::SingleLine { auto_width: false },
 1090            buffer,
 1091            None,
 1092            false,
 1093            window,
 1094            cx,
 1095        )
 1096    }
 1097
 1098    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1099        let buffer = cx.new(|cx| Buffer::local("", cx));
 1100        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1101        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1102    }
 1103
 1104    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1105        let buffer = cx.new(|cx| Buffer::local("", cx));
 1106        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1107        Self::new(
 1108            EditorMode::SingleLine { auto_width: true },
 1109            buffer,
 1110            None,
 1111            false,
 1112            window,
 1113            cx,
 1114        )
 1115    }
 1116
 1117    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1118        let buffer = cx.new(|cx| Buffer::local("", cx));
 1119        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1120        Self::new(
 1121            EditorMode::AutoHeight { max_lines },
 1122            buffer,
 1123            None,
 1124            false,
 1125            window,
 1126            cx,
 1127        )
 1128    }
 1129
 1130    pub fn for_buffer(
 1131        buffer: Entity<Buffer>,
 1132        project: Option<Entity<Project>>,
 1133        window: &mut Window,
 1134        cx: &mut Context<Self>,
 1135    ) -> Self {
 1136        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1137        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1138    }
 1139
 1140    pub fn for_multibuffer(
 1141        buffer: Entity<MultiBuffer>,
 1142        project: Option<Entity<Project>>,
 1143        show_excerpt_controls: bool,
 1144        window: &mut Window,
 1145        cx: &mut Context<Self>,
 1146    ) -> Self {
 1147        Self::new(
 1148            EditorMode::Full,
 1149            buffer,
 1150            project,
 1151            show_excerpt_controls,
 1152            window,
 1153            cx,
 1154        )
 1155    }
 1156
 1157    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1158        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1159        let mut clone = Self::new(
 1160            self.mode,
 1161            self.buffer.clone(),
 1162            self.project.clone(),
 1163            show_excerpt_controls,
 1164            window,
 1165            cx,
 1166        );
 1167        self.display_map.update(cx, |display_map, cx| {
 1168            let snapshot = display_map.snapshot(cx);
 1169            clone.display_map.update(cx, |display_map, cx| {
 1170                display_map.set_state(&snapshot, cx);
 1171            });
 1172        });
 1173        clone.selections.clone_state(&self.selections);
 1174        clone.scroll_manager.clone_state(&self.scroll_manager);
 1175        clone.searchable = self.searchable;
 1176        clone
 1177    }
 1178
 1179    pub fn new(
 1180        mode: EditorMode,
 1181        buffer: Entity<MultiBuffer>,
 1182        project: Option<Entity<Project>>,
 1183        show_excerpt_controls: bool,
 1184        window: &mut Window,
 1185        cx: &mut Context<Self>,
 1186    ) -> Self {
 1187        let style = window.text_style();
 1188        let font_size = style.font_size.to_pixels(window.rem_size());
 1189        let editor = cx.entity().downgrade();
 1190        let fold_placeholder = FoldPlaceholder {
 1191            constrain_width: true,
 1192            render: Arc::new(move |fold_id, fold_range, cx| {
 1193                let editor = editor.clone();
 1194                div()
 1195                    .id(fold_id)
 1196                    .bg(cx.theme().colors().ghost_element_background)
 1197                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1198                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1199                    .rounded_sm()
 1200                    .size_full()
 1201                    .cursor_pointer()
 1202                    .child("")
 1203                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1204                    .on_click(move |_, _window, cx| {
 1205                        editor
 1206                            .update(cx, |editor, cx| {
 1207                                editor.unfold_ranges(
 1208                                    &[fold_range.start..fold_range.end],
 1209                                    true,
 1210                                    false,
 1211                                    cx,
 1212                                );
 1213                                cx.stop_propagation();
 1214                            })
 1215                            .ok();
 1216                    })
 1217                    .into_any()
 1218            }),
 1219            merge_adjacent: true,
 1220            ..Default::default()
 1221        };
 1222        let display_map = cx.new(|cx| {
 1223            DisplayMap::new(
 1224                buffer.clone(),
 1225                style.font(),
 1226                font_size,
 1227                None,
 1228                show_excerpt_controls,
 1229                FILE_HEADER_HEIGHT,
 1230                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1231                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1232                fold_placeholder,
 1233                cx,
 1234            )
 1235        });
 1236
 1237        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1238
 1239        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1240
 1241        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1242            .then(|| language_settings::SoftWrap::None);
 1243
 1244        let mut project_subscriptions = Vec::new();
 1245        if mode == EditorMode::Full {
 1246            if let Some(project) = project.as_ref() {
 1247                if buffer.read(cx).is_singleton() {
 1248                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1249                        cx.emit(EditorEvent::TitleChanged);
 1250                    }));
 1251                }
 1252                project_subscriptions.push(cx.subscribe_in(
 1253                    project,
 1254                    window,
 1255                    |editor, _, event, window, cx| {
 1256                        if let project::Event::RefreshInlayHints = event {
 1257                            editor
 1258                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1259                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1260                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1261                                let focus_handle = editor.focus_handle(cx);
 1262                                if focus_handle.is_focused(window) {
 1263                                    let snapshot = buffer.read(cx).snapshot();
 1264                                    for (range, snippet) in snippet_edits {
 1265                                        let editor_range =
 1266                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1267                                        editor
 1268                                            .insert_snippet(
 1269                                                &[editor_range],
 1270                                                snippet.clone(),
 1271                                                window,
 1272                                                cx,
 1273                                            )
 1274                                            .ok();
 1275                                    }
 1276                                }
 1277                            }
 1278                        }
 1279                    },
 1280                ));
 1281                if let Some(task_inventory) = project
 1282                    .read(cx)
 1283                    .task_store()
 1284                    .read(cx)
 1285                    .task_inventory()
 1286                    .cloned()
 1287                {
 1288                    project_subscriptions.push(cx.observe_in(
 1289                        &task_inventory,
 1290                        window,
 1291                        |editor, _, window, cx| {
 1292                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1293                        },
 1294                    ));
 1295                }
 1296            }
 1297        }
 1298
 1299        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1300
 1301        let inlay_hint_settings =
 1302            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1303        let focus_handle = cx.focus_handle();
 1304        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1305            .detach();
 1306        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1307            .detach();
 1308        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1309            .detach();
 1310        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1311            .detach();
 1312
 1313        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1314            Some(false)
 1315        } else {
 1316            None
 1317        };
 1318
 1319        let mut code_action_providers = Vec::new();
 1320        let mut load_uncommitted_diff = None;
 1321        if let Some(project) = project.clone() {
 1322            load_uncommitted_diff = Some(
 1323                get_uncommitted_diff_for_buffer(
 1324                    &project,
 1325                    buffer.read(cx).all_buffers(),
 1326                    buffer.clone(),
 1327                    cx,
 1328                )
 1329                .shared(),
 1330            );
 1331            code_action_providers.push(Rc::new(project) as Rc<_>);
 1332        }
 1333
 1334        let mut this = Self {
 1335            focus_handle,
 1336            show_cursor_when_unfocused: false,
 1337            last_focused_descendant: None,
 1338            buffer: buffer.clone(),
 1339            display_map: display_map.clone(),
 1340            selections,
 1341            scroll_manager: ScrollManager::new(cx),
 1342            columnar_selection_tail: None,
 1343            add_selections_state: None,
 1344            select_next_state: None,
 1345            select_prev_state: None,
 1346            selection_history: Default::default(),
 1347            autoclose_regions: Default::default(),
 1348            snippet_stack: Default::default(),
 1349            select_larger_syntax_node_stack: Vec::new(),
 1350            ime_transaction: Default::default(),
 1351            active_diagnostics: None,
 1352            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1353            inline_diagnostics_update: Task::ready(()),
 1354            inline_diagnostics: Vec::new(),
 1355            soft_wrap_mode_override,
 1356            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1357            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1358            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1359            project,
 1360            blink_manager: blink_manager.clone(),
 1361            show_local_selections: true,
 1362            show_scrollbars: true,
 1363            mode,
 1364            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1365            show_gutter: mode == EditorMode::Full,
 1366            show_line_numbers: None,
 1367            use_relative_line_numbers: None,
 1368            show_git_diff_gutter: None,
 1369            show_code_actions: None,
 1370            show_runnables: None,
 1371            show_wrap_guides: None,
 1372            show_indent_guides,
 1373            placeholder_text: None,
 1374            highlight_order: 0,
 1375            highlighted_rows: HashMap::default(),
 1376            background_highlights: Default::default(),
 1377            gutter_highlights: TreeMap::default(),
 1378            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1379            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1380            nav_history: None,
 1381            context_menu: RefCell::new(None),
 1382            mouse_context_menu: None,
 1383            completion_tasks: Default::default(),
 1384            signature_help_state: SignatureHelpState::default(),
 1385            auto_signature_help: None,
 1386            find_all_references_task_sources: Vec::new(),
 1387            next_completion_id: 0,
 1388            next_inlay_id: 0,
 1389            code_action_providers,
 1390            available_code_actions: Default::default(),
 1391            code_actions_task: Default::default(),
 1392            selection_highlight_task: Default::default(),
 1393            document_highlights_task: Default::default(),
 1394            linked_editing_range_task: Default::default(),
 1395            pending_rename: Default::default(),
 1396            searchable: true,
 1397            cursor_shape: EditorSettings::get_global(cx)
 1398                .cursor_shape
 1399                .unwrap_or_default(),
 1400            current_line_highlight: None,
 1401            autoindent_mode: Some(AutoindentMode::EachLine),
 1402            collapse_matches: false,
 1403            workspace: None,
 1404            input_enabled: true,
 1405            use_modal_editing: mode == EditorMode::Full,
 1406            read_only: false,
 1407            use_autoclose: true,
 1408            use_auto_surround: true,
 1409            auto_replace_emoji_shortcode: false,
 1410            leader_peer_id: None,
 1411            remote_id: None,
 1412            hover_state: Default::default(),
 1413            pending_mouse_down: None,
 1414            hovered_link_state: Default::default(),
 1415            edit_prediction_provider: None,
 1416            active_inline_completion: None,
 1417            stale_inline_completion_in_menu: None,
 1418            edit_prediction_preview: EditPredictionPreview::Inactive {
 1419                released_too_fast: false,
 1420            },
 1421            inline_diagnostics_enabled: mode == EditorMode::Full,
 1422            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1423
 1424            gutter_hovered: false,
 1425            pixel_position_of_newest_cursor: None,
 1426            last_bounds: None,
 1427            last_position_map: None,
 1428            expect_bounds_change: None,
 1429            gutter_dimensions: GutterDimensions::default(),
 1430            style: None,
 1431            show_cursor_names: false,
 1432            hovered_cursors: Default::default(),
 1433            next_editor_action_id: EditorActionId::default(),
 1434            editor_actions: Rc::default(),
 1435            inline_completions_hidden_for_vim_mode: false,
 1436            show_inline_completions_override: None,
 1437            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1438            edit_prediction_settings: EditPredictionSettings::Disabled,
 1439            edit_prediction_indent_conflict: false,
 1440            edit_prediction_requires_modifier_in_indent_conflict: true,
 1441            custom_context_menu: None,
 1442            show_git_blame_gutter: false,
 1443            show_git_blame_inline: false,
 1444            show_selection_menu: None,
 1445            show_git_blame_inline_delay_task: None,
 1446            git_blame_inline_tooltip: None,
 1447            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1448            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1449                .session
 1450                .restore_unsaved_buffers,
 1451            blame: None,
 1452            blame_subscription: None,
 1453            tasks: Default::default(),
 1454            _subscriptions: vec![
 1455                cx.observe(&buffer, Self::on_buffer_changed),
 1456                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1457                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1458                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1459                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1460                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1461                cx.observe_window_activation(window, |editor, window, cx| {
 1462                    let active = window.is_window_active();
 1463                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1464                        if active {
 1465                            blink_manager.enable(cx);
 1466                        } else {
 1467                            blink_manager.disable(cx);
 1468                        }
 1469                    });
 1470                }),
 1471            ],
 1472            tasks_update_task: None,
 1473            linked_edit_ranges: Default::default(),
 1474            in_project_search: false,
 1475            previous_search_ranges: None,
 1476            breadcrumb_header: None,
 1477            focused_block: None,
 1478            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1479            addons: HashMap::default(),
 1480            registered_buffers: HashMap::default(),
 1481            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1482            selection_mark_mode: false,
 1483            toggle_fold_multiple_buffers: Task::ready(()),
 1484            serialize_selections: Task::ready(()),
 1485            text_style_refinement: None,
 1486            load_diff_task: load_uncommitted_diff,
 1487        };
 1488        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1489        this._subscriptions.extend(project_subscriptions);
 1490
 1491        this.end_selection(window, cx);
 1492        this.scroll_manager.show_scrollbar(window, cx);
 1493
 1494        if mode == EditorMode::Full {
 1495            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1496            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1497
 1498            if this.git_blame_inline_enabled {
 1499                this.git_blame_inline_enabled = true;
 1500                this.start_git_blame_inline(false, window, cx);
 1501            }
 1502
 1503            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1504                if let Some(project) = this.project.as_ref() {
 1505                    let handle = project.update(cx, |project, cx| {
 1506                        project.register_buffer_with_language_servers(&buffer, cx)
 1507                    });
 1508                    this.registered_buffers
 1509                        .insert(buffer.read(cx).remote_id(), handle);
 1510                }
 1511            }
 1512        }
 1513
 1514        this.report_editor_event("Editor Opened", None, cx);
 1515        this
 1516    }
 1517
 1518    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1519        self.mouse_context_menu
 1520            .as_ref()
 1521            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1522    }
 1523
 1524    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1525        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1526    }
 1527
 1528    fn key_context_internal(
 1529        &self,
 1530        has_active_edit_prediction: bool,
 1531        window: &Window,
 1532        cx: &App,
 1533    ) -> KeyContext {
 1534        let mut key_context = KeyContext::new_with_defaults();
 1535        key_context.add("Editor");
 1536        let mode = match self.mode {
 1537            EditorMode::SingleLine { .. } => "single_line",
 1538            EditorMode::AutoHeight { .. } => "auto_height",
 1539            EditorMode::Full => "full",
 1540        };
 1541
 1542        if EditorSettings::jupyter_enabled(cx) {
 1543            key_context.add("jupyter");
 1544        }
 1545
 1546        key_context.set("mode", mode);
 1547        if self.pending_rename.is_some() {
 1548            key_context.add("renaming");
 1549        }
 1550
 1551        match self.context_menu.borrow().as_ref() {
 1552            Some(CodeContextMenu::Completions(_)) => {
 1553                key_context.add("menu");
 1554                key_context.add("showing_completions");
 1555            }
 1556            Some(CodeContextMenu::CodeActions(_)) => {
 1557                key_context.add("menu");
 1558                key_context.add("showing_code_actions")
 1559            }
 1560            None => {}
 1561        }
 1562
 1563        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1564        if !self.focus_handle(cx).contains_focused(window, cx)
 1565            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1566        {
 1567            for addon in self.addons.values() {
 1568                addon.extend_key_context(&mut key_context, cx)
 1569            }
 1570        }
 1571
 1572        if let Some(extension) = self
 1573            .buffer
 1574            .read(cx)
 1575            .as_singleton()
 1576            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1577        {
 1578            key_context.set("extension", extension.to_string());
 1579        }
 1580
 1581        if has_active_edit_prediction {
 1582            if self.edit_prediction_in_conflict() {
 1583                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1584            } else {
 1585                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1586                key_context.add("copilot_suggestion");
 1587            }
 1588        }
 1589
 1590        if self.selection_mark_mode {
 1591            key_context.add("selection_mode");
 1592        }
 1593
 1594        key_context
 1595    }
 1596
 1597    pub fn edit_prediction_in_conflict(&self) -> bool {
 1598        if !self.show_edit_predictions_in_menu() {
 1599            return false;
 1600        }
 1601
 1602        let showing_completions = self
 1603            .context_menu
 1604            .borrow()
 1605            .as_ref()
 1606            .map_or(false, |context| {
 1607                matches!(context, CodeContextMenu::Completions(_))
 1608            });
 1609
 1610        showing_completions
 1611            || self.edit_prediction_requires_modifier()
 1612            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1613            // bindings to insert tab characters.
 1614            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1615    }
 1616
 1617    pub fn accept_edit_prediction_keybind(
 1618        &self,
 1619        window: &Window,
 1620        cx: &App,
 1621    ) -> AcceptEditPredictionBinding {
 1622        let key_context = self.key_context_internal(true, window, cx);
 1623        let in_conflict = self.edit_prediction_in_conflict();
 1624
 1625        AcceptEditPredictionBinding(
 1626            window
 1627                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1628                .into_iter()
 1629                .filter(|binding| {
 1630                    !in_conflict
 1631                        || binding
 1632                            .keystrokes()
 1633                            .first()
 1634                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1635                })
 1636                .rev()
 1637                .min_by_key(|binding| {
 1638                    binding
 1639                        .keystrokes()
 1640                        .first()
 1641                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1642                }),
 1643        )
 1644    }
 1645
 1646    pub fn new_file(
 1647        workspace: &mut Workspace,
 1648        _: &workspace::NewFile,
 1649        window: &mut Window,
 1650        cx: &mut Context<Workspace>,
 1651    ) {
 1652        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1653            "Failed to create buffer",
 1654            window,
 1655            cx,
 1656            |e, _, _| match e.error_code() {
 1657                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1658                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1659                e.error_tag("required").unwrap_or("the latest version")
 1660            )),
 1661                _ => None,
 1662            },
 1663        );
 1664    }
 1665
 1666    pub fn new_in_workspace(
 1667        workspace: &mut Workspace,
 1668        window: &mut Window,
 1669        cx: &mut Context<Workspace>,
 1670    ) -> Task<Result<Entity<Editor>>> {
 1671        let project = workspace.project().clone();
 1672        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1673
 1674        cx.spawn_in(window, |workspace, mut cx| async move {
 1675            let buffer = create.await?;
 1676            workspace.update_in(&mut cx, |workspace, window, cx| {
 1677                let editor =
 1678                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1679                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1680                editor
 1681            })
 1682        })
 1683    }
 1684
 1685    fn new_file_vertical(
 1686        workspace: &mut Workspace,
 1687        _: &workspace::NewFileSplitVertical,
 1688        window: &mut Window,
 1689        cx: &mut Context<Workspace>,
 1690    ) {
 1691        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1692    }
 1693
 1694    fn new_file_horizontal(
 1695        workspace: &mut Workspace,
 1696        _: &workspace::NewFileSplitHorizontal,
 1697        window: &mut Window,
 1698        cx: &mut Context<Workspace>,
 1699    ) {
 1700        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1701    }
 1702
 1703    fn new_file_in_direction(
 1704        workspace: &mut Workspace,
 1705        direction: SplitDirection,
 1706        window: &mut Window,
 1707        cx: &mut Context<Workspace>,
 1708    ) {
 1709        let project = workspace.project().clone();
 1710        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1711
 1712        cx.spawn_in(window, |workspace, mut cx| async move {
 1713            let buffer = create.await?;
 1714            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1715                workspace.split_item(
 1716                    direction,
 1717                    Box::new(
 1718                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1719                    ),
 1720                    window,
 1721                    cx,
 1722                )
 1723            })?;
 1724            anyhow::Ok(())
 1725        })
 1726        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1727            match e.error_code() {
 1728                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1729                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1730                e.error_tag("required").unwrap_or("the latest version")
 1731            )),
 1732                _ => None,
 1733            }
 1734        });
 1735    }
 1736
 1737    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1738        self.leader_peer_id
 1739    }
 1740
 1741    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1742        &self.buffer
 1743    }
 1744
 1745    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1746        self.workspace.as_ref()?.0.upgrade()
 1747    }
 1748
 1749    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1750        self.buffer().read(cx).title(cx)
 1751    }
 1752
 1753    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1754        let git_blame_gutter_max_author_length = self
 1755            .render_git_blame_gutter(cx)
 1756            .then(|| {
 1757                if let Some(blame) = self.blame.as_ref() {
 1758                    let max_author_length =
 1759                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1760                    Some(max_author_length)
 1761                } else {
 1762                    None
 1763                }
 1764            })
 1765            .flatten();
 1766
 1767        EditorSnapshot {
 1768            mode: self.mode,
 1769            show_gutter: self.show_gutter,
 1770            show_line_numbers: self.show_line_numbers,
 1771            show_git_diff_gutter: self.show_git_diff_gutter,
 1772            show_code_actions: self.show_code_actions,
 1773            show_runnables: self.show_runnables,
 1774            git_blame_gutter_max_author_length,
 1775            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1776            scroll_anchor: self.scroll_manager.anchor(),
 1777            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1778            placeholder_text: self.placeholder_text.clone(),
 1779            is_focused: self.focus_handle.is_focused(window),
 1780            current_line_highlight: self
 1781                .current_line_highlight
 1782                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1783            gutter_hovered: self.gutter_hovered,
 1784        }
 1785    }
 1786
 1787    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1788        self.buffer.read(cx).language_at(point, cx)
 1789    }
 1790
 1791    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1792        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1793    }
 1794
 1795    pub fn active_excerpt(
 1796        &self,
 1797        cx: &App,
 1798    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1799        self.buffer
 1800            .read(cx)
 1801            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1802    }
 1803
 1804    pub fn mode(&self) -> EditorMode {
 1805        self.mode
 1806    }
 1807
 1808    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1809        self.collaboration_hub.as_deref()
 1810    }
 1811
 1812    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1813        self.collaboration_hub = Some(hub);
 1814    }
 1815
 1816    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1817        self.in_project_search = in_project_search;
 1818    }
 1819
 1820    pub fn set_custom_context_menu(
 1821        &mut self,
 1822        f: impl 'static
 1823            + Fn(
 1824                &mut Self,
 1825                DisplayPoint,
 1826                &mut Window,
 1827                &mut Context<Self>,
 1828            ) -> Option<Entity<ui::ContextMenu>>,
 1829    ) {
 1830        self.custom_context_menu = Some(Box::new(f))
 1831    }
 1832
 1833    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1834        self.completion_provider = provider;
 1835    }
 1836
 1837    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1838        self.semantics_provider.clone()
 1839    }
 1840
 1841    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1842        self.semantics_provider = provider;
 1843    }
 1844
 1845    pub fn set_edit_prediction_provider<T>(
 1846        &mut self,
 1847        provider: Option<Entity<T>>,
 1848        window: &mut Window,
 1849        cx: &mut Context<Self>,
 1850    ) where
 1851        T: EditPredictionProvider,
 1852    {
 1853        self.edit_prediction_provider =
 1854            provider.map(|provider| RegisteredInlineCompletionProvider {
 1855                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1856                    if this.focus_handle.is_focused(window) {
 1857                        this.update_visible_inline_completion(window, cx);
 1858                    }
 1859                }),
 1860                provider: Arc::new(provider),
 1861            });
 1862        self.update_edit_prediction_settings(cx);
 1863        self.refresh_inline_completion(false, false, window, cx);
 1864    }
 1865
 1866    pub fn placeholder_text(&self) -> Option<&str> {
 1867        self.placeholder_text.as_deref()
 1868    }
 1869
 1870    pub fn set_placeholder_text(
 1871        &mut self,
 1872        placeholder_text: impl Into<Arc<str>>,
 1873        cx: &mut Context<Self>,
 1874    ) {
 1875        let placeholder_text = Some(placeholder_text.into());
 1876        if self.placeholder_text != placeholder_text {
 1877            self.placeholder_text = placeholder_text;
 1878            cx.notify();
 1879        }
 1880    }
 1881
 1882    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1883        self.cursor_shape = cursor_shape;
 1884
 1885        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1886        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1887
 1888        cx.notify();
 1889    }
 1890
 1891    pub fn set_current_line_highlight(
 1892        &mut self,
 1893        current_line_highlight: Option<CurrentLineHighlight>,
 1894    ) {
 1895        self.current_line_highlight = current_line_highlight;
 1896    }
 1897
 1898    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1899        self.collapse_matches = collapse_matches;
 1900    }
 1901
 1902    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1903        let buffers = self.buffer.read(cx).all_buffers();
 1904        let Some(project) = self.project.as_ref() else {
 1905            return;
 1906        };
 1907        project.update(cx, |project, cx| {
 1908            for buffer in buffers {
 1909                self.registered_buffers
 1910                    .entry(buffer.read(cx).remote_id())
 1911                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1912            }
 1913        })
 1914    }
 1915
 1916    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1917        if self.collapse_matches {
 1918            return range.start..range.start;
 1919        }
 1920        range.clone()
 1921    }
 1922
 1923    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1924        if self.display_map.read(cx).clip_at_line_ends != clip {
 1925            self.display_map
 1926                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1927        }
 1928    }
 1929
 1930    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1931        self.input_enabled = input_enabled;
 1932    }
 1933
 1934    pub fn set_inline_completions_hidden_for_vim_mode(
 1935        &mut self,
 1936        hidden: bool,
 1937        window: &mut Window,
 1938        cx: &mut Context<Self>,
 1939    ) {
 1940        if hidden != self.inline_completions_hidden_for_vim_mode {
 1941            self.inline_completions_hidden_for_vim_mode = hidden;
 1942            if hidden {
 1943                self.update_visible_inline_completion(window, cx);
 1944            } else {
 1945                self.refresh_inline_completion(true, false, window, cx);
 1946            }
 1947        }
 1948    }
 1949
 1950    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1951        self.menu_inline_completions_policy = value;
 1952    }
 1953
 1954    pub fn set_autoindent(&mut self, autoindent: bool) {
 1955        if autoindent {
 1956            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1957        } else {
 1958            self.autoindent_mode = None;
 1959        }
 1960    }
 1961
 1962    pub fn read_only(&self, cx: &App) -> bool {
 1963        self.read_only || self.buffer.read(cx).read_only()
 1964    }
 1965
 1966    pub fn set_read_only(&mut self, read_only: bool) {
 1967        self.read_only = read_only;
 1968    }
 1969
 1970    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1971        self.use_autoclose = autoclose;
 1972    }
 1973
 1974    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1975        self.use_auto_surround = auto_surround;
 1976    }
 1977
 1978    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1979        self.auto_replace_emoji_shortcode = auto_replace;
 1980    }
 1981
 1982    pub fn toggle_edit_predictions(
 1983        &mut self,
 1984        _: &ToggleEditPrediction,
 1985        window: &mut Window,
 1986        cx: &mut Context<Self>,
 1987    ) {
 1988        if self.show_inline_completions_override.is_some() {
 1989            self.set_show_edit_predictions(None, window, cx);
 1990        } else {
 1991            let show_edit_predictions = !self.edit_predictions_enabled();
 1992            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1993        }
 1994    }
 1995
 1996    pub fn set_show_edit_predictions(
 1997        &mut self,
 1998        show_edit_predictions: Option<bool>,
 1999        window: &mut Window,
 2000        cx: &mut Context<Self>,
 2001    ) {
 2002        self.show_inline_completions_override = show_edit_predictions;
 2003        self.update_edit_prediction_settings(cx);
 2004
 2005        if let Some(false) = show_edit_predictions {
 2006            self.discard_inline_completion(false, cx);
 2007        } else {
 2008            self.refresh_inline_completion(false, true, window, cx);
 2009        }
 2010    }
 2011
 2012    fn inline_completions_disabled_in_scope(
 2013        &self,
 2014        buffer: &Entity<Buffer>,
 2015        buffer_position: language::Anchor,
 2016        cx: &App,
 2017    ) -> bool {
 2018        let snapshot = buffer.read(cx).snapshot();
 2019        let settings = snapshot.settings_at(buffer_position, cx);
 2020
 2021        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2022            return false;
 2023        };
 2024
 2025        scope.override_name().map_or(false, |scope_name| {
 2026            settings
 2027                .edit_predictions_disabled_in
 2028                .iter()
 2029                .any(|s| s == scope_name)
 2030        })
 2031    }
 2032
 2033    pub fn set_use_modal_editing(&mut self, to: bool) {
 2034        self.use_modal_editing = to;
 2035    }
 2036
 2037    pub fn use_modal_editing(&self) -> bool {
 2038        self.use_modal_editing
 2039    }
 2040
 2041    fn selections_did_change(
 2042        &mut self,
 2043        local: bool,
 2044        old_cursor_position: &Anchor,
 2045        show_completions: bool,
 2046        window: &mut Window,
 2047        cx: &mut Context<Self>,
 2048    ) {
 2049        window.invalidate_character_coordinates();
 2050
 2051        // Copy selections to primary selection buffer
 2052        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2053        if local {
 2054            let selections = self.selections.all::<usize>(cx);
 2055            let buffer_handle = self.buffer.read(cx).read(cx);
 2056
 2057            let mut text = String::new();
 2058            for (index, selection) in selections.iter().enumerate() {
 2059                let text_for_selection = buffer_handle
 2060                    .text_for_range(selection.start..selection.end)
 2061                    .collect::<String>();
 2062
 2063                text.push_str(&text_for_selection);
 2064                if index != selections.len() - 1 {
 2065                    text.push('\n');
 2066                }
 2067            }
 2068
 2069            if !text.is_empty() {
 2070                cx.write_to_primary(ClipboardItem::new_string(text));
 2071            }
 2072        }
 2073
 2074        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2075            self.buffer.update(cx, |buffer, cx| {
 2076                buffer.set_active_selections(
 2077                    &self.selections.disjoint_anchors(),
 2078                    self.selections.line_mode,
 2079                    self.cursor_shape,
 2080                    cx,
 2081                )
 2082            });
 2083        }
 2084        let display_map = self
 2085            .display_map
 2086            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2087        let buffer = &display_map.buffer_snapshot;
 2088        self.add_selections_state = None;
 2089        self.select_next_state = None;
 2090        self.select_prev_state = None;
 2091        self.select_larger_syntax_node_stack.clear();
 2092        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2093        self.snippet_stack
 2094            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2095        self.take_rename(false, window, cx);
 2096
 2097        let new_cursor_position = self.selections.newest_anchor().head();
 2098
 2099        self.push_to_nav_history(
 2100            *old_cursor_position,
 2101            Some(new_cursor_position.to_point(buffer)),
 2102            cx,
 2103        );
 2104
 2105        if local {
 2106            let new_cursor_position = self.selections.newest_anchor().head();
 2107            let mut context_menu = self.context_menu.borrow_mut();
 2108            let completion_menu = match context_menu.as_ref() {
 2109                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2110                _ => {
 2111                    *context_menu = None;
 2112                    None
 2113                }
 2114            };
 2115            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2116                if !self.registered_buffers.contains_key(&buffer_id) {
 2117                    if let Some(project) = self.project.as_ref() {
 2118                        project.update(cx, |project, cx| {
 2119                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2120                                return;
 2121                            };
 2122                            self.registered_buffers.insert(
 2123                                buffer_id,
 2124                                project.register_buffer_with_language_servers(&buffer, cx),
 2125                            );
 2126                        })
 2127                    }
 2128                }
 2129            }
 2130
 2131            if let Some(completion_menu) = completion_menu {
 2132                let cursor_position = new_cursor_position.to_offset(buffer);
 2133                let (word_range, kind) =
 2134                    buffer.surrounding_word(completion_menu.initial_position, true);
 2135                if kind == Some(CharKind::Word)
 2136                    && word_range.to_inclusive().contains(&cursor_position)
 2137                {
 2138                    let mut completion_menu = completion_menu.clone();
 2139                    drop(context_menu);
 2140
 2141                    let query = Self::completion_query(buffer, cursor_position);
 2142                    cx.spawn(move |this, mut cx| async move {
 2143                        completion_menu
 2144                            .filter(query.as_deref(), cx.background_executor().clone())
 2145                            .await;
 2146
 2147                        this.update(&mut cx, |this, cx| {
 2148                            let mut context_menu = this.context_menu.borrow_mut();
 2149                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2150                            else {
 2151                                return;
 2152                            };
 2153
 2154                            if menu.id > completion_menu.id {
 2155                                return;
 2156                            }
 2157
 2158                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2159                            drop(context_menu);
 2160                            cx.notify();
 2161                        })
 2162                    })
 2163                    .detach();
 2164
 2165                    if show_completions {
 2166                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2167                    }
 2168                } else {
 2169                    drop(context_menu);
 2170                    self.hide_context_menu(window, cx);
 2171                }
 2172            } else {
 2173                drop(context_menu);
 2174            }
 2175
 2176            hide_hover(self, cx);
 2177
 2178            if old_cursor_position.to_display_point(&display_map).row()
 2179                != new_cursor_position.to_display_point(&display_map).row()
 2180            {
 2181                self.available_code_actions.take();
 2182            }
 2183            self.refresh_code_actions(window, cx);
 2184            self.refresh_document_highlights(cx);
 2185            self.refresh_selected_text_highlights(window, cx);
 2186            refresh_matching_bracket_highlights(self, window, cx);
 2187            self.update_visible_inline_completion(window, cx);
 2188            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2189            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2190            if self.git_blame_inline_enabled {
 2191                self.start_inline_blame_timer(window, cx);
 2192            }
 2193        }
 2194
 2195        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2196        cx.emit(EditorEvent::SelectionsChanged { local });
 2197
 2198        let selections = &self.selections.disjoint;
 2199        if selections.len() == 1 {
 2200            cx.emit(SearchEvent::ActiveMatchChanged)
 2201        }
 2202        if local
 2203            && self.is_singleton(cx)
 2204            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2205        {
 2206            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2207                let background_executor = cx.background_executor().clone();
 2208                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2209                let snapshot = self.buffer().read(cx).snapshot(cx);
 2210                let selections = selections.clone();
 2211                self.serialize_selections = cx.background_spawn(async move {
 2212                    background_executor.timer(Duration::from_millis(100)).await;
 2213                    let selections = selections
 2214                        .iter()
 2215                        .map(|selection| {
 2216                            (
 2217                                selection.start.to_offset(&snapshot),
 2218                                selection.end.to_offset(&snapshot),
 2219                            )
 2220                        })
 2221                        .collect();
 2222                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2223                        .await
 2224                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2225                        .log_err();
 2226                });
 2227            }
 2228        }
 2229
 2230        cx.notify();
 2231    }
 2232
 2233    pub fn change_selections<R>(
 2234        &mut self,
 2235        autoscroll: Option<Autoscroll>,
 2236        window: &mut Window,
 2237        cx: &mut Context<Self>,
 2238        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2239    ) -> R {
 2240        self.change_selections_inner(autoscroll, true, window, cx, change)
 2241    }
 2242
 2243    fn change_selections_inner<R>(
 2244        &mut self,
 2245        autoscroll: Option<Autoscroll>,
 2246        request_completions: bool,
 2247        window: &mut Window,
 2248        cx: &mut Context<Self>,
 2249        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2250    ) -> R {
 2251        let old_cursor_position = self.selections.newest_anchor().head();
 2252        self.push_to_selection_history();
 2253
 2254        let (changed, result) = self.selections.change_with(cx, change);
 2255
 2256        if changed {
 2257            if let Some(autoscroll) = autoscroll {
 2258                self.request_autoscroll(autoscroll, cx);
 2259            }
 2260            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2261
 2262            if self.should_open_signature_help_automatically(
 2263                &old_cursor_position,
 2264                self.signature_help_state.backspace_pressed(),
 2265                cx,
 2266            ) {
 2267                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2268            }
 2269            self.signature_help_state.set_backspace_pressed(false);
 2270        }
 2271
 2272        result
 2273    }
 2274
 2275    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2276    where
 2277        I: IntoIterator<Item = (Range<S>, T)>,
 2278        S: ToOffset,
 2279        T: Into<Arc<str>>,
 2280    {
 2281        if self.read_only(cx) {
 2282            return;
 2283        }
 2284
 2285        self.buffer
 2286            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2287    }
 2288
 2289    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2290    where
 2291        I: IntoIterator<Item = (Range<S>, T)>,
 2292        S: ToOffset,
 2293        T: Into<Arc<str>>,
 2294    {
 2295        if self.read_only(cx) {
 2296            return;
 2297        }
 2298
 2299        self.buffer.update(cx, |buffer, cx| {
 2300            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2301        });
 2302    }
 2303
 2304    pub fn edit_with_block_indent<I, S, T>(
 2305        &mut self,
 2306        edits: I,
 2307        original_start_columns: Vec<u32>,
 2308        cx: &mut Context<Self>,
 2309    ) where
 2310        I: IntoIterator<Item = (Range<S>, T)>,
 2311        S: ToOffset,
 2312        T: Into<Arc<str>>,
 2313    {
 2314        if self.read_only(cx) {
 2315            return;
 2316        }
 2317
 2318        self.buffer.update(cx, |buffer, cx| {
 2319            buffer.edit(
 2320                edits,
 2321                Some(AutoindentMode::Block {
 2322                    original_start_columns,
 2323                }),
 2324                cx,
 2325            )
 2326        });
 2327    }
 2328
 2329    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2330        self.hide_context_menu(window, cx);
 2331
 2332        match phase {
 2333            SelectPhase::Begin {
 2334                position,
 2335                add,
 2336                click_count,
 2337            } => self.begin_selection(position, add, click_count, window, cx),
 2338            SelectPhase::BeginColumnar {
 2339                position,
 2340                goal_column,
 2341                reset,
 2342            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2343            SelectPhase::Extend {
 2344                position,
 2345                click_count,
 2346            } => self.extend_selection(position, click_count, window, cx),
 2347            SelectPhase::Update {
 2348                position,
 2349                goal_column,
 2350                scroll_delta,
 2351            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2352            SelectPhase::End => self.end_selection(window, cx),
 2353        }
 2354    }
 2355
 2356    fn extend_selection(
 2357        &mut self,
 2358        position: DisplayPoint,
 2359        click_count: usize,
 2360        window: &mut Window,
 2361        cx: &mut Context<Self>,
 2362    ) {
 2363        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2364        let tail = self.selections.newest::<usize>(cx).tail();
 2365        self.begin_selection(position, false, click_count, window, cx);
 2366
 2367        let position = position.to_offset(&display_map, Bias::Left);
 2368        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2369
 2370        let mut pending_selection = self
 2371            .selections
 2372            .pending_anchor()
 2373            .expect("extend_selection not called with pending selection");
 2374        if position >= tail {
 2375            pending_selection.start = tail_anchor;
 2376        } else {
 2377            pending_selection.end = tail_anchor;
 2378            pending_selection.reversed = true;
 2379        }
 2380
 2381        let mut pending_mode = self.selections.pending_mode().unwrap();
 2382        match &mut pending_mode {
 2383            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2384            _ => {}
 2385        }
 2386
 2387        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2388            s.set_pending(pending_selection, pending_mode)
 2389        });
 2390    }
 2391
 2392    fn begin_selection(
 2393        &mut self,
 2394        position: DisplayPoint,
 2395        add: bool,
 2396        click_count: usize,
 2397        window: &mut Window,
 2398        cx: &mut Context<Self>,
 2399    ) {
 2400        if !self.focus_handle.is_focused(window) {
 2401            self.last_focused_descendant = None;
 2402            window.focus(&self.focus_handle);
 2403        }
 2404
 2405        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2406        let buffer = &display_map.buffer_snapshot;
 2407        let newest_selection = self.selections.newest_anchor().clone();
 2408        let position = display_map.clip_point(position, Bias::Left);
 2409
 2410        let start;
 2411        let end;
 2412        let mode;
 2413        let mut auto_scroll;
 2414        match click_count {
 2415            1 => {
 2416                start = buffer.anchor_before(position.to_point(&display_map));
 2417                end = start;
 2418                mode = SelectMode::Character;
 2419                auto_scroll = true;
 2420            }
 2421            2 => {
 2422                let range = movement::surrounding_word(&display_map, position);
 2423                start = buffer.anchor_before(range.start.to_point(&display_map));
 2424                end = buffer.anchor_before(range.end.to_point(&display_map));
 2425                mode = SelectMode::Word(start..end);
 2426                auto_scroll = true;
 2427            }
 2428            3 => {
 2429                let position = display_map
 2430                    .clip_point(position, Bias::Left)
 2431                    .to_point(&display_map);
 2432                let line_start = display_map.prev_line_boundary(position).0;
 2433                let next_line_start = buffer.clip_point(
 2434                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2435                    Bias::Left,
 2436                );
 2437                start = buffer.anchor_before(line_start);
 2438                end = buffer.anchor_before(next_line_start);
 2439                mode = SelectMode::Line(start..end);
 2440                auto_scroll = true;
 2441            }
 2442            _ => {
 2443                start = buffer.anchor_before(0);
 2444                end = buffer.anchor_before(buffer.len());
 2445                mode = SelectMode::All;
 2446                auto_scroll = false;
 2447            }
 2448        }
 2449        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2450
 2451        let point_to_delete: Option<usize> = {
 2452            let selected_points: Vec<Selection<Point>> =
 2453                self.selections.disjoint_in_range(start..end, cx);
 2454
 2455            if !add || click_count > 1 {
 2456                None
 2457            } else if !selected_points.is_empty() {
 2458                Some(selected_points[0].id)
 2459            } else {
 2460                let clicked_point_already_selected =
 2461                    self.selections.disjoint.iter().find(|selection| {
 2462                        selection.start.to_point(buffer) == start.to_point(buffer)
 2463                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2464                    });
 2465
 2466                clicked_point_already_selected.map(|selection| selection.id)
 2467            }
 2468        };
 2469
 2470        let selections_count = self.selections.count();
 2471
 2472        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2473            if let Some(point_to_delete) = point_to_delete {
 2474                s.delete(point_to_delete);
 2475
 2476                if selections_count == 1 {
 2477                    s.set_pending_anchor_range(start..end, mode);
 2478                }
 2479            } else {
 2480                if !add {
 2481                    s.clear_disjoint();
 2482                } else if click_count > 1 {
 2483                    s.delete(newest_selection.id)
 2484                }
 2485
 2486                s.set_pending_anchor_range(start..end, mode);
 2487            }
 2488        });
 2489    }
 2490
 2491    fn begin_columnar_selection(
 2492        &mut self,
 2493        position: DisplayPoint,
 2494        goal_column: u32,
 2495        reset: bool,
 2496        window: &mut Window,
 2497        cx: &mut Context<Self>,
 2498    ) {
 2499        if !self.focus_handle.is_focused(window) {
 2500            self.last_focused_descendant = None;
 2501            window.focus(&self.focus_handle);
 2502        }
 2503
 2504        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2505
 2506        if reset {
 2507            let pointer_position = display_map
 2508                .buffer_snapshot
 2509                .anchor_before(position.to_point(&display_map));
 2510
 2511            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2512                s.clear_disjoint();
 2513                s.set_pending_anchor_range(
 2514                    pointer_position..pointer_position,
 2515                    SelectMode::Character,
 2516                );
 2517            });
 2518        }
 2519
 2520        let tail = self.selections.newest::<Point>(cx).tail();
 2521        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2522
 2523        if !reset {
 2524            self.select_columns(
 2525                tail.to_display_point(&display_map),
 2526                position,
 2527                goal_column,
 2528                &display_map,
 2529                window,
 2530                cx,
 2531            );
 2532        }
 2533    }
 2534
 2535    fn update_selection(
 2536        &mut self,
 2537        position: DisplayPoint,
 2538        goal_column: u32,
 2539        scroll_delta: gpui::Point<f32>,
 2540        window: &mut Window,
 2541        cx: &mut Context<Self>,
 2542    ) {
 2543        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2544
 2545        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2546            let tail = tail.to_display_point(&display_map);
 2547            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2548        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2549            let buffer = self.buffer.read(cx).snapshot(cx);
 2550            let head;
 2551            let tail;
 2552            let mode = self.selections.pending_mode().unwrap();
 2553            match &mode {
 2554                SelectMode::Character => {
 2555                    head = position.to_point(&display_map);
 2556                    tail = pending.tail().to_point(&buffer);
 2557                }
 2558                SelectMode::Word(original_range) => {
 2559                    let original_display_range = original_range.start.to_display_point(&display_map)
 2560                        ..original_range.end.to_display_point(&display_map);
 2561                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2562                        ..original_display_range.end.to_point(&display_map);
 2563                    if movement::is_inside_word(&display_map, position)
 2564                        || original_display_range.contains(&position)
 2565                    {
 2566                        let word_range = movement::surrounding_word(&display_map, position);
 2567                        if word_range.start < original_display_range.start {
 2568                            head = word_range.start.to_point(&display_map);
 2569                        } else {
 2570                            head = word_range.end.to_point(&display_map);
 2571                        }
 2572                    } else {
 2573                        head = position.to_point(&display_map);
 2574                    }
 2575
 2576                    if head <= original_buffer_range.start {
 2577                        tail = original_buffer_range.end;
 2578                    } else {
 2579                        tail = original_buffer_range.start;
 2580                    }
 2581                }
 2582                SelectMode::Line(original_range) => {
 2583                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2584
 2585                    let position = display_map
 2586                        .clip_point(position, Bias::Left)
 2587                        .to_point(&display_map);
 2588                    let line_start = display_map.prev_line_boundary(position).0;
 2589                    let next_line_start = buffer.clip_point(
 2590                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2591                        Bias::Left,
 2592                    );
 2593
 2594                    if line_start < original_range.start {
 2595                        head = line_start
 2596                    } else {
 2597                        head = next_line_start
 2598                    }
 2599
 2600                    if head <= original_range.start {
 2601                        tail = original_range.end;
 2602                    } else {
 2603                        tail = original_range.start;
 2604                    }
 2605                }
 2606                SelectMode::All => {
 2607                    return;
 2608                }
 2609            };
 2610
 2611            if head < tail {
 2612                pending.start = buffer.anchor_before(head);
 2613                pending.end = buffer.anchor_before(tail);
 2614                pending.reversed = true;
 2615            } else {
 2616                pending.start = buffer.anchor_before(tail);
 2617                pending.end = buffer.anchor_before(head);
 2618                pending.reversed = false;
 2619            }
 2620
 2621            self.change_selections(None, window, cx, |s| {
 2622                s.set_pending(pending, mode);
 2623            });
 2624        } else {
 2625            log::error!("update_selection dispatched with no pending selection");
 2626            return;
 2627        }
 2628
 2629        self.apply_scroll_delta(scroll_delta, window, cx);
 2630        cx.notify();
 2631    }
 2632
 2633    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2634        self.columnar_selection_tail.take();
 2635        if self.selections.pending_anchor().is_some() {
 2636            let selections = self.selections.all::<usize>(cx);
 2637            self.change_selections(None, window, cx, |s| {
 2638                s.select(selections);
 2639                s.clear_pending();
 2640            });
 2641        }
 2642    }
 2643
 2644    fn select_columns(
 2645        &mut self,
 2646        tail: DisplayPoint,
 2647        head: DisplayPoint,
 2648        goal_column: u32,
 2649        display_map: &DisplaySnapshot,
 2650        window: &mut Window,
 2651        cx: &mut Context<Self>,
 2652    ) {
 2653        let start_row = cmp::min(tail.row(), head.row());
 2654        let end_row = cmp::max(tail.row(), head.row());
 2655        let start_column = cmp::min(tail.column(), goal_column);
 2656        let end_column = cmp::max(tail.column(), goal_column);
 2657        let reversed = start_column < tail.column();
 2658
 2659        let selection_ranges = (start_row.0..=end_row.0)
 2660            .map(DisplayRow)
 2661            .filter_map(|row| {
 2662                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2663                    let start = display_map
 2664                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2665                        .to_point(display_map);
 2666                    let end = display_map
 2667                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2668                        .to_point(display_map);
 2669                    if reversed {
 2670                        Some(end..start)
 2671                    } else {
 2672                        Some(start..end)
 2673                    }
 2674                } else {
 2675                    None
 2676                }
 2677            })
 2678            .collect::<Vec<_>>();
 2679
 2680        self.change_selections(None, window, cx, |s| {
 2681            s.select_ranges(selection_ranges);
 2682        });
 2683        cx.notify();
 2684    }
 2685
 2686    pub fn has_pending_nonempty_selection(&self) -> bool {
 2687        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2688            Some(Selection { start, end, .. }) => start != end,
 2689            None => false,
 2690        };
 2691
 2692        pending_nonempty_selection
 2693            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2694    }
 2695
 2696    pub fn has_pending_selection(&self) -> bool {
 2697        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2698    }
 2699
 2700    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2701        self.selection_mark_mode = false;
 2702
 2703        if self.clear_expanded_diff_hunks(cx) {
 2704            cx.notify();
 2705            return;
 2706        }
 2707        if self.dismiss_menus_and_popups(true, window, cx) {
 2708            return;
 2709        }
 2710
 2711        if self.mode == EditorMode::Full
 2712            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2713        {
 2714            return;
 2715        }
 2716
 2717        cx.propagate();
 2718    }
 2719
 2720    pub fn dismiss_menus_and_popups(
 2721        &mut self,
 2722        is_user_requested: bool,
 2723        window: &mut Window,
 2724        cx: &mut Context<Self>,
 2725    ) -> bool {
 2726        if self.take_rename(false, window, cx).is_some() {
 2727            return true;
 2728        }
 2729
 2730        if hide_hover(self, cx) {
 2731            return true;
 2732        }
 2733
 2734        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2735            return true;
 2736        }
 2737
 2738        if self.hide_context_menu(window, cx).is_some() {
 2739            return true;
 2740        }
 2741
 2742        if self.mouse_context_menu.take().is_some() {
 2743            return true;
 2744        }
 2745
 2746        if is_user_requested && self.discard_inline_completion(true, cx) {
 2747            return true;
 2748        }
 2749
 2750        if self.snippet_stack.pop().is_some() {
 2751            return true;
 2752        }
 2753
 2754        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2755            self.dismiss_diagnostics(cx);
 2756            return true;
 2757        }
 2758
 2759        false
 2760    }
 2761
 2762    fn linked_editing_ranges_for(
 2763        &self,
 2764        selection: Range<text::Anchor>,
 2765        cx: &App,
 2766    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2767        if self.linked_edit_ranges.is_empty() {
 2768            return None;
 2769        }
 2770        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2771            selection.end.buffer_id.and_then(|end_buffer_id| {
 2772                if selection.start.buffer_id != Some(end_buffer_id) {
 2773                    return None;
 2774                }
 2775                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2776                let snapshot = buffer.read(cx).snapshot();
 2777                self.linked_edit_ranges
 2778                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2779                    .map(|ranges| (ranges, snapshot, buffer))
 2780            })?;
 2781        use text::ToOffset as TO;
 2782        // find offset from the start of current range to current cursor position
 2783        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2784
 2785        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2786        let start_difference = start_offset - start_byte_offset;
 2787        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2788        let end_difference = end_offset - start_byte_offset;
 2789        // Current range has associated linked ranges.
 2790        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2791        for range in linked_ranges.iter() {
 2792            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2793            let end_offset = start_offset + end_difference;
 2794            let start_offset = start_offset + start_difference;
 2795            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2796                continue;
 2797            }
 2798            if self.selections.disjoint_anchor_ranges().any(|s| {
 2799                if s.start.buffer_id != selection.start.buffer_id
 2800                    || s.end.buffer_id != selection.end.buffer_id
 2801                {
 2802                    return false;
 2803                }
 2804                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2805                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2806            }) {
 2807                continue;
 2808            }
 2809            let start = buffer_snapshot.anchor_after(start_offset);
 2810            let end = buffer_snapshot.anchor_after(end_offset);
 2811            linked_edits
 2812                .entry(buffer.clone())
 2813                .or_default()
 2814                .push(start..end);
 2815        }
 2816        Some(linked_edits)
 2817    }
 2818
 2819    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2820        let text: Arc<str> = text.into();
 2821
 2822        if self.read_only(cx) {
 2823            return;
 2824        }
 2825
 2826        let selections = self.selections.all_adjusted(cx);
 2827        let mut bracket_inserted = false;
 2828        let mut edits = Vec::new();
 2829        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2830        let mut new_selections = Vec::with_capacity(selections.len());
 2831        let mut new_autoclose_regions = Vec::new();
 2832        let snapshot = self.buffer.read(cx).read(cx);
 2833
 2834        for (selection, autoclose_region) in
 2835            self.selections_with_autoclose_regions(selections, &snapshot)
 2836        {
 2837            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2838                // Determine if the inserted text matches the opening or closing
 2839                // bracket of any of this language's bracket pairs.
 2840                let mut bracket_pair = None;
 2841                let mut is_bracket_pair_start = false;
 2842                let mut is_bracket_pair_end = false;
 2843                if !text.is_empty() {
 2844                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2845                    //  and they are removing the character that triggered IME popup.
 2846                    for (pair, enabled) in scope.brackets() {
 2847                        if !pair.close && !pair.surround {
 2848                            continue;
 2849                        }
 2850
 2851                        if enabled && pair.start.ends_with(text.as_ref()) {
 2852                            let prefix_len = pair.start.len() - text.len();
 2853                            let preceding_text_matches_prefix = prefix_len == 0
 2854                                || (selection.start.column >= (prefix_len as u32)
 2855                                    && snapshot.contains_str_at(
 2856                                        Point::new(
 2857                                            selection.start.row,
 2858                                            selection.start.column - (prefix_len as u32),
 2859                                        ),
 2860                                        &pair.start[..prefix_len],
 2861                                    ));
 2862                            if preceding_text_matches_prefix {
 2863                                bracket_pair = Some(pair.clone());
 2864                                is_bracket_pair_start = true;
 2865                                break;
 2866                            }
 2867                        }
 2868                        if pair.end.as_str() == text.as_ref() {
 2869                            bracket_pair = Some(pair.clone());
 2870                            is_bracket_pair_end = true;
 2871                            break;
 2872                        }
 2873                    }
 2874                }
 2875
 2876                if let Some(bracket_pair) = bracket_pair {
 2877                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2878                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2879                    let auto_surround =
 2880                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2881                    if selection.is_empty() {
 2882                        if is_bracket_pair_start {
 2883                            // If the inserted text is a suffix of an opening bracket and the
 2884                            // selection is preceded by the rest of the opening bracket, then
 2885                            // insert the closing bracket.
 2886                            let following_text_allows_autoclose = snapshot
 2887                                .chars_at(selection.start)
 2888                                .next()
 2889                                .map_or(true, |c| scope.should_autoclose_before(c));
 2890
 2891                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2892                                && bracket_pair.start.len() == 1
 2893                            {
 2894                                let target = bracket_pair.start.chars().next().unwrap();
 2895                                let current_line_count = snapshot
 2896                                    .reversed_chars_at(selection.start)
 2897                                    .take_while(|&c| c != '\n')
 2898                                    .filter(|&c| c == target)
 2899                                    .count();
 2900                                current_line_count % 2 == 1
 2901                            } else {
 2902                                false
 2903                            };
 2904
 2905                            if autoclose
 2906                                && bracket_pair.close
 2907                                && following_text_allows_autoclose
 2908                                && !is_closing_quote
 2909                            {
 2910                                let anchor = snapshot.anchor_before(selection.end);
 2911                                new_selections.push((selection.map(|_| anchor), text.len()));
 2912                                new_autoclose_regions.push((
 2913                                    anchor,
 2914                                    text.len(),
 2915                                    selection.id,
 2916                                    bracket_pair.clone(),
 2917                                ));
 2918                                edits.push((
 2919                                    selection.range(),
 2920                                    format!("{}{}", text, bracket_pair.end).into(),
 2921                                ));
 2922                                bracket_inserted = true;
 2923                                continue;
 2924                            }
 2925                        }
 2926
 2927                        if let Some(region) = autoclose_region {
 2928                            // If the selection is followed by an auto-inserted closing bracket,
 2929                            // then don't insert that closing bracket again; just move the selection
 2930                            // past the closing bracket.
 2931                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2932                                && text.as_ref() == region.pair.end.as_str();
 2933                            if should_skip {
 2934                                let anchor = snapshot.anchor_after(selection.end);
 2935                                new_selections
 2936                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2937                                continue;
 2938                            }
 2939                        }
 2940
 2941                        let always_treat_brackets_as_autoclosed = snapshot
 2942                            .settings_at(selection.start, cx)
 2943                            .always_treat_brackets_as_autoclosed;
 2944                        if always_treat_brackets_as_autoclosed
 2945                            && is_bracket_pair_end
 2946                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2947                        {
 2948                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2949                            // and the inserted text is a closing bracket and the selection is followed
 2950                            // by the closing bracket then move the selection past the closing bracket.
 2951                            let anchor = snapshot.anchor_after(selection.end);
 2952                            new_selections.push((selection.map(|_| anchor), text.len()));
 2953                            continue;
 2954                        }
 2955                    }
 2956                    // If an opening bracket is 1 character long and is typed while
 2957                    // text is selected, then surround that text with the bracket pair.
 2958                    else if auto_surround
 2959                        && bracket_pair.surround
 2960                        && is_bracket_pair_start
 2961                        && bracket_pair.start.chars().count() == 1
 2962                    {
 2963                        edits.push((selection.start..selection.start, text.clone()));
 2964                        edits.push((
 2965                            selection.end..selection.end,
 2966                            bracket_pair.end.as_str().into(),
 2967                        ));
 2968                        bracket_inserted = true;
 2969                        new_selections.push((
 2970                            Selection {
 2971                                id: selection.id,
 2972                                start: snapshot.anchor_after(selection.start),
 2973                                end: snapshot.anchor_before(selection.end),
 2974                                reversed: selection.reversed,
 2975                                goal: selection.goal,
 2976                            },
 2977                            0,
 2978                        ));
 2979                        continue;
 2980                    }
 2981                }
 2982            }
 2983
 2984            if self.auto_replace_emoji_shortcode
 2985                && selection.is_empty()
 2986                && text.as_ref().ends_with(':')
 2987            {
 2988                if let Some(possible_emoji_short_code) =
 2989                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2990                {
 2991                    if !possible_emoji_short_code.is_empty() {
 2992                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2993                            let emoji_shortcode_start = Point::new(
 2994                                selection.start.row,
 2995                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2996                            );
 2997
 2998                            // Remove shortcode from buffer
 2999                            edits.push((
 3000                                emoji_shortcode_start..selection.start,
 3001                                "".to_string().into(),
 3002                            ));
 3003                            new_selections.push((
 3004                                Selection {
 3005                                    id: selection.id,
 3006                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3007                                    end: snapshot.anchor_before(selection.start),
 3008                                    reversed: selection.reversed,
 3009                                    goal: selection.goal,
 3010                                },
 3011                                0,
 3012                            ));
 3013
 3014                            // Insert emoji
 3015                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3016                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3017                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3018
 3019                            continue;
 3020                        }
 3021                    }
 3022                }
 3023            }
 3024
 3025            // If not handling any auto-close operation, then just replace the selected
 3026            // text with the given input and move the selection to the end of the
 3027            // newly inserted text.
 3028            let anchor = snapshot.anchor_after(selection.end);
 3029            if !self.linked_edit_ranges.is_empty() {
 3030                let start_anchor = snapshot.anchor_before(selection.start);
 3031
 3032                let is_word_char = text.chars().next().map_or(true, |char| {
 3033                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3034                    classifier.is_word(char)
 3035                });
 3036
 3037                if is_word_char {
 3038                    if let Some(ranges) = self
 3039                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3040                    {
 3041                        for (buffer, edits) in ranges {
 3042                            linked_edits
 3043                                .entry(buffer.clone())
 3044                                .or_default()
 3045                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3046                        }
 3047                    }
 3048                }
 3049            }
 3050
 3051            new_selections.push((selection.map(|_| anchor), 0));
 3052            edits.push((selection.start..selection.end, text.clone()));
 3053        }
 3054
 3055        drop(snapshot);
 3056
 3057        self.transact(window, cx, |this, window, cx| {
 3058            this.buffer.update(cx, |buffer, cx| {
 3059                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3060            });
 3061            for (buffer, edits) in linked_edits {
 3062                buffer.update(cx, |buffer, cx| {
 3063                    let snapshot = buffer.snapshot();
 3064                    let edits = edits
 3065                        .into_iter()
 3066                        .map(|(range, text)| {
 3067                            use text::ToPoint as TP;
 3068                            let end_point = TP::to_point(&range.end, &snapshot);
 3069                            let start_point = TP::to_point(&range.start, &snapshot);
 3070                            (start_point..end_point, text)
 3071                        })
 3072                        .sorted_by_key(|(range, _)| range.start)
 3073                        .collect::<Vec<_>>();
 3074                    buffer.edit(edits, None, cx);
 3075                })
 3076            }
 3077            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3078            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3079            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3080            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3081                .zip(new_selection_deltas)
 3082                .map(|(selection, delta)| Selection {
 3083                    id: selection.id,
 3084                    start: selection.start + delta,
 3085                    end: selection.end + delta,
 3086                    reversed: selection.reversed,
 3087                    goal: SelectionGoal::None,
 3088                })
 3089                .collect::<Vec<_>>();
 3090
 3091            let mut i = 0;
 3092            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3093                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3094                let start = map.buffer_snapshot.anchor_before(position);
 3095                let end = map.buffer_snapshot.anchor_after(position);
 3096                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3097                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3098                        Ordering::Less => i += 1,
 3099                        Ordering::Greater => break,
 3100                        Ordering::Equal => {
 3101                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3102                                Ordering::Less => i += 1,
 3103                                Ordering::Equal => break,
 3104                                Ordering::Greater => break,
 3105                            }
 3106                        }
 3107                    }
 3108                }
 3109                this.autoclose_regions.insert(
 3110                    i,
 3111                    AutocloseRegion {
 3112                        selection_id,
 3113                        range: start..end,
 3114                        pair,
 3115                    },
 3116                );
 3117            }
 3118
 3119            let had_active_inline_completion = this.has_active_inline_completion();
 3120            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3121                s.select(new_selections)
 3122            });
 3123
 3124            if !bracket_inserted {
 3125                if let Some(on_type_format_task) =
 3126                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3127                {
 3128                    on_type_format_task.detach_and_log_err(cx);
 3129                }
 3130            }
 3131
 3132            let editor_settings = EditorSettings::get_global(cx);
 3133            if bracket_inserted
 3134                && (editor_settings.auto_signature_help
 3135                    || editor_settings.show_signature_help_after_edits)
 3136            {
 3137                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3138            }
 3139
 3140            let trigger_in_words =
 3141                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3142            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3143            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3144            this.refresh_inline_completion(true, false, window, cx);
 3145        });
 3146    }
 3147
 3148    fn find_possible_emoji_shortcode_at_position(
 3149        snapshot: &MultiBufferSnapshot,
 3150        position: Point,
 3151    ) -> Option<String> {
 3152        let mut chars = Vec::new();
 3153        let mut found_colon = false;
 3154        for char in snapshot.reversed_chars_at(position).take(100) {
 3155            // Found a possible emoji shortcode in the middle of the buffer
 3156            if found_colon {
 3157                if char.is_whitespace() {
 3158                    chars.reverse();
 3159                    return Some(chars.iter().collect());
 3160                }
 3161                // If the previous character is not a whitespace, we are in the middle of a word
 3162                // and we only want to complete the shortcode if the word is made up of other emojis
 3163                let mut containing_word = String::new();
 3164                for ch in snapshot
 3165                    .reversed_chars_at(position)
 3166                    .skip(chars.len() + 1)
 3167                    .take(100)
 3168                {
 3169                    if ch.is_whitespace() {
 3170                        break;
 3171                    }
 3172                    containing_word.push(ch);
 3173                }
 3174                let containing_word = containing_word.chars().rev().collect::<String>();
 3175                if util::word_consists_of_emojis(containing_word.as_str()) {
 3176                    chars.reverse();
 3177                    return Some(chars.iter().collect());
 3178                }
 3179            }
 3180
 3181            if char.is_whitespace() || !char.is_ascii() {
 3182                return None;
 3183            }
 3184            if char == ':' {
 3185                found_colon = true;
 3186            } else {
 3187                chars.push(char);
 3188            }
 3189        }
 3190        // Found a possible emoji shortcode at the beginning of the buffer
 3191        chars.reverse();
 3192        Some(chars.iter().collect())
 3193    }
 3194
 3195    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3196        self.transact(window, cx, |this, window, cx| {
 3197            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3198                let selections = this.selections.all::<usize>(cx);
 3199                let multi_buffer = this.buffer.read(cx);
 3200                let buffer = multi_buffer.snapshot(cx);
 3201                selections
 3202                    .iter()
 3203                    .map(|selection| {
 3204                        let start_point = selection.start.to_point(&buffer);
 3205                        let mut indent =
 3206                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3207                        indent.len = cmp::min(indent.len, start_point.column);
 3208                        let start = selection.start;
 3209                        let end = selection.end;
 3210                        let selection_is_empty = start == end;
 3211                        let language_scope = buffer.language_scope_at(start);
 3212                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3213                            &language_scope
 3214                        {
 3215                            let insert_extra_newline =
 3216                                insert_extra_newline_brackets(&buffer, start..end, language)
 3217                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3218
 3219                            // Comment extension on newline is allowed only for cursor selections
 3220                            let comment_delimiter = maybe!({
 3221                                if !selection_is_empty {
 3222                                    return None;
 3223                                }
 3224
 3225                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3226                                    return None;
 3227                                }
 3228
 3229                                let delimiters = language.line_comment_prefixes();
 3230                                let max_len_of_delimiter =
 3231                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3232                                let (snapshot, range) =
 3233                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3234
 3235                                let mut index_of_first_non_whitespace = 0;
 3236                                let comment_candidate = snapshot
 3237                                    .chars_for_range(range)
 3238                                    .skip_while(|c| {
 3239                                        let should_skip = c.is_whitespace();
 3240                                        if should_skip {
 3241                                            index_of_first_non_whitespace += 1;
 3242                                        }
 3243                                        should_skip
 3244                                    })
 3245                                    .take(max_len_of_delimiter)
 3246                                    .collect::<String>();
 3247                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3248                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3249                                })?;
 3250                                let cursor_is_placed_after_comment_marker =
 3251                                    index_of_first_non_whitespace + comment_prefix.len()
 3252                                        <= start_point.column as usize;
 3253                                if cursor_is_placed_after_comment_marker {
 3254                                    Some(comment_prefix.clone())
 3255                                } else {
 3256                                    None
 3257                                }
 3258                            });
 3259                            (comment_delimiter, insert_extra_newline)
 3260                        } else {
 3261                            (None, false)
 3262                        };
 3263
 3264                        let capacity_for_delimiter = comment_delimiter
 3265                            .as_deref()
 3266                            .map(str::len)
 3267                            .unwrap_or_default();
 3268                        let mut new_text =
 3269                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3270                        new_text.push('\n');
 3271                        new_text.extend(indent.chars());
 3272                        if let Some(delimiter) = &comment_delimiter {
 3273                            new_text.push_str(delimiter);
 3274                        }
 3275                        if insert_extra_newline {
 3276                            new_text = new_text.repeat(2);
 3277                        }
 3278
 3279                        let anchor = buffer.anchor_after(end);
 3280                        let new_selection = selection.map(|_| anchor);
 3281                        (
 3282                            (start..end, new_text),
 3283                            (insert_extra_newline, new_selection),
 3284                        )
 3285                    })
 3286                    .unzip()
 3287            };
 3288
 3289            this.edit_with_autoindent(edits, cx);
 3290            let buffer = this.buffer.read(cx).snapshot(cx);
 3291            let new_selections = selection_fixup_info
 3292                .into_iter()
 3293                .map(|(extra_newline_inserted, new_selection)| {
 3294                    let mut cursor = new_selection.end.to_point(&buffer);
 3295                    if extra_newline_inserted {
 3296                        cursor.row -= 1;
 3297                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3298                    }
 3299                    new_selection.map(|_| cursor)
 3300                })
 3301                .collect();
 3302
 3303            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3304                s.select(new_selections)
 3305            });
 3306            this.refresh_inline_completion(true, false, window, cx);
 3307        });
 3308    }
 3309
 3310    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3311        let buffer = self.buffer.read(cx);
 3312        let snapshot = buffer.snapshot(cx);
 3313
 3314        let mut edits = Vec::new();
 3315        let mut rows = Vec::new();
 3316
 3317        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3318            let cursor = selection.head();
 3319            let row = cursor.row;
 3320
 3321            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3322
 3323            let newline = "\n".to_string();
 3324            edits.push((start_of_line..start_of_line, newline));
 3325
 3326            rows.push(row + rows_inserted as u32);
 3327        }
 3328
 3329        self.transact(window, cx, |editor, window, cx| {
 3330            editor.edit(edits, cx);
 3331
 3332            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3333                let mut index = 0;
 3334                s.move_cursors_with(|map, _, _| {
 3335                    let row = rows[index];
 3336                    index += 1;
 3337
 3338                    let point = Point::new(row, 0);
 3339                    let boundary = map.next_line_boundary(point).1;
 3340                    let clipped = map.clip_point(boundary, Bias::Left);
 3341
 3342                    (clipped, SelectionGoal::None)
 3343                });
 3344            });
 3345
 3346            let mut indent_edits = Vec::new();
 3347            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3348            for row in rows {
 3349                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3350                for (row, indent) in indents {
 3351                    if indent.len == 0 {
 3352                        continue;
 3353                    }
 3354
 3355                    let text = match indent.kind {
 3356                        IndentKind::Space => " ".repeat(indent.len as usize),
 3357                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3358                    };
 3359                    let point = Point::new(row.0, 0);
 3360                    indent_edits.push((point..point, text));
 3361                }
 3362            }
 3363            editor.edit(indent_edits, cx);
 3364        });
 3365    }
 3366
 3367    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3368        let buffer = self.buffer.read(cx);
 3369        let snapshot = buffer.snapshot(cx);
 3370
 3371        let mut edits = Vec::new();
 3372        let mut rows = Vec::new();
 3373        let mut rows_inserted = 0;
 3374
 3375        for selection in self.selections.all_adjusted(cx) {
 3376            let cursor = selection.head();
 3377            let row = cursor.row;
 3378
 3379            let point = Point::new(row + 1, 0);
 3380            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3381
 3382            let newline = "\n".to_string();
 3383            edits.push((start_of_line..start_of_line, newline));
 3384
 3385            rows_inserted += 1;
 3386            rows.push(row + rows_inserted);
 3387        }
 3388
 3389        self.transact(window, cx, |editor, window, cx| {
 3390            editor.edit(edits, cx);
 3391
 3392            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3393                let mut index = 0;
 3394                s.move_cursors_with(|map, _, _| {
 3395                    let row = rows[index];
 3396                    index += 1;
 3397
 3398                    let point = Point::new(row, 0);
 3399                    let boundary = map.next_line_boundary(point).1;
 3400                    let clipped = map.clip_point(boundary, Bias::Left);
 3401
 3402                    (clipped, SelectionGoal::None)
 3403                });
 3404            });
 3405
 3406            let mut indent_edits = Vec::new();
 3407            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3408            for row in rows {
 3409                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3410                for (row, indent) in indents {
 3411                    if indent.len == 0 {
 3412                        continue;
 3413                    }
 3414
 3415                    let text = match indent.kind {
 3416                        IndentKind::Space => " ".repeat(indent.len as usize),
 3417                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3418                    };
 3419                    let point = Point::new(row.0, 0);
 3420                    indent_edits.push((point..point, text));
 3421                }
 3422            }
 3423            editor.edit(indent_edits, cx);
 3424        });
 3425    }
 3426
 3427    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3428        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3429            original_start_columns: Vec::new(),
 3430        });
 3431        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3432    }
 3433
 3434    fn insert_with_autoindent_mode(
 3435        &mut self,
 3436        text: &str,
 3437        autoindent_mode: Option<AutoindentMode>,
 3438        window: &mut Window,
 3439        cx: &mut Context<Self>,
 3440    ) {
 3441        if self.read_only(cx) {
 3442            return;
 3443        }
 3444
 3445        let text: Arc<str> = text.into();
 3446        self.transact(window, cx, |this, window, cx| {
 3447            let old_selections = this.selections.all_adjusted(cx);
 3448            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3449                let anchors = {
 3450                    let snapshot = buffer.read(cx);
 3451                    old_selections
 3452                        .iter()
 3453                        .map(|s| {
 3454                            let anchor = snapshot.anchor_after(s.head());
 3455                            s.map(|_| anchor)
 3456                        })
 3457                        .collect::<Vec<_>>()
 3458                };
 3459                buffer.edit(
 3460                    old_selections
 3461                        .iter()
 3462                        .map(|s| (s.start..s.end, text.clone())),
 3463                    autoindent_mode,
 3464                    cx,
 3465                );
 3466                anchors
 3467            });
 3468
 3469            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3470                s.select_anchors(selection_anchors);
 3471            });
 3472
 3473            cx.notify();
 3474        });
 3475    }
 3476
 3477    fn trigger_completion_on_input(
 3478        &mut self,
 3479        text: &str,
 3480        trigger_in_words: bool,
 3481        window: &mut Window,
 3482        cx: &mut Context<Self>,
 3483    ) {
 3484        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3485            self.show_completions(
 3486                &ShowCompletions {
 3487                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3488                },
 3489                window,
 3490                cx,
 3491            );
 3492        } else {
 3493            self.hide_context_menu(window, cx);
 3494        }
 3495    }
 3496
 3497    fn is_completion_trigger(
 3498        &self,
 3499        text: &str,
 3500        trigger_in_words: bool,
 3501        cx: &mut Context<Self>,
 3502    ) -> bool {
 3503        let position = self.selections.newest_anchor().head();
 3504        let multibuffer = self.buffer.read(cx);
 3505        let Some(buffer) = position
 3506            .buffer_id
 3507            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3508        else {
 3509            return false;
 3510        };
 3511
 3512        if let Some(completion_provider) = &self.completion_provider {
 3513            completion_provider.is_completion_trigger(
 3514                &buffer,
 3515                position.text_anchor,
 3516                text,
 3517                trigger_in_words,
 3518                cx,
 3519            )
 3520        } else {
 3521            false
 3522        }
 3523    }
 3524
 3525    /// If any empty selections is touching the start of its innermost containing autoclose
 3526    /// region, expand it to select the brackets.
 3527    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3528        let selections = self.selections.all::<usize>(cx);
 3529        let buffer = self.buffer.read(cx).read(cx);
 3530        let new_selections = self
 3531            .selections_with_autoclose_regions(selections, &buffer)
 3532            .map(|(mut selection, region)| {
 3533                if !selection.is_empty() {
 3534                    return selection;
 3535                }
 3536
 3537                if let Some(region) = region {
 3538                    let mut range = region.range.to_offset(&buffer);
 3539                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3540                        range.start -= region.pair.start.len();
 3541                        if buffer.contains_str_at(range.start, &region.pair.start)
 3542                            && buffer.contains_str_at(range.end, &region.pair.end)
 3543                        {
 3544                            range.end += region.pair.end.len();
 3545                            selection.start = range.start;
 3546                            selection.end = range.end;
 3547
 3548                            return selection;
 3549                        }
 3550                    }
 3551                }
 3552
 3553                let always_treat_brackets_as_autoclosed = buffer
 3554                    .settings_at(selection.start, cx)
 3555                    .always_treat_brackets_as_autoclosed;
 3556
 3557                if !always_treat_brackets_as_autoclosed {
 3558                    return selection;
 3559                }
 3560
 3561                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3562                    for (pair, enabled) in scope.brackets() {
 3563                        if !enabled || !pair.close {
 3564                            continue;
 3565                        }
 3566
 3567                        if buffer.contains_str_at(selection.start, &pair.end) {
 3568                            let pair_start_len = pair.start.len();
 3569                            if buffer.contains_str_at(
 3570                                selection.start.saturating_sub(pair_start_len),
 3571                                &pair.start,
 3572                            ) {
 3573                                selection.start -= pair_start_len;
 3574                                selection.end += pair.end.len();
 3575
 3576                                return selection;
 3577                            }
 3578                        }
 3579                    }
 3580                }
 3581
 3582                selection
 3583            })
 3584            .collect();
 3585
 3586        drop(buffer);
 3587        self.change_selections(None, window, cx, |selections| {
 3588            selections.select(new_selections)
 3589        });
 3590    }
 3591
 3592    /// Iterate the given selections, and for each one, find the smallest surrounding
 3593    /// autoclose region. This uses the ordering of the selections and the autoclose
 3594    /// regions to avoid repeated comparisons.
 3595    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3596        &'a self,
 3597        selections: impl IntoIterator<Item = Selection<D>>,
 3598        buffer: &'a MultiBufferSnapshot,
 3599    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3600        let mut i = 0;
 3601        let mut regions = self.autoclose_regions.as_slice();
 3602        selections.into_iter().map(move |selection| {
 3603            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3604
 3605            let mut enclosing = None;
 3606            while let Some(pair_state) = regions.get(i) {
 3607                if pair_state.range.end.to_offset(buffer) < range.start {
 3608                    regions = &regions[i + 1..];
 3609                    i = 0;
 3610                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3611                    break;
 3612                } else {
 3613                    if pair_state.selection_id == selection.id {
 3614                        enclosing = Some(pair_state);
 3615                    }
 3616                    i += 1;
 3617                }
 3618            }
 3619
 3620            (selection, enclosing)
 3621        })
 3622    }
 3623
 3624    /// Remove any autoclose regions that no longer contain their selection.
 3625    fn invalidate_autoclose_regions(
 3626        &mut self,
 3627        mut selections: &[Selection<Anchor>],
 3628        buffer: &MultiBufferSnapshot,
 3629    ) {
 3630        self.autoclose_regions.retain(|state| {
 3631            let mut i = 0;
 3632            while let Some(selection) = selections.get(i) {
 3633                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3634                    selections = &selections[1..];
 3635                    continue;
 3636                }
 3637                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3638                    break;
 3639                }
 3640                if selection.id == state.selection_id {
 3641                    return true;
 3642                } else {
 3643                    i += 1;
 3644                }
 3645            }
 3646            false
 3647        });
 3648    }
 3649
 3650    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3651        let offset = position.to_offset(buffer);
 3652        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3653        if offset > word_range.start && kind == Some(CharKind::Word) {
 3654            Some(
 3655                buffer
 3656                    .text_for_range(word_range.start..offset)
 3657                    .collect::<String>(),
 3658            )
 3659        } else {
 3660            None
 3661        }
 3662    }
 3663
 3664    pub fn toggle_inlay_hints(
 3665        &mut self,
 3666        _: &ToggleInlayHints,
 3667        _: &mut Window,
 3668        cx: &mut Context<Self>,
 3669    ) {
 3670        self.refresh_inlay_hints(
 3671            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3672            cx,
 3673        );
 3674    }
 3675
 3676    pub fn inlay_hints_enabled(&self) -> bool {
 3677        self.inlay_hint_cache.enabled
 3678    }
 3679
 3680    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3681        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3682            return;
 3683        }
 3684
 3685        let reason_description = reason.description();
 3686        let ignore_debounce = matches!(
 3687            reason,
 3688            InlayHintRefreshReason::SettingsChange(_)
 3689                | InlayHintRefreshReason::Toggle(_)
 3690                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3691        );
 3692        let (invalidate_cache, required_languages) = match reason {
 3693            InlayHintRefreshReason::Toggle(enabled) => {
 3694                self.inlay_hint_cache.enabled = enabled;
 3695                if enabled {
 3696                    (InvalidationStrategy::RefreshRequested, None)
 3697                } else {
 3698                    self.inlay_hint_cache.clear();
 3699                    self.splice_inlays(
 3700                        &self
 3701                            .visible_inlay_hints(cx)
 3702                            .iter()
 3703                            .map(|inlay| inlay.id)
 3704                            .collect::<Vec<InlayId>>(),
 3705                        Vec::new(),
 3706                        cx,
 3707                    );
 3708                    return;
 3709                }
 3710            }
 3711            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3712                match self.inlay_hint_cache.update_settings(
 3713                    &self.buffer,
 3714                    new_settings,
 3715                    self.visible_inlay_hints(cx),
 3716                    cx,
 3717                ) {
 3718                    ControlFlow::Break(Some(InlaySplice {
 3719                        to_remove,
 3720                        to_insert,
 3721                    })) => {
 3722                        self.splice_inlays(&to_remove, to_insert, cx);
 3723                        return;
 3724                    }
 3725                    ControlFlow::Break(None) => return,
 3726                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3727                }
 3728            }
 3729            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3730                if let Some(InlaySplice {
 3731                    to_remove,
 3732                    to_insert,
 3733                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3734                {
 3735                    self.splice_inlays(&to_remove, to_insert, cx);
 3736                }
 3737                return;
 3738            }
 3739            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3740            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3741                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3742            }
 3743            InlayHintRefreshReason::RefreshRequested => {
 3744                (InvalidationStrategy::RefreshRequested, None)
 3745            }
 3746        };
 3747
 3748        if let Some(InlaySplice {
 3749            to_remove,
 3750            to_insert,
 3751        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3752            reason_description,
 3753            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3754            invalidate_cache,
 3755            ignore_debounce,
 3756            cx,
 3757        ) {
 3758            self.splice_inlays(&to_remove, to_insert, cx);
 3759        }
 3760    }
 3761
 3762    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3763        self.display_map
 3764            .read(cx)
 3765            .current_inlays()
 3766            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3767            .cloned()
 3768            .collect()
 3769    }
 3770
 3771    pub fn excerpts_for_inlay_hints_query(
 3772        &self,
 3773        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3774        cx: &mut Context<Editor>,
 3775    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3776        let Some(project) = self.project.as_ref() else {
 3777            return HashMap::default();
 3778        };
 3779        let project = project.read(cx);
 3780        let multi_buffer = self.buffer().read(cx);
 3781        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3782        let multi_buffer_visible_start = self
 3783            .scroll_manager
 3784            .anchor()
 3785            .anchor
 3786            .to_point(&multi_buffer_snapshot);
 3787        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3788            multi_buffer_visible_start
 3789                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3790            Bias::Left,
 3791        );
 3792        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3793        multi_buffer_snapshot
 3794            .range_to_buffer_ranges(multi_buffer_visible_range)
 3795            .into_iter()
 3796            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3797            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3798                let buffer_file = project::File::from_dyn(buffer.file())?;
 3799                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3800                let worktree_entry = buffer_worktree
 3801                    .read(cx)
 3802                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3803                if worktree_entry.is_ignored {
 3804                    return None;
 3805                }
 3806
 3807                let language = buffer.language()?;
 3808                if let Some(restrict_to_languages) = restrict_to_languages {
 3809                    if !restrict_to_languages.contains(language) {
 3810                        return None;
 3811                    }
 3812                }
 3813                Some((
 3814                    excerpt_id,
 3815                    (
 3816                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3817                        buffer.version().clone(),
 3818                        excerpt_visible_range,
 3819                    ),
 3820                ))
 3821            })
 3822            .collect()
 3823    }
 3824
 3825    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3826        TextLayoutDetails {
 3827            text_system: window.text_system().clone(),
 3828            editor_style: self.style.clone().unwrap(),
 3829            rem_size: window.rem_size(),
 3830            scroll_anchor: self.scroll_manager.anchor(),
 3831            visible_rows: self.visible_line_count(),
 3832            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3833        }
 3834    }
 3835
 3836    pub fn splice_inlays(
 3837        &self,
 3838        to_remove: &[InlayId],
 3839        to_insert: Vec<Inlay>,
 3840        cx: &mut Context<Self>,
 3841    ) {
 3842        self.display_map.update(cx, |display_map, cx| {
 3843            display_map.splice_inlays(to_remove, to_insert, cx)
 3844        });
 3845        cx.notify();
 3846    }
 3847
 3848    fn trigger_on_type_formatting(
 3849        &self,
 3850        input: String,
 3851        window: &mut Window,
 3852        cx: &mut Context<Self>,
 3853    ) -> Option<Task<Result<()>>> {
 3854        if input.len() != 1 {
 3855            return None;
 3856        }
 3857
 3858        let project = self.project.as_ref()?;
 3859        let position = self.selections.newest_anchor().head();
 3860        let (buffer, buffer_position) = self
 3861            .buffer
 3862            .read(cx)
 3863            .text_anchor_for_position(position, cx)?;
 3864
 3865        let settings = language_settings::language_settings(
 3866            buffer
 3867                .read(cx)
 3868                .language_at(buffer_position)
 3869                .map(|l| l.name()),
 3870            buffer.read(cx).file(),
 3871            cx,
 3872        );
 3873        if !settings.use_on_type_format {
 3874            return None;
 3875        }
 3876
 3877        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3878        // hence we do LSP request & edit on host side only — add formats to host's history.
 3879        let push_to_lsp_host_history = true;
 3880        // If this is not the host, append its history with new edits.
 3881        let push_to_client_history = project.read(cx).is_via_collab();
 3882
 3883        let on_type_formatting = project.update(cx, |project, cx| {
 3884            project.on_type_format(
 3885                buffer.clone(),
 3886                buffer_position,
 3887                input,
 3888                push_to_lsp_host_history,
 3889                cx,
 3890            )
 3891        });
 3892        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3893            if let Some(transaction) = on_type_formatting.await? {
 3894                if push_to_client_history {
 3895                    buffer
 3896                        .update(&mut cx, |buffer, _| {
 3897                            buffer.push_transaction(transaction, Instant::now());
 3898                        })
 3899                        .ok();
 3900                }
 3901                editor.update(&mut cx, |editor, cx| {
 3902                    editor.refresh_document_highlights(cx);
 3903                })?;
 3904            }
 3905            Ok(())
 3906        }))
 3907    }
 3908
 3909    pub fn show_completions(
 3910        &mut self,
 3911        options: &ShowCompletions,
 3912        window: &mut Window,
 3913        cx: &mut Context<Self>,
 3914    ) {
 3915        if self.pending_rename.is_some() {
 3916            return;
 3917        }
 3918
 3919        let Some(provider) = self.completion_provider.as_ref() else {
 3920            return;
 3921        };
 3922
 3923        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3924            return;
 3925        }
 3926
 3927        let position = self.selections.newest_anchor().head();
 3928        if position.diff_base_anchor.is_some() {
 3929            return;
 3930        }
 3931        let (buffer, buffer_position) =
 3932            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3933                output
 3934            } else {
 3935                return;
 3936            };
 3937        let show_completion_documentation = buffer
 3938            .read(cx)
 3939            .snapshot()
 3940            .settings_at(buffer_position, cx)
 3941            .show_completion_documentation;
 3942
 3943        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3944
 3945        let trigger_kind = match &options.trigger {
 3946            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3947                CompletionTriggerKind::TRIGGER_CHARACTER
 3948            }
 3949            _ => CompletionTriggerKind::INVOKED,
 3950        };
 3951        let completion_context = CompletionContext {
 3952            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3953                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3954                    Some(String::from(trigger))
 3955                } else {
 3956                    None
 3957                }
 3958            }),
 3959            trigger_kind,
 3960        };
 3961        let completions =
 3962            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3963        let sort_completions = provider.sort_completions();
 3964
 3965        let id = post_inc(&mut self.next_completion_id);
 3966        let task = cx.spawn_in(window, |editor, mut cx| {
 3967            async move {
 3968                editor.update(&mut cx, |this, _| {
 3969                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3970                })?;
 3971                let completions = completions.await.log_err();
 3972                let menu = if let Some(completions) = completions {
 3973                    let mut menu = CompletionsMenu::new(
 3974                        id,
 3975                        sort_completions,
 3976                        show_completion_documentation,
 3977                        position,
 3978                        buffer.clone(),
 3979                        completions.into(),
 3980                    );
 3981
 3982                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3983                        .await;
 3984
 3985                    menu.visible().then_some(menu)
 3986                } else {
 3987                    None
 3988                };
 3989
 3990                editor.update_in(&mut cx, |editor, window, cx| {
 3991                    match editor.context_menu.borrow().as_ref() {
 3992                        None => {}
 3993                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3994                            if prev_menu.id > id {
 3995                                return;
 3996                            }
 3997                        }
 3998                        _ => return,
 3999                    }
 4000
 4001                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4002                        let mut menu = menu.unwrap();
 4003                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4004
 4005                        *editor.context_menu.borrow_mut() =
 4006                            Some(CodeContextMenu::Completions(menu));
 4007
 4008                        if editor.show_edit_predictions_in_menu() {
 4009                            editor.update_visible_inline_completion(window, cx);
 4010                        } else {
 4011                            editor.discard_inline_completion(false, cx);
 4012                        }
 4013
 4014                        cx.notify();
 4015                    } else if editor.completion_tasks.len() <= 1 {
 4016                        // If there are no more completion tasks and the last menu was
 4017                        // empty, we should hide it.
 4018                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4019                        // If it was already hidden and we don't show inline
 4020                        // completions in the menu, we should also show the
 4021                        // inline-completion when available.
 4022                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4023                            editor.update_visible_inline_completion(window, cx);
 4024                        }
 4025                    }
 4026                })?;
 4027
 4028                Ok::<_, anyhow::Error>(())
 4029            }
 4030            .log_err()
 4031        });
 4032
 4033        self.completion_tasks.push((id, task));
 4034    }
 4035
 4036    pub fn confirm_completion(
 4037        &mut self,
 4038        action: &ConfirmCompletion,
 4039        window: &mut Window,
 4040        cx: &mut Context<Self>,
 4041    ) -> Option<Task<Result<()>>> {
 4042        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4043    }
 4044
 4045    pub fn compose_completion(
 4046        &mut self,
 4047        action: &ComposeCompletion,
 4048        window: &mut Window,
 4049        cx: &mut Context<Self>,
 4050    ) -> Option<Task<Result<()>>> {
 4051        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4052    }
 4053
 4054    fn do_completion(
 4055        &mut self,
 4056        item_ix: Option<usize>,
 4057        intent: CompletionIntent,
 4058        window: &mut Window,
 4059        cx: &mut Context<Editor>,
 4060    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4061        use language::ToOffset as _;
 4062
 4063        let completions_menu =
 4064            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4065                menu
 4066            } else {
 4067                return None;
 4068            };
 4069
 4070        let entries = completions_menu.entries.borrow();
 4071        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4072        if self.show_edit_predictions_in_menu() {
 4073            self.discard_inline_completion(true, cx);
 4074        }
 4075        let candidate_id = mat.candidate_id;
 4076        drop(entries);
 4077
 4078        let buffer_handle = completions_menu.buffer;
 4079        let completion = completions_menu
 4080            .completions
 4081            .borrow()
 4082            .get(candidate_id)?
 4083            .clone();
 4084        cx.stop_propagation();
 4085
 4086        let snippet;
 4087        let text;
 4088
 4089        if completion.is_snippet() {
 4090            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4091            text = snippet.as_ref().unwrap().text.clone();
 4092        } else {
 4093            snippet = None;
 4094            text = completion.new_text.clone();
 4095        };
 4096        let selections = self.selections.all::<usize>(cx);
 4097        let buffer = buffer_handle.read(cx);
 4098        let old_range = completion.old_range.to_offset(buffer);
 4099        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4100
 4101        let newest_selection = self.selections.newest_anchor();
 4102        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4103            return None;
 4104        }
 4105
 4106        let lookbehind = newest_selection
 4107            .start
 4108            .text_anchor
 4109            .to_offset(buffer)
 4110            .saturating_sub(old_range.start);
 4111        let lookahead = old_range
 4112            .end
 4113            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4114        let mut common_prefix_len = old_text
 4115            .bytes()
 4116            .zip(text.bytes())
 4117            .take_while(|(a, b)| a == b)
 4118            .count();
 4119
 4120        let snapshot = self.buffer.read(cx).snapshot(cx);
 4121        let mut range_to_replace: Option<Range<isize>> = None;
 4122        let mut ranges = Vec::new();
 4123        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4124        for selection in &selections {
 4125            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4126                let start = selection.start.saturating_sub(lookbehind);
 4127                let end = selection.end + lookahead;
 4128                if selection.id == newest_selection.id {
 4129                    range_to_replace = Some(
 4130                        ((start + common_prefix_len) as isize - selection.start as isize)
 4131                            ..(end as isize - selection.start as isize),
 4132                    );
 4133                }
 4134                ranges.push(start + common_prefix_len..end);
 4135            } else {
 4136                common_prefix_len = 0;
 4137                ranges.clear();
 4138                ranges.extend(selections.iter().map(|s| {
 4139                    if s.id == newest_selection.id {
 4140                        range_to_replace = Some(
 4141                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4142                                - selection.start as isize
 4143                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4144                                    - selection.start as isize,
 4145                        );
 4146                        old_range.clone()
 4147                    } else {
 4148                        s.start..s.end
 4149                    }
 4150                }));
 4151                break;
 4152            }
 4153            if !self.linked_edit_ranges.is_empty() {
 4154                let start_anchor = snapshot.anchor_before(selection.head());
 4155                let end_anchor = snapshot.anchor_after(selection.tail());
 4156                if let Some(ranges) = self
 4157                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4158                {
 4159                    for (buffer, edits) in ranges {
 4160                        linked_edits.entry(buffer.clone()).or_default().extend(
 4161                            edits
 4162                                .into_iter()
 4163                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4164                        );
 4165                    }
 4166                }
 4167            }
 4168        }
 4169        let text = &text[common_prefix_len..];
 4170
 4171        cx.emit(EditorEvent::InputHandled {
 4172            utf16_range_to_replace: range_to_replace,
 4173            text: text.into(),
 4174        });
 4175
 4176        self.transact(window, cx, |this, window, cx| {
 4177            if let Some(mut snippet) = snippet {
 4178                snippet.text = text.to_string();
 4179                for tabstop in snippet
 4180                    .tabstops
 4181                    .iter_mut()
 4182                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4183                {
 4184                    tabstop.start -= common_prefix_len as isize;
 4185                    tabstop.end -= common_prefix_len as isize;
 4186                }
 4187
 4188                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4189            } else {
 4190                this.buffer.update(cx, |buffer, cx| {
 4191                    buffer.edit(
 4192                        ranges.iter().map(|range| (range.clone(), text)),
 4193                        this.autoindent_mode.clone(),
 4194                        cx,
 4195                    );
 4196                });
 4197            }
 4198            for (buffer, edits) in linked_edits {
 4199                buffer.update(cx, |buffer, cx| {
 4200                    let snapshot = buffer.snapshot();
 4201                    let edits = edits
 4202                        .into_iter()
 4203                        .map(|(range, text)| {
 4204                            use text::ToPoint as TP;
 4205                            let end_point = TP::to_point(&range.end, &snapshot);
 4206                            let start_point = TP::to_point(&range.start, &snapshot);
 4207                            (start_point..end_point, text)
 4208                        })
 4209                        .sorted_by_key(|(range, _)| range.start)
 4210                        .collect::<Vec<_>>();
 4211                    buffer.edit(edits, None, cx);
 4212                })
 4213            }
 4214
 4215            this.refresh_inline_completion(true, false, window, cx);
 4216        });
 4217
 4218        let show_new_completions_on_confirm = completion
 4219            .confirm
 4220            .as_ref()
 4221            .map_or(false, |confirm| confirm(intent, window, cx));
 4222        if show_new_completions_on_confirm {
 4223            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4224        }
 4225
 4226        let provider = self.completion_provider.as_ref()?;
 4227        drop(completion);
 4228        let apply_edits = provider.apply_additional_edits_for_completion(
 4229            buffer_handle,
 4230            completions_menu.completions.clone(),
 4231            candidate_id,
 4232            true,
 4233            cx,
 4234        );
 4235
 4236        let editor_settings = EditorSettings::get_global(cx);
 4237        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4238            // After the code completion is finished, users often want to know what signatures are needed.
 4239            // so we should automatically call signature_help
 4240            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4241        }
 4242
 4243        Some(cx.foreground_executor().spawn(async move {
 4244            apply_edits.await?;
 4245            Ok(())
 4246        }))
 4247    }
 4248
 4249    pub fn toggle_code_actions(
 4250        &mut self,
 4251        action: &ToggleCodeActions,
 4252        window: &mut Window,
 4253        cx: &mut Context<Self>,
 4254    ) {
 4255        let mut context_menu = self.context_menu.borrow_mut();
 4256        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4257            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4258                // Toggle if we're selecting the same one
 4259                *context_menu = None;
 4260                cx.notify();
 4261                return;
 4262            } else {
 4263                // Otherwise, clear it and start a new one
 4264                *context_menu = None;
 4265                cx.notify();
 4266            }
 4267        }
 4268        drop(context_menu);
 4269        let snapshot = self.snapshot(window, cx);
 4270        let deployed_from_indicator = action.deployed_from_indicator;
 4271        let mut task = self.code_actions_task.take();
 4272        let action = action.clone();
 4273        cx.spawn_in(window, |editor, mut cx| async move {
 4274            while let Some(prev_task) = task {
 4275                prev_task.await.log_err();
 4276                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4277            }
 4278
 4279            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4280                if editor.focus_handle.is_focused(window) {
 4281                    let multibuffer_point = action
 4282                        .deployed_from_indicator
 4283                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4284                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4285                    let (buffer, buffer_row) = snapshot
 4286                        .buffer_snapshot
 4287                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4288                        .and_then(|(buffer_snapshot, range)| {
 4289                            editor
 4290                                .buffer
 4291                                .read(cx)
 4292                                .buffer(buffer_snapshot.remote_id())
 4293                                .map(|buffer| (buffer, range.start.row))
 4294                        })?;
 4295                    let (_, code_actions) = editor
 4296                        .available_code_actions
 4297                        .clone()
 4298                        .and_then(|(location, code_actions)| {
 4299                            let snapshot = location.buffer.read(cx).snapshot();
 4300                            let point_range = location.range.to_point(&snapshot);
 4301                            let point_range = point_range.start.row..=point_range.end.row;
 4302                            if point_range.contains(&buffer_row) {
 4303                                Some((location, code_actions))
 4304                            } else {
 4305                                None
 4306                            }
 4307                        })
 4308                        .unzip();
 4309                    let buffer_id = buffer.read(cx).remote_id();
 4310                    let tasks = editor
 4311                        .tasks
 4312                        .get(&(buffer_id, buffer_row))
 4313                        .map(|t| Arc::new(t.to_owned()));
 4314                    if tasks.is_none() && code_actions.is_none() {
 4315                        return None;
 4316                    }
 4317
 4318                    editor.completion_tasks.clear();
 4319                    editor.discard_inline_completion(false, cx);
 4320                    let task_context =
 4321                        tasks
 4322                            .as_ref()
 4323                            .zip(editor.project.clone())
 4324                            .map(|(tasks, project)| {
 4325                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4326                            });
 4327
 4328                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4329                        let task_context = match task_context {
 4330                            Some(task_context) => task_context.await,
 4331                            None => None,
 4332                        };
 4333                        let resolved_tasks =
 4334                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4335                                Rc::new(ResolvedTasks {
 4336                                    templates: tasks.resolve(&task_context).collect(),
 4337                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4338                                        multibuffer_point.row,
 4339                                        tasks.column,
 4340                                    )),
 4341                                })
 4342                            });
 4343                        let spawn_straight_away = resolved_tasks
 4344                            .as_ref()
 4345                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4346                            && code_actions
 4347                                .as_ref()
 4348                                .map_or(true, |actions| actions.is_empty());
 4349                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4350                            *editor.context_menu.borrow_mut() =
 4351                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4352                                    buffer,
 4353                                    actions: CodeActionContents {
 4354                                        tasks: resolved_tasks,
 4355                                        actions: code_actions,
 4356                                    },
 4357                                    selected_item: Default::default(),
 4358                                    scroll_handle: UniformListScrollHandle::default(),
 4359                                    deployed_from_indicator,
 4360                                }));
 4361                            if spawn_straight_away {
 4362                                if let Some(task) = editor.confirm_code_action(
 4363                                    &ConfirmCodeAction { item_ix: Some(0) },
 4364                                    window,
 4365                                    cx,
 4366                                ) {
 4367                                    cx.notify();
 4368                                    return task;
 4369                                }
 4370                            }
 4371                            cx.notify();
 4372                            Task::ready(Ok(()))
 4373                        }) {
 4374                            task.await
 4375                        } else {
 4376                            Ok(())
 4377                        }
 4378                    }))
 4379                } else {
 4380                    Some(Task::ready(Ok(())))
 4381                }
 4382            })?;
 4383            if let Some(task) = spawned_test_task {
 4384                task.await?;
 4385            }
 4386
 4387            Ok::<_, anyhow::Error>(())
 4388        })
 4389        .detach_and_log_err(cx);
 4390    }
 4391
 4392    pub fn confirm_code_action(
 4393        &mut self,
 4394        action: &ConfirmCodeAction,
 4395        window: &mut Window,
 4396        cx: &mut Context<Self>,
 4397    ) -> Option<Task<Result<()>>> {
 4398        let actions_menu =
 4399            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4400                menu
 4401            } else {
 4402                return None;
 4403            };
 4404        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4405        let action = actions_menu.actions.get(action_ix)?;
 4406        let title = action.label();
 4407        let buffer = actions_menu.buffer;
 4408        let workspace = self.workspace()?;
 4409
 4410        match action {
 4411            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4412                workspace.update(cx, |workspace, cx| {
 4413                    workspace::tasks::schedule_resolved_task(
 4414                        workspace,
 4415                        task_source_kind,
 4416                        resolved_task,
 4417                        false,
 4418                        cx,
 4419                    );
 4420
 4421                    Some(Task::ready(Ok(())))
 4422                })
 4423            }
 4424            CodeActionsItem::CodeAction {
 4425                excerpt_id,
 4426                action,
 4427                provider,
 4428            } => {
 4429                let apply_code_action =
 4430                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4431                let workspace = workspace.downgrade();
 4432                Some(cx.spawn_in(window, |editor, cx| async move {
 4433                    let project_transaction = apply_code_action.await?;
 4434                    Self::open_project_transaction(
 4435                        &editor,
 4436                        workspace,
 4437                        project_transaction,
 4438                        title,
 4439                        cx,
 4440                    )
 4441                    .await
 4442                }))
 4443            }
 4444        }
 4445    }
 4446
 4447    pub async fn open_project_transaction(
 4448        this: &WeakEntity<Editor>,
 4449        workspace: WeakEntity<Workspace>,
 4450        transaction: ProjectTransaction,
 4451        title: String,
 4452        mut cx: AsyncWindowContext,
 4453    ) -> Result<()> {
 4454        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4455        cx.update(|_, cx| {
 4456            entries.sort_unstable_by_key(|(buffer, _)| {
 4457                buffer.read(cx).file().map(|f| f.path().clone())
 4458            });
 4459        })?;
 4460
 4461        // If the project transaction's edits are all contained within this editor, then
 4462        // avoid opening a new editor to display them.
 4463
 4464        if let Some((buffer, transaction)) = entries.first() {
 4465            if entries.len() == 1 {
 4466                let excerpt = this.update(&mut cx, |editor, cx| {
 4467                    editor
 4468                        .buffer()
 4469                        .read(cx)
 4470                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4471                })?;
 4472                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4473                    if excerpted_buffer == *buffer {
 4474                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4475                            let excerpt_range = excerpt_range.to_offset(buffer);
 4476                            buffer
 4477                                .edited_ranges_for_transaction::<usize>(transaction)
 4478                                .all(|range| {
 4479                                    excerpt_range.start <= range.start
 4480                                        && excerpt_range.end >= range.end
 4481                                })
 4482                        })?;
 4483
 4484                        if all_edits_within_excerpt {
 4485                            return Ok(());
 4486                        }
 4487                    }
 4488                }
 4489            }
 4490        } else {
 4491            return Ok(());
 4492        }
 4493
 4494        let mut ranges_to_highlight = Vec::new();
 4495        let excerpt_buffer = cx.new(|cx| {
 4496            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4497            for (buffer_handle, transaction) in &entries {
 4498                let buffer = buffer_handle.read(cx);
 4499                ranges_to_highlight.extend(
 4500                    multibuffer.push_excerpts_with_context_lines(
 4501                        buffer_handle.clone(),
 4502                        buffer
 4503                            .edited_ranges_for_transaction::<usize>(transaction)
 4504                            .collect(),
 4505                        DEFAULT_MULTIBUFFER_CONTEXT,
 4506                        cx,
 4507                    ),
 4508                );
 4509            }
 4510            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4511            multibuffer
 4512        })?;
 4513
 4514        workspace.update_in(&mut cx, |workspace, window, cx| {
 4515            let project = workspace.project().clone();
 4516            let editor = cx
 4517                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4518            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4519            editor.update(cx, |editor, cx| {
 4520                editor.highlight_background::<Self>(
 4521                    &ranges_to_highlight,
 4522                    |theme| theme.editor_highlighted_line_background,
 4523                    cx,
 4524                );
 4525            });
 4526        })?;
 4527
 4528        Ok(())
 4529    }
 4530
 4531    pub fn clear_code_action_providers(&mut self) {
 4532        self.code_action_providers.clear();
 4533        self.available_code_actions.take();
 4534    }
 4535
 4536    pub fn add_code_action_provider(
 4537        &mut self,
 4538        provider: Rc<dyn CodeActionProvider>,
 4539        window: &mut Window,
 4540        cx: &mut Context<Self>,
 4541    ) {
 4542        if self
 4543            .code_action_providers
 4544            .iter()
 4545            .any(|existing_provider| existing_provider.id() == provider.id())
 4546        {
 4547            return;
 4548        }
 4549
 4550        self.code_action_providers.push(provider);
 4551        self.refresh_code_actions(window, cx);
 4552    }
 4553
 4554    pub fn remove_code_action_provider(
 4555        &mut self,
 4556        id: Arc<str>,
 4557        window: &mut Window,
 4558        cx: &mut Context<Self>,
 4559    ) {
 4560        self.code_action_providers
 4561            .retain(|provider| provider.id() != id);
 4562        self.refresh_code_actions(window, cx);
 4563    }
 4564
 4565    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4566        let buffer = self.buffer.read(cx);
 4567        let newest_selection = self.selections.newest_anchor().clone();
 4568        if newest_selection.head().diff_base_anchor.is_some() {
 4569            return None;
 4570        }
 4571        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4572        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4573        if start_buffer != end_buffer {
 4574            return None;
 4575        }
 4576
 4577        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4578            cx.background_executor()
 4579                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4580                .await;
 4581
 4582            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4583                let providers = this.code_action_providers.clone();
 4584                let tasks = this
 4585                    .code_action_providers
 4586                    .iter()
 4587                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4588                    .collect::<Vec<_>>();
 4589                (providers, tasks)
 4590            })?;
 4591
 4592            let mut actions = Vec::new();
 4593            for (provider, provider_actions) in
 4594                providers.into_iter().zip(future::join_all(tasks).await)
 4595            {
 4596                if let Some(provider_actions) = provider_actions.log_err() {
 4597                    actions.extend(provider_actions.into_iter().map(|action| {
 4598                        AvailableCodeAction {
 4599                            excerpt_id: newest_selection.start.excerpt_id,
 4600                            action,
 4601                            provider: provider.clone(),
 4602                        }
 4603                    }));
 4604                }
 4605            }
 4606
 4607            this.update(&mut cx, |this, cx| {
 4608                this.available_code_actions = if actions.is_empty() {
 4609                    None
 4610                } else {
 4611                    Some((
 4612                        Location {
 4613                            buffer: start_buffer,
 4614                            range: start..end,
 4615                        },
 4616                        actions.into(),
 4617                    ))
 4618                };
 4619                cx.notify();
 4620            })
 4621        }));
 4622        None
 4623    }
 4624
 4625    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4626        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4627            self.show_git_blame_inline = false;
 4628
 4629            self.show_git_blame_inline_delay_task =
 4630                Some(cx.spawn_in(window, |this, mut cx| async move {
 4631                    cx.background_executor().timer(delay).await;
 4632
 4633                    this.update(&mut cx, |this, cx| {
 4634                        this.show_git_blame_inline = true;
 4635                        cx.notify();
 4636                    })
 4637                    .log_err();
 4638                }));
 4639        }
 4640    }
 4641
 4642    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4643        if self.pending_rename.is_some() {
 4644            return None;
 4645        }
 4646
 4647        let provider = self.semantics_provider.clone()?;
 4648        let buffer = self.buffer.read(cx);
 4649        let newest_selection = self.selections.newest_anchor().clone();
 4650        let cursor_position = newest_selection.head();
 4651        let (cursor_buffer, cursor_buffer_position) =
 4652            buffer.text_anchor_for_position(cursor_position, cx)?;
 4653        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4654        if cursor_buffer != tail_buffer {
 4655            return None;
 4656        }
 4657        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4658        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4659            cx.background_executor()
 4660                .timer(Duration::from_millis(debounce))
 4661                .await;
 4662
 4663            let highlights = if let Some(highlights) = cx
 4664                .update(|cx| {
 4665                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4666                })
 4667                .ok()
 4668                .flatten()
 4669            {
 4670                highlights.await.log_err()
 4671            } else {
 4672                None
 4673            };
 4674
 4675            if let Some(highlights) = highlights {
 4676                this.update(&mut cx, |this, cx| {
 4677                    if this.pending_rename.is_some() {
 4678                        return;
 4679                    }
 4680
 4681                    let buffer_id = cursor_position.buffer_id;
 4682                    let buffer = this.buffer.read(cx);
 4683                    if !buffer
 4684                        .text_anchor_for_position(cursor_position, cx)
 4685                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4686                    {
 4687                        return;
 4688                    }
 4689
 4690                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4691                    let mut write_ranges = Vec::new();
 4692                    let mut read_ranges = Vec::new();
 4693                    for highlight in highlights {
 4694                        for (excerpt_id, excerpt_range) in
 4695                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4696                        {
 4697                            let start = highlight
 4698                                .range
 4699                                .start
 4700                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4701                            let end = highlight
 4702                                .range
 4703                                .end
 4704                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4705                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4706                                continue;
 4707                            }
 4708
 4709                            let range = Anchor {
 4710                                buffer_id,
 4711                                excerpt_id,
 4712                                text_anchor: start,
 4713                                diff_base_anchor: None,
 4714                            }..Anchor {
 4715                                buffer_id,
 4716                                excerpt_id,
 4717                                text_anchor: end,
 4718                                diff_base_anchor: None,
 4719                            };
 4720                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4721                                write_ranges.push(range);
 4722                            } else {
 4723                                read_ranges.push(range);
 4724                            }
 4725                        }
 4726                    }
 4727
 4728                    this.highlight_background::<DocumentHighlightRead>(
 4729                        &read_ranges,
 4730                        |theme| theme.editor_document_highlight_read_background,
 4731                        cx,
 4732                    );
 4733                    this.highlight_background::<DocumentHighlightWrite>(
 4734                        &write_ranges,
 4735                        |theme| theme.editor_document_highlight_write_background,
 4736                        cx,
 4737                    );
 4738                    cx.notify();
 4739                })
 4740                .log_err();
 4741            }
 4742        }));
 4743        None
 4744    }
 4745
 4746    pub fn refresh_selected_text_highlights(
 4747        &mut self,
 4748        window: &mut Window,
 4749        cx: &mut Context<Editor>,
 4750    ) {
 4751        self.selection_highlight_task.take();
 4752        if !EditorSettings::get_global(cx).selection_highlight {
 4753            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4754            return;
 4755        }
 4756        if self.selections.count() != 1 || self.selections.line_mode {
 4757            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4758            return;
 4759        }
 4760        let selection = self.selections.newest::<Point>(cx);
 4761        if selection.is_empty() || selection.start.row != selection.end.row {
 4762            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4763            return;
 4764        }
 4765        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4766        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4767            cx.background_executor()
 4768                .timer(Duration::from_millis(debounce))
 4769                .await;
 4770            let Some(Some(matches_task)) = editor
 4771                .update_in(&mut cx, |editor, _, cx| {
 4772                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4773                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4774                        return None;
 4775                    }
 4776                    let selection = editor.selections.newest::<Point>(cx);
 4777                    if selection.is_empty() || selection.start.row != selection.end.row {
 4778                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4779                        return None;
 4780                    }
 4781                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4782                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4783                    if query.trim().is_empty() {
 4784                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4785                        return None;
 4786                    }
 4787                    Some(cx.background_spawn(async move {
 4788                        let mut ranges = Vec::new();
 4789                        let selection_anchors = selection.range().to_anchors(&buffer);
 4790                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4791                            for (search_buffer, search_range, excerpt_id) in
 4792                                buffer.range_to_buffer_ranges(range)
 4793                            {
 4794                                ranges.extend(
 4795                                    project::search::SearchQuery::text(
 4796                                        query.clone(),
 4797                                        false,
 4798                                        false,
 4799                                        false,
 4800                                        Default::default(),
 4801                                        Default::default(),
 4802                                        None,
 4803                                    )
 4804                                    .unwrap()
 4805                                    .search(search_buffer, Some(search_range.clone()))
 4806                                    .await
 4807                                    .into_iter()
 4808                                    .filter_map(
 4809                                        |match_range| {
 4810                                            let start = search_buffer.anchor_after(
 4811                                                search_range.start + match_range.start,
 4812                                            );
 4813                                            let end = search_buffer.anchor_before(
 4814                                                search_range.start + match_range.end,
 4815                                            );
 4816                                            let range = Anchor::range_in_buffer(
 4817                                                excerpt_id,
 4818                                                search_buffer.remote_id(),
 4819                                                start..end,
 4820                                            );
 4821                                            (range != selection_anchors).then_some(range)
 4822                                        },
 4823                                    ),
 4824                                );
 4825                            }
 4826                        }
 4827                        ranges
 4828                    }))
 4829                })
 4830                .log_err()
 4831            else {
 4832                return;
 4833            };
 4834            let matches = matches_task.await;
 4835            editor
 4836                .update_in(&mut cx, |editor, _, cx| {
 4837                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4838                    if !matches.is_empty() {
 4839                        editor.highlight_background::<SelectedTextHighlight>(
 4840                            &matches,
 4841                            |theme| theme.editor_document_highlight_bracket_background,
 4842                            cx,
 4843                        )
 4844                    }
 4845                })
 4846                .log_err();
 4847        }));
 4848    }
 4849
 4850    pub fn refresh_inline_completion(
 4851        &mut self,
 4852        debounce: bool,
 4853        user_requested: bool,
 4854        window: &mut Window,
 4855        cx: &mut Context<Self>,
 4856    ) -> Option<()> {
 4857        let provider = self.edit_prediction_provider()?;
 4858        let cursor = self.selections.newest_anchor().head();
 4859        let (buffer, cursor_buffer_position) =
 4860            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4861
 4862        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4863            self.discard_inline_completion(false, cx);
 4864            return None;
 4865        }
 4866
 4867        if !user_requested
 4868            && (!self.should_show_edit_predictions()
 4869                || !self.is_focused(window)
 4870                || buffer.read(cx).is_empty())
 4871        {
 4872            self.discard_inline_completion(false, cx);
 4873            return None;
 4874        }
 4875
 4876        self.update_visible_inline_completion(window, cx);
 4877        provider.refresh(
 4878            self.project.clone(),
 4879            buffer,
 4880            cursor_buffer_position,
 4881            debounce,
 4882            cx,
 4883        );
 4884        Some(())
 4885    }
 4886
 4887    fn show_edit_predictions_in_menu(&self) -> bool {
 4888        match self.edit_prediction_settings {
 4889            EditPredictionSettings::Disabled => false,
 4890            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4891        }
 4892    }
 4893
 4894    pub fn edit_predictions_enabled(&self) -> bool {
 4895        match self.edit_prediction_settings {
 4896            EditPredictionSettings::Disabled => false,
 4897            EditPredictionSettings::Enabled { .. } => true,
 4898        }
 4899    }
 4900
 4901    fn edit_prediction_requires_modifier(&self) -> bool {
 4902        match self.edit_prediction_settings {
 4903            EditPredictionSettings::Disabled => false,
 4904            EditPredictionSettings::Enabled {
 4905                preview_requires_modifier,
 4906                ..
 4907            } => preview_requires_modifier,
 4908        }
 4909    }
 4910
 4911    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4912        if self.edit_prediction_provider.is_none() {
 4913            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4914        } else {
 4915            let selection = self.selections.newest_anchor();
 4916            let cursor = selection.head();
 4917
 4918            if let Some((buffer, cursor_buffer_position)) =
 4919                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4920            {
 4921                self.edit_prediction_settings =
 4922                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4923            }
 4924        }
 4925    }
 4926
 4927    fn edit_prediction_settings_at_position(
 4928        &self,
 4929        buffer: &Entity<Buffer>,
 4930        buffer_position: language::Anchor,
 4931        cx: &App,
 4932    ) -> EditPredictionSettings {
 4933        if self.mode != EditorMode::Full
 4934            || !self.show_inline_completions_override.unwrap_or(true)
 4935            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4936        {
 4937            return EditPredictionSettings::Disabled;
 4938        }
 4939
 4940        let buffer = buffer.read(cx);
 4941
 4942        let file = buffer.file();
 4943
 4944        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4945            return EditPredictionSettings::Disabled;
 4946        };
 4947
 4948        let by_provider = matches!(
 4949            self.menu_inline_completions_policy,
 4950            MenuInlineCompletionsPolicy::ByProvider
 4951        );
 4952
 4953        let show_in_menu = by_provider
 4954            && self
 4955                .edit_prediction_provider
 4956                .as_ref()
 4957                .map_or(false, |provider| {
 4958                    provider.provider.show_completions_in_menu()
 4959                });
 4960
 4961        let preview_requires_modifier =
 4962            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4963
 4964        EditPredictionSettings::Enabled {
 4965            show_in_menu,
 4966            preview_requires_modifier,
 4967        }
 4968    }
 4969
 4970    fn should_show_edit_predictions(&self) -> bool {
 4971        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4972    }
 4973
 4974    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4975        matches!(
 4976            self.edit_prediction_preview,
 4977            EditPredictionPreview::Active { .. }
 4978        )
 4979    }
 4980
 4981    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 4982        let cursor = self.selections.newest_anchor().head();
 4983        if let Some((buffer, cursor_position)) =
 4984            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4985        {
 4986            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 4987        } else {
 4988            false
 4989        }
 4990    }
 4991
 4992    fn edit_predictions_enabled_in_buffer(
 4993        &self,
 4994        buffer: &Entity<Buffer>,
 4995        buffer_position: language::Anchor,
 4996        cx: &App,
 4997    ) -> bool {
 4998        maybe!({
 4999            let provider = self.edit_prediction_provider()?;
 5000            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5001                return Some(false);
 5002            }
 5003            let buffer = buffer.read(cx);
 5004            let Some(file) = buffer.file() else {
 5005                return Some(true);
 5006            };
 5007            let settings = all_language_settings(Some(file), cx);
 5008            Some(settings.inline_completions_enabled_for_path(file.path()))
 5009        })
 5010        .unwrap_or(false)
 5011    }
 5012
 5013    fn cycle_inline_completion(
 5014        &mut self,
 5015        direction: Direction,
 5016        window: &mut Window,
 5017        cx: &mut Context<Self>,
 5018    ) -> Option<()> {
 5019        let provider = self.edit_prediction_provider()?;
 5020        let cursor = self.selections.newest_anchor().head();
 5021        let (buffer, cursor_buffer_position) =
 5022            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5023        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5024            return None;
 5025        }
 5026
 5027        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5028        self.update_visible_inline_completion(window, cx);
 5029
 5030        Some(())
 5031    }
 5032
 5033    pub fn show_inline_completion(
 5034        &mut self,
 5035        _: &ShowEditPrediction,
 5036        window: &mut Window,
 5037        cx: &mut Context<Self>,
 5038    ) {
 5039        if !self.has_active_inline_completion() {
 5040            self.refresh_inline_completion(false, true, window, cx);
 5041            return;
 5042        }
 5043
 5044        self.update_visible_inline_completion(window, cx);
 5045    }
 5046
 5047    pub fn display_cursor_names(
 5048        &mut self,
 5049        _: &DisplayCursorNames,
 5050        window: &mut Window,
 5051        cx: &mut Context<Self>,
 5052    ) {
 5053        self.show_cursor_names(window, cx);
 5054    }
 5055
 5056    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5057        self.show_cursor_names = true;
 5058        cx.notify();
 5059        cx.spawn_in(window, |this, mut cx| async move {
 5060            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5061            this.update(&mut cx, |this, cx| {
 5062                this.show_cursor_names = false;
 5063                cx.notify()
 5064            })
 5065            .ok()
 5066        })
 5067        .detach();
 5068    }
 5069
 5070    pub fn next_edit_prediction(
 5071        &mut self,
 5072        _: &NextEditPrediction,
 5073        window: &mut Window,
 5074        cx: &mut Context<Self>,
 5075    ) {
 5076        if self.has_active_inline_completion() {
 5077            self.cycle_inline_completion(Direction::Next, window, cx);
 5078        } else {
 5079            let is_copilot_disabled = self
 5080                .refresh_inline_completion(false, true, window, cx)
 5081                .is_none();
 5082            if is_copilot_disabled {
 5083                cx.propagate();
 5084            }
 5085        }
 5086    }
 5087
 5088    pub fn previous_edit_prediction(
 5089        &mut self,
 5090        _: &PreviousEditPrediction,
 5091        window: &mut Window,
 5092        cx: &mut Context<Self>,
 5093    ) {
 5094        if self.has_active_inline_completion() {
 5095            self.cycle_inline_completion(Direction::Prev, window, cx);
 5096        } else {
 5097            let is_copilot_disabled = self
 5098                .refresh_inline_completion(false, true, window, cx)
 5099                .is_none();
 5100            if is_copilot_disabled {
 5101                cx.propagate();
 5102            }
 5103        }
 5104    }
 5105
 5106    pub fn accept_edit_prediction(
 5107        &mut self,
 5108        _: &AcceptEditPrediction,
 5109        window: &mut Window,
 5110        cx: &mut Context<Self>,
 5111    ) {
 5112        if self.show_edit_predictions_in_menu() {
 5113            self.hide_context_menu(window, cx);
 5114        }
 5115
 5116        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5117            return;
 5118        };
 5119
 5120        self.report_inline_completion_event(
 5121            active_inline_completion.completion_id.clone(),
 5122            true,
 5123            cx,
 5124        );
 5125
 5126        match &active_inline_completion.completion {
 5127            InlineCompletion::Move { target, .. } => {
 5128                let target = *target;
 5129
 5130                if let Some(position_map) = &self.last_position_map {
 5131                    if position_map
 5132                        .visible_row_range
 5133                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5134                        || !self.edit_prediction_requires_modifier()
 5135                    {
 5136                        self.unfold_ranges(&[target..target], true, false, cx);
 5137                        // Note that this is also done in vim's handler of the Tab action.
 5138                        self.change_selections(
 5139                            Some(Autoscroll::newest()),
 5140                            window,
 5141                            cx,
 5142                            |selections| {
 5143                                selections.select_anchor_ranges([target..target]);
 5144                            },
 5145                        );
 5146                        self.clear_row_highlights::<EditPredictionPreview>();
 5147
 5148                        self.edit_prediction_preview
 5149                            .set_previous_scroll_position(None);
 5150                    } else {
 5151                        self.edit_prediction_preview
 5152                            .set_previous_scroll_position(Some(
 5153                                position_map.snapshot.scroll_anchor,
 5154                            ));
 5155
 5156                        self.highlight_rows::<EditPredictionPreview>(
 5157                            target..target,
 5158                            cx.theme().colors().editor_highlighted_line_background,
 5159                            true,
 5160                            cx,
 5161                        );
 5162                        self.request_autoscroll(Autoscroll::fit(), cx);
 5163                    }
 5164                }
 5165            }
 5166            InlineCompletion::Edit { edits, .. } => {
 5167                if let Some(provider) = self.edit_prediction_provider() {
 5168                    provider.accept(cx);
 5169                }
 5170
 5171                let snapshot = self.buffer.read(cx).snapshot(cx);
 5172                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5173
 5174                self.buffer.update(cx, |buffer, cx| {
 5175                    buffer.edit(edits.iter().cloned(), None, cx)
 5176                });
 5177
 5178                self.change_selections(None, window, cx, |s| {
 5179                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5180                });
 5181
 5182                self.update_visible_inline_completion(window, cx);
 5183                if self.active_inline_completion.is_none() {
 5184                    self.refresh_inline_completion(true, true, window, cx);
 5185                }
 5186
 5187                cx.notify();
 5188            }
 5189        }
 5190
 5191        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5192    }
 5193
 5194    pub fn accept_partial_inline_completion(
 5195        &mut self,
 5196        _: &AcceptPartialEditPrediction,
 5197        window: &mut Window,
 5198        cx: &mut Context<Self>,
 5199    ) {
 5200        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5201            return;
 5202        };
 5203        if self.selections.count() != 1 {
 5204            return;
 5205        }
 5206
 5207        self.report_inline_completion_event(
 5208            active_inline_completion.completion_id.clone(),
 5209            true,
 5210            cx,
 5211        );
 5212
 5213        match &active_inline_completion.completion {
 5214            InlineCompletion::Move { target, .. } => {
 5215                let target = *target;
 5216                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5217                    selections.select_anchor_ranges([target..target]);
 5218                });
 5219            }
 5220            InlineCompletion::Edit { edits, .. } => {
 5221                // Find an insertion that starts at the cursor position.
 5222                let snapshot = self.buffer.read(cx).snapshot(cx);
 5223                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5224                let insertion = edits.iter().find_map(|(range, text)| {
 5225                    let range = range.to_offset(&snapshot);
 5226                    if range.is_empty() && range.start == cursor_offset {
 5227                        Some(text)
 5228                    } else {
 5229                        None
 5230                    }
 5231                });
 5232
 5233                if let Some(text) = insertion {
 5234                    let mut partial_completion = text
 5235                        .chars()
 5236                        .by_ref()
 5237                        .take_while(|c| c.is_alphabetic())
 5238                        .collect::<String>();
 5239                    if partial_completion.is_empty() {
 5240                        partial_completion = text
 5241                            .chars()
 5242                            .by_ref()
 5243                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5244                            .collect::<String>();
 5245                    }
 5246
 5247                    cx.emit(EditorEvent::InputHandled {
 5248                        utf16_range_to_replace: None,
 5249                        text: partial_completion.clone().into(),
 5250                    });
 5251
 5252                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5253
 5254                    self.refresh_inline_completion(true, true, window, cx);
 5255                    cx.notify();
 5256                } else {
 5257                    self.accept_edit_prediction(&Default::default(), window, cx);
 5258                }
 5259            }
 5260        }
 5261    }
 5262
 5263    fn discard_inline_completion(
 5264        &mut self,
 5265        should_report_inline_completion_event: bool,
 5266        cx: &mut Context<Self>,
 5267    ) -> bool {
 5268        if should_report_inline_completion_event {
 5269            let completion_id = self
 5270                .active_inline_completion
 5271                .as_ref()
 5272                .and_then(|active_completion| active_completion.completion_id.clone());
 5273
 5274            self.report_inline_completion_event(completion_id, false, cx);
 5275        }
 5276
 5277        if let Some(provider) = self.edit_prediction_provider() {
 5278            provider.discard(cx);
 5279        }
 5280
 5281        self.take_active_inline_completion(cx)
 5282    }
 5283
 5284    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5285        let Some(provider) = self.edit_prediction_provider() else {
 5286            return;
 5287        };
 5288
 5289        let Some((_, buffer, _)) = self
 5290            .buffer
 5291            .read(cx)
 5292            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5293        else {
 5294            return;
 5295        };
 5296
 5297        let extension = buffer
 5298            .read(cx)
 5299            .file()
 5300            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5301
 5302        let event_type = match accepted {
 5303            true => "Edit Prediction Accepted",
 5304            false => "Edit Prediction Discarded",
 5305        };
 5306        telemetry::event!(
 5307            event_type,
 5308            provider = provider.name(),
 5309            prediction_id = id,
 5310            suggestion_accepted = accepted,
 5311            file_extension = extension,
 5312        );
 5313    }
 5314
 5315    pub fn has_active_inline_completion(&self) -> bool {
 5316        self.active_inline_completion.is_some()
 5317    }
 5318
 5319    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5320        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5321            return false;
 5322        };
 5323
 5324        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5325        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5326        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5327        true
 5328    }
 5329
 5330    /// Returns true when we're displaying the edit prediction popover below the cursor
 5331    /// like we are not previewing and the LSP autocomplete menu is visible
 5332    /// or we are in `when_holding_modifier` mode.
 5333    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5334        if self.edit_prediction_preview_is_active()
 5335            || !self.show_edit_predictions_in_menu()
 5336            || !self.edit_predictions_enabled()
 5337        {
 5338            return false;
 5339        }
 5340
 5341        if self.has_visible_completions_menu() {
 5342            return true;
 5343        }
 5344
 5345        has_completion && self.edit_prediction_requires_modifier()
 5346    }
 5347
 5348    fn handle_modifiers_changed(
 5349        &mut self,
 5350        modifiers: Modifiers,
 5351        position_map: &PositionMap,
 5352        window: &mut Window,
 5353        cx: &mut Context<Self>,
 5354    ) {
 5355        if self.show_edit_predictions_in_menu() {
 5356            self.update_edit_prediction_preview(&modifiers, window, cx);
 5357        }
 5358
 5359        self.update_selection_mode(&modifiers, position_map, window, cx);
 5360
 5361        let mouse_position = window.mouse_position();
 5362        if !position_map.text_hitbox.is_hovered(window) {
 5363            return;
 5364        }
 5365
 5366        self.update_hovered_link(
 5367            position_map.point_for_position(mouse_position),
 5368            &position_map.snapshot,
 5369            modifiers,
 5370            window,
 5371            cx,
 5372        )
 5373    }
 5374
 5375    fn update_selection_mode(
 5376        &mut self,
 5377        modifiers: &Modifiers,
 5378        position_map: &PositionMap,
 5379        window: &mut Window,
 5380        cx: &mut Context<Self>,
 5381    ) {
 5382        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5383            return;
 5384        }
 5385
 5386        let mouse_position = window.mouse_position();
 5387        let point_for_position = position_map.point_for_position(mouse_position);
 5388        let position = point_for_position.previous_valid;
 5389
 5390        self.select(
 5391            SelectPhase::BeginColumnar {
 5392                position,
 5393                reset: false,
 5394                goal_column: point_for_position.exact_unclipped.column(),
 5395            },
 5396            window,
 5397            cx,
 5398        );
 5399    }
 5400
 5401    fn update_edit_prediction_preview(
 5402        &mut self,
 5403        modifiers: &Modifiers,
 5404        window: &mut Window,
 5405        cx: &mut Context<Self>,
 5406    ) {
 5407        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5408        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5409            return;
 5410        };
 5411
 5412        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5413            if matches!(
 5414                self.edit_prediction_preview,
 5415                EditPredictionPreview::Inactive { .. }
 5416            ) {
 5417                self.edit_prediction_preview = EditPredictionPreview::Active {
 5418                    previous_scroll_position: None,
 5419                    since: Instant::now(),
 5420                };
 5421
 5422                self.update_visible_inline_completion(window, cx);
 5423                cx.notify();
 5424            }
 5425        } else if let EditPredictionPreview::Active {
 5426            previous_scroll_position,
 5427            since,
 5428        } = self.edit_prediction_preview
 5429        {
 5430            if let (Some(previous_scroll_position), Some(position_map)) =
 5431                (previous_scroll_position, self.last_position_map.as_ref())
 5432            {
 5433                self.set_scroll_position(
 5434                    previous_scroll_position
 5435                        .scroll_position(&position_map.snapshot.display_snapshot),
 5436                    window,
 5437                    cx,
 5438                );
 5439            }
 5440
 5441            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5442                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5443            };
 5444            self.clear_row_highlights::<EditPredictionPreview>();
 5445            self.update_visible_inline_completion(window, cx);
 5446            cx.notify();
 5447        }
 5448    }
 5449
 5450    fn update_visible_inline_completion(
 5451        &mut self,
 5452        _window: &mut Window,
 5453        cx: &mut Context<Self>,
 5454    ) -> Option<()> {
 5455        let selection = self.selections.newest_anchor();
 5456        let cursor = selection.head();
 5457        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5458        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5459        let excerpt_id = cursor.excerpt_id;
 5460
 5461        let show_in_menu = self.show_edit_predictions_in_menu();
 5462        let completions_menu_has_precedence = !show_in_menu
 5463            && (self.context_menu.borrow().is_some()
 5464                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5465
 5466        if completions_menu_has_precedence
 5467            || !offset_selection.is_empty()
 5468            || self
 5469                .active_inline_completion
 5470                .as_ref()
 5471                .map_or(false, |completion| {
 5472                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5473                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5474                    !invalidation_range.contains(&offset_selection.head())
 5475                })
 5476        {
 5477            self.discard_inline_completion(false, cx);
 5478            return None;
 5479        }
 5480
 5481        self.take_active_inline_completion(cx);
 5482        let Some(provider) = self.edit_prediction_provider() else {
 5483            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5484            return None;
 5485        };
 5486
 5487        let (buffer, cursor_buffer_position) =
 5488            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5489
 5490        self.edit_prediction_settings =
 5491            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5492
 5493        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5494
 5495        if self.edit_prediction_indent_conflict {
 5496            let cursor_point = cursor.to_point(&multibuffer);
 5497
 5498            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5499
 5500            if let Some((_, indent)) = indents.iter().next() {
 5501                if indent.len == cursor_point.column {
 5502                    self.edit_prediction_indent_conflict = false;
 5503                }
 5504            }
 5505        }
 5506
 5507        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5508        let edits = inline_completion
 5509            .edits
 5510            .into_iter()
 5511            .flat_map(|(range, new_text)| {
 5512                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5513                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5514                Some((start..end, new_text))
 5515            })
 5516            .collect::<Vec<_>>();
 5517        if edits.is_empty() {
 5518            return None;
 5519        }
 5520
 5521        let first_edit_start = edits.first().unwrap().0.start;
 5522        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5523        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5524
 5525        let last_edit_end = edits.last().unwrap().0.end;
 5526        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5527        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5528
 5529        let cursor_row = cursor.to_point(&multibuffer).row;
 5530
 5531        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5532
 5533        let mut inlay_ids = Vec::new();
 5534        let invalidation_row_range;
 5535        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5536            Some(cursor_row..edit_end_row)
 5537        } else if cursor_row > edit_end_row {
 5538            Some(edit_start_row..cursor_row)
 5539        } else {
 5540            None
 5541        };
 5542        let is_move =
 5543            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5544        let completion = if is_move {
 5545            invalidation_row_range =
 5546                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5547            let target = first_edit_start;
 5548            InlineCompletion::Move { target, snapshot }
 5549        } else {
 5550            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5551                && !self.inline_completions_hidden_for_vim_mode;
 5552
 5553            if show_completions_in_buffer {
 5554                if edits
 5555                    .iter()
 5556                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5557                {
 5558                    let mut inlays = Vec::new();
 5559                    for (range, new_text) in &edits {
 5560                        let inlay = Inlay::inline_completion(
 5561                            post_inc(&mut self.next_inlay_id),
 5562                            range.start,
 5563                            new_text.as_str(),
 5564                        );
 5565                        inlay_ids.push(inlay.id);
 5566                        inlays.push(inlay);
 5567                    }
 5568
 5569                    self.splice_inlays(&[], inlays, cx);
 5570                } else {
 5571                    let background_color = cx.theme().status().deleted_background;
 5572                    self.highlight_text::<InlineCompletionHighlight>(
 5573                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5574                        HighlightStyle {
 5575                            background_color: Some(background_color),
 5576                            ..Default::default()
 5577                        },
 5578                        cx,
 5579                    );
 5580                }
 5581            }
 5582
 5583            invalidation_row_range = edit_start_row..edit_end_row;
 5584
 5585            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5586                if provider.show_tab_accept_marker() {
 5587                    EditDisplayMode::TabAccept
 5588                } else {
 5589                    EditDisplayMode::Inline
 5590                }
 5591            } else {
 5592                EditDisplayMode::DiffPopover
 5593            };
 5594
 5595            InlineCompletion::Edit {
 5596                edits,
 5597                edit_preview: inline_completion.edit_preview,
 5598                display_mode,
 5599                snapshot,
 5600            }
 5601        };
 5602
 5603        let invalidation_range = multibuffer
 5604            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5605            ..multibuffer.anchor_after(Point::new(
 5606                invalidation_row_range.end,
 5607                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5608            ));
 5609
 5610        self.stale_inline_completion_in_menu = None;
 5611        self.active_inline_completion = Some(InlineCompletionState {
 5612            inlay_ids,
 5613            completion,
 5614            completion_id: inline_completion.id,
 5615            invalidation_range,
 5616        });
 5617
 5618        cx.notify();
 5619
 5620        Some(())
 5621    }
 5622
 5623    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5624        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5625    }
 5626
 5627    fn render_code_actions_indicator(
 5628        &self,
 5629        _style: &EditorStyle,
 5630        row: DisplayRow,
 5631        is_active: bool,
 5632        cx: &mut Context<Self>,
 5633    ) -> Option<IconButton> {
 5634        if self.available_code_actions.is_some() {
 5635            Some(
 5636                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5637                    .shape(ui::IconButtonShape::Square)
 5638                    .icon_size(IconSize::XSmall)
 5639                    .icon_color(Color::Muted)
 5640                    .toggle_state(is_active)
 5641                    .tooltip({
 5642                        let focus_handle = self.focus_handle.clone();
 5643                        move |window, cx| {
 5644                            Tooltip::for_action_in(
 5645                                "Toggle Code Actions",
 5646                                &ToggleCodeActions {
 5647                                    deployed_from_indicator: None,
 5648                                },
 5649                                &focus_handle,
 5650                                window,
 5651                                cx,
 5652                            )
 5653                        }
 5654                    })
 5655                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5656                        window.focus(&editor.focus_handle(cx));
 5657                        editor.toggle_code_actions(
 5658                            &ToggleCodeActions {
 5659                                deployed_from_indicator: Some(row),
 5660                            },
 5661                            window,
 5662                            cx,
 5663                        );
 5664                    })),
 5665            )
 5666        } else {
 5667            None
 5668        }
 5669    }
 5670
 5671    fn clear_tasks(&mut self) {
 5672        self.tasks.clear()
 5673    }
 5674
 5675    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5676        if self.tasks.insert(key, value).is_some() {
 5677            // This case should hopefully be rare, but just in case...
 5678            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5679        }
 5680    }
 5681
 5682    fn build_tasks_context(
 5683        project: &Entity<Project>,
 5684        buffer: &Entity<Buffer>,
 5685        buffer_row: u32,
 5686        tasks: &Arc<RunnableTasks>,
 5687        cx: &mut Context<Self>,
 5688    ) -> Task<Option<task::TaskContext>> {
 5689        let position = Point::new(buffer_row, tasks.column);
 5690        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5691        let location = Location {
 5692            buffer: buffer.clone(),
 5693            range: range_start..range_start,
 5694        };
 5695        // Fill in the environmental variables from the tree-sitter captures
 5696        let mut captured_task_variables = TaskVariables::default();
 5697        for (capture_name, value) in tasks.extra_variables.clone() {
 5698            captured_task_variables.insert(
 5699                task::VariableName::Custom(capture_name.into()),
 5700                value.clone(),
 5701            );
 5702        }
 5703        project.update(cx, |project, cx| {
 5704            project.task_store().update(cx, |task_store, cx| {
 5705                task_store.task_context_for_location(captured_task_variables, location, cx)
 5706            })
 5707        })
 5708    }
 5709
 5710    pub fn spawn_nearest_task(
 5711        &mut self,
 5712        action: &SpawnNearestTask,
 5713        window: &mut Window,
 5714        cx: &mut Context<Self>,
 5715    ) {
 5716        let Some((workspace, _)) = self.workspace.clone() else {
 5717            return;
 5718        };
 5719        let Some(project) = self.project.clone() else {
 5720            return;
 5721        };
 5722
 5723        // Try to find a closest, enclosing node using tree-sitter that has a
 5724        // task
 5725        let Some((buffer, buffer_row, tasks)) = self
 5726            .find_enclosing_node_task(cx)
 5727            // Or find the task that's closest in row-distance.
 5728            .or_else(|| self.find_closest_task(cx))
 5729        else {
 5730            return;
 5731        };
 5732
 5733        let reveal_strategy = action.reveal;
 5734        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5735        cx.spawn_in(window, |_, mut cx| async move {
 5736            let context = task_context.await?;
 5737            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5738
 5739            let resolved = resolved_task.resolved.as_mut()?;
 5740            resolved.reveal = reveal_strategy;
 5741
 5742            workspace
 5743                .update(&mut cx, |workspace, cx| {
 5744                    workspace::tasks::schedule_resolved_task(
 5745                        workspace,
 5746                        task_source_kind,
 5747                        resolved_task,
 5748                        false,
 5749                        cx,
 5750                    );
 5751                })
 5752                .ok()
 5753        })
 5754        .detach();
 5755    }
 5756
 5757    fn find_closest_task(
 5758        &mut self,
 5759        cx: &mut Context<Self>,
 5760    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5761        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5762
 5763        let ((buffer_id, row), tasks) = self
 5764            .tasks
 5765            .iter()
 5766            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5767
 5768        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5769        let tasks = Arc::new(tasks.to_owned());
 5770        Some((buffer, *row, tasks))
 5771    }
 5772
 5773    fn find_enclosing_node_task(
 5774        &mut self,
 5775        cx: &mut Context<Self>,
 5776    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5777        let snapshot = self.buffer.read(cx).snapshot(cx);
 5778        let offset = self.selections.newest::<usize>(cx).head();
 5779        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5780        let buffer_id = excerpt.buffer().remote_id();
 5781
 5782        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5783        let mut cursor = layer.node().walk();
 5784
 5785        while cursor.goto_first_child_for_byte(offset).is_some() {
 5786            if cursor.node().end_byte() == offset {
 5787                cursor.goto_next_sibling();
 5788            }
 5789        }
 5790
 5791        // Ascend to the smallest ancestor that contains the range and has a task.
 5792        loop {
 5793            let node = cursor.node();
 5794            let node_range = node.byte_range();
 5795            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5796
 5797            // Check if this node contains our offset
 5798            if node_range.start <= offset && node_range.end >= offset {
 5799                // If it contains offset, check for task
 5800                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5801                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5802                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5803                }
 5804            }
 5805
 5806            if !cursor.goto_parent() {
 5807                break;
 5808            }
 5809        }
 5810        None
 5811    }
 5812
 5813    fn render_run_indicator(
 5814        &self,
 5815        _style: &EditorStyle,
 5816        is_active: bool,
 5817        row: DisplayRow,
 5818        cx: &mut Context<Self>,
 5819    ) -> IconButton {
 5820        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5821            .shape(ui::IconButtonShape::Square)
 5822            .icon_size(IconSize::XSmall)
 5823            .icon_color(Color::Muted)
 5824            .toggle_state(is_active)
 5825            .on_click(cx.listener(move |editor, _e, window, cx| {
 5826                window.focus(&editor.focus_handle(cx));
 5827                editor.toggle_code_actions(
 5828                    &ToggleCodeActions {
 5829                        deployed_from_indicator: Some(row),
 5830                    },
 5831                    window,
 5832                    cx,
 5833                );
 5834            }))
 5835    }
 5836
 5837    pub fn context_menu_visible(&self) -> bool {
 5838        !self.edit_prediction_preview_is_active()
 5839            && self
 5840                .context_menu
 5841                .borrow()
 5842                .as_ref()
 5843                .map_or(false, |menu| menu.visible())
 5844    }
 5845
 5846    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5847        self.context_menu
 5848            .borrow()
 5849            .as_ref()
 5850            .map(|menu| menu.origin())
 5851    }
 5852
 5853    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5854    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5855
 5856    #[allow(clippy::too_many_arguments)]
 5857    fn render_edit_prediction_popover(
 5858        &mut self,
 5859        text_bounds: &Bounds<Pixels>,
 5860        content_origin: gpui::Point<Pixels>,
 5861        editor_snapshot: &EditorSnapshot,
 5862        visible_row_range: Range<DisplayRow>,
 5863        scroll_top: f32,
 5864        scroll_bottom: f32,
 5865        line_layouts: &[LineWithInvisibles],
 5866        line_height: Pixels,
 5867        scroll_pixel_position: gpui::Point<Pixels>,
 5868        newest_selection_head: Option<DisplayPoint>,
 5869        editor_width: Pixels,
 5870        style: &EditorStyle,
 5871        window: &mut Window,
 5872        cx: &mut App,
 5873    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5874        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5875
 5876        if self.edit_prediction_visible_in_cursor_popover(true) {
 5877            return None;
 5878        }
 5879
 5880        match &active_inline_completion.completion {
 5881            InlineCompletion::Move { target, .. } => {
 5882                let target_display_point = target.to_display_point(editor_snapshot);
 5883
 5884                if self.edit_prediction_requires_modifier() {
 5885                    if !self.edit_prediction_preview_is_active() {
 5886                        return None;
 5887                    }
 5888
 5889                    self.render_edit_prediction_modifier_jump_popover(
 5890                        text_bounds,
 5891                        content_origin,
 5892                        visible_row_range,
 5893                        line_layouts,
 5894                        line_height,
 5895                        scroll_pixel_position,
 5896                        newest_selection_head,
 5897                        target_display_point,
 5898                        window,
 5899                        cx,
 5900                    )
 5901                } else {
 5902                    self.render_edit_prediction_eager_jump_popover(
 5903                        text_bounds,
 5904                        content_origin,
 5905                        editor_snapshot,
 5906                        visible_row_range,
 5907                        scroll_top,
 5908                        scroll_bottom,
 5909                        line_height,
 5910                        scroll_pixel_position,
 5911                        target_display_point,
 5912                        editor_width,
 5913                        window,
 5914                        cx,
 5915                    )
 5916                }
 5917            }
 5918            InlineCompletion::Edit {
 5919                display_mode: EditDisplayMode::Inline,
 5920                ..
 5921            } => None,
 5922            InlineCompletion::Edit {
 5923                display_mode: EditDisplayMode::TabAccept,
 5924                edits,
 5925                ..
 5926            } => {
 5927                let range = &edits.first()?.0;
 5928                let target_display_point = range.end.to_display_point(editor_snapshot);
 5929
 5930                self.render_edit_prediction_end_of_line_popover(
 5931                    "Accept",
 5932                    editor_snapshot,
 5933                    visible_row_range,
 5934                    target_display_point,
 5935                    line_height,
 5936                    scroll_pixel_position,
 5937                    content_origin,
 5938                    editor_width,
 5939                    window,
 5940                    cx,
 5941                )
 5942            }
 5943            InlineCompletion::Edit {
 5944                edits,
 5945                edit_preview,
 5946                display_mode: EditDisplayMode::DiffPopover,
 5947                snapshot,
 5948            } => self.render_edit_prediction_diff_popover(
 5949                text_bounds,
 5950                content_origin,
 5951                editor_snapshot,
 5952                visible_row_range,
 5953                line_layouts,
 5954                line_height,
 5955                scroll_pixel_position,
 5956                newest_selection_head,
 5957                editor_width,
 5958                style,
 5959                edits,
 5960                edit_preview,
 5961                snapshot,
 5962                window,
 5963                cx,
 5964            ),
 5965        }
 5966    }
 5967
 5968    #[allow(clippy::too_many_arguments)]
 5969    fn render_edit_prediction_modifier_jump_popover(
 5970        &mut self,
 5971        text_bounds: &Bounds<Pixels>,
 5972        content_origin: gpui::Point<Pixels>,
 5973        visible_row_range: Range<DisplayRow>,
 5974        line_layouts: &[LineWithInvisibles],
 5975        line_height: Pixels,
 5976        scroll_pixel_position: gpui::Point<Pixels>,
 5977        newest_selection_head: Option<DisplayPoint>,
 5978        target_display_point: DisplayPoint,
 5979        window: &mut Window,
 5980        cx: &mut App,
 5981    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5982        let scrolled_content_origin =
 5983            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 5984
 5985        const SCROLL_PADDING_Y: Pixels = px(12.);
 5986
 5987        if target_display_point.row() < visible_row_range.start {
 5988            return self.render_edit_prediction_scroll_popover(
 5989                |_| SCROLL_PADDING_Y,
 5990                IconName::ArrowUp,
 5991                visible_row_range,
 5992                line_layouts,
 5993                newest_selection_head,
 5994                scrolled_content_origin,
 5995                window,
 5996                cx,
 5997            );
 5998        } else if target_display_point.row() >= visible_row_range.end {
 5999            return self.render_edit_prediction_scroll_popover(
 6000                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6001                IconName::ArrowDown,
 6002                visible_row_range,
 6003                line_layouts,
 6004                newest_selection_head,
 6005                scrolled_content_origin,
 6006                window,
 6007                cx,
 6008            );
 6009        }
 6010
 6011        const POLE_WIDTH: Pixels = px(2.);
 6012
 6013        let line_layout =
 6014            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6015        let target_column = target_display_point.column() as usize;
 6016
 6017        let target_x = line_layout.x_for_index(target_column);
 6018        let target_y =
 6019            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6020
 6021        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6022
 6023        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6024        border_color.l += 0.001;
 6025
 6026        let mut element = v_flex()
 6027            .items_end()
 6028            .when(flag_on_right, |el| el.items_start())
 6029            .child(if flag_on_right {
 6030                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6031                    .rounded_bl(px(0.))
 6032                    .rounded_tl(px(0.))
 6033                    .border_l_2()
 6034                    .border_color(border_color)
 6035            } else {
 6036                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6037                    .rounded_br(px(0.))
 6038                    .rounded_tr(px(0.))
 6039                    .border_r_2()
 6040                    .border_color(border_color)
 6041            })
 6042            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6043            .into_any();
 6044
 6045        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6046
 6047        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6048            - point(
 6049                if flag_on_right {
 6050                    POLE_WIDTH
 6051                } else {
 6052                    size.width - POLE_WIDTH
 6053                },
 6054                size.height - line_height,
 6055            );
 6056
 6057        origin.x = origin.x.max(content_origin.x);
 6058
 6059        element.prepaint_at(origin, window, cx);
 6060
 6061        Some((element, origin))
 6062    }
 6063
 6064    #[allow(clippy::too_many_arguments)]
 6065    fn render_edit_prediction_scroll_popover(
 6066        &mut self,
 6067        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6068        scroll_icon: IconName,
 6069        visible_row_range: Range<DisplayRow>,
 6070        line_layouts: &[LineWithInvisibles],
 6071        newest_selection_head: Option<DisplayPoint>,
 6072        scrolled_content_origin: gpui::Point<Pixels>,
 6073        window: &mut Window,
 6074        cx: &mut App,
 6075    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6076        let mut element = self
 6077            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6078            .into_any();
 6079
 6080        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6081
 6082        let cursor = newest_selection_head?;
 6083        let cursor_row_layout =
 6084            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6085        let cursor_column = cursor.column() as usize;
 6086
 6087        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6088
 6089        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6090
 6091        element.prepaint_at(origin, window, cx);
 6092        Some((element, origin))
 6093    }
 6094
 6095    #[allow(clippy::too_many_arguments)]
 6096    fn render_edit_prediction_eager_jump_popover(
 6097        &mut self,
 6098        text_bounds: &Bounds<Pixels>,
 6099        content_origin: gpui::Point<Pixels>,
 6100        editor_snapshot: &EditorSnapshot,
 6101        visible_row_range: Range<DisplayRow>,
 6102        scroll_top: f32,
 6103        scroll_bottom: f32,
 6104        line_height: Pixels,
 6105        scroll_pixel_position: gpui::Point<Pixels>,
 6106        target_display_point: DisplayPoint,
 6107        editor_width: Pixels,
 6108        window: &mut Window,
 6109        cx: &mut App,
 6110    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6111        if target_display_point.row().as_f32() < scroll_top {
 6112            let mut element = self
 6113                .render_edit_prediction_line_popover(
 6114                    "Jump to Edit",
 6115                    Some(IconName::ArrowUp),
 6116                    window,
 6117                    cx,
 6118                )?
 6119                .into_any();
 6120
 6121            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6122            let offset = point(
 6123                (text_bounds.size.width - size.width) / 2.,
 6124                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6125            );
 6126
 6127            let origin = text_bounds.origin + offset;
 6128            element.prepaint_at(origin, window, cx);
 6129            Some((element, origin))
 6130        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6131            let mut element = self
 6132                .render_edit_prediction_line_popover(
 6133                    "Jump to Edit",
 6134                    Some(IconName::ArrowDown),
 6135                    window,
 6136                    cx,
 6137                )?
 6138                .into_any();
 6139
 6140            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6141            let offset = point(
 6142                (text_bounds.size.width - size.width) / 2.,
 6143                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6144            );
 6145
 6146            let origin = text_bounds.origin + offset;
 6147            element.prepaint_at(origin, window, cx);
 6148            Some((element, origin))
 6149        } else {
 6150            self.render_edit_prediction_end_of_line_popover(
 6151                "Jump to Edit",
 6152                editor_snapshot,
 6153                visible_row_range,
 6154                target_display_point,
 6155                line_height,
 6156                scroll_pixel_position,
 6157                content_origin,
 6158                editor_width,
 6159                window,
 6160                cx,
 6161            )
 6162        }
 6163    }
 6164
 6165    #[allow(clippy::too_many_arguments)]
 6166    fn render_edit_prediction_end_of_line_popover(
 6167        self: &mut Editor,
 6168        label: &'static str,
 6169        editor_snapshot: &EditorSnapshot,
 6170        visible_row_range: Range<DisplayRow>,
 6171        target_display_point: DisplayPoint,
 6172        line_height: Pixels,
 6173        scroll_pixel_position: gpui::Point<Pixels>,
 6174        content_origin: gpui::Point<Pixels>,
 6175        editor_width: Pixels,
 6176        window: &mut Window,
 6177        cx: &mut App,
 6178    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6179        let target_line_end = DisplayPoint::new(
 6180            target_display_point.row(),
 6181            editor_snapshot.line_len(target_display_point.row()),
 6182        );
 6183
 6184        let mut element = self
 6185            .render_edit_prediction_line_popover(label, None, window, cx)?
 6186            .into_any();
 6187
 6188        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6189
 6190        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6191
 6192        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6193        let mut origin = start_point
 6194            + line_origin
 6195            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6196        origin.x = origin.x.max(content_origin.x);
 6197
 6198        let max_x = content_origin.x + editor_width - size.width;
 6199
 6200        if origin.x > max_x {
 6201            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6202
 6203            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6204                origin.y += offset;
 6205                IconName::ArrowUp
 6206            } else {
 6207                origin.y -= offset;
 6208                IconName::ArrowDown
 6209            };
 6210
 6211            element = self
 6212                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6213                .into_any();
 6214
 6215            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6216
 6217            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6218        }
 6219
 6220        element.prepaint_at(origin, window, cx);
 6221        Some((element, origin))
 6222    }
 6223
 6224    #[allow(clippy::too_many_arguments)]
 6225    fn render_edit_prediction_diff_popover(
 6226        self: &Editor,
 6227        text_bounds: &Bounds<Pixels>,
 6228        content_origin: gpui::Point<Pixels>,
 6229        editor_snapshot: &EditorSnapshot,
 6230        visible_row_range: Range<DisplayRow>,
 6231        line_layouts: &[LineWithInvisibles],
 6232        line_height: Pixels,
 6233        scroll_pixel_position: gpui::Point<Pixels>,
 6234        newest_selection_head: Option<DisplayPoint>,
 6235        editor_width: Pixels,
 6236        style: &EditorStyle,
 6237        edits: &Vec<(Range<Anchor>, String)>,
 6238        edit_preview: &Option<language::EditPreview>,
 6239        snapshot: &language::BufferSnapshot,
 6240        window: &mut Window,
 6241        cx: &mut App,
 6242    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6243        let edit_start = edits
 6244            .first()
 6245            .unwrap()
 6246            .0
 6247            .start
 6248            .to_display_point(editor_snapshot);
 6249        let edit_end = edits
 6250            .last()
 6251            .unwrap()
 6252            .0
 6253            .end
 6254            .to_display_point(editor_snapshot);
 6255
 6256        let is_visible = visible_row_range.contains(&edit_start.row())
 6257            || visible_row_range.contains(&edit_end.row());
 6258        if !is_visible {
 6259            return None;
 6260        }
 6261
 6262        let highlighted_edits =
 6263            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6264
 6265        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6266        let line_count = highlighted_edits.text.lines().count();
 6267
 6268        const BORDER_WIDTH: Pixels = px(1.);
 6269
 6270        let mut element = h_flex()
 6271            .items_start()
 6272            .child(
 6273                h_flex()
 6274                    .bg(cx.theme().colors().editor_background)
 6275                    .border(BORDER_WIDTH)
 6276                    .shadow_sm()
 6277                    .border_color(cx.theme().colors().border)
 6278                    .rounded_l_lg()
 6279                    .when(line_count > 1, |el| el.rounded_br_lg())
 6280                    .pr_1()
 6281                    .child(styled_text),
 6282            )
 6283            .child(
 6284                h_flex()
 6285                    .h(line_height + BORDER_WIDTH * px(2.))
 6286                    .px_1p5()
 6287                    .gap_1()
 6288                    // Workaround: For some reason, there's a gap if we don't do this
 6289                    .ml(-BORDER_WIDTH)
 6290                    .shadow(smallvec![gpui::BoxShadow {
 6291                        color: gpui::black().opacity(0.05),
 6292                        offset: point(px(1.), px(1.)),
 6293                        blur_radius: px(2.),
 6294                        spread_radius: px(0.),
 6295                    }])
 6296                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6297                    .border(BORDER_WIDTH)
 6298                    .border_color(cx.theme().colors().border)
 6299                    .rounded_r_lg()
 6300                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6301            )
 6302            .into_any();
 6303
 6304        let longest_row =
 6305            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6306        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6307            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6308        } else {
 6309            layout_line(
 6310                longest_row,
 6311                editor_snapshot,
 6312                style,
 6313                editor_width,
 6314                |_| false,
 6315                window,
 6316                cx,
 6317            )
 6318            .width
 6319        };
 6320
 6321        let viewport_bounds =
 6322            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6323                right: -EditorElement::SCROLLBAR_WIDTH,
 6324                ..Default::default()
 6325            });
 6326
 6327        let x_after_longest =
 6328            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6329                - scroll_pixel_position.x;
 6330
 6331        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6332
 6333        // Fully visible if it can be displayed within the window (allow overlapping other
 6334        // panes). However, this is only allowed if the popover starts within text_bounds.
 6335        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6336            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6337
 6338        let mut origin = if can_position_to_the_right {
 6339            point(
 6340                x_after_longest,
 6341                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6342                    - scroll_pixel_position.y,
 6343            )
 6344        } else {
 6345            let cursor_row = newest_selection_head.map(|head| head.row());
 6346            let above_edit = edit_start
 6347                .row()
 6348                .0
 6349                .checked_sub(line_count as u32)
 6350                .map(DisplayRow);
 6351            let below_edit = Some(edit_end.row() + 1);
 6352            let above_cursor =
 6353                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6354            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6355
 6356            // Place the edit popover adjacent to the edit if there is a location
 6357            // available that is onscreen and does not obscure the cursor. Otherwise,
 6358            // place it adjacent to the cursor.
 6359            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6360                .into_iter()
 6361                .flatten()
 6362                .find(|&start_row| {
 6363                    let end_row = start_row + line_count as u32;
 6364                    visible_row_range.contains(&start_row)
 6365                        && visible_row_range.contains(&end_row)
 6366                        && cursor_row.map_or(true, |cursor_row| {
 6367                            !((start_row..end_row).contains(&cursor_row))
 6368                        })
 6369                })?;
 6370
 6371            content_origin
 6372                + point(
 6373                    -scroll_pixel_position.x,
 6374                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6375                )
 6376        };
 6377
 6378        origin.x -= BORDER_WIDTH;
 6379
 6380        window.defer_draw(element, origin, 1);
 6381
 6382        // Do not return an element, since it will already be drawn due to defer_draw.
 6383        None
 6384    }
 6385
 6386    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6387        px(30.)
 6388    }
 6389
 6390    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6391        if self.read_only(cx) {
 6392            cx.theme().players().read_only()
 6393        } else {
 6394            self.style.as_ref().unwrap().local_player
 6395        }
 6396    }
 6397
 6398    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6399        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6400        let accept_keystroke = accept_binding.keystroke()?;
 6401
 6402        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6403
 6404        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6405            Color::Accent
 6406        } else {
 6407            Color::Muted
 6408        };
 6409
 6410        h_flex()
 6411            .px_0p5()
 6412            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6413            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6414            .text_size(TextSize::XSmall.rems(cx))
 6415            .child(h_flex().children(ui::render_modifiers(
 6416                &accept_keystroke.modifiers,
 6417                PlatformStyle::platform(),
 6418                Some(modifiers_color),
 6419                Some(IconSize::XSmall.rems().into()),
 6420                true,
 6421            )))
 6422            .when(is_platform_style_mac, |parent| {
 6423                parent.child(accept_keystroke.key.clone())
 6424            })
 6425            .when(!is_platform_style_mac, |parent| {
 6426                parent.child(
 6427                    Key::new(
 6428                        util::capitalize(&accept_keystroke.key),
 6429                        Some(Color::Default),
 6430                    )
 6431                    .size(Some(IconSize::XSmall.rems().into())),
 6432                )
 6433            })
 6434            .into()
 6435    }
 6436
 6437    fn render_edit_prediction_line_popover(
 6438        &self,
 6439        label: impl Into<SharedString>,
 6440        icon: Option<IconName>,
 6441        window: &mut Window,
 6442        cx: &App,
 6443    ) -> Option<Div> {
 6444        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6445
 6446        let result = h_flex()
 6447            .py_0p5()
 6448            .pl_1()
 6449            .pr(padding_right)
 6450            .gap_1()
 6451            .rounded(px(6.))
 6452            .border_1()
 6453            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6454            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6455            .shadow_sm()
 6456            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6457            .child(Label::new(label).size(LabelSize::Small))
 6458            .when_some(icon, |element, icon| {
 6459                element.child(
 6460                    div()
 6461                        .mt(px(1.5))
 6462                        .child(Icon::new(icon).size(IconSize::Small)),
 6463                )
 6464            });
 6465
 6466        Some(result)
 6467    }
 6468
 6469    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6470        let accent_color = cx.theme().colors().text_accent;
 6471        let editor_bg_color = cx.theme().colors().editor_background;
 6472        editor_bg_color.blend(accent_color.opacity(0.1))
 6473    }
 6474
 6475    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6476        let accent_color = cx.theme().colors().text_accent;
 6477        let editor_bg_color = cx.theme().colors().editor_background;
 6478        editor_bg_color.blend(accent_color.opacity(0.6))
 6479    }
 6480
 6481    #[allow(clippy::too_many_arguments)]
 6482    fn render_edit_prediction_cursor_popover(
 6483        &self,
 6484        min_width: Pixels,
 6485        max_width: Pixels,
 6486        cursor_point: Point,
 6487        style: &EditorStyle,
 6488        accept_keystroke: Option<&gpui::Keystroke>,
 6489        _window: &Window,
 6490        cx: &mut Context<Editor>,
 6491    ) -> Option<AnyElement> {
 6492        let provider = self.edit_prediction_provider.as_ref()?;
 6493
 6494        if provider.provider.needs_terms_acceptance(cx) {
 6495            return Some(
 6496                h_flex()
 6497                    .min_w(min_width)
 6498                    .flex_1()
 6499                    .px_2()
 6500                    .py_1()
 6501                    .gap_3()
 6502                    .elevation_2(cx)
 6503                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6504                    .id("accept-terms")
 6505                    .cursor_pointer()
 6506                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6507                    .on_click(cx.listener(|this, _event, window, cx| {
 6508                        cx.stop_propagation();
 6509                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6510                        window.dispatch_action(
 6511                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6512                            cx,
 6513                        );
 6514                    }))
 6515                    .child(
 6516                        h_flex()
 6517                            .flex_1()
 6518                            .gap_2()
 6519                            .child(Icon::new(IconName::ZedPredict))
 6520                            .child(Label::new("Accept Terms of Service"))
 6521                            .child(div().w_full())
 6522                            .child(
 6523                                Icon::new(IconName::ArrowUpRight)
 6524                                    .color(Color::Muted)
 6525                                    .size(IconSize::Small),
 6526                            )
 6527                            .into_any_element(),
 6528                    )
 6529                    .into_any(),
 6530            );
 6531        }
 6532
 6533        let is_refreshing = provider.provider.is_refreshing(cx);
 6534
 6535        fn pending_completion_container() -> Div {
 6536            h_flex()
 6537                .h_full()
 6538                .flex_1()
 6539                .gap_2()
 6540                .child(Icon::new(IconName::ZedPredict))
 6541        }
 6542
 6543        let completion = match &self.active_inline_completion {
 6544            Some(prediction) => {
 6545                if !self.has_visible_completions_menu() {
 6546                    const RADIUS: Pixels = px(6.);
 6547                    const BORDER_WIDTH: Pixels = px(1.);
 6548
 6549                    return Some(
 6550                        h_flex()
 6551                            .elevation_2(cx)
 6552                            .border(BORDER_WIDTH)
 6553                            .border_color(cx.theme().colors().border)
 6554                            .rounded(RADIUS)
 6555                            .rounded_tl(px(0.))
 6556                            .overflow_hidden()
 6557                            .child(div().px_1p5().child(match &prediction.completion {
 6558                                InlineCompletion::Move { target, snapshot } => {
 6559                                    use text::ToPoint as _;
 6560                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6561                                    {
 6562                                        Icon::new(IconName::ZedPredictDown)
 6563                                    } else {
 6564                                        Icon::new(IconName::ZedPredictUp)
 6565                                    }
 6566                                }
 6567                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6568                            }))
 6569                            .child(
 6570                                h_flex()
 6571                                    .gap_1()
 6572                                    .py_1()
 6573                                    .px_2()
 6574                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6575                                    .border_l_1()
 6576                                    .border_color(cx.theme().colors().border)
 6577                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6578                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6579                                        el.child(
 6580                                            Label::new("Hold")
 6581                                                .size(LabelSize::Small)
 6582                                                .line_height_style(LineHeightStyle::UiLabel),
 6583                                        )
 6584                                    })
 6585                                    .child(h_flex().children(ui::render_modifiers(
 6586                                        &accept_keystroke?.modifiers,
 6587                                        PlatformStyle::platform(),
 6588                                        Some(Color::Default),
 6589                                        Some(IconSize::XSmall.rems().into()),
 6590                                        false,
 6591                                    ))),
 6592                            )
 6593                            .into_any(),
 6594                    );
 6595                }
 6596
 6597                self.render_edit_prediction_cursor_popover_preview(
 6598                    prediction,
 6599                    cursor_point,
 6600                    style,
 6601                    cx,
 6602                )?
 6603            }
 6604
 6605            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6606                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6607                    stale_completion,
 6608                    cursor_point,
 6609                    style,
 6610                    cx,
 6611                )?,
 6612
 6613                None => {
 6614                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6615                }
 6616            },
 6617
 6618            None => pending_completion_container().child(Label::new("No Prediction")),
 6619        };
 6620
 6621        let completion = if is_refreshing {
 6622            completion
 6623                .with_animation(
 6624                    "loading-completion",
 6625                    Animation::new(Duration::from_secs(2))
 6626                        .repeat()
 6627                        .with_easing(pulsating_between(0.4, 0.8)),
 6628                    |label, delta| label.opacity(delta),
 6629                )
 6630                .into_any_element()
 6631        } else {
 6632            completion.into_any_element()
 6633        };
 6634
 6635        let has_completion = self.active_inline_completion.is_some();
 6636
 6637        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6638        Some(
 6639            h_flex()
 6640                .min_w(min_width)
 6641                .max_w(max_width)
 6642                .flex_1()
 6643                .elevation_2(cx)
 6644                .border_color(cx.theme().colors().border)
 6645                .child(
 6646                    div()
 6647                        .flex_1()
 6648                        .py_1()
 6649                        .px_2()
 6650                        .overflow_hidden()
 6651                        .child(completion),
 6652                )
 6653                .when_some(accept_keystroke, |el, accept_keystroke| {
 6654                    if !accept_keystroke.modifiers.modified() {
 6655                        return el;
 6656                    }
 6657
 6658                    el.child(
 6659                        h_flex()
 6660                            .h_full()
 6661                            .border_l_1()
 6662                            .rounded_r_lg()
 6663                            .border_color(cx.theme().colors().border)
 6664                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6665                            .gap_1()
 6666                            .py_1()
 6667                            .px_2()
 6668                            .child(
 6669                                h_flex()
 6670                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6671                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6672                                    .child(h_flex().children(ui::render_modifiers(
 6673                                        &accept_keystroke.modifiers,
 6674                                        PlatformStyle::platform(),
 6675                                        Some(if !has_completion {
 6676                                            Color::Muted
 6677                                        } else {
 6678                                            Color::Default
 6679                                        }),
 6680                                        None,
 6681                                        false,
 6682                                    ))),
 6683                            )
 6684                            .child(Label::new("Preview").into_any_element())
 6685                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6686                    )
 6687                })
 6688                .into_any(),
 6689        )
 6690    }
 6691
 6692    fn render_edit_prediction_cursor_popover_preview(
 6693        &self,
 6694        completion: &InlineCompletionState,
 6695        cursor_point: Point,
 6696        style: &EditorStyle,
 6697        cx: &mut Context<Editor>,
 6698    ) -> Option<Div> {
 6699        use text::ToPoint as _;
 6700
 6701        fn render_relative_row_jump(
 6702            prefix: impl Into<String>,
 6703            current_row: u32,
 6704            target_row: u32,
 6705        ) -> Div {
 6706            let (row_diff, arrow) = if target_row < current_row {
 6707                (current_row - target_row, IconName::ArrowUp)
 6708            } else {
 6709                (target_row - current_row, IconName::ArrowDown)
 6710            };
 6711
 6712            h_flex()
 6713                .child(
 6714                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6715                        .color(Color::Muted)
 6716                        .size(LabelSize::Small),
 6717                )
 6718                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6719        }
 6720
 6721        match &completion.completion {
 6722            InlineCompletion::Move {
 6723                target, snapshot, ..
 6724            } => Some(
 6725                h_flex()
 6726                    .px_2()
 6727                    .gap_2()
 6728                    .flex_1()
 6729                    .child(
 6730                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6731                            Icon::new(IconName::ZedPredictDown)
 6732                        } else {
 6733                            Icon::new(IconName::ZedPredictUp)
 6734                        },
 6735                    )
 6736                    .child(Label::new("Jump to Edit")),
 6737            ),
 6738
 6739            InlineCompletion::Edit {
 6740                edits,
 6741                edit_preview,
 6742                snapshot,
 6743                display_mode: _,
 6744            } => {
 6745                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6746
 6747                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6748                    &snapshot,
 6749                    &edits,
 6750                    edit_preview.as_ref()?,
 6751                    true,
 6752                    cx,
 6753                )
 6754                .first_line_preview();
 6755
 6756                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6757                    .with_highlights(&style.text, highlighted_edits.highlights);
 6758
 6759                let preview = h_flex()
 6760                    .gap_1()
 6761                    .min_w_16()
 6762                    .child(styled_text)
 6763                    .when(has_more_lines, |parent| parent.child(""));
 6764
 6765                let left = if first_edit_row != cursor_point.row {
 6766                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6767                        .into_any_element()
 6768                } else {
 6769                    Icon::new(IconName::ZedPredict).into_any_element()
 6770                };
 6771
 6772                Some(
 6773                    h_flex()
 6774                        .h_full()
 6775                        .flex_1()
 6776                        .gap_2()
 6777                        .pr_1()
 6778                        .overflow_x_hidden()
 6779                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6780                        .child(left)
 6781                        .child(preview),
 6782                )
 6783            }
 6784        }
 6785    }
 6786
 6787    fn render_context_menu(
 6788        &self,
 6789        style: &EditorStyle,
 6790        max_height_in_lines: u32,
 6791        y_flipped: bool,
 6792        window: &mut Window,
 6793        cx: &mut Context<Editor>,
 6794    ) -> Option<AnyElement> {
 6795        let menu = self.context_menu.borrow();
 6796        let menu = menu.as_ref()?;
 6797        if !menu.visible() {
 6798            return None;
 6799        };
 6800        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6801    }
 6802
 6803    fn render_context_menu_aside(
 6804        &mut self,
 6805        max_size: Size<Pixels>,
 6806        window: &mut Window,
 6807        cx: &mut Context<Editor>,
 6808    ) -> Option<AnyElement> {
 6809        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6810            if menu.visible() {
 6811                menu.render_aside(self, max_size, window, cx)
 6812            } else {
 6813                None
 6814            }
 6815        })
 6816    }
 6817
 6818    fn hide_context_menu(
 6819        &mut self,
 6820        window: &mut Window,
 6821        cx: &mut Context<Self>,
 6822    ) -> Option<CodeContextMenu> {
 6823        cx.notify();
 6824        self.completion_tasks.clear();
 6825        let context_menu = self.context_menu.borrow_mut().take();
 6826        self.stale_inline_completion_in_menu.take();
 6827        self.update_visible_inline_completion(window, cx);
 6828        context_menu
 6829    }
 6830
 6831    fn show_snippet_choices(
 6832        &mut self,
 6833        choices: &Vec<String>,
 6834        selection: Range<Anchor>,
 6835        cx: &mut Context<Self>,
 6836    ) {
 6837        if selection.start.buffer_id.is_none() {
 6838            return;
 6839        }
 6840        let buffer_id = selection.start.buffer_id.unwrap();
 6841        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6842        let id = post_inc(&mut self.next_completion_id);
 6843
 6844        if let Some(buffer) = buffer {
 6845            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6846                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6847            ));
 6848        }
 6849    }
 6850
 6851    pub fn insert_snippet(
 6852        &mut self,
 6853        insertion_ranges: &[Range<usize>],
 6854        snippet: Snippet,
 6855        window: &mut Window,
 6856        cx: &mut Context<Self>,
 6857    ) -> Result<()> {
 6858        struct Tabstop<T> {
 6859            is_end_tabstop: bool,
 6860            ranges: Vec<Range<T>>,
 6861            choices: Option<Vec<String>>,
 6862        }
 6863
 6864        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6865            let snippet_text: Arc<str> = snippet.text.clone().into();
 6866            buffer.edit(
 6867                insertion_ranges
 6868                    .iter()
 6869                    .cloned()
 6870                    .map(|range| (range, snippet_text.clone())),
 6871                Some(AutoindentMode::EachLine),
 6872                cx,
 6873            );
 6874
 6875            let snapshot = &*buffer.read(cx);
 6876            let snippet = &snippet;
 6877            snippet
 6878                .tabstops
 6879                .iter()
 6880                .map(|tabstop| {
 6881                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6882                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6883                    });
 6884                    let mut tabstop_ranges = tabstop
 6885                        .ranges
 6886                        .iter()
 6887                        .flat_map(|tabstop_range| {
 6888                            let mut delta = 0_isize;
 6889                            insertion_ranges.iter().map(move |insertion_range| {
 6890                                let insertion_start = insertion_range.start as isize + delta;
 6891                                delta +=
 6892                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6893
 6894                                let start = ((insertion_start + tabstop_range.start) as usize)
 6895                                    .min(snapshot.len());
 6896                                let end = ((insertion_start + tabstop_range.end) as usize)
 6897                                    .min(snapshot.len());
 6898                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6899                            })
 6900                        })
 6901                        .collect::<Vec<_>>();
 6902                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6903
 6904                    Tabstop {
 6905                        is_end_tabstop,
 6906                        ranges: tabstop_ranges,
 6907                        choices: tabstop.choices.clone(),
 6908                    }
 6909                })
 6910                .collect::<Vec<_>>()
 6911        });
 6912        if let Some(tabstop) = tabstops.first() {
 6913            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6914                s.select_ranges(tabstop.ranges.iter().cloned());
 6915            });
 6916
 6917            if let Some(choices) = &tabstop.choices {
 6918                if let Some(selection) = tabstop.ranges.first() {
 6919                    self.show_snippet_choices(choices, selection.clone(), cx)
 6920                }
 6921            }
 6922
 6923            // If we're already at the last tabstop and it's at the end of the snippet,
 6924            // we're done, we don't need to keep the state around.
 6925            if !tabstop.is_end_tabstop {
 6926                let choices = tabstops
 6927                    .iter()
 6928                    .map(|tabstop| tabstop.choices.clone())
 6929                    .collect();
 6930
 6931                let ranges = tabstops
 6932                    .into_iter()
 6933                    .map(|tabstop| tabstop.ranges)
 6934                    .collect::<Vec<_>>();
 6935
 6936                self.snippet_stack.push(SnippetState {
 6937                    active_index: 0,
 6938                    ranges,
 6939                    choices,
 6940                });
 6941            }
 6942
 6943            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6944            if self.autoclose_regions.is_empty() {
 6945                let snapshot = self.buffer.read(cx).snapshot(cx);
 6946                for selection in &mut self.selections.all::<Point>(cx) {
 6947                    let selection_head = selection.head();
 6948                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6949                        continue;
 6950                    };
 6951
 6952                    let mut bracket_pair = None;
 6953                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6954                    let prev_chars = snapshot
 6955                        .reversed_chars_at(selection_head)
 6956                        .collect::<String>();
 6957                    for (pair, enabled) in scope.brackets() {
 6958                        if enabled
 6959                            && pair.close
 6960                            && prev_chars.starts_with(pair.start.as_str())
 6961                            && next_chars.starts_with(pair.end.as_str())
 6962                        {
 6963                            bracket_pair = Some(pair.clone());
 6964                            break;
 6965                        }
 6966                    }
 6967                    if let Some(pair) = bracket_pair {
 6968                        let start = snapshot.anchor_after(selection_head);
 6969                        let end = snapshot.anchor_after(selection_head);
 6970                        self.autoclose_regions.push(AutocloseRegion {
 6971                            selection_id: selection.id,
 6972                            range: start..end,
 6973                            pair,
 6974                        });
 6975                    }
 6976                }
 6977            }
 6978        }
 6979        Ok(())
 6980    }
 6981
 6982    pub fn move_to_next_snippet_tabstop(
 6983        &mut self,
 6984        window: &mut Window,
 6985        cx: &mut Context<Self>,
 6986    ) -> bool {
 6987        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6988    }
 6989
 6990    pub fn move_to_prev_snippet_tabstop(
 6991        &mut self,
 6992        window: &mut Window,
 6993        cx: &mut Context<Self>,
 6994    ) -> bool {
 6995        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6996    }
 6997
 6998    pub fn move_to_snippet_tabstop(
 6999        &mut self,
 7000        bias: Bias,
 7001        window: &mut Window,
 7002        cx: &mut Context<Self>,
 7003    ) -> bool {
 7004        if let Some(mut snippet) = self.snippet_stack.pop() {
 7005            match bias {
 7006                Bias::Left => {
 7007                    if snippet.active_index > 0 {
 7008                        snippet.active_index -= 1;
 7009                    } else {
 7010                        self.snippet_stack.push(snippet);
 7011                        return false;
 7012                    }
 7013                }
 7014                Bias::Right => {
 7015                    if snippet.active_index + 1 < snippet.ranges.len() {
 7016                        snippet.active_index += 1;
 7017                    } else {
 7018                        self.snippet_stack.push(snippet);
 7019                        return false;
 7020                    }
 7021                }
 7022            }
 7023            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7024                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7025                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7026                });
 7027
 7028                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7029                    if let Some(selection) = current_ranges.first() {
 7030                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7031                    }
 7032                }
 7033
 7034                // If snippet state is not at the last tabstop, push it back on the stack
 7035                if snippet.active_index + 1 < snippet.ranges.len() {
 7036                    self.snippet_stack.push(snippet);
 7037                }
 7038                return true;
 7039            }
 7040        }
 7041
 7042        false
 7043    }
 7044
 7045    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7046        self.transact(window, cx, |this, window, cx| {
 7047            this.select_all(&SelectAll, window, cx);
 7048            this.insert("", window, cx);
 7049        });
 7050    }
 7051
 7052    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7053        self.transact(window, cx, |this, window, cx| {
 7054            this.select_autoclose_pair(window, cx);
 7055            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7056            if !this.linked_edit_ranges.is_empty() {
 7057                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7058                let snapshot = this.buffer.read(cx).snapshot(cx);
 7059
 7060                for selection in selections.iter() {
 7061                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7062                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7063                    if selection_start.buffer_id != selection_end.buffer_id {
 7064                        continue;
 7065                    }
 7066                    if let Some(ranges) =
 7067                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7068                    {
 7069                        for (buffer, entries) in ranges {
 7070                            linked_ranges.entry(buffer).or_default().extend(entries);
 7071                        }
 7072                    }
 7073                }
 7074            }
 7075
 7076            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7077            if !this.selections.line_mode {
 7078                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7079                for selection in &mut selections {
 7080                    if selection.is_empty() {
 7081                        let old_head = selection.head();
 7082                        let mut new_head =
 7083                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7084                                .to_point(&display_map);
 7085                        if let Some((buffer, line_buffer_range)) = display_map
 7086                            .buffer_snapshot
 7087                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7088                        {
 7089                            let indent_size =
 7090                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7091                            let indent_len = match indent_size.kind {
 7092                                IndentKind::Space => {
 7093                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7094                                }
 7095                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7096                            };
 7097                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7098                                let indent_len = indent_len.get();
 7099                                new_head = cmp::min(
 7100                                    new_head,
 7101                                    MultiBufferPoint::new(
 7102                                        old_head.row,
 7103                                        ((old_head.column - 1) / indent_len) * indent_len,
 7104                                    ),
 7105                                );
 7106                            }
 7107                        }
 7108
 7109                        selection.set_head(new_head, SelectionGoal::None);
 7110                    }
 7111                }
 7112            }
 7113
 7114            this.signature_help_state.set_backspace_pressed(true);
 7115            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7116                s.select(selections)
 7117            });
 7118            this.insert("", window, cx);
 7119            let empty_str: Arc<str> = Arc::from("");
 7120            for (buffer, edits) in linked_ranges {
 7121                let snapshot = buffer.read(cx).snapshot();
 7122                use text::ToPoint as TP;
 7123
 7124                let edits = edits
 7125                    .into_iter()
 7126                    .map(|range| {
 7127                        let end_point = TP::to_point(&range.end, &snapshot);
 7128                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7129
 7130                        if end_point == start_point {
 7131                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7132                                .saturating_sub(1);
 7133                            start_point =
 7134                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7135                        };
 7136
 7137                        (start_point..end_point, empty_str.clone())
 7138                    })
 7139                    .sorted_by_key(|(range, _)| range.start)
 7140                    .collect::<Vec<_>>();
 7141                buffer.update(cx, |this, cx| {
 7142                    this.edit(edits, None, cx);
 7143                })
 7144            }
 7145            this.refresh_inline_completion(true, false, window, cx);
 7146            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7147        });
 7148    }
 7149
 7150    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7151        self.transact(window, cx, |this, window, cx| {
 7152            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7153                let line_mode = s.line_mode;
 7154                s.move_with(|map, selection| {
 7155                    if selection.is_empty() && !line_mode {
 7156                        let cursor = movement::right(map, selection.head());
 7157                        selection.end = cursor;
 7158                        selection.reversed = true;
 7159                        selection.goal = SelectionGoal::None;
 7160                    }
 7161                })
 7162            });
 7163            this.insert("", window, cx);
 7164            this.refresh_inline_completion(true, false, window, cx);
 7165        });
 7166    }
 7167
 7168    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 7169        if self.move_to_prev_snippet_tabstop(window, cx) {
 7170            return;
 7171        }
 7172
 7173        self.outdent(&Outdent, window, cx);
 7174    }
 7175
 7176    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7177        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7178            return;
 7179        }
 7180
 7181        let mut selections = self.selections.all_adjusted(cx);
 7182        let buffer = self.buffer.read(cx);
 7183        let snapshot = buffer.snapshot(cx);
 7184        let rows_iter = selections.iter().map(|s| s.head().row);
 7185        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7186
 7187        let mut edits = Vec::new();
 7188        let mut prev_edited_row = 0;
 7189        let mut row_delta = 0;
 7190        for selection in &mut selections {
 7191            if selection.start.row != prev_edited_row {
 7192                row_delta = 0;
 7193            }
 7194            prev_edited_row = selection.end.row;
 7195
 7196            // If the selection is non-empty, then increase the indentation of the selected lines.
 7197            if !selection.is_empty() {
 7198                row_delta =
 7199                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7200                continue;
 7201            }
 7202
 7203            // If the selection is empty and the cursor is in the leading whitespace before the
 7204            // suggested indentation, then auto-indent the line.
 7205            let cursor = selection.head();
 7206            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7207            if let Some(suggested_indent) =
 7208                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7209            {
 7210                if cursor.column < suggested_indent.len
 7211                    && cursor.column <= current_indent.len
 7212                    && current_indent.len <= suggested_indent.len
 7213                {
 7214                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7215                    selection.end = selection.start;
 7216                    if row_delta == 0 {
 7217                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7218                            cursor.row,
 7219                            current_indent,
 7220                            suggested_indent,
 7221                        ));
 7222                        row_delta = suggested_indent.len - current_indent.len;
 7223                    }
 7224                    continue;
 7225                }
 7226            }
 7227
 7228            // Otherwise, insert a hard or soft tab.
 7229            let settings = buffer.settings_at(cursor, cx);
 7230            let tab_size = if settings.hard_tabs {
 7231                IndentSize::tab()
 7232            } else {
 7233                let tab_size = settings.tab_size.get();
 7234                let char_column = snapshot
 7235                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7236                    .flat_map(str::chars)
 7237                    .count()
 7238                    + row_delta as usize;
 7239                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7240                IndentSize::spaces(chars_to_next_tab_stop)
 7241            };
 7242            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7243            selection.end = selection.start;
 7244            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7245            row_delta += tab_size.len;
 7246        }
 7247
 7248        self.transact(window, cx, |this, window, cx| {
 7249            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7250            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7251                s.select(selections)
 7252            });
 7253            this.refresh_inline_completion(true, false, window, cx);
 7254        });
 7255    }
 7256
 7257    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7258        if self.read_only(cx) {
 7259            return;
 7260        }
 7261        let mut selections = self.selections.all::<Point>(cx);
 7262        let mut prev_edited_row = 0;
 7263        let mut row_delta = 0;
 7264        let mut edits = Vec::new();
 7265        let buffer = self.buffer.read(cx);
 7266        let snapshot = buffer.snapshot(cx);
 7267        for selection in &mut selections {
 7268            if selection.start.row != prev_edited_row {
 7269                row_delta = 0;
 7270            }
 7271            prev_edited_row = selection.end.row;
 7272
 7273            row_delta =
 7274                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7275        }
 7276
 7277        self.transact(window, cx, |this, window, cx| {
 7278            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7279            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7280                s.select(selections)
 7281            });
 7282        });
 7283    }
 7284
 7285    fn indent_selection(
 7286        buffer: &MultiBuffer,
 7287        snapshot: &MultiBufferSnapshot,
 7288        selection: &mut Selection<Point>,
 7289        edits: &mut Vec<(Range<Point>, String)>,
 7290        delta_for_start_row: u32,
 7291        cx: &App,
 7292    ) -> u32 {
 7293        let settings = buffer.settings_at(selection.start, cx);
 7294        let tab_size = settings.tab_size.get();
 7295        let indent_kind = if settings.hard_tabs {
 7296            IndentKind::Tab
 7297        } else {
 7298            IndentKind::Space
 7299        };
 7300        let mut start_row = selection.start.row;
 7301        let mut end_row = selection.end.row + 1;
 7302
 7303        // If a selection ends at the beginning of a line, don't indent
 7304        // that last line.
 7305        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7306            end_row -= 1;
 7307        }
 7308
 7309        // Avoid re-indenting a row that has already been indented by a
 7310        // previous selection, but still update this selection's column
 7311        // to reflect that indentation.
 7312        if delta_for_start_row > 0 {
 7313            start_row += 1;
 7314            selection.start.column += delta_for_start_row;
 7315            if selection.end.row == selection.start.row {
 7316                selection.end.column += delta_for_start_row;
 7317            }
 7318        }
 7319
 7320        let mut delta_for_end_row = 0;
 7321        let has_multiple_rows = start_row + 1 != end_row;
 7322        for row in start_row..end_row {
 7323            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7324            let indent_delta = match (current_indent.kind, indent_kind) {
 7325                (IndentKind::Space, IndentKind::Space) => {
 7326                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7327                    IndentSize::spaces(columns_to_next_tab_stop)
 7328                }
 7329                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7330                (_, IndentKind::Tab) => IndentSize::tab(),
 7331            };
 7332
 7333            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7334                0
 7335            } else {
 7336                selection.start.column
 7337            };
 7338            let row_start = Point::new(row, start);
 7339            edits.push((
 7340                row_start..row_start,
 7341                indent_delta.chars().collect::<String>(),
 7342            ));
 7343
 7344            // Update this selection's endpoints to reflect the indentation.
 7345            if row == selection.start.row {
 7346                selection.start.column += indent_delta.len;
 7347            }
 7348            if row == selection.end.row {
 7349                selection.end.column += indent_delta.len;
 7350                delta_for_end_row = indent_delta.len;
 7351            }
 7352        }
 7353
 7354        if selection.start.row == selection.end.row {
 7355            delta_for_start_row + delta_for_end_row
 7356        } else {
 7357            delta_for_end_row
 7358        }
 7359    }
 7360
 7361    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7362        if self.read_only(cx) {
 7363            return;
 7364        }
 7365        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7366        let selections = self.selections.all::<Point>(cx);
 7367        let mut deletion_ranges = Vec::new();
 7368        let mut last_outdent = None;
 7369        {
 7370            let buffer = self.buffer.read(cx);
 7371            let snapshot = buffer.snapshot(cx);
 7372            for selection in &selections {
 7373                let settings = buffer.settings_at(selection.start, cx);
 7374                let tab_size = settings.tab_size.get();
 7375                let mut rows = selection.spanned_rows(false, &display_map);
 7376
 7377                // Avoid re-outdenting a row that has already been outdented by a
 7378                // previous selection.
 7379                if let Some(last_row) = last_outdent {
 7380                    if last_row == rows.start {
 7381                        rows.start = rows.start.next_row();
 7382                    }
 7383                }
 7384                let has_multiple_rows = rows.len() > 1;
 7385                for row in rows.iter_rows() {
 7386                    let indent_size = snapshot.indent_size_for_line(row);
 7387                    if indent_size.len > 0 {
 7388                        let deletion_len = match indent_size.kind {
 7389                            IndentKind::Space => {
 7390                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7391                                if columns_to_prev_tab_stop == 0 {
 7392                                    tab_size
 7393                                } else {
 7394                                    columns_to_prev_tab_stop
 7395                                }
 7396                            }
 7397                            IndentKind::Tab => 1,
 7398                        };
 7399                        let start = if has_multiple_rows
 7400                            || deletion_len > selection.start.column
 7401                            || indent_size.len < selection.start.column
 7402                        {
 7403                            0
 7404                        } else {
 7405                            selection.start.column - deletion_len
 7406                        };
 7407                        deletion_ranges.push(
 7408                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7409                        );
 7410                        last_outdent = Some(row);
 7411                    }
 7412                }
 7413            }
 7414        }
 7415
 7416        self.transact(window, cx, |this, window, cx| {
 7417            this.buffer.update(cx, |buffer, cx| {
 7418                let empty_str: Arc<str> = Arc::default();
 7419                buffer.edit(
 7420                    deletion_ranges
 7421                        .into_iter()
 7422                        .map(|range| (range, empty_str.clone())),
 7423                    None,
 7424                    cx,
 7425                );
 7426            });
 7427            let selections = this.selections.all::<usize>(cx);
 7428            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7429                s.select(selections)
 7430            });
 7431        });
 7432    }
 7433
 7434    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7435        if self.read_only(cx) {
 7436            return;
 7437        }
 7438        let selections = self
 7439            .selections
 7440            .all::<usize>(cx)
 7441            .into_iter()
 7442            .map(|s| s.range());
 7443
 7444        self.transact(window, cx, |this, window, cx| {
 7445            this.buffer.update(cx, |buffer, cx| {
 7446                buffer.autoindent_ranges(selections, cx);
 7447            });
 7448            let selections = this.selections.all::<usize>(cx);
 7449            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7450                s.select(selections)
 7451            });
 7452        });
 7453    }
 7454
 7455    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7456        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7457        let selections = self.selections.all::<Point>(cx);
 7458
 7459        let mut new_cursors = Vec::new();
 7460        let mut edit_ranges = Vec::new();
 7461        let mut selections = selections.iter().peekable();
 7462        while let Some(selection) = selections.next() {
 7463            let mut rows = selection.spanned_rows(false, &display_map);
 7464            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7465
 7466            // Accumulate contiguous regions of rows that we want to delete.
 7467            while let Some(next_selection) = selections.peek() {
 7468                let next_rows = next_selection.spanned_rows(false, &display_map);
 7469                if next_rows.start <= rows.end {
 7470                    rows.end = next_rows.end;
 7471                    selections.next().unwrap();
 7472                } else {
 7473                    break;
 7474                }
 7475            }
 7476
 7477            let buffer = &display_map.buffer_snapshot;
 7478            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7479            let edit_end;
 7480            let cursor_buffer_row;
 7481            if buffer.max_point().row >= rows.end.0 {
 7482                // If there's a line after the range, delete the \n from the end of the row range
 7483                // and position the cursor on the next line.
 7484                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7485                cursor_buffer_row = rows.end;
 7486            } else {
 7487                // If there isn't a line after the range, delete the \n from the line before the
 7488                // start of the row range and position the cursor there.
 7489                edit_start = edit_start.saturating_sub(1);
 7490                edit_end = buffer.len();
 7491                cursor_buffer_row = rows.start.previous_row();
 7492            }
 7493
 7494            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7495            *cursor.column_mut() =
 7496                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7497
 7498            new_cursors.push((
 7499                selection.id,
 7500                buffer.anchor_after(cursor.to_point(&display_map)),
 7501            ));
 7502            edit_ranges.push(edit_start..edit_end);
 7503        }
 7504
 7505        self.transact(window, cx, |this, window, cx| {
 7506            let buffer = this.buffer.update(cx, |buffer, cx| {
 7507                let empty_str: Arc<str> = Arc::default();
 7508                buffer.edit(
 7509                    edit_ranges
 7510                        .into_iter()
 7511                        .map(|range| (range, empty_str.clone())),
 7512                    None,
 7513                    cx,
 7514                );
 7515                buffer.snapshot(cx)
 7516            });
 7517            let new_selections = new_cursors
 7518                .into_iter()
 7519                .map(|(id, cursor)| {
 7520                    let cursor = cursor.to_point(&buffer);
 7521                    Selection {
 7522                        id,
 7523                        start: cursor,
 7524                        end: cursor,
 7525                        reversed: false,
 7526                        goal: SelectionGoal::None,
 7527                    }
 7528                })
 7529                .collect();
 7530
 7531            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7532                s.select(new_selections);
 7533            });
 7534        });
 7535    }
 7536
 7537    pub fn join_lines_impl(
 7538        &mut self,
 7539        insert_whitespace: bool,
 7540        window: &mut Window,
 7541        cx: &mut Context<Self>,
 7542    ) {
 7543        if self.read_only(cx) {
 7544            return;
 7545        }
 7546        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7547        for selection in self.selections.all::<Point>(cx) {
 7548            let start = MultiBufferRow(selection.start.row);
 7549            // Treat single line selections as if they include the next line. Otherwise this action
 7550            // would do nothing for single line selections individual cursors.
 7551            let end = if selection.start.row == selection.end.row {
 7552                MultiBufferRow(selection.start.row + 1)
 7553            } else {
 7554                MultiBufferRow(selection.end.row)
 7555            };
 7556
 7557            if let Some(last_row_range) = row_ranges.last_mut() {
 7558                if start <= last_row_range.end {
 7559                    last_row_range.end = end;
 7560                    continue;
 7561                }
 7562            }
 7563            row_ranges.push(start..end);
 7564        }
 7565
 7566        let snapshot = self.buffer.read(cx).snapshot(cx);
 7567        let mut cursor_positions = Vec::new();
 7568        for row_range in &row_ranges {
 7569            let anchor = snapshot.anchor_before(Point::new(
 7570                row_range.end.previous_row().0,
 7571                snapshot.line_len(row_range.end.previous_row()),
 7572            ));
 7573            cursor_positions.push(anchor..anchor);
 7574        }
 7575
 7576        self.transact(window, cx, |this, window, cx| {
 7577            for row_range in row_ranges.into_iter().rev() {
 7578                for row in row_range.iter_rows().rev() {
 7579                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7580                    let next_line_row = row.next_row();
 7581                    let indent = snapshot.indent_size_for_line(next_line_row);
 7582                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7583
 7584                    let replace =
 7585                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7586                            " "
 7587                        } else {
 7588                            ""
 7589                        };
 7590
 7591                    this.buffer.update(cx, |buffer, cx| {
 7592                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7593                    });
 7594                }
 7595            }
 7596
 7597            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7598                s.select_anchor_ranges(cursor_positions)
 7599            });
 7600        });
 7601    }
 7602
 7603    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7604        self.join_lines_impl(true, window, cx);
 7605    }
 7606
 7607    pub fn sort_lines_case_sensitive(
 7608        &mut self,
 7609        _: &SortLinesCaseSensitive,
 7610        window: &mut Window,
 7611        cx: &mut Context<Self>,
 7612    ) {
 7613        self.manipulate_lines(window, cx, |lines| lines.sort())
 7614    }
 7615
 7616    pub fn sort_lines_case_insensitive(
 7617        &mut self,
 7618        _: &SortLinesCaseInsensitive,
 7619        window: &mut Window,
 7620        cx: &mut Context<Self>,
 7621    ) {
 7622        self.manipulate_lines(window, cx, |lines| {
 7623            lines.sort_by_key(|line| line.to_lowercase())
 7624        })
 7625    }
 7626
 7627    pub fn unique_lines_case_insensitive(
 7628        &mut self,
 7629        _: &UniqueLinesCaseInsensitive,
 7630        window: &mut Window,
 7631        cx: &mut Context<Self>,
 7632    ) {
 7633        self.manipulate_lines(window, cx, |lines| {
 7634            let mut seen = HashSet::default();
 7635            lines.retain(|line| seen.insert(line.to_lowercase()));
 7636        })
 7637    }
 7638
 7639    pub fn unique_lines_case_sensitive(
 7640        &mut self,
 7641        _: &UniqueLinesCaseSensitive,
 7642        window: &mut Window,
 7643        cx: &mut Context<Self>,
 7644    ) {
 7645        self.manipulate_lines(window, cx, |lines| {
 7646            let mut seen = HashSet::default();
 7647            lines.retain(|line| seen.insert(*line));
 7648        })
 7649    }
 7650
 7651    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7652        let Some(project) = self.project.clone() else {
 7653            return;
 7654        };
 7655        self.reload(project, window, cx)
 7656            .detach_and_notify_err(window, cx);
 7657    }
 7658
 7659    pub fn restore_file(
 7660        &mut self,
 7661        _: &::git::RestoreFile,
 7662        window: &mut Window,
 7663        cx: &mut Context<Self>,
 7664    ) {
 7665        let mut buffer_ids = HashSet::default();
 7666        let snapshot = self.buffer().read(cx).snapshot(cx);
 7667        for selection in self.selections.all::<usize>(cx) {
 7668            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7669        }
 7670
 7671        let buffer = self.buffer().read(cx);
 7672        let ranges = buffer_ids
 7673            .into_iter()
 7674            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7675            .collect::<Vec<_>>();
 7676
 7677        self.restore_hunks_in_ranges(ranges, window, cx);
 7678    }
 7679
 7680    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7681        let selections = self
 7682            .selections
 7683            .all(cx)
 7684            .into_iter()
 7685            .map(|s| s.range())
 7686            .collect();
 7687        self.restore_hunks_in_ranges(selections, window, cx);
 7688    }
 7689
 7690    fn restore_hunks_in_ranges(
 7691        &mut self,
 7692        ranges: Vec<Range<Point>>,
 7693        window: &mut Window,
 7694        cx: &mut Context<Editor>,
 7695    ) {
 7696        let mut revert_changes = HashMap::default();
 7697        let snapshot = self.buffer.read(cx).snapshot(cx);
 7698        let Some(project) = &self.project else {
 7699            return;
 7700        };
 7701
 7702        let chunk_by = self
 7703            .snapshot(window, cx)
 7704            .hunks_for_ranges(ranges.into_iter())
 7705            .into_iter()
 7706            .chunk_by(|hunk| hunk.buffer_id);
 7707        for (buffer_id, hunks) in &chunk_by {
 7708            let hunks = hunks.collect::<Vec<_>>();
 7709            for hunk in &hunks {
 7710                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7711            }
 7712            Self::do_stage_or_unstage(
 7713                project,
 7714                false,
 7715                buffer_id,
 7716                hunks.into_iter(),
 7717                &snapshot,
 7718                window,
 7719                cx,
 7720            );
 7721        }
 7722        drop(chunk_by);
 7723        if !revert_changes.is_empty() {
 7724            self.transact(window, cx, |editor, window, cx| {
 7725                editor.revert(revert_changes, window, cx);
 7726            });
 7727        }
 7728    }
 7729
 7730    pub fn open_active_item_in_terminal(
 7731        &mut self,
 7732        _: &OpenInTerminal,
 7733        window: &mut Window,
 7734        cx: &mut Context<Self>,
 7735    ) {
 7736        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7737            let project_path = buffer.read(cx).project_path(cx)?;
 7738            let project = self.project.as_ref()?.read(cx);
 7739            let entry = project.entry_for_path(&project_path, cx)?;
 7740            let parent = match &entry.canonical_path {
 7741                Some(canonical_path) => canonical_path.to_path_buf(),
 7742                None => project.absolute_path(&project_path, cx)?,
 7743            }
 7744            .parent()?
 7745            .to_path_buf();
 7746            Some(parent)
 7747        }) {
 7748            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7749        }
 7750    }
 7751
 7752    pub fn prepare_restore_change(
 7753        &self,
 7754        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7755        hunk: &MultiBufferDiffHunk,
 7756        cx: &mut App,
 7757    ) -> Option<()> {
 7758        let buffer = self.buffer.read(cx);
 7759        let diff = buffer.diff_for(hunk.buffer_id)?;
 7760        let buffer = buffer.buffer(hunk.buffer_id)?;
 7761        let buffer = buffer.read(cx);
 7762        let original_text = diff
 7763            .read(cx)
 7764            .base_text()
 7765            .as_ref()?
 7766            .as_rope()
 7767            .slice(hunk.diff_base_byte_range.clone());
 7768        let buffer_snapshot = buffer.snapshot();
 7769        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7770        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7771            probe
 7772                .0
 7773                .start
 7774                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7775                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7776        }) {
 7777            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7778            Some(())
 7779        } else {
 7780            None
 7781        }
 7782    }
 7783
 7784    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7785        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7786    }
 7787
 7788    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7789        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7790    }
 7791
 7792    fn manipulate_lines<Fn>(
 7793        &mut self,
 7794        window: &mut Window,
 7795        cx: &mut Context<Self>,
 7796        mut callback: Fn,
 7797    ) where
 7798        Fn: FnMut(&mut Vec<&str>),
 7799    {
 7800        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7801        let buffer = self.buffer.read(cx).snapshot(cx);
 7802
 7803        let mut edits = Vec::new();
 7804
 7805        let selections = self.selections.all::<Point>(cx);
 7806        let mut selections = selections.iter().peekable();
 7807        let mut contiguous_row_selections = Vec::new();
 7808        let mut new_selections = Vec::new();
 7809        let mut added_lines = 0;
 7810        let mut removed_lines = 0;
 7811
 7812        while let Some(selection) = selections.next() {
 7813            let (start_row, end_row) = consume_contiguous_rows(
 7814                &mut contiguous_row_selections,
 7815                selection,
 7816                &display_map,
 7817                &mut selections,
 7818            );
 7819
 7820            let start_point = Point::new(start_row.0, 0);
 7821            let end_point = Point::new(
 7822                end_row.previous_row().0,
 7823                buffer.line_len(end_row.previous_row()),
 7824            );
 7825            let text = buffer
 7826                .text_for_range(start_point..end_point)
 7827                .collect::<String>();
 7828
 7829            let mut lines = text.split('\n').collect_vec();
 7830
 7831            let lines_before = lines.len();
 7832            callback(&mut lines);
 7833            let lines_after = lines.len();
 7834
 7835            edits.push((start_point..end_point, lines.join("\n")));
 7836
 7837            // Selections must change based on added and removed line count
 7838            let start_row =
 7839                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7840            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7841            new_selections.push(Selection {
 7842                id: selection.id,
 7843                start: start_row,
 7844                end: end_row,
 7845                goal: SelectionGoal::None,
 7846                reversed: selection.reversed,
 7847            });
 7848
 7849            if lines_after > lines_before {
 7850                added_lines += lines_after - lines_before;
 7851            } else if lines_before > lines_after {
 7852                removed_lines += lines_before - lines_after;
 7853            }
 7854        }
 7855
 7856        self.transact(window, cx, |this, window, cx| {
 7857            let buffer = this.buffer.update(cx, |buffer, cx| {
 7858                buffer.edit(edits, None, cx);
 7859                buffer.snapshot(cx)
 7860            });
 7861
 7862            // Recalculate offsets on newly edited buffer
 7863            let new_selections = new_selections
 7864                .iter()
 7865                .map(|s| {
 7866                    let start_point = Point::new(s.start.0, 0);
 7867                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7868                    Selection {
 7869                        id: s.id,
 7870                        start: buffer.point_to_offset(start_point),
 7871                        end: buffer.point_to_offset(end_point),
 7872                        goal: s.goal,
 7873                        reversed: s.reversed,
 7874                    }
 7875                })
 7876                .collect();
 7877
 7878            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7879                s.select(new_selections);
 7880            });
 7881
 7882            this.request_autoscroll(Autoscroll::fit(), cx);
 7883        });
 7884    }
 7885
 7886    pub fn convert_to_upper_case(
 7887        &mut self,
 7888        _: &ConvertToUpperCase,
 7889        window: &mut Window,
 7890        cx: &mut Context<Self>,
 7891    ) {
 7892        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7893    }
 7894
 7895    pub fn convert_to_lower_case(
 7896        &mut self,
 7897        _: &ConvertToLowerCase,
 7898        window: &mut Window,
 7899        cx: &mut Context<Self>,
 7900    ) {
 7901        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7902    }
 7903
 7904    pub fn convert_to_title_case(
 7905        &mut self,
 7906        _: &ConvertToTitleCase,
 7907        window: &mut Window,
 7908        cx: &mut Context<Self>,
 7909    ) {
 7910        self.manipulate_text(window, cx, |text| {
 7911            text.split('\n')
 7912                .map(|line| line.to_case(Case::Title))
 7913                .join("\n")
 7914        })
 7915    }
 7916
 7917    pub fn convert_to_snake_case(
 7918        &mut self,
 7919        _: &ConvertToSnakeCase,
 7920        window: &mut Window,
 7921        cx: &mut Context<Self>,
 7922    ) {
 7923        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7924    }
 7925
 7926    pub fn convert_to_kebab_case(
 7927        &mut self,
 7928        _: &ConvertToKebabCase,
 7929        window: &mut Window,
 7930        cx: &mut Context<Self>,
 7931    ) {
 7932        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7933    }
 7934
 7935    pub fn convert_to_upper_camel_case(
 7936        &mut self,
 7937        _: &ConvertToUpperCamelCase,
 7938        window: &mut Window,
 7939        cx: &mut Context<Self>,
 7940    ) {
 7941        self.manipulate_text(window, cx, |text| {
 7942            text.split('\n')
 7943                .map(|line| line.to_case(Case::UpperCamel))
 7944                .join("\n")
 7945        })
 7946    }
 7947
 7948    pub fn convert_to_lower_camel_case(
 7949        &mut self,
 7950        _: &ConvertToLowerCamelCase,
 7951        window: &mut Window,
 7952        cx: &mut Context<Self>,
 7953    ) {
 7954        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7955    }
 7956
 7957    pub fn convert_to_opposite_case(
 7958        &mut self,
 7959        _: &ConvertToOppositeCase,
 7960        window: &mut Window,
 7961        cx: &mut Context<Self>,
 7962    ) {
 7963        self.manipulate_text(window, cx, |text| {
 7964            text.chars()
 7965                .fold(String::with_capacity(text.len()), |mut t, c| {
 7966                    if c.is_uppercase() {
 7967                        t.extend(c.to_lowercase());
 7968                    } else {
 7969                        t.extend(c.to_uppercase());
 7970                    }
 7971                    t
 7972                })
 7973        })
 7974    }
 7975
 7976    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7977    where
 7978        Fn: FnMut(&str) -> String,
 7979    {
 7980        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7981        let buffer = self.buffer.read(cx).snapshot(cx);
 7982
 7983        let mut new_selections = Vec::new();
 7984        let mut edits = Vec::new();
 7985        let mut selection_adjustment = 0i32;
 7986
 7987        for selection in self.selections.all::<usize>(cx) {
 7988            let selection_is_empty = selection.is_empty();
 7989
 7990            let (start, end) = if selection_is_empty {
 7991                let word_range = movement::surrounding_word(
 7992                    &display_map,
 7993                    selection.start.to_display_point(&display_map),
 7994                );
 7995                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7996                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7997                (start, end)
 7998            } else {
 7999                (selection.start, selection.end)
 8000            };
 8001
 8002            let text = buffer.text_for_range(start..end).collect::<String>();
 8003            let old_length = text.len() as i32;
 8004            let text = callback(&text);
 8005
 8006            new_selections.push(Selection {
 8007                start: (start as i32 - selection_adjustment) as usize,
 8008                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8009                goal: SelectionGoal::None,
 8010                ..selection
 8011            });
 8012
 8013            selection_adjustment += old_length - text.len() as i32;
 8014
 8015            edits.push((start..end, text));
 8016        }
 8017
 8018        self.transact(window, cx, |this, window, cx| {
 8019            this.buffer.update(cx, |buffer, cx| {
 8020                buffer.edit(edits, None, cx);
 8021            });
 8022
 8023            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8024                s.select(new_selections);
 8025            });
 8026
 8027            this.request_autoscroll(Autoscroll::fit(), cx);
 8028        });
 8029    }
 8030
 8031    pub fn duplicate(
 8032        &mut self,
 8033        upwards: bool,
 8034        whole_lines: bool,
 8035        window: &mut Window,
 8036        cx: &mut Context<Self>,
 8037    ) {
 8038        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8039        let buffer = &display_map.buffer_snapshot;
 8040        let selections = self.selections.all::<Point>(cx);
 8041
 8042        let mut edits = Vec::new();
 8043        let mut selections_iter = selections.iter().peekable();
 8044        while let Some(selection) = selections_iter.next() {
 8045            let mut rows = selection.spanned_rows(false, &display_map);
 8046            // duplicate line-wise
 8047            if whole_lines || selection.start == selection.end {
 8048                // Avoid duplicating the same lines twice.
 8049                while let Some(next_selection) = selections_iter.peek() {
 8050                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8051                    if next_rows.start < rows.end {
 8052                        rows.end = next_rows.end;
 8053                        selections_iter.next().unwrap();
 8054                    } else {
 8055                        break;
 8056                    }
 8057                }
 8058
 8059                // Copy the text from the selected row region and splice it either at the start
 8060                // or end of the region.
 8061                let start = Point::new(rows.start.0, 0);
 8062                let end = Point::new(
 8063                    rows.end.previous_row().0,
 8064                    buffer.line_len(rows.end.previous_row()),
 8065                );
 8066                let text = buffer
 8067                    .text_for_range(start..end)
 8068                    .chain(Some("\n"))
 8069                    .collect::<String>();
 8070                let insert_location = if upwards {
 8071                    Point::new(rows.end.0, 0)
 8072                } else {
 8073                    start
 8074                };
 8075                edits.push((insert_location..insert_location, text));
 8076            } else {
 8077                // duplicate character-wise
 8078                let start = selection.start;
 8079                let end = selection.end;
 8080                let text = buffer.text_for_range(start..end).collect::<String>();
 8081                edits.push((selection.end..selection.end, text));
 8082            }
 8083        }
 8084
 8085        self.transact(window, cx, |this, _, cx| {
 8086            this.buffer.update(cx, |buffer, cx| {
 8087                buffer.edit(edits, None, cx);
 8088            });
 8089
 8090            this.request_autoscroll(Autoscroll::fit(), cx);
 8091        });
 8092    }
 8093
 8094    pub fn duplicate_line_up(
 8095        &mut self,
 8096        _: &DuplicateLineUp,
 8097        window: &mut Window,
 8098        cx: &mut Context<Self>,
 8099    ) {
 8100        self.duplicate(true, true, window, cx);
 8101    }
 8102
 8103    pub fn duplicate_line_down(
 8104        &mut self,
 8105        _: &DuplicateLineDown,
 8106        window: &mut Window,
 8107        cx: &mut Context<Self>,
 8108    ) {
 8109        self.duplicate(false, true, window, cx);
 8110    }
 8111
 8112    pub fn duplicate_selection(
 8113        &mut self,
 8114        _: &DuplicateSelection,
 8115        window: &mut Window,
 8116        cx: &mut Context<Self>,
 8117    ) {
 8118        self.duplicate(false, false, window, cx);
 8119    }
 8120
 8121    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8122        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8123        let buffer = self.buffer.read(cx).snapshot(cx);
 8124
 8125        let mut edits = Vec::new();
 8126        let mut unfold_ranges = Vec::new();
 8127        let mut refold_creases = Vec::new();
 8128
 8129        let selections = self.selections.all::<Point>(cx);
 8130        let mut selections = selections.iter().peekable();
 8131        let mut contiguous_row_selections = Vec::new();
 8132        let mut new_selections = Vec::new();
 8133
 8134        while let Some(selection) = selections.next() {
 8135            // Find all the selections that span a contiguous row range
 8136            let (start_row, end_row) = consume_contiguous_rows(
 8137                &mut contiguous_row_selections,
 8138                selection,
 8139                &display_map,
 8140                &mut selections,
 8141            );
 8142
 8143            // Move the text spanned by the row range to be before the line preceding the row range
 8144            if start_row.0 > 0 {
 8145                let range_to_move = Point::new(
 8146                    start_row.previous_row().0,
 8147                    buffer.line_len(start_row.previous_row()),
 8148                )
 8149                    ..Point::new(
 8150                        end_row.previous_row().0,
 8151                        buffer.line_len(end_row.previous_row()),
 8152                    );
 8153                let insertion_point = display_map
 8154                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8155                    .0;
 8156
 8157                // Don't move lines across excerpts
 8158                if buffer
 8159                    .excerpt_containing(insertion_point..range_to_move.end)
 8160                    .is_some()
 8161                {
 8162                    let text = buffer
 8163                        .text_for_range(range_to_move.clone())
 8164                        .flat_map(|s| s.chars())
 8165                        .skip(1)
 8166                        .chain(['\n'])
 8167                        .collect::<String>();
 8168
 8169                    edits.push((
 8170                        buffer.anchor_after(range_to_move.start)
 8171                            ..buffer.anchor_before(range_to_move.end),
 8172                        String::new(),
 8173                    ));
 8174                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8175                    edits.push((insertion_anchor..insertion_anchor, text));
 8176
 8177                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8178
 8179                    // Move selections up
 8180                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8181                        |mut selection| {
 8182                            selection.start.row -= row_delta;
 8183                            selection.end.row -= row_delta;
 8184                            selection
 8185                        },
 8186                    ));
 8187
 8188                    // Move folds up
 8189                    unfold_ranges.push(range_to_move.clone());
 8190                    for fold in display_map.folds_in_range(
 8191                        buffer.anchor_before(range_to_move.start)
 8192                            ..buffer.anchor_after(range_to_move.end),
 8193                    ) {
 8194                        let mut start = fold.range.start.to_point(&buffer);
 8195                        let mut end = fold.range.end.to_point(&buffer);
 8196                        start.row -= row_delta;
 8197                        end.row -= row_delta;
 8198                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8199                    }
 8200                }
 8201            }
 8202
 8203            // If we didn't move line(s), preserve the existing selections
 8204            new_selections.append(&mut contiguous_row_selections);
 8205        }
 8206
 8207        self.transact(window, cx, |this, window, cx| {
 8208            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8209            this.buffer.update(cx, |buffer, cx| {
 8210                for (range, text) in edits {
 8211                    buffer.edit([(range, text)], None, cx);
 8212                }
 8213            });
 8214            this.fold_creases(refold_creases, true, window, cx);
 8215            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8216                s.select(new_selections);
 8217            })
 8218        });
 8219    }
 8220
 8221    pub fn move_line_down(
 8222        &mut self,
 8223        _: &MoveLineDown,
 8224        window: &mut Window,
 8225        cx: &mut Context<Self>,
 8226    ) {
 8227        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8228        let buffer = self.buffer.read(cx).snapshot(cx);
 8229
 8230        let mut edits = Vec::new();
 8231        let mut unfold_ranges = Vec::new();
 8232        let mut refold_creases = Vec::new();
 8233
 8234        let selections = self.selections.all::<Point>(cx);
 8235        let mut selections = selections.iter().peekable();
 8236        let mut contiguous_row_selections = Vec::new();
 8237        let mut new_selections = Vec::new();
 8238
 8239        while let Some(selection) = selections.next() {
 8240            // Find all the selections that span a contiguous row range
 8241            let (start_row, end_row) = consume_contiguous_rows(
 8242                &mut contiguous_row_selections,
 8243                selection,
 8244                &display_map,
 8245                &mut selections,
 8246            );
 8247
 8248            // Move the text spanned by the row range to be after the last line of the row range
 8249            if end_row.0 <= buffer.max_point().row {
 8250                let range_to_move =
 8251                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8252                let insertion_point = display_map
 8253                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8254                    .0;
 8255
 8256                // Don't move lines across excerpt boundaries
 8257                if buffer
 8258                    .excerpt_containing(range_to_move.start..insertion_point)
 8259                    .is_some()
 8260                {
 8261                    let mut text = String::from("\n");
 8262                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8263                    text.pop(); // Drop trailing newline
 8264                    edits.push((
 8265                        buffer.anchor_after(range_to_move.start)
 8266                            ..buffer.anchor_before(range_to_move.end),
 8267                        String::new(),
 8268                    ));
 8269                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8270                    edits.push((insertion_anchor..insertion_anchor, text));
 8271
 8272                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8273
 8274                    // Move selections down
 8275                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8276                        |mut selection| {
 8277                            selection.start.row += row_delta;
 8278                            selection.end.row += row_delta;
 8279                            selection
 8280                        },
 8281                    ));
 8282
 8283                    // Move folds down
 8284                    unfold_ranges.push(range_to_move.clone());
 8285                    for fold in display_map.folds_in_range(
 8286                        buffer.anchor_before(range_to_move.start)
 8287                            ..buffer.anchor_after(range_to_move.end),
 8288                    ) {
 8289                        let mut start = fold.range.start.to_point(&buffer);
 8290                        let mut end = fold.range.end.to_point(&buffer);
 8291                        start.row += row_delta;
 8292                        end.row += row_delta;
 8293                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8294                    }
 8295                }
 8296            }
 8297
 8298            // If we didn't move line(s), preserve the existing selections
 8299            new_selections.append(&mut contiguous_row_selections);
 8300        }
 8301
 8302        self.transact(window, cx, |this, window, cx| {
 8303            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8304            this.buffer.update(cx, |buffer, cx| {
 8305                for (range, text) in edits {
 8306                    buffer.edit([(range, text)], None, cx);
 8307                }
 8308            });
 8309            this.fold_creases(refold_creases, true, window, cx);
 8310            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8311                s.select(new_selections)
 8312            });
 8313        });
 8314    }
 8315
 8316    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8317        let text_layout_details = &self.text_layout_details(window);
 8318        self.transact(window, cx, |this, window, cx| {
 8319            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8320                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8321                let line_mode = s.line_mode;
 8322                s.move_with(|display_map, selection| {
 8323                    if !selection.is_empty() || line_mode {
 8324                        return;
 8325                    }
 8326
 8327                    let mut head = selection.head();
 8328                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8329                    if head.column() == display_map.line_len(head.row()) {
 8330                        transpose_offset = display_map
 8331                            .buffer_snapshot
 8332                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8333                    }
 8334
 8335                    if transpose_offset == 0 {
 8336                        return;
 8337                    }
 8338
 8339                    *head.column_mut() += 1;
 8340                    head = display_map.clip_point(head, Bias::Right);
 8341                    let goal = SelectionGoal::HorizontalPosition(
 8342                        display_map
 8343                            .x_for_display_point(head, text_layout_details)
 8344                            .into(),
 8345                    );
 8346                    selection.collapse_to(head, goal);
 8347
 8348                    let transpose_start = display_map
 8349                        .buffer_snapshot
 8350                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8351                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8352                        let transpose_end = display_map
 8353                            .buffer_snapshot
 8354                            .clip_offset(transpose_offset + 1, Bias::Right);
 8355                        if let Some(ch) =
 8356                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8357                        {
 8358                            edits.push((transpose_start..transpose_offset, String::new()));
 8359                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8360                        }
 8361                    }
 8362                });
 8363                edits
 8364            });
 8365            this.buffer
 8366                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8367            let selections = this.selections.all::<usize>(cx);
 8368            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8369                s.select(selections);
 8370            });
 8371        });
 8372    }
 8373
 8374    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8375        self.rewrap_impl(IsVimMode::No, cx)
 8376    }
 8377
 8378    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8379        let buffer = self.buffer.read(cx).snapshot(cx);
 8380        let selections = self.selections.all::<Point>(cx);
 8381        let mut selections = selections.iter().peekable();
 8382
 8383        let mut edits = Vec::new();
 8384        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8385
 8386        while let Some(selection) = selections.next() {
 8387            let mut start_row = selection.start.row;
 8388            let mut end_row = selection.end.row;
 8389
 8390            // Skip selections that overlap with a range that has already been rewrapped.
 8391            let selection_range = start_row..end_row;
 8392            if rewrapped_row_ranges
 8393                .iter()
 8394                .any(|range| range.overlaps(&selection_range))
 8395            {
 8396                continue;
 8397            }
 8398
 8399            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8400
 8401            // Since not all lines in the selection may be at the same indent
 8402            // level, choose the indent size that is the most common between all
 8403            // of the lines.
 8404            //
 8405            // If there is a tie, we use the deepest indent.
 8406            let (indent_size, indent_end) = {
 8407                let mut indent_size_occurrences = HashMap::default();
 8408                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8409
 8410                for row in start_row..=end_row {
 8411                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8412                    rows_by_indent_size.entry(indent).or_default().push(row);
 8413                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8414                }
 8415
 8416                let indent_size = indent_size_occurrences
 8417                    .into_iter()
 8418                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8419                    .map(|(indent, _)| indent)
 8420                    .unwrap_or_default();
 8421                let row = rows_by_indent_size[&indent_size][0];
 8422                let indent_end = Point::new(row, indent_size.len);
 8423
 8424                (indent_size, indent_end)
 8425            };
 8426
 8427            let mut line_prefix = indent_size.chars().collect::<String>();
 8428
 8429            let mut inside_comment = false;
 8430            if let Some(comment_prefix) =
 8431                buffer
 8432                    .language_scope_at(selection.head())
 8433                    .and_then(|language| {
 8434                        language
 8435                            .line_comment_prefixes()
 8436                            .iter()
 8437                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8438                            .cloned()
 8439                    })
 8440            {
 8441                line_prefix.push_str(&comment_prefix);
 8442                inside_comment = true;
 8443            }
 8444
 8445            let language_settings = buffer.settings_at(selection.head(), cx);
 8446            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8447                RewrapBehavior::InComments => inside_comment,
 8448                RewrapBehavior::InSelections => !selection.is_empty(),
 8449                RewrapBehavior::Anywhere => true,
 8450            };
 8451
 8452            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8453            if !should_rewrap {
 8454                continue;
 8455            }
 8456
 8457            if selection.is_empty() {
 8458                'expand_upwards: while start_row > 0 {
 8459                    let prev_row = start_row - 1;
 8460                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8461                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8462                    {
 8463                        start_row = prev_row;
 8464                    } else {
 8465                        break 'expand_upwards;
 8466                    }
 8467                }
 8468
 8469                'expand_downwards: while end_row < buffer.max_point().row {
 8470                    let next_row = end_row + 1;
 8471                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8472                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8473                    {
 8474                        end_row = next_row;
 8475                    } else {
 8476                        break 'expand_downwards;
 8477                    }
 8478                }
 8479            }
 8480
 8481            let start = Point::new(start_row, 0);
 8482            let start_offset = start.to_offset(&buffer);
 8483            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8484            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8485            let Some(lines_without_prefixes) = selection_text
 8486                .lines()
 8487                .map(|line| {
 8488                    line.strip_prefix(&line_prefix)
 8489                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8490                        .ok_or_else(|| {
 8491                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8492                        })
 8493                })
 8494                .collect::<Result<Vec<_>, _>>()
 8495                .log_err()
 8496            else {
 8497                continue;
 8498            };
 8499
 8500            let wrap_column = buffer
 8501                .settings_at(Point::new(start_row, 0), cx)
 8502                .preferred_line_length as usize;
 8503            let wrapped_text = wrap_with_prefix(
 8504                line_prefix,
 8505                lines_without_prefixes.join(" "),
 8506                wrap_column,
 8507                tab_size,
 8508            );
 8509
 8510            // TODO: should always use char-based diff while still supporting cursor behavior that
 8511            // matches vim.
 8512            let mut diff_options = DiffOptions::default();
 8513            if is_vim_mode == IsVimMode::Yes {
 8514                diff_options.max_word_diff_len = 0;
 8515                diff_options.max_word_diff_line_count = 0;
 8516            } else {
 8517                diff_options.max_word_diff_len = usize::MAX;
 8518                diff_options.max_word_diff_line_count = usize::MAX;
 8519            }
 8520
 8521            for (old_range, new_text) in
 8522                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8523            {
 8524                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8525                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8526                edits.push((edit_start..edit_end, new_text));
 8527            }
 8528
 8529            rewrapped_row_ranges.push(start_row..=end_row);
 8530        }
 8531
 8532        self.buffer
 8533            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8534    }
 8535
 8536    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8537        let mut text = String::new();
 8538        let buffer = self.buffer.read(cx).snapshot(cx);
 8539        let mut selections = self.selections.all::<Point>(cx);
 8540        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8541        {
 8542            let max_point = buffer.max_point();
 8543            let mut is_first = true;
 8544            for selection in &mut selections {
 8545                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8546                if is_entire_line {
 8547                    selection.start = Point::new(selection.start.row, 0);
 8548                    if !selection.is_empty() && selection.end.column == 0 {
 8549                        selection.end = cmp::min(max_point, selection.end);
 8550                    } else {
 8551                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8552                    }
 8553                    selection.goal = SelectionGoal::None;
 8554                }
 8555                if is_first {
 8556                    is_first = false;
 8557                } else {
 8558                    text += "\n";
 8559                }
 8560                let mut len = 0;
 8561                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8562                    text.push_str(chunk);
 8563                    len += chunk.len();
 8564                }
 8565                clipboard_selections.push(ClipboardSelection {
 8566                    len,
 8567                    is_entire_line,
 8568                    start_column: selection.start.column,
 8569                });
 8570            }
 8571        }
 8572
 8573        self.transact(window, cx, |this, window, cx| {
 8574            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8575                s.select(selections);
 8576            });
 8577            this.insert("", window, cx);
 8578        });
 8579        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8580    }
 8581
 8582    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8583        let item = self.cut_common(window, cx);
 8584        cx.write_to_clipboard(item);
 8585    }
 8586
 8587    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8588        self.change_selections(None, window, cx, |s| {
 8589            s.move_with(|snapshot, sel| {
 8590                if sel.is_empty() {
 8591                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8592                }
 8593            });
 8594        });
 8595        let item = self.cut_common(window, cx);
 8596        cx.set_global(KillRing(item))
 8597    }
 8598
 8599    pub fn kill_ring_yank(
 8600        &mut self,
 8601        _: &KillRingYank,
 8602        window: &mut Window,
 8603        cx: &mut Context<Self>,
 8604    ) {
 8605        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8606            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8607                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8608            } else {
 8609                return;
 8610            }
 8611        } else {
 8612            return;
 8613        };
 8614        self.do_paste(&text, metadata, false, window, cx);
 8615    }
 8616
 8617    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8618        let selections = self.selections.all::<Point>(cx);
 8619        let buffer = self.buffer.read(cx).read(cx);
 8620        let mut text = String::new();
 8621
 8622        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8623        {
 8624            let max_point = buffer.max_point();
 8625            let mut is_first = true;
 8626            for selection in selections.iter() {
 8627                let mut start = selection.start;
 8628                let mut end = selection.end;
 8629                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8630                if is_entire_line {
 8631                    start = Point::new(start.row, 0);
 8632                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8633                }
 8634                if is_first {
 8635                    is_first = false;
 8636                } else {
 8637                    text += "\n";
 8638                }
 8639                let mut len = 0;
 8640                for chunk in buffer.text_for_range(start..end) {
 8641                    text.push_str(chunk);
 8642                    len += chunk.len();
 8643                }
 8644                clipboard_selections.push(ClipboardSelection {
 8645                    len,
 8646                    is_entire_line,
 8647                    start_column: start.column,
 8648                });
 8649            }
 8650        }
 8651
 8652        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8653            text,
 8654            clipboard_selections,
 8655        ));
 8656    }
 8657
 8658    pub fn do_paste(
 8659        &mut self,
 8660        text: &String,
 8661        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8662        handle_entire_lines: bool,
 8663        window: &mut Window,
 8664        cx: &mut Context<Self>,
 8665    ) {
 8666        if self.read_only(cx) {
 8667            return;
 8668        }
 8669
 8670        let clipboard_text = Cow::Borrowed(text);
 8671
 8672        self.transact(window, cx, |this, window, cx| {
 8673            if let Some(mut clipboard_selections) = clipboard_selections {
 8674                let old_selections = this.selections.all::<usize>(cx);
 8675                let all_selections_were_entire_line =
 8676                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8677                let first_selection_start_column =
 8678                    clipboard_selections.first().map(|s| s.start_column);
 8679                if clipboard_selections.len() != old_selections.len() {
 8680                    clipboard_selections.drain(..);
 8681                }
 8682                let cursor_offset = this.selections.last::<usize>(cx).head();
 8683                let mut auto_indent_on_paste = true;
 8684
 8685                this.buffer.update(cx, |buffer, cx| {
 8686                    let snapshot = buffer.read(cx);
 8687                    auto_indent_on_paste =
 8688                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8689
 8690                    let mut start_offset = 0;
 8691                    let mut edits = Vec::new();
 8692                    let mut original_start_columns = Vec::new();
 8693                    for (ix, selection) in old_selections.iter().enumerate() {
 8694                        let to_insert;
 8695                        let entire_line;
 8696                        let original_start_column;
 8697                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8698                            let end_offset = start_offset + clipboard_selection.len;
 8699                            to_insert = &clipboard_text[start_offset..end_offset];
 8700                            entire_line = clipboard_selection.is_entire_line;
 8701                            start_offset = end_offset + 1;
 8702                            original_start_column = Some(clipboard_selection.start_column);
 8703                        } else {
 8704                            to_insert = clipboard_text.as_str();
 8705                            entire_line = all_selections_were_entire_line;
 8706                            original_start_column = first_selection_start_column
 8707                        }
 8708
 8709                        // If the corresponding selection was empty when this slice of the
 8710                        // clipboard text was written, then the entire line containing the
 8711                        // selection was copied. If this selection is also currently empty,
 8712                        // then paste the line before the current line of the buffer.
 8713                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8714                            let column = selection.start.to_point(&snapshot).column as usize;
 8715                            let line_start = selection.start - column;
 8716                            line_start..line_start
 8717                        } else {
 8718                            selection.range()
 8719                        };
 8720
 8721                        edits.push((range, to_insert));
 8722                        original_start_columns.extend(original_start_column);
 8723                    }
 8724                    drop(snapshot);
 8725
 8726                    buffer.edit(
 8727                        edits,
 8728                        if auto_indent_on_paste {
 8729                            Some(AutoindentMode::Block {
 8730                                original_start_columns,
 8731                            })
 8732                        } else {
 8733                            None
 8734                        },
 8735                        cx,
 8736                    );
 8737                });
 8738
 8739                let selections = this.selections.all::<usize>(cx);
 8740                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8741                    s.select(selections)
 8742                });
 8743            } else {
 8744                this.insert(&clipboard_text, window, cx);
 8745            }
 8746        });
 8747    }
 8748
 8749    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8750        if let Some(item) = cx.read_from_clipboard() {
 8751            let entries = item.entries();
 8752
 8753            match entries.first() {
 8754                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8755                // of all the pasted entries.
 8756                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8757                    .do_paste(
 8758                        clipboard_string.text(),
 8759                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8760                        true,
 8761                        window,
 8762                        cx,
 8763                    ),
 8764                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8765            }
 8766        }
 8767    }
 8768
 8769    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8770        if self.read_only(cx) {
 8771            return;
 8772        }
 8773
 8774        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8775            if let Some((selections, _)) =
 8776                self.selection_history.transaction(transaction_id).cloned()
 8777            {
 8778                self.change_selections(None, window, cx, |s| {
 8779                    s.select_anchors(selections.to_vec());
 8780                });
 8781            }
 8782            self.request_autoscroll(Autoscroll::fit(), cx);
 8783            self.unmark_text(window, cx);
 8784            self.refresh_inline_completion(true, false, window, cx);
 8785            cx.emit(EditorEvent::Edited { transaction_id });
 8786            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8787        }
 8788    }
 8789
 8790    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8791        if self.read_only(cx) {
 8792            return;
 8793        }
 8794
 8795        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8796            if let Some((_, Some(selections))) =
 8797                self.selection_history.transaction(transaction_id).cloned()
 8798            {
 8799                self.change_selections(None, window, cx, |s| {
 8800                    s.select_anchors(selections.to_vec());
 8801                });
 8802            }
 8803            self.request_autoscroll(Autoscroll::fit(), cx);
 8804            self.unmark_text(window, cx);
 8805            self.refresh_inline_completion(true, false, window, cx);
 8806            cx.emit(EditorEvent::Edited { transaction_id });
 8807        }
 8808    }
 8809
 8810    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8811        self.buffer
 8812            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8813    }
 8814
 8815    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8816        self.buffer
 8817            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8818    }
 8819
 8820    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8822            let line_mode = s.line_mode;
 8823            s.move_with(|map, selection| {
 8824                let cursor = if selection.is_empty() && !line_mode {
 8825                    movement::left(map, selection.start)
 8826                } else {
 8827                    selection.start
 8828                };
 8829                selection.collapse_to(cursor, SelectionGoal::None);
 8830            });
 8831        })
 8832    }
 8833
 8834    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8835        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8836            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8837        })
 8838    }
 8839
 8840    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8841        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8842            let line_mode = s.line_mode;
 8843            s.move_with(|map, selection| {
 8844                let cursor = if selection.is_empty() && !line_mode {
 8845                    movement::right(map, selection.end)
 8846                } else {
 8847                    selection.end
 8848                };
 8849                selection.collapse_to(cursor, SelectionGoal::None)
 8850            });
 8851        })
 8852    }
 8853
 8854    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8856            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8857        })
 8858    }
 8859
 8860    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8861        if self.take_rename(true, window, cx).is_some() {
 8862            return;
 8863        }
 8864
 8865        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8866            cx.propagate();
 8867            return;
 8868        }
 8869
 8870        let text_layout_details = &self.text_layout_details(window);
 8871        let selection_count = self.selections.count();
 8872        let first_selection = self.selections.first_anchor();
 8873
 8874        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8875            let line_mode = s.line_mode;
 8876            s.move_with(|map, selection| {
 8877                if !selection.is_empty() && !line_mode {
 8878                    selection.goal = SelectionGoal::None;
 8879                }
 8880                let (cursor, goal) = movement::up(
 8881                    map,
 8882                    selection.start,
 8883                    selection.goal,
 8884                    false,
 8885                    text_layout_details,
 8886                );
 8887                selection.collapse_to(cursor, goal);
 8888            });
 8889        });
 8890
 8891        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8892        {
 8893            cx.propagate();
 8894        }
 8895    }
 8896
 8897    pub fn move_up_by_lines(
 8898        &mut self,
 8899        action: &MoveUpByLines,
 8900        window: &mut Window,
 8901        cx: &mut Context<Self>,
 8902    ) {
 8903        if self.take_rename(true, window, cx).is_some() {
 8904            return;
 8905        }
 8906
 8907        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8908            cx.propagate();
 8909            return;
 8910        }
 8911
 8912        let text_layout_details = &self.text_layout_details(window);
 8913
 8914        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8915            let line_mode = s.line_mode;
 8916            s.move_with(|map, selection| {
 8917                if !selection.is_empty() && !line_mode {
 8918                    selection.goal = SelectionGoal::None;
 8919                }
 8920                let (cursor, goal) = movement::up_by_rows(
 8921                    map,
 8922                    selection.start,
 8923                    action.lines,
 8924                    selection.goal,
 8925                    false,
 8926                    text_layout_details,
 8927                );
 8928                selection.collapse_to(cursor, goal);
 8929            });
 8930        })
 8931    }
 8932
 8933    pub fn move_down_by_lines(
 8934        &mut self,
 8935        action: &MoveDownByLines,
 8936        window: &mut Window,
 8937        cx: &mut Context<Self>,
 8938    ) {
 8939        if self.take_rename(true, window, cx).is_some() {
 8940            return;
 8941        }
 8942
 8943        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8944            cx.propagate();
 8945            return;
 8946        }
 8947
 8948        let text_layout_details = &self.text_layout_details(window);
 8949
 8950        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8951            let line_mode = s.line_mode;
 8952            s.move_with(|map, selection| {
 8953                if !selection.is_empty() && !line_mode {
 8954                    selection.goal = SelectionGoal::None;
 8955                }
 8956                let (cursor, goal) = movement::down_by_rows(
 8957                    map,
 8958                    selection.start,
 8959                    action.lines,
 8960                    selection.goal,
 8961                    false,
 8962                    text_layout_details,
 8963                );
 8964                selection.collapse_to(cursor, goal);
 8965            });
 8966        })
 8967    }
 8968
 8969    pub fn select_down_by_lines(
 8970        &mut self,
 8971        action: &SelectDownByLines,
 8972        window: &mut Window,
 8973        cx: &mut Context<Self>,
 8974    ) {
 8975        let text_layout_details = &self.text_layout_details(window);
 8976        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8977            s.move_heads_with(|map, head, goal| {
 8978                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8979            })
 8980        })
 8981    }
 8982
 8983    pub fn select_up_by_lines(
 8984        &mut self,
 8985        action: &SelectUpByLines,
 8986        window: &mut Window,
 8987        cx: &mut Context<Self>,
 8988    ) {
 8989        let text_layout_details = &self.text_layout_details(window);
 8990        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8991            s.move_heads_with(|map, head, goal| {
 8992                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8993            })
 8994        })
 8995    }
 8996
 8997    pub fn select_page_up(
 8998        &mut self,
 8999        _: &SelectPageUp,
 9000        window: &mut Window,
 9001        cx: &mut Context<Self>,
 9002    ) {
 9003        let Some(row_count) = self.visible_row_count() else {
 9004            return;
 9005        };
 9006
 9007        let text_layout_details = &self.text_layout_details(window);
 9008
 9009        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9010            s.move_heads_with(|map, head, goal| {
 9011                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9012            })
 9013        })
 9014    }
 9015
 9016    pub fn move_page_up(
 9017        &mut self,
 9018        action: &MovePageUp,
 9019        window: &mut Window,
 9020        cx: &mut Context<Self>,
 9021    ) {
 9022        if self.take_rename(true, window, cx).is_some() {
 9023            return;
 9024        }
 9025
 9026        if self
 9027            .context_menu
 9028            .borrow_mut()
 9029            .as_mut()
 9030            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9031            .unwrap_or(false)
 9032        {
 9033            return;
 9034        }
 9035
 9036        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9037            cx.propagate();
 9038            return;
 9039        }
 9040
 9041        let Some(row_count) = self.visible_row_count() else {
 9042            return;
 9043        };
 9044
 9045        let autoscroll = if action.center_cursor {
 9046            Autoscroll::center()
 9047        } else {
 9048            Autoscroll::fit()
 9049        };
 9050
 9051        let text_layout_details = &self.text_layout_details(window);
 9052
 9053        self.change_selections(Some(autoscroll), window, cx, |s| {
 9054            let line_mode = s.line_mode;
 9055            s.move_with(|map, selection| {
 9056                if !selection.is_empty() && !line_mode {
 9057                    selection.goal = SelectionGoal::None;
 9058                }
 9059                let (cursor, goal) = movement::up_by_rows(
 9060                    map,
 9061                    selection.end,
 9062                    row_count,
 9063                    selection.goal,
 9064                    false,
 9065                    text_layout_details,
 9066                );
 9067                selection.collapse_to(cursor, goal);
 9068            });
 9069        });
 9070    }
 9071
 9072    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9073        let text_layout_details = &self.text_layout_details(window);
 9074        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9075            s.move_heads_with(|map, head, goal| {
 9076                movement::up(map, head, goal, false, text_layout_details)
 9077            })
 9078        })
 9079    }
 9080
 9081    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9082        self.take_rename(true, window, cx);
 9083
 9084        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9085            cx.propagate();
 9086            return;
 9087        }
 9088
 9089        let text_layout_details = &self.text_layout_details(window);
 9090        let selection_count = self.selections.count();
 9091        let first_selection = self.selections.first_anchor();
 9092
 9093        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9094            let line_mode = s.line_mode;
 9095            s.move_with(|map, selection| {
 9096                if !selection.is_empty() && !line_mode {
 9097                    selection.goal = SelectionGoal::None;
 9098                }
 9099                let (cursor, goal) = movement::down(
 9100                    map,
 9101                    selection.end,
 9102                    selection.goal,
 9103                    false,
 9104                    text_layout_details,
 9105                );
 9106                selection.collapse_to(cursor, goal);
 9107            });
 9108        });
 9109
 9110        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9111        {
 9112            cx.propagate();
 9113        }
 9114    }
 9115
 9116    pub fn select_page_down(
 9117        &mut self,
 9118        _: &SelectPageDown,
 9119        window: &mut Window,
 9120        cx: &mut Context<Self>,
 9121    ) {
 9122        let Some(row_count) = self.visible_row_count() else {
 9123            return;
 9124        };
 9125
 9126        let text_layout_details = &self.text_layout_details(window);
 9127
 9128        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9129            s.move_heads_with(|map, head, goal| {
 9130                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9131            })
 9132        })
 9133    }
 9134
 9135    pub fn move_page_down(
 9136        &mut self,
 9137        action: &MovePageDown,
 9138        window: &mut Window,
 9139        cx: &mut Context<Self>,
 9140    ) {
 9141        if self.take_rename(true, window, cx).is_some() {
 9142            return;
 9143        }
 9144
 9145        if self
 9146            .context_menu
 9147            .borrow_mut()
 9148            .as_mut()
 9149            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9150            .unwrap_or(false)
 9151        {
 9152            return;
 9153        }
 9154
 9155        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9156            cx.propagate();
 9157            return;
 9158        }
 9159
 9160        let Some(row_count) = self.visible_row_count() else {
 9161            return;
 9162        };
 9163
 9164        let autoscroll = if action.center_cursor {
 9165            Autoscroll::center()
 9166        } else {
 9167            Autoscroll::fit()
 9168        };
 9169
 9170        let text_layout_details = &self.text_layout_details(window);
 9171        self.change_selections(Some(autoscroll), window, cx, |s| {
 9172            let line_mode = s.line_mode;
 9173            s.move_with(|map, selection| {
 9174                if !selection.is_empty() && !line_mode {
 9175                    selection.goal = SelectionGoal::None;
 9176                }
 9177                let (cursor, goal) = movement::down_by_rows(
 9178                    map,
 9179                    selection.end,
 9180                    row_count,
 9181                    selection.goal,
 9182                    false,
 9183                    text_layout_details,
 9184                );
 9185                selection.collapse_to(cursor, goal);
 9186            });
 9187        });
 9188    }
 9189
 9190    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9191        let text_layout_details = &self.text_layout_details(window);
 9192        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9193            s.move_heads_with(|map, head, goal| {
 9194                movement::down(map, head, goal, false, text_layout_details)
 9195            })
 9196        });
 9197    }
 9198
 9199    pub fn context_menu_first(
 9200        &mut self,
 9201        _: &ContextMenuFirst,
 9202        _window: &mut Window,
 9203        cx: &mut Context<Self>,
 9204    ) {
 9205        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9206            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9207        }
 9208    }
 9209
 9210    pub fn context_menu_prev(
 9211        &mut self,
 9212        _: &ContextMenuPrev,
 9213        _window: &mut Window,
 9214        cx: &mut Context<Self>,
 9215    ) {
 9216        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9217            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9218        }
 9219    }
 9220
 9221    pub fn context_menu_next(
 9222        &mut self,
 9223        _: &ContextMenuNext,
 9224        _window: &mut Window,
 9225        cx: &mut Context<Self>,
 9226    ) {
 9227        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9228            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9229        }
 9230    }
 9231
 9232    pub fn context_menu_last(
 9233        &mut self,
 9234        _: &ContextMenuLast,
 9235        _window: &mut Window,
 9236        cx: &mut Context<Self>,
 9237    ) {
 9238        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9239            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9240        }
 9241    }
 9242
 9243    pub fn move_to_previous_word_start(
 9244        &mut self,
 9245        _: &MoveToPreviousWordStart,
 9246        window: &mut Window,
 9247        cx: &mut Context<Self>,
 9248    ) {
 9249        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9250            s.move_cursors_with(|map, head, _| {
 9251                (
 9252                    movement::previous_word_start(map, head),
 9253                    SelectionGoal::None,
 9254                )
 9255            });
 9256        })
 9257    }
 9258
 9259    pub fn move_to_previous_subword_start(
 9260        &mut self,
 9261        _: &MoveToPreviousSubwordStart,
 9262        window: &mut Window,
 9263        cx: &mut Context<Self>,
 9264    ) {
 9265        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9266            s.move_cursors_with(|map, head, _| {
 9267                (
 9268                    movement::previous_subword_start(map, head),
 9269                    SelectionGoal::None,
 9270                )
 9271            });
 9272        })
 9273    }
 9274
 9275    pub fn select_to_previous_word_start(
 9276        &mut self,
 9277        _: &SelectToPreviousWordStart,
 9278        window: &mut Window,
 9279        cx: &mut Context<Self>,
 9280    ) {
 9281        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9282            s.move_heads_with(|map, head, _| {
 9283                (
 9284                    movement::previous_word_start(map, head),
 9285                    SelectionGoal::None,
 9286                )
 9287            });
 9288        })
 9289    }
 9290
 9291    pub fn select_to_previous_subword_start(
 9292        &mut self,
 9293        _: &SelectToPreviousSubwordStart,
 9294        window: &mut Window,
 9295        cx: &mut Context<Self>,
 9296    ) {
 9297        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9298            s.move_heads_with(|map, head, _| {
 9299                (
 9300                    movement::previous_subword_start(map, head),
 9301                    SelectionGoal::None,
 9302                )
 9303            });
 9304        })
 9305    }
 9306
 9307    pub fn delete_to_previous_word_start(
 9308        &mut self,
 9309        action: &DeleteToPreviousWordStart,
 9310        window: &mut Window,
 9311        cx: &mut Context<Self>,
 9312    ) {
 9313        self.transact(window, cx, |this, window, cx| {
 9314            this.select_autoclose_pair(window, cx);
 9315            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9316                let line_mode = s.line_mode;
 9317                s.move_with(|map, selection| {
 9318                    if selection.is_empty() && !line_mode {
 9319                        let cursor = if action.ignore_newlines {
 9320                            movement::previous_word_start(map, selection.head())
 9321                        } else {
 9322                            movement::previous_word_start_or_newline(map, selection.head())
 9323                        };
 9324                        selection.set_head(cursor, SelectionGoal::None);
 9325                    }
 9326                });
 9327            });
 9328            this.insert("", window, cx);
 9329        });
 9330    }
 9331
 9332    pub fn delete_to_previous_subword_start(
 9333        &mut self,
 9334        _: &DeleteToPreviousSubwordStart,
 9335        window: &mut Window,
 9336        cx: &mut Context<Self>,
 9337    ) {
 9338        self.transact(window, cx, |this, window, cx| {
 9339            this.select_autoclose_pair(window, cx);
 9340            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9341                let line_mode = s.line_mode;
 9342                s.move_with(|map, selection| {
 9343                    if selection.is_empty() && !line_mode {
 9344                        let cursor = movement::previous_subword_start(map, selection.head());
 9345                        selection.set_head(cursor, SelectionGoal::None);
 9346                    }
 9347                });
 9348            });
 9349            this.insert("", window, cx);
 9350        });
 9351    }
 9352
 9353    pub fn move_to_next_word_end(
 9354        &mut self,
 9355        _: &MoveToNextWordEnd,
 9356        window: &mut Window,
 9357        cx: &mut Context<Self>,
 9358    ) {
 9359        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9360            s.move_cursors_with(|map, head, _| {
 9361                (movement::next_word_end(map, head), SelectionGoal::None)
 9362            });
 9363        })
 9364    }
 9365
 9366    pub fn move_to_next_subword_end(
 9367        &mut self,
 9368        _: &MoveToNextSubwordEnd,
 9369        window: &mut Window,
 9370        cx: &mut Context<Self>,
 9371    ) {
 9372        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9373            s.move_cursors_with(|map, head, _| {
 9374                (movement::next_subword_end(map, head), SelectionGoal::None)
 9375            });
 9376        })
 9377    }
 9378
 9379    pub fn select_to_next_word_end(
 9380        &mut self,
 9381        _: &SelectToNextWordEnd,
 9382        window: &mut Window,
 9383        cx: &mut Context<Self>,
 9384    ) {
 9385        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9386            s.move_heads_with(|map, head, _| {
 9387                (movement::next_word_end(map, head), SelectionGoal::None)
 9388            });
 9389        })
 9390    }
 9391
 9392    pub fn select_to_next_subword_end(
 9393        &mut self,
 9394        _: &SelectToNextSubwordEnd,
 9395        window: &mut Window,
 9396        cx: &mut Context<Self>,
 9397    ) {
 9398        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9399            s.move_heads_with(|map, head, _| {
 9400                (movement::next_subword_end(map, head), SelectionGoal::None)
 9401            });
 9402        })
 9403    }
 9404
 9405    pub fn delete_to_next_word_end(
 9406        &mut self,
 9407        action: &DeleteToNextWordEnd,
 9408        window: &mut Window,
 9409        cx: &mut Context<Self>,
 9410    ) {
 9411        self.transact(window, cx, |this, window, cx| {
 9412            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9413                let line_mode = s.line_mode;
 9414                s.move_with(|map, selection| {
 9415                    if selection.is_empty() && !line_mode {
 9416                        let cursor = if action.ignore_newlines {
 9417                            movement::next_word_end(map, selection.head())
 9418                        } else {
 9419                            movement::next_word_end_or_newline(map, selection.head())
 9420                        };
 9421                        selection.set_head(cursor, SelectionGoal::None);
 9422                    }
 9423                });
 9424            });
 9425            this.insert("", window, cx);
 9426        });
 9427    }
 9428
 9429    pub fn delete_to_next_subword_end(
 9430        &mut self,
 9431        _: &DeleteToNextSubwordEnd,
 9432        window: &mut Window,
 9433        cx: &mut Context<Self>,
 9434    ) {
 9435        self.transact(window, cx, |this, window, cx| {
 9436            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9437                s.move_with(|map, selection| {
 9438                    if selection.is_empty() {
 9439                        let cursor = movement::next_subword_end(map, selection.head());
 9440                        selection.set_head(cursor, SelectionGoal::None);
 9441                    }
 9442                });
 9443            });
 9444            this.insert("", window, cx);
 9445        });
 9446    }
 9447
 9448    pub fn move_to_beginning_of_line(
 9449        &mut self,
 9450        action: &MoveToBeginningOfLine,
 9451        window: &mut Window,
 9452        cx: &mut Context<Self>,
 9453    ) {
 9454        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9455            s.move_cursors_with(|map, head, _| {
 9456                (
 9457                    movement::indented_line_beginning(
 9458                        map,
 9459                        head,
 9460                        action.stop_at_soft_wraps,
 9461                        action.stop_at_indent,
 9462                    ),
 9463                    SelectionGoal::None,
 9464                )
 9465            });
 9466        })
 9467    }
 9468
 9469    pub fn select_to_beginning_of_line(
 9470        &mut self,
 9471        action: &SelectToBeginningOfLine,
 9472        window: &mut Window,
 9473        cx: &mut Context<Self>,
 9474    ) {
 9475        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9476            s.move_heads_with(|map, head, _| {
 9477                (
 9478                    movement::indented_line_beginning(
 9479                        map,
 9480                        head,
 9481                        action.stop_at_soft_wraps,
 9482                        action.stop_at_indent,
 9483                    ),
 9484                    SelectionGoal::None,
 9485                )
 9486            });
 9487        });
 9488    }
 9489
 9490    pub fn delete_to_beginning_of_line(
 9491        &mut self,
 9492        _: &DeleteToBeginningOfLine,
 9493        window: &mut Window,
 9494        cx: &mut Context<Self>,
 9495    ) {
 9496        self.transact(window, cx, |this, window, cx| {
 9497            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9498                s.move_with(|_, selection| {
 9499                    selection.reversed = true;
 9500                });
 9501            });
 9502
 9503            this.select_to_beginning_of_line(
 9504                &SelectToBeginningOfLine {
 9505                    stop_at_soft_wraps: false,
 9506                    stop_at_indent: false,
 9507                },
 9508                window,
 9509                cx,
 9510            );
 9511            this.backspace(&Backspace, window, cx);
 9512        });
 9513    }
 9514
 9515    pub fn move_to_end_of_line(
 9516        &mut self,
 9517        action: &MoveToEndOfLine,
 9518        window: &mut Window,
 9519        cx: &mut Context<Self>,
 9520    ) {
 9521        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9522            s.move_cursors_with(|map, head, _| {
 9523                (
 9524                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9525                    SelectionGoal::None,
 9526                )
 9527            });
 9528        })
 9529    }
 9530
 9531    pub fn select_to_end_of_line(
 9532        &mut self,
 9533        action: &SelectToEndOfLine,
 9534        window: &mut Window,
 9535        cx: &mut Context<Self>,
 9536    ) {
 9537        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9538            s.move_heads_with(|map, head, _| {
 9539                (
 9540                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9541                    SelectionGoal::None,
 9542                )
 9543            });
 9544        })
 9545    }
 9546
 9547    pub fn delete_to_end_of_line(
 9548        &mut self,
 9549        _: &DeleteToEndOfLine,
 9550        window: &mut Window,
 9551        cx: &mut Context<Self>,
 9552    ) {
 9553        self.transact(window, cx, |this, window, cx| {
 9554            this.select_to_end_of_line(
 9555                &SelectToEndOfLine {
 9556                    stop_at_soft_wraps: false,
 9557                },
 9558                window,
 9559                cx,
 9560            );
 9561            this.delete(&Delete, window, cx);
 9562        });
 9563    }
 9564
 9565    pub fn cut_to_end_of_line(
 9566        &mut self,
 9567        _: &CutToEndOfLine,
 9568        window: &mut Window,
 9569        cx: &mut Context<Self>,
 9570    ) {
 9571        self.transact(window, cx, |this, window, cx| {
 9572            this.select_to_end_of_line(
 9573                &SelectToEndOfLine {
 9574                    stop_at_soft_wraps: false,
 9575                },
 9576                window,
 9577                cx,
 9578            );
 9579            this.cut(&Cut, window, cx);
 9580        });
 9581    }
 9582
 9583    pub fn move_to_start_of_paragraph(
 9584        &mut self,
 9585        _: &MoveToStartOfParagraph,
 9586        window: &mut Window,
 9587        cx: &mut Context<Self>,
 9588    ) {
 9589        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9590            cx.propagate();
 9591            return;
 9592        }
 9593
 9594        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9595            s.move_with(|map, selection| {
 9596                selection.collapse_to(
 9597                    movement::start_of_paragraph(map, selection.head(), 1),
 9598                    SelectionGoal::None,
 9599                )
 9600            });
 9601        })
 9602    }
 9603
 9604    pub fn move_to_end_of_paragraph(
 9605        &mut self,
 9606        _: &MoveToEndOfParagraph,
 9607        window: &mut Window,
 9608        cx: &mut Context<Self>,
 9609    ) {
 9610        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9611            cx.propagate();
 9612            return;
 9613        }
 9614
 9615        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9616            s.move_with(|map, selection| {
 9617                selection.collapse_to(
 9618                    movement::end_of_paragraph(map, selection.head(), 1),
 9619                    SelectionGoal::None,
 9620                )
 9621            });
 9622        })
 9623    }
 9624
 9625    pub fn select_to_start_of_paragraph(
 9626        &mut self,
 9627        _: &SelectToStartOfParagraph,
 9628        window: &mut Window,
 9629        cx: &mut Context<Self>,
 9630    ) {
 9631        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9632            cx.propagate();
 9633            return;
 9634        }
 9635
 9636        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9637            s.move_heads_with(|map, head, _| {
 9638                (
 9639                    movement::start_of_paragraph(map, head, 1),
 9640                    SelectionGoal::None,
 9641                )
 9642            });
 9643        })
 9644    }
 9645
 9646    pub fn select_to_end_of_paragraph(
 9647        &mut self,
 9648        _: &SelectToEndOfParagraph,
 9649        window: &mut Window,
 9650        cx: &mut Context<Self>,
 9651    ) {
 9652        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9653            cx.propagate();
 9654            return;
 9655        }
 9656
 9657        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9658            s.move_heads_with(|map, head, _| {
 9659                (
 9660                    movement::end_of_paragraph(map, head, 1),
 9661                    SelectionGoal::None,
 9662                )
 9663            });
 9664        })
 9665    }
 9666
 9667    pub fn move_to_start_of_excerpt(
 9668        &mut self,
 9669        _: &MoveToStartOfExcerpt,
 9670        window: &mut Window,
 9671        cx: &mut Context<Self>,
 9672    ) {
 9673        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9674            cx.propagate();
 9675            return;
 9676        }
 9677
 9678        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9679            s.move_with(|map, selection| {
 9680                selection.collapse_to(
 9681                    movement::start_of_excerpt(
 9682                        map,
 9683                        selection.head(),
 9684                        workspace::searchable::Direction::Prev,
 9685                    ),
 9686                    SelectionGoal::None,
 9687                )
 9688            });
 9689        })
 9690    }
 9691
 9692    pub fn move_to_end_of_excerpt(
 9693        &mut self,
 9694        _: &MoveToEndOfExcerpt,
 9695        window: &mut Window,
 9696        cx: &mut Context<Self>,
 9697    ) {
 9698        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9699            cx.propagate();
 9700            return;
 9701        }
 9702
 9703        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9704            s.move_with(|map, selection| {
 9705                selection.collapse_to(
 9706                    movement::end_of_excerpt(
 9707                        map,
 9708                        selection.head(),
 9709                        workspace::searchable::Direction::Next,
 9710                    ),
 9711                    SelectionGoal::None,
 9712                )
 9713            });
 9714        })
 9715    }
 9716
 9717    pub fn select_to_start_of_excerpt(
 9718        &mut self,
 9719        _: &SelectToStartOfExcerpt,
 9720        window: &mut Window,
 9721        cx: &mut Context<Self>,
 9722    ) {
 9723        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9724            cx.propagate();
 9725            return;
 9726        }
 9727
 9728        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9729            s.move_heads_with(|map, head, _| {
 9730                (
 9731                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9732                    SelectionGoal::None,
 9733                )
 9734            });
 9735        })
 9736    }
 9737
 9738    pub fn select_to_end_of_excerpt(
 9739        &mut self,
 9740        _: &SelectToEndOfExcerpt,
 9741        window: &mut Window,
 9742        cx: &mut Context<Self>,
 9743    ) {
 9744        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9745            cx.propagate();
 9746            return;
 9747        }
 9748
 9749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9750            s.move_heads_with(|map, head, _| {
 9751                (
 9752                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9753                    SelectionGoal::None,
 9754                )
 9755            });
 9756        })
 9757    }
 9758
 9759    pub fn move_to_beginning(
 9760        &mut self,
 9761        _: &MoveToBeginning,
 9762        window: &mut Window,
 9763        cx: &mut Context<Self>,
 9764    ) {
 9765        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9766            cx.propagate();
 9767            return;
 9768        }
 9769
 9770        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9771            s.select_ranges(vec![0..0]);
 9772        });
 9773    }
 9774
 9775    pub fn select_to_beginning(
 9776        &mut self,
 9777        _: &SelectToBeginning,
 9778        window: &mut Window,
 9779        cx: &mut Context<Self>,
 9780    ) {
 9781        let mut selection = self.selections.last::<Point>(cx);
 9782        selection.set_head(Point::zero(), SelectionGoal::None);
 9783
 9784        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9785            s.select(vec![selection]);
 9786        });
 9787    }
 9788
 9789    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9790        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9791            cx.propagate();
 9792            return;
 9793        }
 9794
 9795        let cursor = self.buffer.read(cx).read(cx).len();
 9796        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9797            s.select_ranges(vec![cursor..cursor])
 9798        });
 9799    }
 9800
 9801    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9802        self.nav_history = nav_history;
 9803    }
 9804
 9805    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9806        self.nav_history.as_ref()
 9807    }
 9808
 9809    fn push_to_nav_history(
 9810        &mut self,
 9811        cursor_anchor: Anchor,
 9812        new_position: Option<Point>,
 9813        cx: &mut Context<Self>,
 9814    ) {
 9815        if let Some(nav_history) = self.nav_history.as_mut() {
 9816            let buffer = self.buffer.read(cx).read(cx);
 9817            let cursor_position = cursor_anchor.to_point(&buffer);
 9818            let scroll_state = self.scroll_manager.anchor();
 9819            let scroll_top_row = scroll_state.top_row(&buffer);
 9820            drop(buffer);
 9821
 9822            if let Some(new_position) = new_position {
 9823                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9824                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9825                    return;
 9826                }
 9827            }
 9828
 9829            nav_history.push(
 9830                Some(NavigationData {
 9831                    cursor_anchor,
 9832                    cursor_position,
 9833                    scroll_anchor: scroll_state,
 9834                    scroll_top_row,
 9835                }),
 9836                cx,
 9837            );
 9838        }
 9839    }
 9840
 9841    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9842        let buffer = self.buffer.read(cx).snapshot(cx);
 9843        let mut selection = self.selections.first::<usize>(cx);
 9844        selection.set_head(buffer.len(), SelectionGoal::None);
 9845        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9846            s.select(vec![selection]);
 9847        });
 9848    }
 9849
 9850    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9851        let end = self.buffer.read(cx).read(cx).len();
 9852        self.change_selections(None, window, cx, |s| {
 9853            s.select_ranges(vec![0..end]);
 9854        });
 9855    }
 9856
 9857    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9858        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9859        let mut selections = self.selections.all::<Point>(cx);
 9860        let max_point = display_map.buffer_snapshot.max_point();
 9861        for selection in &mut selections {
 9862            let rows = selection.spanned_rows(true, &display_map);
 9863            selection.start = Point::new(rows.start.0, 0);
 9864            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9865            selection.reversed = false;
 9866        }
 9867        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9868            s.select(selections);
 9869        });
 9870    }
 9871
 9872    pub fn split_selection_into_lines(
 9873        &mut self,
 9874        _: &SplitSelectionIntoLines,
 9875        window: &mut Window,
 9876        cx: &mut Context<Self>,
 9877    ) {
 9878        let selections = self
 9879            .selections
 9880            .all::<Point>(cx)
 9881            .into_iter()
 9882            .map(|selection| selection.start..selection.end)
 9883            .collect::<Vec<_>>();
 9884        self.unfold_ranges(&selections, true, true, cx);
 9885
 9886        let mut new_selection_ranges = Vec::new();
 9887        {
 9888            let buffer = self.buffer.read(cx).read(cx);
 9889            for selection in selections {
 9890                for row in selection.start.row..selection.end.row {
 9891                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9892                    new_selection_ranges.push(cursor..cursor);
 9893                }
 9894
 9895                let is_multiline_selection = selection.start.row != selection.end.row;
 9896                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9897                // so this action feels more ergonomic when paired with other selection operations
 9898                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9899                if !should_skip_last {
 9900                    new_selection_ranges.push(selection.end..selection.end);
 9901                }
 9902            }
 9903        }
 9904        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9905            s.select_ranges(new_selection_ranges);
 9906        });
 9907    }
 9908
 9909    pub fn add_selection_above(
 9910        &mut self,
 9911        _: &AddSelectionAbove,
 9912        window: &mut Window,
 9913        cx: &mut Context<Self>,
 9914    ) {
 9915        self.add_selection(true, window, cx);
 9916    }
 9917
 9918    pub fn add_selection_below(
 9919        &mut self,
 9920        _: &AddSelectionBelow,
 9921        window: &mut Window,
 9922        cx: &mut Context<Self>,
 9923    ) {
 9924        self.add_selection(false, window, cx);
 9925    }
 9926
 9927    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9928        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9929        let mut selections = self.selections.all::<Point>(cx);
 9930        let text_layout_details = self.text_layout_details(window);
 9931        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9932            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9933            let range = oldest_selection.display_range(&display_map).sorted();
 9934
 9935            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9936            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9937            let positions = start_x.min(end_x)..start_x.max(end_x);
 9938
 9939            selections.clear();
 9940            let mut stack = Vec::new();
 9941            for row in range.start.row().0..=range.end.row().0 {
 9942                if let Some(selection) = self.selections.build_columnar_selection(
 9943                    &display_map,
 9944                    DisplayRow(row),
 9945                    &positions,
 9946                    oldest_selection.reversed,
 9947                    &text_layout_details,
 9948                ) {
 9949                    stack.push(selection.id);
 9950                    selections.push(selection);
 9951                }
 9952            }
 9953
 9954            if above {
 9955                stack.reverse();
 9956            }
 9957
 9958            AddSelectionsState { above, stack }
 9959        });
 9960
 9961        let last_added_selection = *state.stack.last().unwrap();
 9962        let mut new_selections = Vec::new();
 9963        if above == state.above {
 9964            let end_row = if above {
 9965                DisplayRow(0)
 9966            } else {
 9967                display_map.max_point().row()
 9968            };
 9969
 9970            'outer: for selection in selections {
 9971                if selection.id == last_added_selection {
 9972                    let range = selection.display_range(&display_map).sorted();
 9973                    debug_assert_eq!(range.start.row(), range.end.row());
 9974                    let mut row = range.start.row();
 9975                    let positions =
 9976                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9977                            px(start)..px(end)
 9978                        } else {
 9979                            let start_x =
 9980                                display_map.x_for_display_point(range.start, &text_layout_details);
 9981                            let end_x =
 9982                                display_map.x_for_display_point(range.end, &text_layout_details);
 9983                            start_x.min(end_x)..start_x.max(end_x)
 9984                        };
 9985
 9986                    while row != end_row {
 9987                        if above {
 9988                            row.0 -= 1;
 9989                        } else {
 9990                            row.0 += 1;
 9991                        }
 9992
 9993                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9994                            &display_map,
 9995                            row,
 9996                            &positions,
 9997                            selection.reversed,
 9998                            &text_layout_details,
 9999                        ) {
10000                            state.stack.push(new_selection.id);
10001                            if above {
10002                                new_selections.push(new_selection);
10003                                new_selections.push(selection);
10004                            } else {
10005                                new_selections.push(selection);
10006                                new_selections.push(new_selection);
10007                            }
10008
10009                            continue 'outer;
10010                        }
10011                    }
10012                }
10013
10014                new_selections.push(selection);
10015            }
10016        } else {
10017            new_selections = selections;
10018            new_selections.retain(|s| s.id != last_added_selection);
10019            state.stack.pop();
10020        }
10021
10022        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10023            s.select(new_selections);
10024        });
10025        if state.stack.len() > 1 {
10026            self.add_selections_state = Some(state);
10027        }
10028    }
10029
10030    pub fn select_next_match_internal(
10031        &mut self,
10032        display_map: &DisplaySnapshot,
10033        replace_newest: bool,
10034        autoscroll: Option<Autoscroll>,
10035        window: &mut Window,
10036        cx: &mut Context<Self>,
10037    ) -> Result<()> {
10038        fn select_next_match_ranges(
10039            this: &mut Editor,
10040            range: Range<usize>,
10041            replace_newest: bool,
10042            auto_scroll: Option<Autoscroll>,
10043            window: &mut Window,
10044            cx: &mut Context<Editor>,
10045        ) {
10046            this.unfold_ranges(&[range.clone()], false, true, cx);
10047            this.change_selections(auto_scroll, window, cx, |s| {
10048                if replace_newest {
10049                    s.delete(s.newest_anchor().id);
10050                }
10051                s.insert_range(range.clone());
10052            });
10053        }
10054
10055        let buffer = &display_map.buffer_snapshot;
10056        let mut selections = self.selections.all::<usize>(cx);
10057        if let Some(mut select_next_state) = self.select_next_state.take() {
10058            let query = &select_next_state.query;
10059            if !select_next_state.done {
10060                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10061                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10062                let mut next_selected_range = None;
10063
10064                let bytes_after_last_selection =
10065                    buffer.bytes_in_range(last_selection.end..buffer.len());
10066                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10067                let query_matches = query
10068                    .stream_find_iter(bytes_after_last_selection)
10069                    .map(|result| (last_selection.end, result))
10070                    .chain(
10071                        query
10072                            .stream_find_iter(bytes_before_first_selection)
10073                            .map(|result| (0, result)),
10074                    );
10075
10076                for (start_offset, query_match) in query_matches {
10077                    let query_match = query_match.unwrap(); // can only fail due to I/O
10078                    let offset_range =
10079                        start_offset + query_match.start()..start_offset + query_match.end();
10080                    let display_range = offset_range.start.to_display_point(display_map)
10081                        ..offset_range.end.to_display_point(display_map);
10082
10083                    if !select_next_state.wordwise
10084                        || (!movement::is_inside_word(display_map, display_range.start)
10085                            && !movement::is_inside_word(display_map, display_range.end))
10086                    {
10087                        // TODO: This is n^2, because we might check all the selections
10088                        if !selections
10089                            .iter()
10090                            .any(|selection| selection.range().overlaps(&offset_range))
10091                        {
10092                            next_selected_range = Some(offset_range);
10093                            break;
10094                        }
10095                    }
10096                }
10097
10098                if let Some(next_selected_range) = next_selected_range {
10099                    select_next_match_ranges(
10100                        self,
10101                        next_selected_range,
10102                        replace_newest,
10103                        autoscroll,
10104                        window,
10105                        cx,
10106                    );
10107                } else {
10108                    select_next_state.done = true;
10109                }
10110            }
10111
10112            self.select_next_state = Some(select_next_state);
10113        } else {
10114            let mut only_carets = true;
10115            let mut same_text_selected = true;
10116            let mut selected_text = None;
10117
10118            let mut selections_iter = selections.iter().peekable();
10119            while let Some(selection) = selections_iter.next() {
10120                if selection.start != selection.end {
10121                    only_carets = false;
10122                }
10123
10124                if same_text_selected {
10125                    if selected_text.is_none() {
10126                        selected_text =
10127                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10128                    }
10129
10130                    if let Some(next_selection) = selections_iter.peek() {
10131                        if next_selection.range().len() == selection.range().len() {
10132                            let next_selected_text = buffer
10133                                .text_for_range(next_selection.range())
10134                                .collect::<String>();
10135                            if Some(next_selected_text) != selected_text {
10136                                same_text_selected = false;
10137                                selected_text = None;
10138                            }
10139                        } else {
10140                            same_text_selected = false;
10141                            selected_text = None;
10142                        }
10143                    }
10144                }
10145            }
10146
10147            if only_carets {
10148                for selection in &mut selections {
10149                    let word_range = movement::surrounding_word(
10150                        display_map,
10151                        selection.start.to_display_point(display_map),
10152                    );
10153                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10154                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10155                    selection.goal = SelectionGoal::None;
10156                    selection.reversed = false;
10157                    select_next_match_ranges(
10158                        self,
10159                        selection.start..selection.end,
10160                        replace_newest,
10161                        autoscroll,
10162                        window,
10163                        cx,
10164                    );
10165                }
10166
10167                if selections.len() == 1 {
10168                    let selection = selections
10169                        .last()
10170                        .expect("ensured that there's only one selection");
10171                    let query = buffer
10172                        .text_for_range(selection.start..selection.end)
10173                        .collect::<String>();
10174                    let is_empty = query.is_empty();
10175                    let select_state = SelectNextState {
10176                        query: AhoCorasick::new(&[query])?,
10177                        wordwise: true,
10178                        done: is_empty,
10179                    };
10180                    self.select_next_state = Some(select_state);
10181                } else {
10182                    self.select_next_state = None;
10183                }
10184            } else if let Some(selected_text) = selected_text {
10185                self.select_next_state = Some(SelectNextState {
10186                    query: AhoCorasick::new(&[selected_text])?,
10187                    wordwise: false,
10188                    done: false,
10189                });
10190                self.select_next_match_internal(
10191                    display_map,
10192                    replace_newest,
10193                    autoscroll,
10194                    window,
10195                    cx,
10196                )?;
10197            }
10198        }
10199        Ok(())
10200    }
10201
10202    pub fn select_all_matches(
10203        &mut self,
10204        _action: &SelectAllMatches,
10205        window: &mut Window,
10206        cx: &mut Context<Self>,
10207    ) -> Result<()> {
10208        self.push_to_selection_history();
10209        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10210
10211        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10212        let Some(select_next_state) = self.select_next_state.as_mut() else {
10213            return Ok(());
10214        };
10215        if select_next_state.done {
10216            return Ok(());
10217        }
10218
10219        let mut new_selections = self.selections.all::<usize>(cx);
10220
10221        let buffer = &display_map.buffer_snapshot;
10222        let query_matches = select_next_state
10223            .query
10224            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10225
10226        for query_match in query_matches {
10227            let query_match = query_match.unwrap(); // can only fail due to I/O
10228            let offset_range = query_match.start()..query_match.end();
10229            let display_range = offset_range.start.to_display_point(&display_map)
10230                ..offset_range.end.to_display_point(&display_map);
10231
10232            if !select_next_state.wordwise
10233                || (!movement::is_inside_word(&display_map, display_range.start)
10234                    && !movement::is_inside_word(&display_map, display_range.end))
10235            {
10236                self.selections.change_with(cx, |selections| {
10237                    new_selections.push(Selection {
10238                        id: selections.new_selection_id(),
10239                        start: offset_range.start,
10240                        end: offset_range.end,
10241                        reversed: false,
10242                        goal: SelectionGoal::None,
10243                    });
10244                });
10245            }
10246        }
10247
10248        new_selections.sort_by_key(|selection| selection.start);
10249        let mut ix = 0;
10250        while ix + 1 < new_selections.len() {
10251            let current_selection = &new_selections[ix];
10252            let next_selection = &new_selections[ix + 1];
10253            if current_selection.range().overlaps(&next_selection.range()) {
10254                if current_selection.id < next_selection.id {
10255                    new_selections.remove(ix + 1);
10256                } else {
10257                    new_selections.remove(ix);
10258                }
10259            } else {
10260                ix += 1;
10261            }
10262        }
10263
10264        let reversed = self.selections.oldest::<usize>(cx).reversed;
10265
10266        for selection in new_selections.iter_mut() {
10267            selection.reversed = reversed;
10268        }
10269
10270        select_next_state.done = true;
10271        self.unfold_ranges(
10272            &new_selections
10273                .iter()
10274                .map(|selection| selection.range())
10275                .collect::<Vec<_>>(),
10276            false,
10277            false,
10278            cx,
10279        );
10280        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10281            selections.select(new_selections)
10282        });
10283
10284        Ok(())
10285    }
10286
10287    pub fn select_next(
10288        &mut self,
10289        action: &SelectNext,
10290        window: &mut Window,
10291        cx: &mut Context<Self>,
10292    ) -> Result<()> {
10293        self.push_to_selection_history();
10294        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10295        self.select_next_match_internal(
10296            &display_map,
10297            action.replace_newest,
10298            Some(Autoscroll::newest()),
10299            window,
10300            cx,
10301        )?;
10302        Ok(())
10303    }
10304
10305    pub fn select_previous(
10306        &mut self,
10307        action: &SelectPrevious,
10308        window: &mut Window,
10309        cx: &mut Context<Self>,
10310    ) -> Result<()> {
10311        self.push_to_selection_history();
10312        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10313        let buffer = &display_map.buffer_snapshot;
10314        let mut selections = self.selections.all::<usize>(cx);
10315        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10316            let query = &select_prev_state.query;
10317            if !select_prev_state.done {
10318                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10319                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10320                let mut next_selected_range = None;
10321                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10322                let bytes_before_last_selection =
10323                    buffer.reversed_bytes_in_range(0..last_selection.start);
10324                let bytes_after_first_selection =
10325                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10326                let query_matches = query
10327                    .stream_find_iter(bytes_before_last_selection)
10328                    .map(|result| (last_selection.start, result))
10329                    .chain(
10330                        query
10331                            .stream_find_iter(bytes_after_first_selection)
10332                            .map(|result| (buffer.len(), result)),
10333                    );
10334                for (end_offset, query_match) in query_matches {
10335                    let query_match = query_match.unwrap(); // can only fail due to I/O
10336                    let offset_range =
10337                        end_offset - query_match.end()..end_offset - query_match.start();
10338                    let display_range = offset_range.start.to_display_point(&display_map)
10339                        ..offset_range.end.to_display_point(&display_map);
10340
10341                    if !select_prev_state.wordwise
10342                        || (!movement::is_inside_word(&display_map, display_range.start)
10343                            && !movement::is_inside_word(&display_map, display_range.end))
10344                    {
10345                        next_selected_range = Some(offset_range);
10346                        break;
10347                    }
10348                }
10349
10350                if let Some(next_selected_range) = next_selected_range {
10351                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10352                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10353                        if action.replace_newest {
10354                            s.delete(s.newest_anchor().id);
10355                        }
10356                        s.insert_range(next_selected_range);
10357                    });
10358                } else {
10359                    select_prev_state.done = true;
10360                }
10361            }
10362
10363            self.select_prev_state = Some(select_prev_state);
10364        } else {
10365            let mut only_carets = true;
10366            let mut same_text_selected = true;
10367            let mut selected_text = None;
10368
10369            let mut selections_iter = selections.iter().peekable();
10370            while let Some(selection) = selections_iter.next() {
10371                if selection.start != selection.end {
10372                    only_carets = false;
10373                }
10374
10375                if same_text_selected {
10376                    if selected_text.is_none() {
10377                        selected_text =
10378                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10379                    }
10380
10381                    if let Some(next_selection) = selections_iter.peek() {
10382                        if next_selection.range().len() == selection.range().len() {
10383                            let next_selected_text = buffer
10384                                .text_for_range(next_selection.range())
10385                                .collect::<String>();
10386                            if Some(next_selected_text) != selected_text {
10387                                same_text_selected = false;
10388                                selected_text = None;
10389                            }
10390                        } else {
10391                            same_text_selected = false;
10392                            selected_text = None;
10393                        }
10394                    }
10395                }
10396            }
10397
10398            if only_carets {
10399                for selection in &mut selections {
10400                    let word_range = movement::surrounding_word(
10401                        &display_map,
10402                        selection.start.to_display_point(&display_map),
10403                    );
10404                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10405                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10406                    selection.goal = SelectionGoal::None;
10407                    selection.reversed = false;
10408                }
10409                if selections.len() == 1 {
10410                    let selection = selections
10411                        .last()
10412                        .expect("ensured that there's only one selection");
10413                    let query = buffer
10414                        .text_for_range(selection.start..selection.end)
10415                        .collect::<String>();
10416                    let is_empty = query.is_empty();
10417                    let select_state = SelectNextState {
10418                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10419                        wordwise: true,
10420                        done: is_empty,
10421                    };
10422                    self.select_prev_state = Some(select_state);
10423                } else {
10424                    self.select_prev_state = None;
10425                }
10426
10427                self.unfold_ranges(
10428                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10429                    false,
10430                    true,
10431                    cx,
10432                );
10433                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10434                    s.select(selections);
10435                });
10436            } else if let Some(selected_text) = selected_text {
10437                self.select_prev_state = Some(SelectNextState {
10438                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10439                    wordwise: false,
10440                    done: false,
10441                });
10442                self.select_previous(action, window, cx)?;
10443            }
10444        }
10445        Ok(())
10446    }
10447
10448    pub fn toggle_comments(
10449        &mut self,
10450        action: &ToggleComments,
10451        window: &mut Window,
10452        cx: &mut Context<Self>,
10453    ) {
10454        if self.read_only(cx) {
10455            return;
10456        }
10457        let text_layout_details = &self.text_layout_details(window);
10458        self.transact(window, cx, |this, window, cx| {
10459            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10460            let mut edits = Vec::new();
10461            let mut selection_edit_ranges = Vec::new();
10462            let mut last_toggled_row = None;
10463            let snapshot = this.buffer.read(cx).read(cx);
10464            let empty_str: Arc<str> = Arc::default();
10465            let mut suffixes_inserted = Vec::new();
10466            let ignore_indent = action.ignore_indent;
10467
10468            fn comment_prefix_range(
10469                snapshot: &MultiBufferSnapshot,
10470                row: MultiBufferRow,
10471                comment_prefix: &str,
10472                comment_prefix_whitespace: &str,
10473                ignore_indent: bool,
10474            ) -> Range<Point> {
10475                let indent_size = if ignore_indent {
10476                    0
10477                } else {
10478                    snapshot.indent_size_for_line(row).len
10479                };
10480
10481                let start = Point::new(row.0, indent_size);
10482
10483                let mut line_bytes = snapshot
10484                    .bytes_in_range(start..snapshot.max_point())
10485                    .flatten()
10486                    .copied();
10487
10488                // If this line currently begins with the line comment prefix, then record
10489                // the range containing the prefix.
10490                if line_bytes
10491                    .by_ref()
10492                    .take(comment_prefix.len())
10493                    .eq(comment_prefix.bytes())
10494                {
10495                    // Include any whitespace that matches the comment prefix.
10496                    let matching_whitespace_len = line_bytes
10497                        .zip(comment_prefix_whitespace.bytes())
10498                        .take_while(|(a, b)| a == b)
10499                        .count() as u32;
10500                    let end = Point::new(
10501                        start.row,
10502                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10503                    );
10504                    start..end
10505                } else {
10506                    start..start
10507                }
10508            }
10509
10510            fn comment_suffix_range(
10511                snapshot: &MultiBufferSnapshot,
10512                row: MultiBufferRow,
10513                comment_suffix: &str,
10514                comment_suffix_has_leading_space: bool,
10515            ) -> Range<Point> {
10516                let end = Point::new(row.0, snapshot.line_len(row));
10517                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10518
10519                let mut line_end_bytes = snapshot
10520                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10521                    .flatten()
10522                    .copied();
10523
10524                let leading_space_len = if suffix_start_column > 0
10525                    && line_end_bytes.next() == Some(b' ')
10526                    && comment_suffix_has_leading_space
10527                {
10528                    1
10529                } else {
10530                    0
10531                };
10532
10533                // If this line currently begins with the line comment prefix, then record
10534                // the range containing the prefix.
10535                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10536                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10537                    start..end
10538                } else {
10539                    end..end
10540                }
10541            }
10542
10543            // TODO: Handle selections that cross excerpts
10544            for selection in &mut selections {
10545                let start_column = snapshot
10546                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10547                    .len;
10548                let language = if let Some(language) =
10549                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10550                {
10551                    language
10552                } else {
10553                    continue;
10554                };
10555
10556                selection_edit_ranges.clear();
10557
10558                // If multiple selections contain a given row, avoid processing that
10559                // row more than once.
10560                let mut start_row = MultiBufferRow(selection.start.row);
10561                if last_toggled_row == Some(start_row) {
10562                    start_row = start_row.next_row();
10563                }
10564                let end_row =
10565                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10566                        MultiBufferRow(selection.end.row - 1)
10567                    } else {
10568                        MultiBufferRow(selection.end.row)
10569                    };
10570                last_toggled_row = Some(end_row);
10571
10572                if start_row > end_row {
10573                    continue;
10574                }
10575
10576                // If the language has line comments, toggle those.
10577                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10578
10579                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10580                if ignore_indent {
10581                    full_comment_prefixes = full_comment_prefixes
10582                        .into_iter()
10583                        .map(|s| Arc::from(s.trim_end()))
10584                        .collect();
10585                }
10586
10587                if !full_comment_prefixes.is_empty() {
10588                    let first_prefix = full_comment_prefixes
10589                        .first()
10590                        .expect("prefixes is non-empty");
10591                    let prefix_trimmed_lengths = full_comment_prefixes
10592                        .iter()
10593                        .map(|p| p.trim_end_matches(' ').len())
10594                        .collect::<SmallVec<[usize; 4]>>();
10595
10596                    let mut all_selection_lines_are_comments = true;
10597
10598                    for row in start_row.0..=end_row.0 {
10599                        let row = MultiBufferRow(row);
10600                        if start_row < end_row && snapshot.is_line_blank(row) {
10601                            continue;
10602                        }
10603
10604                        let prefix_range = full_comment_prefixes
10605                            .iter()
10606                            .zip(prefix_trimmed_lengths.iter().copied())
10607                            .map(|(prefix, trimmed_prefix_len)| {
10608                                comment_prefix_range(
10609                                    snapshot.deref(),
10610                                    row,
10611                                    &prefix[..trimmed_prefix_len],
10612                                    &prefix[trimmed_prefix_len..],
10613                                    ignore_indent,
10614                                )
10615                            })
10616                            .max_by_key(|range| range.end.column - range.start.column)
10617                            .expect("prefixes is non-empty");
10618
10619                        if prefix_range.is_empty() {
10620                            all_selection_lines_are_comments = false;
10621                        }
10622
10623                        selection_edit_ranges.push(prefix_range);
10624                    }
10625
10626                    if all_selection_lines_are_comments {
10627                        edits.extend(
10628                            selection_edit_ranges
10629                                .iter()
10630                                .cloned()
10631                                .map(|range| (range, empty_str.clone())),
10632                        );
10633                    } else {
10634                        let min_column = selection_edit_ranges
10635                            .iter()
10636                            .map(|range| range.start.column)
10637                            .min()
10638                            .unwrap_or(0);
10639                        edits.extend(selection_edit_ranges.iter().map(|range| {
10640                            let position = Point::new(range.start.row, min_column);
10641                            (position..position, first_prefix.clone())
10642                        }));
10643                    }
10644                } else if let Some((full_comment_prefix, comment_suffix)) =
10645                    language.block_comment_delimiters()
10646                {
10647                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10648                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10649                    let prefix_range = comment_prefix_range(
10650                        snapshot.deref(),
10651                        start_row,
10652                        comment_prefix,
10653                        comment_prefix_whitespace,
10654                        ignore_indent,
10655                    );
10656                    let suffix_range = comment_suffix_range(
10657                        snapshot.deref(),
10658                        end_row,
10659                        comment_suffix.trim_start_matches(' '),
10660                        comment_suffix.starts_with(' '),
10661                    );
10662
10663                    if prefix_range.is_empty() || suffix_range.is_empty() {
10664                        edits.push((
10665                            prefix_range.start..prefix_range.start,
10666                            full_comment_prefix.clone(),
10667                        ));
10668                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10669                        suffixes_inserted.push((end_row, comment_suffix.len()));
10670                    } else {
10671                        edits.push((prefix_range, empty_str.clone()));
10672                        edits.push((suffix_range, empty_str.clone()));
10673                    }
10674                } else {
10675                    continue;
10676                }
10677            }
10678
10679            drop(snapshot);
10680            this.buffer.update(cx, |buffer, cx| {
10681                buffer.edit(edits, None, cx);
10682            });
10683
10684            // Adjust selections so that they end before any comment suffixes that
10685            // were inserted.
10686            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10687            let mut selections = this.selections.all::<Point>(cx);
10688            let snapshot = this.buffer.read(cx).read(cx);
10689            for selection in &mut selections {
10690                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10691                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10692                        Ordering::Less => {
10693                            suffixes_inserted.next();
10694                            continue;
10695                        }
10696                        Ordering::Greater => break,
10697                        Ordering::Equal => {
10698                            if selection.end.column == snapshot.line_len(row) {
10699                                if selection.is_empty() {
10700                                    selection.start.column -= suffix_len as u32;
10701                                }
10702                                selection.end.column -= suffix_len as u32;
10703                            }
10704                            break;
10705                        }
10706                    }
10707                }
10708            }
10709
10710            drop(snapshot);
10711            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10712                s.select(selections)
10713            });
10714
10715            let selections = this.selections.all::<Point>(cx);
10716            let selections_on_single_row = selections.windows(2).all(|selections| {
10717                selections[0].start.row == selections[1].start.row
10718                    && selections[0].end.row == selections[1].end.row
10719                    && selections[0].start.row == selections[0].end.row
10720            });
10721            let selections_selecting = selections
10722                .iter()
10723                .any(|selection| selection.start != selection.end);
10724            let advance_downwards = action.advance_downwards
10725                && selections_on_single_row
10726                && !selections_selecting
10727                && !matches!(this.mode, EditorMode::SingleLine { .. });
10728
10729            if advance_downwards {
10730                let snapshot = this.buffer.read(cx).snapshot(cx);
10731
10732                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10733                    s.move_cursors_with(|display_snapshot, display_point, _| {
10734                        let mut point = display_point.to_point(display_snapshot);
10735                        point.row += 1;
10736                        point = snapshot.clip_point(point, Bias::Left);
10737                        let display_point = point.to_display_point(display_snapshot);
10738                        let goal = SelectionGoal::HorizontalPosition(
10739                            display_snapshot
10740                                .x_for_display_point(display_point, text_layout_details)
10741                                .into(),
10742                        );
10743                        (display_point, goal)
10744                    })
10745                });
10746            }
10747        });
10748    }
10749
10750    pub fn select_enclosing_symbol(
10751        &mut self,
10752        _: &SelectEnclosingSymbol,
10753        window: &mut Window,
10754        cx: &mut Context<Self>,
10755    ) {
10756        let buffer = self.buffer.read(cx).snapshot(cx);
10757        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10758
10759        fn update_selection(
10760            selection: &Selection<usize>,
10761            buffer_snap: &MultiBufferSnapshot,
10762        ) -> Option<Selection<usize>> {
10763            let cursor = selection.head();
10764            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10765            for symbol in symbols.iter().rev() {
10766                let start = symbol.range.start.to_offset(buffer_snap);
10767                let end = symbol.range.end.to_offset(buffer_snap);
10768                let new_range = start..end;
10769                if start < selection.start || end > selection.end {
10770                    return Some(Selection {
10771                        id: selection.id,
10772                        start: new_range.start,
10773                        end: new_range.end,
10774                        goal: SelectionGoal::None,
10775                        reversed: selection.reversed,
10776                    });
10777                }
10778            }
10779            None
10780        }
10781
10782        let mut selected_larger_symbol = false;
10783        let new_selections = old_selections
10784            .iter()
10785            .map(|selection| match update_selection(selection, &buffer) {
10786                Some(new_selection) => {
10787                    if new_selection.range() != selection.range() {
10788                        selected_larger_symbol = true;
10789                    }
10790                    new_selection
10791                }
10792                None => selection.clone(),
10793            })
10794            .collect::<Vec<_>>();
10795
10796        if selected_larger_symbol {
10797            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10798                s.select(new_selections);
10799            });
10800        }
10801    }
10802
10803    pub fn select_larger_syntax_node(
10804        &mut self,
10805        _: &SelectLargerSyntaxNode,
10806        window: &mut Window,
10807        cx: &mut Context<Self>,
10808    ) {
10809        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10810        let buffer = self.buffer.read(cx).snapshot(cx);
10811        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10812
10813        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10814        let mut selected_larger_node = false;
10815        let new_selections = old_selections
10816            .iter()
10817            .map(|selection| {
10818                let old_range = selection.start..selection.end;
10819                let mut new_range = old_range.clone();
10820                let mut new_node = None;
10821                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10822                {
10823                    new_node = Some(node);
10824                    new_range = match containing_range {
10825                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10826                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10827                    };
10828                    if !display_map.intersects_fold(new_range.start)
10829                        && !display_map.intersects_fold(new_range.end)
10830                    {
10831                        break;
10832                    }
10833                }
10834
10835                if let Some(node) = new_node {
10836                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10837                    // nodes. Parent and grandparent are also logged because this operation will not
10838                    // visit nodes that have the same range as their parent.
10839                    log::info!("Node: {node:?}");
10840                    let parent = node.parent();
10841                    log::info!("Parent: {parent:?}");
10842                    let grandparent = parent.and_then(|x| x.parent());
10843                    log::info!("Grandparent: {grandparent:?}");
10844                }
10845
10846                selected_larger_node |= new_range != old_range;
10847                Selection {
10848                    id: selection.id,
10849                    start: new_range.start,
10850                    end: new_range.end,
10851                    goal: SelectionGoal::None,
10852                    reversed: selection.reversed,
10853                }
10854            })
10855            .collect::<Vec<_>>();
10856
10857        if selected_larger_node {
10858            stack.push(old_selections);
10859            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10860                s.select(new_selections);
10861            });
10862        }
10863        self.select_larger_syntax_node_stack = stack;
10864    }
10865
10866    pub fn select_smaller_syntax_node(
10867        &mut self,
10868        _: &SelectSmallerSyntaxNode,
10869        window: &mut Window,
10870        cx: &mut Context<Self>,
10871    ) {
10872        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10873        if let Some(selections) = stack.pop() {
10874            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10875                s.select(selections.to_vec());
10876            });
10877        }
10878        self.select_larger_syntax_node_stack = stack;
10879    }
10880
10881    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10882        if !EditorSettings::get_global(cx).gutter.runnables {
10883            self.clear_tasks();
10884            return Task::ready(());
10885        }
10886        let project = self.project.as_ref().map(Entity::downgrade);
10887        cx.spawn_in(window, |this, mut cx| async move {
10888            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10889            let Some(project) = project.and_then(|p| p.upgrade()) else {
10890                return;
10891            };
10892            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10893                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10894            }) else {
10895                return;
10896            };
10897
10898            let hide_runnables = project
10899                .update(&mut cx, |project, cx| {
10900                    // Do not display any test indicators in non-dev server remote projects.
10901                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10902                })
10903                .unwrap_or(true);
10904            if hide_runnables {
10905                return;
10906            }
10907            let new_rows =
10908                cx.background_spawn({
10909                    let snapshot = display_snapshot.clone();
10910                    async move {
10911                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10912                    }
10913                })
10914                    .await;
10915
10916            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10917            this.update(&mut cx, |this, _| {
10918                this.clear_tasks();
10919                for (key, value) in rows {
10920                    this.insert_tasks(key, value);
10921                }
10922            })
10923            .ok();
10924        })
10925    }
10926    fn fetch_runnable_ranges(
10927        snapshot: &DisplaySnapshot,
10928        range: Range<Anchor>,
10929    ) -> Vec<language::RunnableRange> {
10930        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10931    }
10932
10933    fn runnable_rows(
10934        project: Entity<Project>,
10935        snapshot: DisplaySnapshot,
10936        runnable_ranges: Vec<RunnableRange>,
10937        mut cx: AsyncWindowContext,
10938    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10939        runnable_ranges
10940            .into_iter()
10941            .filter_map(|mut runnable| {
10942                let tasks = cx
10943                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10944                    .ok()?;
10945                if tasks.is_empty() {
10946                    return None;
10947                }
10948
10949                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10950
10951                let row = snapshot
10952                    .buffer_snapshot
10953                    .buffer_line_for_row(MultiBufferRow(point.row))?
10954                    .1
10955                    .start
10956                    .row;
10957
10958                let context_range =
10959                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10960                Some((
10961                    (runnable.buffer_id, row),
10962                    RunnableTasks {
10963                        templates: tasks,
10964                        offset: snapshot
10965                            .buffer_snapshot
10966                            .anchor_before(runnable.run_range.start),
10967                        context_range,
10968                        column: point.column,
10969                        extra_variables: runnable.extra_captures,
10970                    },
10971                ))
10972            })
10973            .collect()
10974    }
10975
10976    fn templates_with_tags(
10977        project: &Entity<Project>,
10978        runnable: &mut Runnable,
10979        cx: &mut App,
10980    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10981        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10982            let (worktree_id, file) = project
10983                .buffer_for_id(runnable.buffer, cx)
10984                .and_then(|buffer| buffer.read(cx).file())
10985                .map(|file| (file.worktree_id(cx), file.clone()))
10986                .unzip();
10987
10988            (
10989                project.task_store().read(cx).task_inventory().cloned(),
10990                worktree_id,
10991                file,
10992            )
10993        });
10994
10995        let tags = mem::take(&mut runnable.tags);
10996        let mut tags: Vec<_> = tags
10997            .into_iter()
10998            .flat_map(|tag| {
10999                let tag = tag.0.clone();
11000                inventory
11001                    .as_ref()
11002                    .into_iter()
11003                    .flat_map(|inventory| {
11004                        inventory.read(cx).list_tasks(
11005                            file.clone(),
11006                            Some(runnable.language.clone()),
11007                            worktree_id,
11008                            cx,
11009                        )
11010                    })
11011                    .filter(move |(_, template)| {
11012                        template.tags.iter().any(|source_tag| source_tag == &tag)
11013                    })
11014            })
11015            .sorted_by_key(|(kind, _)| kind.to_owned())
11016            .collect();
11017        if let Some((leading_tag_source, _)) = tags.first() {
11018            // Strongest source wins; if we have worktree tag binding, prefer that to
11019            // global and language bindings;
11020            // if we have a global binding, prefer that to language binding.
11021            let first_mismatch = tags
11022                .iter()
11023                .position(|(tag_source, _)| tag_source != leading_tag_source);
11024            if let Some(index) = first_mismatch {
11025                tags.truncate(index);
11026            }
11027        }
11028
11029        tags
11030    }
11031
11032    pub fn move_to_enclosing_bracket(
11033        &mut self,
11034        _: &MoveToEnclosingBracket,
11035        window: &mut Window,
11036        cx: &mut Context<Self>,
11037    ) {
11038        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11039            s.move_offsets_with(|snapshot, selection| {
11040                let Some(enclosing_bracket_ranges) =
11041                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11042                else {
11043                    return;
11044                };
11045
11046                let mut best_length = usize::MAX;
11047                let mut best_inside = false;
11048                let mut best_in_bracket_range = false;
11049                let mut best_destination = None;
11050                for (open, close) in enclosing_bracket_ranges {
11051                    let close = close.to_inclusive();
11052                    let length = close.end() - open.start;
11053                    let inside = selection.start >= open.end && selection.end <= *close.start();
11054                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11055                        || close.contains(&selection.head());
11056
11057                    // If best is next to a bracket and current isn't, skip
11058                    if !in_bracket_range && best_in_bracket_range {
11059                        continue;
11060                    }
11061
11062                    // Prefer smaller lengths unless best is inside and current isn't
11063                    if length > best_length && (best_inside || !inside) {
11064                        continue;
11065                    }
11066
11067                    best_length = length;
11068                    best_inside = inside;
11069                    best_in_bracket_range = in_bracket_range;
11070                    best_destination = Some(
11071                        if close.contains(&selection.start) && close.contains(&selection.end) {
11072                            if inside {
11073                                open.end
11074                            } else {
11075                                open.start
11076                            }
11077                        } else if inside {
11078                            *close.start()
11079                        } else {
11080                            *close.end()
11081                        },
11082                    );
11083                }
11084
11085                if let Some(destination) = best_destination {
11086                    selection.collapse_to(destination, SelectionGoal::None);
11087                }
11088            })
11089        });
11090    }
11091
11092    pub fn undo_selection(
11093        &mut self,
11094        _: &UndoSelection,
11095        window: &mut Window,
11096        cx: &mut Context<Self>,
11097    ) {
11098        self.end_selection(window, cx);
11099        self.selection_history.mode = SelectionHistoryMode::Undoing;
11100        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11101            self.change_selections(None, window, cx, |s| {
11102                s.select_anchors(entry.selections.to_vec())
11103            });
11104            self.select_next_state = entry.select_next_state;
11105            self.select_prev_state = entry.select_prev_state;
11106            self.add_selections_state = entry.add_selections_state;
11107            self.request_autoscroll(Autoscroll::newest(), cx);
11108        }
11109        self.selection_history.mode = SelectionHistoryMode::Normal;
11110    }
11111
11112    pub fn redo_selection(
11113        &mut self,
11114        _: &RedoSelection,
11115        window: &mut Window,
11116        cx: &mut Context<Self>,
11117    ) {
11118        self.end_selection(window, cx);
11119        self.selection_history.mode = SelectionHistoryMode::Redoing;
11120        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11121            self.change_selections(None, window, cx, |s| {
11122                s.select_anchors(entry.selections.to_vec())
11123            });
11124            self.select_next_state = entry.select_next_state;
11125            self.select_prev_state = entry.select_prev_state;
11126            self.add_selections_state = entry.add_selections_state;
11127            self.request_autoscroll(Autoscroll::newest(), cx);
11128        }
11129        self.selection_history.mode = SelectionHistoryMode::Normal;
11130    }
11131
11132    pub fn expand_excerpts(
11133        &mut self,
11134        action: &ExpandExcerpts,
11135        _: &mut Window,
11136        cx: &mut Context<Self>,
11137    ) {
11138        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11139    }
11140
11141    pub fn expand_excerpts_down(
11142        &mut self,
11143        action: &ExpandExcerptsDown,
11144        _: &mut Window,
11145        cx: &mut Context<Self>,
11146    ) {
11147        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11148    }
11149
11150    pub fn expand_excerpts_up(
11151        &mut self,
11152        action: &ExpandExcerptsUp,
11153        _: &mut Window,
11154        cx: &mut Context<Self>,
11155    ) {
11156        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11157    }
11158
11159    pub fn expand_excerpts_for_direction(
11160        &mut self,
11161        lines: u32,
11162        direction: ExpandExcerptDirection,
11163
11164        cx: &mut Context<Self>,
11165    ) {
11166        let selections = self.selections.disjoint_anchors();
11167
11168        let lines = if lines == 0 {
11169            EditorSettings::get_global(cx).expand_excerpt_lines
11170        } else {
11171            lines
11172        };
11173
11174        self.buffer.update(cx, |buffer, cx| {
11175            let snapshot = buffer.snapshot(cx);
11176            let mut excerpt_ids = selections
11177                .iter()
11178                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11179                .collect::<Vec<_>>();
11180            excerpt_ids.sort();
11181            excerpt_ids.dedup();
11182            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11183        })
11184    }
11185
11186    pub fn expand_excerpt(
11187        &mut self,
11188        excerpt: ExcerptId,
11189        direction: ExpandExcerptDirection,
11190        cx: &mut Context<Self>,
11191    ) {
11192        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11193        self.buffer.update(cx, |buffer, cx| {
11194            buffer.expand_excerpts([excerpt], lines, direction, cx)
11195        })
11196    }
11197
11198    pub fn go_to_singleton_buffer_point(
11199        &mut self,
11200        point: Point,
11201        window: &mut Window,
11202        cx: &mut Context<Self>,
11203    ) {
11204        self.go_to_singleton_buffer_range(point..point, window, cx);
11205    }
11206
11207    pub fn go_to_singleton_buffer_range(
11208        &mut self,
11209        range: Range<Point>,
11210        window: &mut Window,
11211        cx: &mut Context<Self>,
11212    ) {
11213        let multibuffer = self.buffer().read(cx);
11214        let Some(buffer) = multibuffer.as_singleton() else {
11215            return;
11216        };
11217        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11218            return;
11219        };
11220        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11221            return;
11222        };
11223        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11224            s.select_anchor_ranges([start..end])
11225        });
11226    }
11227
11228    fn go_to_diagnostic(
11229        &mut self,
11230        _: &GoToDiagnostic,
11231        window: &mut Window,
11232        cx: &mut Context<Self>,
11233    ) {
11234        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11235    }
11236
11237    fn go_to_prev_diagnostic(
11238        &mut self,
11239        _: &GoToPrevDiagnostic,
11240        window: &mut Window,
11241        cx: &mut Context<Self>,
11242    ) {
11243        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11244    }
11245
11246    pub fn go_to_diagnostic_impl(
11247        &mut self,
11248        direction: Direction,
11249        window: &mut Window,
11250        cx: &mut Context<Self>,
11251    ) {
11252        let buffer = self.buffer.read(cx).snapshot(cx);
11253        let selection = self.selections.newest::<usize>(cx);
11254
11255        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11256        if direction == Direction::Next {
11257            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11258                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11259                    return;
11260                };
11261                self.activate_diagnostics(
11262                    buffer_id,
11263                    popover.local_diagnostic.diagnostic.group_id,
11264                    window,
11265                    cx,
11266                );
11267                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11268                    let primary_range_start = active_diagnostics.primary_range.start;
11269                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11270                        let mut new_selection = s.newest_anchor().clone();
11271                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11272                        s.select_anchors(vec![new_selection.clone()]);
11273                    });
11274                    self.refresh_inline_completion(false, true, window, cx);
11275                }
11276                return;
11277            }
11278        }
11279
11280        let active_group_id = self
11281            .active_diagnostics
11282            .as_ref()
11283            .map(|active_group| active_group.group_id);
11284        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11285            active_diagnostics
11286                .primary_range
11287                .to_offset(&buffer)
11288                .to_inclusive()
11289        });
11290        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11291            if active_primary_range.contains(&selection.head()) {
11292                *active_primary_range.start()
11293            } else {
11294                selection.head()
11295            }
11296        } else {
11297            selection.head()
11298        };
11299
11300        let snapshot = self.snapshot(window, cx);
11301        let primary_diagnostics_before = buffer
11302            .diagnostics_in_range::<usize>(0..search_start)
11303            .filter(|entry| entry.diagnostic.is_primary)
11304            .filter(|entry| entry.range.start != entry.range.end)
11305            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11306            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11307            .collect::<Vec<_>>();
11308        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11309            primary_diagnostics_before
11310                .iter()
11311                .position(|entry| entry.diagnostic.group_id == active_group_id)
11312        });
11313
11314        let primary_diagnostics_after = buffer
11315            .diagnostics_in_range::<usize>(search_start..buffer.len())
11316            .filter(|entry| entry.diagnostic.is_primary)
11317            .filter(|entry| entry.range.start != entry.range.end)
11318            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11319            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11320            .collect::<Vec<_>>();
11321        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11322            primary_diagnostics_after
11323                .iter()
11324                .enumerate()
11325                .rev()
11326                .find_map(|(i, entry)| {
11327                    if entry.diagnostic.group_id == active_group_id {
11328                        Some(i)
11329                    } else {
11330                        None
11331                    }
11332                })
11333        });
11334
11335        let next_primary_diagnostic = match direction {
11336            Direction::Prev => primary_diagnostics_before
11337                .iter()
11338                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11339                .rev()
11340                .next(),
11341            Direction::Next => primary_diagnostics_after
11342                .iter()
11343                .skip(
11344                    last_same_group_diagnostic_after
11345                        .map(|index| index + 1)
11346                        .unwrap_or(0),
11347                )
11348                .next(),
11349        };
11350
11351        // Cycle around to the start of the buffer, potentially moving back to the start of
11352        // the currently active diagnostic.
11353        let cycle_around = || match direction {
11354            Direction::Prev => primary_diagnostics_after
11355                .iter()
11356                .rev()
11357                .chain(primary_diagnostics_before.iter().rev())
11358                .next(),
11359            Direction::Next => primary_diagnostics_before
11360                .iter()
11361                .chain(primary_diagnostics_after.iter())
11362                .next(),
11363        };
11364
11365        if let Some((primary_range, group_id)) = next_primary_diagnostic
11366            .or_else(cycle_around)
11367            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11368        {
11369            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11370                return;
11371            };
11372            self.activate_diagnostics(buffer_id, group_id, window, cx);
11373            if self.active_diagnostics.is_some() {
11374                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11375                    s.select(vec![Selection {
11376                        id: selection.id,
11377                        start: primary_range.start,
11378                        end: primary_range.start,
11379                        reversed: false,
11380                        goal: SelectionGoal::None,
11381                    }]);
11382                });
11383                self.refresh_inline_completion(false, true, window, cx);
11384            }
11385        }
11386    }
11387
11388    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11389        let snapshot = self.snapshot(window, cx);
11390        let selection = self.selections.newest::<Point>(cx);
11391        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11392    }
11393
11394    fn go_to_hunk_after_position(
11395        &mut self,
11396        snapshot: &EditorSnapshot,
11397        position: Point,
11398        window: &mut Window,
11399        cx: &mut Context<Editor>,
11400    ) -> Option<MultiBufferDiffHunk> {
11401        let mut hunk = snapshot
11402            .buffer_snapshot
11403            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11404            .find(|hunk| hunk.row_range.start.0 > position.row);
11405        if hunk.is_none() {
11406            hunk = snapshot
11407                .buffer_snapshot
11408                .diff_hunks_in_range(Point::zero()..position)
11409                .find(|hunk| hunk.row_range.end.0 < position.row)
11410        }
11411        if let Some(hunk) = &hunk {
11412            let destination = Point::new(hunk.row_range.start.0, 0);
11413            self.unfold_ranges(&[destination..destination], false, false, cx);
11414            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11415                s.select_ranges(vec![destination..destination]);
11416            });
11417        }
11418
11419        hunk
11420    }
11421
11422    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11423        let snapshot = self.snapshot(window, cx);
11424        let selection = self.selections.newest::<Point>(cx);
11425        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11426    }
11427
11428    fn go_to_hunk_before_position(
11429        &mut self,
11430        snapshot: &EditorSnapshot,
11431        position: Point,
11432        window: &mut Window,
11433        cx: &mut Context<Editor>,
11434    ) -> Option<MultiBufferDiffHunk> {
11435        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11436        if hunk.is_none() {
11437            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11438        }
11439        if let Some(hunk) = &hunk {
11440            let destination = Point::new(hunk.row_range.start.0, 0);
11441            self.unfold_ranges(&[destination..destination], false, false, cx);
11442            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11443                s.select_ranges(vec![destination..destination]);
11444            });
11445        }
11446
11447        hunk
11448    }
11449
11450    pub fn go_to_definition(
11451        &mut self,
11452        _: &GoToDefinition,
11453        window: &mut Window,
11454        cx: &mut Context<Self>,
11455    ) -> Task<Result<Navigated>> {
11456        let definition =
11457            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11458        cx.spawn_in(window, |editor, mut cx| async move {
11459            if definition.await? == Navigated::Yes {
11460                return Ok(Navigated::Yes);
11461            }
11462            match editor.update_in(&mut cx, |editor, window, cx| {
11463                editor.find_all_references(&FindAllReferences, window, cx)
11464            })? {
11465                Some(references) => references.await,
11466                None => Ok(Navigated::No),
11467            }
11468        })
11469    }
11470
11471    pub fn go_to_declaration(
11472        &mut self,
11473        _: &GoToDeclaration,
11474        window: &mut Window,
11475        cx: &mut Context<Self>,
11476    ) -> Task<Result<Navigated>> {
11477        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11478    }
11479
11480    pub fn go_to_declaration_split(
11481        &mut self,
11482        _: &GoToDeclaration,
11483        window: &mut Window,
11484        cx: &mut Context<Self>,
11485    ) -> Task<Result<Navigated>> {
11486        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11487    }
11488
11489    pub fn go_to_implementation(
11490        &mut self,
11491        _: &GoToImplementation,
11492        window: &mut Window,
11493        cx: &mut Context<Self>,
11494    ) -> Task<Result<Navigated>> {
11495        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11496    }
11497
11498    pub fn go_to_implementation_split(
11499        &mut self,
11500        _: &GoToImplementationSplit,
11501        window: &mut Window,
11502        cx: &mut Context<Self>,
11503    ) -> Task<Result<Navigated>> {
11504        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11505    }
11506
11507    pub fn go_to_type_definition(
11508        &mut self,
11509        _: &GoToTypeDefinition,
11510        window: &mut Window,
11511        cx: &mut Context<Self>,
11512    ) -> Task<Result<Navigated>> {
11513        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11514    }
11515
11516    pub fn go_to_definition_split(
11517        &mut self,
11518        _: &GoToDefinitionSplit,
11519        window: &mut Window,
11520        cx: &mut Context<Self>,
11521    ) -> Task<Result<Navigated>> {
11522        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11523    }
11524
11525    pub fn go_to_type_definition_split(
11526        &mut self,
11527        _: &GoToTypeDefinitionSplit,
11528        window: &mut Window,
11529        cx: &mut Context<Self>,
11530    ) -> Task<Result<Navigated>> {
11531        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11532    }
11533
11534    fn go_to_definition_of_kind(
11535        &mut self,
11536        kind: GotoDefinitionKind,
11537        split: bool,
11538        window: &mut Window,
11539        cx: &mut Context<Self>,
11540    ) -> Task<Result<Navigated>> {
11541        let Some(provider) = self.semantics_provider.clone() else {
11542            return Task::ready(Ok(Navigated::No));
11543        };
11544        let head = self.selections.newest::<usize>(cx).head();
11545        let buffer = self.buffer.read(cx);
11546        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11547            text_anchor
11548        } else {
11549            return Task::ready(Ok(Navigated::No));
11550        };
11551
11552        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11553            return Task::ready(Ok(Navigated::No));
11554        };
11555
11556        cx.spawn_in(window, |editor, mut cx| async move {
11557            let definitions = definitions.await?;
11558            let navigated = editor
11559                .update_in(&mut cx, |editor, window, cx| {
11560                    editor.navigate_to_hover_links(
11561                        Some(kind),
11562                        definitions
11563                            .into_iter()
11564                            .filter(|location| {
11565                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11566                            })
11567                            .map(HoverLink::Text)
11568                            .collect::<Vec<_>>(),
11569                        split,
11570                        window,
11571                        cx,
11572                    )
11573                })?
11574                .await?;
11575            anyhow::Ok(navigated)
11576        })
11577    }
11578
11579    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11580        let selection = self.selections.newest_anchor();
11581        let head = selection.head();
11582        let tail = selection.tail();
11583
11584        let Some((buffer, start_position)) =
11585            self.buffer.read(cx).text_anchor_for_position(head, cx)
11586        else {
11587            return;
11588        };
11589
11590        let end_position = if head != tail {
11591            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11592                return;
11593            };
11594            Some(pos)
11595        } else {
11596            None
11597        };
11598
11599        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11600            let url = if let Some(end_pos) = end_position {
11601                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11602            } else {
11603                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11604            };
11605
11606            if let Some(url) = url {
11607                editor.update(&mut cx, |_, cx| {
11608                    cx.open_url(&url);
11609                })
11610            } else {
11611                Ok(())
11612            }
11613        });
11614
11615        url_finder.detach();
11616    }
11617
11618    pub fn open_selected_filename(
11619        &mut self,
11620        _: &OpenSelectedFilename,
11621        window: &mut Window,
11622        cx: &mut Context<Self>,
11623    ) {
11624        let Some(workspace) = self.workspace() else {
11625            return;
11626        };
11627
11628        let position = self.selections.newest_anchor().head();
11629
11630        let Some((buffer, buffer_position)) =
11631            self.buffer.read(cx).text_anchor_for_position(position, cx)
11632        else {
11633            return;
11634        };
11635
11636        let project = self.project.clone();
11637
11638        cx.spawn_in(window, |_, mut cx| async move {
11639            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11640
11641            if let Some((_, path)) = result {
11642                workspace
11643                    .update_in(&mut cx, |workspace, window, cx| {
11644                        workspace.open_resolved_path(path, window, cx)
11645                    })?
11646                    .await?;
11647            }
11648            anyhow::Ok(())
11649        })
11650        .detach();
11651    }
11652
11653    pub(crate) fn navigate_to_hover_links(
11654        &mut self,
11655        kind: Option<GotoDefinitionKind>,
11656        mut definitions: Vec<HoverLink>,
11657        split: bool,
11658        window: &mut Window,
11659        cx: &mut Context<Editor>,
11660    ) -> Task<Result<Navigated>> {
11661        // If there is one definition, just open it directly
11662        if definitions.len() == 1 {
11663            let definition = definitions.pop().unwrap();
11664
11665            enum TargetTaskResult {
11666                Location(Option<Location>),
11667                AlreadyNavigated,
11668            }
11669
11670            let target_task = match definition {
11671                HoverLink::Text(link) => {
11672                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11673                }
11674                HoverLink::InlayHint(lsp_location, server_id) => {
11675                    let computation =
11676                        self.compute_target_location(lsp_location, server_id, window, cx);
11677                    cx.background_spawn(async move {
11678                        let location = computation.await?;
11679                        Ok(TargetTaskResult::Location(location))
11680                    })
11681                }
11682                HoverLink::Url(url) => {
11683                    cx.open_url(&url);
11684                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11685                }
11686                HoverLink::File(path) => {
11687                    if let Some(workspace) = self.workspace() {
11688                        cx.spawn_in(window, |_, mut cx| async move {
11689                            workspace
11690                                .update_in(&mut cx, |workspace, window, cx| {
11691                                    workspace.open_resolved_path(path, window, cx)
11692                                })?
11693                                .await
11694                                .map(|_| TargetTaskResult::AlreadyNavigated)
11695                        })
11696                    } else {
11697                        Task::ready(Ok(TargetTaskResult::Location(None)))
11698                    }
11699                }
11700            };
11701            cx.spawn_in(window, |editor, mut cx| async move {
11702                let target = match target_task.await.context("target resolution task")? {
11703                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11704                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11705                    TargetTaskResult::Location(Some(target)) => target,
11706                };
11707
11708                editor.update_in(&mut cx, |editor, window, cx| {
11709                    let Some(workspace) = editor.workspace() else {
11710                        return Navigated::No;
11711                    };
11712                    let pane = workspace.read(cx).active_pane().clone();
11713
11714                    let range = target.range.to_point(target.buffer.read(cx));
11715                    let range = editor.range_for_match(&range);
11716                    let range = collapse_multiline_range(range);
11717
11718                    if !split
11719                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11720                    {
11721                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11722                    } else {
11723                        window.defer(cx, move |window, cx| {
11724                            let target_editor: Entity<Self> =
11725                                workspace.update(cx, |workspace, cx| {
11726                                    let pane = if split {
11727                                        workspace.adjacent_pane(window, cx)
11728                                    } else {
11729                                        workspace.active_pane().clone()
11730                                    };
11731
11732                                    workspace.open_project_item(
11733                                        pane,
11734                                        target.buffer.clone(),
11735                                        true,
11736                                        true,
11737                                        window,
11738                                        cx,
11739                                    )
11740                                });
11741                            target_editor.update(cx, |target_editor, cx| {
11742                                // When selecting a definition in a different buffer, disable the nav history
11743                                // to avoid creating a history entry at the previous cursor location.
11744                                pane.update(cx, |pane, _| pane.disable_history());
11745                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11746                                pane.update(cx, |pane, _| pane.enable_history());
11747                            });
11748                        });
11749                    }
11750                    Navigated::Yes
11751                })
11752            })
11753        } else if !definitions.is_empty() {
11754            cx.spawn_in(window, |editor, mut cx| async move {
11755                let (title, location_tasks, workspace) = editor
11756                    .update_in(&mut cx, |editor, window, cx| {
11757                        let tab_kind = match kind {
11758                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11759                            _ => "Definitions",
11760                        };
11761                        let title = definitions
11762                            .iter()
11763                            .find_map(|definition| match definition {
11764                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11765                                    let buffer = origin.buffer.read(cx);
11766                                    format!(
11767                                        "{} for {}",
11768                                        tab_kind,
11769                                        buffer
11770                                            .text_for_range(origin.range.clone())
11771                                            .collect::<String>()
11772                                    )
11773                                }),
11774                                HoverLink::InlayHint(_, _) => None,
11775                                HoverLink::Url(_) => None,
11776                                HoverLink::File(_) => None,
11777                            })
11778                            .unwrap_or(tab_kind.to_string());
11779                        let location_tasks = definitions
11780                            .into_iter()
11781                            .map(|definition| match definition {
11782                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11783                                HoverLink::InlayHint(lsp_location, server_id) => editor
11784                                    .compute_target_location(lsp_location, server_id, window, cx),
11785                                HoverLink::Url(_) => Task::ready(Ok(None)),
11786                                HoverLink::File(_) => Task::ready(Ok(None)),
11787                            })
11788                            .collect::<Vec<_>>();
11789                        (title, location_tasks, editor.workspace().clone())
11790                    })
11791                    .context("location tasks preparation")?;
11792
11793                let locations = future::join_all(location_tasks)
11794                    .await
11795                    .into_iter()
11796                    .filter_map(|location| location.transpose())
11797                    .collect::<Result<_>>()
11798                    .context("location tasks")?;
11799
11800                let Some(workspace) = workspace else {
11801                    return Ok(Navigated::No);
11802                };
11803                let opened = workspace
11804                    .update_in(&mut cx, |workspace, window, cx| {
11805                        Self::open_locations_in_multibuffer(
11806                            workspace,
11807                            locations,
11808                            title,
11809                            split,
11810                            MultibufferSelectionMode::First,
11811                            window,
11812                            cx,
11813                        )
11814                    })
11815                    .ok();
11816
11817                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11818            })
11819        } else {
11820            Task::ready(Ok(Navigated::No))
11821        }
11822    }
11823
11824    fn compute_target_location(
11825        &self,
11826        lsp_location: lsp::Location,
11827        server_id: LanguageServerId,
11828        window: &mut Window,
11829        cx: &mut Context<Self>,
11830    ) -> Task<anyhow::Result<Option<Location>>> {
11831        let Some(project) = self.project.clone() else {
11832            return Task::ready(Ok(None));
11833        };
11834
11835        cx.spawn_in(window, move |editor, mut cx| async move {
11836            let location_task = editor.update(&mut cx, |_, cx| {
11837                project.update(cx, |project, cx| {
11838                    let language_server_name = project
11839                        .language_server_statuses(cx)
11840                        .find(|(id, _)| server_id == *id)
11841                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11842                    language_server_name.map(|language_server_name| {
11843                        project.open_local_buffer_via_lsp(
11844                            lsp_location.uri.clone(),
11845                            server_id,
11846                            language_server_name,
11847                            cx,
11848                        )
11849                    })
11850                })
11851            })?;
11852            let location = match location_task {
11853                Some(task) => Some({
11854                    let target_buffer_handle = task.await.context("open local buffer")?;
11855                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11856                        let target_start = target_buffer
11857                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11858                        let target_end = target_buffer
11859                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11860                        target_buffer.anchor_after(target_start)
11861                            ..target_buffer.anchor_before(target_end)
11862                    })?;
11863                    Location {
11864                        buffer: target_buffer_handle,
11865                        range,
11866                    }
11867                }),
11868                None => None,
11869            };
11870            Ok(location)
11871        })
11872    }
11873
11874    pub fn find_all_references(
11875        &mut self,
11876        _: &FindAllReferences,
11877        window: &mut Window,
11878        cx: &mut Context<Self>,
11879    ) -> Option<Task<Result<Navigated>>> {
11880        let selection = self.selections.newest::<usize>(cx);
11881        let multi_buffer = self.buffer.read(cx);
11882        let head = selection.head();
11883
11884        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11885        let head_anchor = multi_buffer_snapshot.anchor_at(
11886            head,
11887            if head < selection.tail() {
11888                Bias::Right
11889            } else {
11890                Bias::Left
11891            },
11892        );
11893
11894        match self
11895            .find_all_references_task_sources
11896            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11897        {
11898            Ok(_) => {
11899                log::info!(
11900                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11901                );
11902                return None;
11903            }
11904            Err(i) => {
11905                self.find_all_references_task_sources.insert(i, head_anchor);
11906            }
11907        }
11908
11909        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11910        let workspace = self.workspace()?;
11911        let project = workspace.read(cx).project().clone();
11912        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11913        Some(cx.spawn_in(window, |editor, mut cx| async move {
11914            let _cleanup = defer({
11915                let mut cx = cx.clone();
11916                move || {
11917                    let _ = editor.update(&mut cx, |editor, _| {
11918                        if let Ok(i) =
11919                            editor
11920                                .find_all_references_task_sources
11921                                .binary_search_by(|anchor| {
11922                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11923                                })
11924                        {
11925                            editor.find_all_references_task_sources.remove(i);
11926                        }
11927                    });
11928                }
11929            });
11930
11931            let locations = references.await?;
11932            if locations.is_empty() {
11933                return anyhow::Ok(Navigated::No);
11934            }
11935
11936            workspace.update_in(&mut cx, |workspace, window, cx| {
11937                let title = locations
11938                    .first()
11939                    .as_ref()
11940                    .map(|location| {
11941                        let buffer = location.buffer.read(cx);
11942                        format!(
11943                            "References to `{}`",
11944                            buffer
11945                                .text_for_range(location.range.clone())
11946                                .collect::<String>()
11947                        )
11948                    })
11949                    .unwrap();
11950                Self::open_locations_in_multibuffer(
11951                    workspace,
11952                    locations,
11953                    title,
11954                    false,
11955                    MultibufferSelectionMode::First,
11956                    window,
11957                    cx,
11958                );
11959                Navigated::Yes
11960            })
11961        }))
11962    }
11963
11964    /// Opens a multibuffer with the given project locations in it
11965    pub fn open_locations_in_multibuffer(
11966        workspace: &mut Workspace,
11967        mut locations: Vec<Location>,
11968        title: String,
11969        split: bool,
11970        multibuffer_selection_mode: MultibufferSelectionMode,
11971        window: &mut Window,
11972        cx: &mut Context<Workspace>,
11973    ) {
11974        // If there are multiple definitions, open them in a multibuffer
11975        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11976        let mut locations = locations.into_iter().peekable();
11977        let mut ranges = Vec::new();
11978        let capability = workspace.project().read(cx).capability();
11979
11980        let excerpt_buffer = cx.new(|cx| {
11981            let mut multibuffer = MultiBuffer::new(capability);
11982            while let Some(location) = locations.next() {
11983                let buffer = location.buffer.read(cx);
11984                let mut ranges_for_buffer = Vec::new();
11985                let range = location.range.to_offset(buffer);
11986                ranges_for_buffer.push(range.clone());
11987
11988                while let Some(next_location) = locations.peek() {
11989                    if next_location.buffer == location.buffer {
11990                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11991                        locations.next();
11992                    } else {
11993                        break;
11994                    }
11995                }
11996
11997                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11998                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11999                    location.buffer.clone(),
12000                    ranges_for_buffer,
12001                    DEFAULT_MULTIBUFFER_CONTEXT,
12002                    cx,
12003                ))
12004            }
12005
12006            multibuffer.with_title(title)
12007        });
12008
12009        let editor = cx.new(|cx| {
12010            Editor::for_multibuffer(
12011                excerpt_buffer,
12012                Some(workspace.project().clone()),
12013                true,
12014                window,
12015                cx,
12016            )
12017        });
12018        editor.update(cx, |editor, cx| {
12019            match multibuffer_selection_mode {
12020                MultibufferSelectionMode::First => {
12021                    if let Some(first_range) = ranges.first() {
12022                        editor.change_selections(None, window, cx, |selections| {
12023                            selections.clear_disjoint();
12024                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12025                        });
12026                    }
12027                    editor.highlight_background::<Self>(
12028                        &ranges,
12029                        |theme| theme.editor_highlighted_line_background,
12030                        cx,
12031                    );
12032                }
12033                MultibufferSelectionMode::All => {
12034                    editor.change_selections(None, window, cx, |selections| {
12035                        selections.clear_disjoint();
12036                        selections.select_anchor_ranges(ranges);
12037                    });
12038                }
12039            }
12040            editor.register_buffers_with_language_servers(cx);
12041        });
12042
12043        let item = Box::new(editor);
12044        let item_id = item.item_id();
12045
12046        if split {
12047            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12048        } else {
12049            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12050                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12051                    pane.close_current_preview_item(window, cx)
12052                } else {
12053                    None
12054                }
12055            });
12056            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12057        }
12058        workspace.active_pane().update(cx, |pane, cx| {
12059            pane.set_preview_item_id(Some(item_id), cx);
12060        });
12061    }
12062
12063    pub fn rename(
12064        &mut self,
12065        _: &Rename,
12066        window: &mut Window,
12067        cx: &mut Context<Self>,
12068    ) -> Option<Task<Result<()>>> {
12069        use language::ToOffset as _;
12070
12071        let provider = self.semantics_provider.clone()?;
12072        let selection = self.selections.newest_anchor().clone();
12073        let (cursor_buffer, cursor_buffer_position) = self
12074            .buffer
12075            .read(cx)
12076            .text_anchor_for_position(selection.head(), cx)?;
12077        let (tail_buffer, cursor_buffer_position_end) = self
12078            .buffer
12079            .read(cx)
12080            .text_anchor_for_position(selection.tail(), cx)?;
12081        if tail_buffer != cursor_buffer {
12082            return None;
12083        }
12084
12085        let snapshot = cursor_buffer.read(cx).snapshot();
12086        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12087        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12088        let prepare_rename = provider
12089            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12090            .unwrap_or_else(|| Task::ready(Ok(None)));
12091        drop(snapshot);
12092
12093        Some(cx.spawn_in(window, |this, mut cx| async move {
12094            let rename_range = if let Some(range) = prepare_rename.await? {
12095                Some(range)
12096            } else {
12097                this.update(&mut cx, |this, cx| {
12098                    let buffer = this.buffer.read(cx).snapshot(cx);
12099                    let mut buffer_highlights = this
12100                        .document_highlights_for_position(selection.head(), &buffer)
12101                        .filter(|highlight| {
12102                            highlight.start.excerpt_id == selection.head().excerpt_id
12103                                && highlight.end.excerpt_id == selection.head().excerpt_id
12104                        });
12105                    buffer_highlights
12106                        .next()
12107                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12108                })?
12109            };
12110            if let Some(rename_range) = rename_range {
12111                this.update_in(&mut cx, |this, window, cx| {
12112                    let snapshot = cursor_buffer.read(cx).snapshot();
12113                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12114                    let cursor_offset_in_rename_range =
12115                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12116                    let cursor_offset_in_rename_range_end =
12117                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12118
12119                    this.take_rename(false, window, cx);
12120                    let buffer = this.buffer.read(cx).read(cx);
12121                    let cursor_offset = selection.head().to_offset(&buffer);
12122                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12123                    let rename_end = rename_start + rename_buffer_range.len();
12124                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12125                    let mut old_highlight_id = None;
12126                    let old_name: Arc<str> = buffer
12127                        .chunks(rename_start..rename_end, true)
12128                        .map(|chunk| {
12129                            if old_highlight_id.is_none() {
12130                                old_highlight_id = chunk.syntax_highlight_id;
12131                            }
12132                            chunk.text
12133                        })
12134                        .collect::<String>()
12135                        .into();
12136
12137                    drop(buffer);
12138
12139                    // Position the selection in the rename editor so that it matches the current selection.
12140                    this.show_local_selections = false;
12141                    let rename_editor = cx.new(|cx| {
12142                        let mut editor = Editor::single_line(window, cx);
12143                        editor.buffer.update(cx, |buffer, cx| {
12144                            buffer.edit([(0..0, old_name.clone())], None, cx)
12145                        });
12146                        let rename_selection_range = match cursor_offset_in_rename_range
12147                            .cmp(&cursor_offset_in_rename_range_end)
12148                        {
12149                            Ordering::Equal => {
12150                                editor.select_all(&SelectAll, window, cx);
12151                                return editor;
12152                            }
12153                            Ordering::Less => {
12154                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12155                            }
12156                            Ordering::Greater => {
12157                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12158                            }
12159                        };
12160                        if rename_selection_range.end > old_name.len() {
12161                            editor.select_all(&SelectAll, window, cx);
12162                        } else {
12163                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12164                                s.select_ranges([rename_selection_range]);
12165                            });
12166                        }
12167                        editor
12168                    });
12169                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12170                        if e == &EditorEvent::Focused {
12171                            cx.emit(EditorEvent::FocusedIn)
12172                        }
12173                    })
12174                    .detach();
12175
12176                    let write_highlights =
12177                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12178                    let read_highlights =
12179                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12180                    let ranges = write_highlights
12181                        .iter()
12182                        .flat_map(|(_, ranges)| ranges.iter())
12183                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12184                        .cloned()
12185                        .collect();
12186
12187                    this.highlight_text::<Rename>(
12188                        ranges,
12189                        HighlightStyle {
12190                            fade_out: Some(0.6),
12191                            ..Default::default()
12192                        },
12193                        cx,
12194                    );
12195                    let rename_focus_handle = rename_editor.focus_handle(cx);
12196                    window.focus(&rename_focus_handle);
12197                    let block_id = this.insert_blocks(
12198                        [BlockProperties {
12199                            style: BlockStyle::Flex,
12200                            placement: BlockPlacement::Below(range.start),
12201                            height: 1,
12202                            render: Arc::new({
12203                                let rename_editor = rename_editor.clone();
12204                                move |cx: &mut BlockContext| {
12205                                    let mut text_style = cx.editor_style.text.clone();
12206                                    if let Some(highlight_style) = old_highlight_id
12207                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12208                                    {
12209                                        text_style = text_style.highlight(highlight_style);
12210                                    }
12211                                    div()
12212                                        .block_mouse_down()
12213                                        .pl(cx.anchor_x)
12214                                        .child(EditorElement::new(
12215                                            &rename_editor,
12216                                            EditorStyle {
12217                                                background: cx.theme().system().transparent,
12218                                                local_player: cx.editor_style.local_player,
12219                                                text: text_style,
12220                                                scrollbar_width: cx.editor_style.scrollbar_width,
12221                                                syntax: cx.editor_style.syntax.clone(),
12222                                                status: cx.editor_style.status.clone(),
12223                                                inlay_hints_style: HighlightStyle {
12224                                                    font_weight: Some(FontWeight::BOLD),
12225                                                    ..make_inlay_hints_style(cx.app)
12226                                                },
12227                                                inline_completion_styles: make_suggestion_styles(
12228                                                    cx.app,
12229                                                ),
12230                                                ..EditorStyle::default()
12231                                            },
12232                                        ))
12233                                        .into_any_element()
12234                                }
12235                            }),
12236                            priority: 0,
12237                        }],
12238                        Some(Autoscroll::fit()),
12239                        cx,
12240                    )[0];
12241                    this.pending_rename = Some(RenameState {
12242                        range,
12243                        old_name,
12244                        editor: rename_editor,
12245                        block_id,
12246                    });
12247                })?;
12248            }
12249
12250            Ok(())
12251        }))
12252    }
12253
12254    pub fn confirm_rename(
12255        &mut self,
12256        _: &ConfirmRename,
12257        window: &mut Window,
12258        cx: &mut Context<Self>,
12259    ) -> Option<Task<Result<()>>> {
12260        let rename = self.take_rename(false, window, cx)?;
12261        let workspace = self.workspace()?.downgrade();
12262        let (buffer, start) = self
12263            .buffer
12264            .read(cx)
12265            .text_anchor_for_position(rename.range.start, cx)?;
12266        let (end_buffer, _) = self
12267            .buffer
12268            .read(cx)
12269            .text_anchor_for_position(rename.range.end, cx)?;
12270        if buffer != end_buffer {
12271            return None;
12272        }
12273
12274        let old_name = rename.old_name;
12275        let new_name = rename.editor.read(cx).text(cx);
12276
12277        let rename = self.semantics_provider.as_ref()?.perform_rename(
12278            &buffer,
12279            start,
12280            new_name.clone(),
12281            cx,
12282        )?;
12283
12284        Some(cx.spawn_in(window, |editor, mut cx| async move {
12285            let project_transaction = rename.await?;
12286            Self::open_project_transaction(
12287                &editor,
12288                workspace,
12289                project_transaction,
12290                format!("Rename: {}{}", old_name, new_name),
12291                cx.clone(),
12292            )
12293            .await?;
12294
12295            editor.update(&mut cx, |editor, cx| {
12296                editor.refresh_document_highlights(cx);
12297            })?;
12298            Ok(())
12299        }))
12300    }
12301
12302    fn take_rename(
12303        &mut self,
12304        moving_cursor: bool,
12305        window: &mut Window,
12306        cx: &mut Context<Self>,
12307    ) -> Option<RenameState> {
12308        let rename = self.pending_rename.take()?;
12309        if rename.editor.focus_handle(cx).is_focused(window) {
12310            window.focus(&self.focus_handle);
12311        }
12312
12313        self.remove_blocks(
12314            [rename.block_id].into_iter().collect(),
12315            Some(Autoscroll::fit()),
12316            cx,
12317        );
12318        self.clear_highlights::<Rename>(cx);
12319        self.show_local_selections = true;
12320
12321        if moving_cursor {
12322            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12323                editor.selections.newest::<usize>(cx).head()
12324            });
12325
12326            // Update the selection to match the position of the selection inside
12327            // the rename editor.
12328            let snapshot = self.buffer.read(cx).read(cx);
12329            let rename_range = rename.range.to_offset(&snapshot);
12330            let cursor_in_editor = snapshot
12331                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12332                .min(rename_range.end);
12333            drop(snapshot);
12334
12335            self.change_selections(None, window, cx, |s| {
12336                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12337            });
12338        } else {
12339            self.refresh_document_highlights(cx);
12340        }
12341
12342        Some(rename)
12343    }
12344
12345    pub fn pending_rename(&self) -> Option<&RenameState> {
12346        self.pending_rename.as_ref()
12347    }
12348
12349    fn format(
12350        &mut self,
12351        _: &Format,
12352        window: &mut Window,
12353        cx: &mut Context<Self>,
12354    ) -> Option<Task<Result<()>>> {
12355        let project = match &self.project {
12356            Some(project) => project.clone(),
12357            None => return None,
12358        };
12359
12360        Some(self.perform_format(
12361            project,
12362            FormatTrigger::Manual,
12363            FormatTarget::Buffers,
12364            window,
12365            cx,
12366        ))
12367    }
12368
12369    fn format_selections(
12370        &mut self,
12371        _: &FormatSelections,
12372        window: &mut Window,
12373        cx: &mut Context<Self>,
12374    ) -> Option<Task<Result<()>>> {
12375        let project = match &self.project {
12376            Some(project) => project.clone(),
12377            None => return None,
12378        };
12379
12380        let ranges = self
12381            .selections
12382            .all_adjusted(cx)
12383            .into_iter()
12384            .map(|selection| selection.range())
12385            .collect_vec();
12386
12387        Some(self.perform_format(
12388            project,
12389            FormatTrigger::Manual,
12390            FormatTarget::Ranges(ranges),
12391            window,
12392            cx,
12393        ))
12394    }
12395
12396    fn perform_format(
12397        &mut self,
12398        project: Entity<Project>,
12399        trigger: FormatTrigger,
12400        target: FormatTarget,
12401        window: &mut Window,
12402        cx: &mut Context<Self>,
12403    ) -> Task<Result<()>> {
12404        let buffer = self.buffer.clone();
12405        let (buffers, target) = match target {
12406            FormatTarget::Buffers => {
12407                let mut buffers = buffer.read(cx).all_buffers();
12408                if trigger == FormatTrigger::Save {
12409                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12410                }
12411                (buffers, LspFormatTarget::Buffers)
12412            }
12413            FormatTarget::Ranges(selection_ranges) => {
12414                let multi_buffer = buffer.read(cx);
12415                let snapshot = multi_buffer.read(cx);
12416                let mut buffers = HashSet::default();
12417                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12418                    BTreeMap::new();
12419                for selection_range in selection_ranges {
12420                    for (buffer, buffer_range, _) in
12421                        snapshot.range_to_buffer_ranges(selection_range)
12422                    {
12423                        let buffer_id = buffer.remote_id();
12424                        let start = buffer.anchor_before(buffer_range.start);
12425                        let end = buffer.anchor_after(buffer_range.end);
12426                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12427                        buffer_id_to_ranges
12428                            .entry(buffer_id)
12429                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12430                            .or_insert_with(|| vec![start..end]);
12431                    }
12432                }
12433                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12434            }
12435        };
12436
12437        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12438        let format = project.update(cx, |project, cx| {
12439            project.format(buffers, target, true, trigger, cx)
12440        });
12441
12442        cx.spawn_in(window, |_, mut cx| async move {
12443            let transaction = futures::select_biased! {
12444                () = timeout => {
12445                    log::warn!("timed out waiting for formatting");
12446                    None
12447                }
12448                transaction = format.log_err().fuse() => transaction,
12449            };
12450
12451            buffer
12452                .update(&mut cx, |buffer, cx| {
12453                    if let Some(transaction) = transaction {
12454                        if !buffer.is_singleton() {
12455                            buffer.push_transaction(&transaction.0, cx);
12456                        }
12457                    }
12458
12459                    cx.notify();
12460                })
12461                .ok();
12462
12463            Ok(())
12464        })
12465    }
12466
12467    fn restart_language_server(
12468        &mut self,
12469        _: &RestartLanguageServer,
12470        _: &mut Window,
12471        cx: &mut Context<Self>,
12472    ) {
12473        if let Some(project) = self.project.clone() {
12474            self.buffer.update(cx, |multi_buffer, cx| {
12475                project.update(cx, |project, cx| {
12476                    project.restart_language_servers_for_buffers(
12477                        multi_buffer.all_buffers().into_iter().collect(),
12478                        cx,
12479                    );
12480                });
12481            })
12482        }
12483    }
12484
12485    fn cancel_language_server_work(
12486        workspace: &mut Workspace,
12487        _: &actions::CancelLanguageServerWork,
12488        _: &mut Window,
12489        cx: &mut Context<Workspace>,
12490    ) {
12491        let project = workspace.project();
12492        let buffers = workspace
12493            .active_item(cx)
12494            .and_then(|item| item.act_as::<Editor>(cx))
12495            .map_or(HashSet::default(), |editor| {
12496                editor.read(cx).buffer.read(cx).all_buffers()
12497            });
12498        project.update(cx, |project, cx| {
12499            project.cancel_language_server_work_for_buffers(buffers, cx);
12500        });
12501    }
12502
12503    fn show_character_palette(
12504        &mut self,
12505        _: &ShowCharacterPalette,
12506        window: &mut Window,
12507        _: &mut Context<Self>,
12508    ) {
12509        window.show_character_palette();
12510    }
12511
12512    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12513        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12514            let buffer = self.buffer.read(cx).snapshot(cx);
12515            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12516            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12517            let is_valid = buffer
12518                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12519                .any(|entry| {
12520                    entry.diagnostic.is_primary
12521                        && !entry.range.is_empty()
12522                        && entry.range.start == primary_range_start
12523                        && entry.diagnostic.message == active_diagnostics.primary_message
12524                });
12525
12526            if is_valid != active_diagnostics.is_valid {
12527                active_diagnostics.is_valid = is_valid;
12528                let mut new_styles = HashMap::default();
12529                for (block_id, diagnostic) in &active_diagnostics.blocks {
12530                    new_styles.insert(
12531                        *block_id,
12532                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12533                    );
12534                }
12535                self.display_map.update(cx, |display_map, _cx| {
12536                    display_map.replace_blocks(new_styles)
12537                });
12538            }
12539        }
12540    }
12541
12542    fn activate_diagnostics(
12543        &mut self,
12544        buffer_id: BufferId,
12545        group_id: usize,
12546        window: &mut Window,
12547        cx: &mut Context<Self>,
12548    ) {
12549        self.dismiss_diagnostics(cx);
12550        let snapshot = self.snapshot(window, cx);
12551        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12552            let buffer = self.buffer.read(cx).snapshot(cx);
12553
12554            let mut primary_range = None;
12555            let mut primary_message = None;
12556            let diagnostic_group = buffer
12557                .diagnostic_group(buffer_id, group_id)
12558                .filter_map(|entry| {
12559                    let start = entry.range.start;
12560                    let end = entry.range.end;
12561                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12562                        && (start.row == end.row
12563                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12564                    {
12565                        return None;
12566                    }
12567                    if entry.diagnostic.is_primary {
12568                        primary_range = Some(entry.range.clone());
12569                        primary_message = Some(entry.diagnostic.message.clone());
12570                    }
12571                    Some(entry)
12572                })
12573                .collect::<Vec<_>>();
12574            let primary_range = primary_range?;
12575            let primary_message = primary_message?;
12576
12577            let blocks = display_map
12578                .insert_blocks(
12579                    diagnostic_group.iter().map(|entry| {
12580                        let diagnostic = entry.diagnostic.clone();
12581                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12582                        BlockProperties {
12583                            style: BlockStyle::Fixed,
12584                            placement: BlockPlacement::Below(
12585                                buffer.anchor_after(entry.range.start),
12586                            ),
12587                            height: message_height,
12588                            render: diagnostic_block_renderer(diagnostic, None, true, true),
12589                            priority: 0,
12590                        }
12591                    }),
12592                    cx,
12593                )
12594                .into_iter()
12595                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12596                .collect();
12597
12598            Some(ActiveDiagnosticGroup {
12599                primary_range: buffer.anchor_before(primary_range.start)
12600                    ..buffer.anchor_after(primary_range.end),
12601                primary_message,
12602                group_id,
12603                blocks,
12604                is_valid: true,
12605            })
12606        });
12607    }
12608
12609    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12610        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12611            self.display_map.update(cx, |display_map, cx| {
12612                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12613            });
12614            cx.notify();
12615        }
12616    }
12617
12618    /// Disable inline diagnostics rendering for this editor.
12619    pub fn disable_inline_diagnostics(&mut self) {
12620        self.inline_diagnostics_enabled = false;
12621        self.inline_diagnostics_update = Task::ready(());
12622        self.inline_diagnostics.clear();
12623    }
12624
12625    pub fn inline_diagnostics_enabled(&self) -> bool {
12626        self.inline_diagnostics_enabled
12627    }
12628
12629    pub fn show_inline_diagnostics(&self) -> bool {
12630        self.show_inline_diagnostics
12631    }
12632
12633    pub fn toggle_inline_diagnostics(
12634        &mut self,
12635        _: &ToggleInlineDiagnostics,
12636        window: &mut Window,
12637        cx: &mut Context<'_, Editor>,
12638    ) {
12639        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12640        self.refresh_inline_diagnostics(false, window, cx);
12641    }
12642
12643    fn refresh_inline_diagnostics(
12644        &mut self,
12645        debounce: bool,
12646        window: &mut Window,
12647        cx: &mut Context<Self>,
12648    ) {
12649        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12650            self.inline_diagnostics_update = Task::ready(());
12651            self.inline_diagnostics.clear();
12652            return;
12653        }
12654
12655        let debounce_ms = ProjectSettings::get_global(cx)
12656            .diagnostics
12657            .inline
12658            .update_debounce_ms;
12659        let debounce = if debounce && debounce_ms > 0 {
12660            Some(Duration::from_millis(debounce_ms))
12661        } else {
12662            None
12663        };
12664        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12665            if let Some(debounce) = debounce {
12666                cx.background_executor().timer(debounce).await;
12667            }
12668            let Some(snapshot) = editor
12669                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12670                .ok()
12671            else {
12672                return;
12673            };
12674
12675            let new_inline_diagnostics = cx
12676                .background_spawn(async move {
12677                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12678                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12679                        let message = diagnostic_entry
12680                            .diagnostic
12681                            .message
12682                            .split_once('\n')
12683                            .map(|(line, _)| line)
12684                            .map(SharedString::new)
12685                            .unwrap_or_else(|| {
12686                                SharedString::from(diagnostic_entry.diagnostic.message)
12687                            });
12688                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12689                        let (Ok(i) | Err(i)) = inline_diagnostics
12690                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12691                        inline_diagnostics.insert(
12692                            i,
12693                            (
12694                                start_anchor,
12695                                InlineDiagnostic {
12696                                    message,
12697                                    group_id: diagnostic_entry.diagnostic.group_id,
12698                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12699                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12700                                    severity: diagnostic_entry.diagnostic.severity,
12701                                },
12702                            ),
12703                        );
12704                    }
12705                    inline_diagnostics
12706                })
12707                .await;
12708
12709            editor
12710                .update(&mut cx, |editor, cx| {
12711                    editor.inline_diagnostics = new_inline_diagnostics;
12712                    cx.notify();
12713                })
12714                .ok();
12715        });
12716    }
12717
12718    pub fn set_selections_from_remote(
12719        &mut self,
12720        selections: Vec<Selection<Anchor>>,
12721        pending_selection: Option<Selection<Anchor>>,
12722        window: &mut Window,
12723        cx: &mut Context<Self>,
12724    ) {
12725        let old_cursor_position = self.selections.newest_anchor().head();
12726        self.selections.change_with(cx, |s| {
12727            s.select_anchors(selections);
12728            if let Some(pending_selection) = pending_selection {
12729                s.set_pending(pending_selection, SelectMode::Character);
12730            } else {
12731                s.clear_pending();
12732            }
12733        });
12734        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12735    }
12736
12737    fn push_to_selection_history(&mut self) {
12738        self.selection_history.push(SelectionHistoryEntry {
12739            selections: self.selections.disjoint_anchors(),
12740            select_next_state: self.select_next_state.clone(),
12741            select_prev_state: self.select_prev_state.clone(),
12742            add_selections_state: self.add_selections_state.clone(),
12743        });
12744    }
12745
12746    pub fn transact(
12747        &mut self,
12748        window: &mut Window,
12749        cx: &mut Context<Self>,
12750        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12751    ) -> Option<TransactionId> {
12752        self.start_transaction_at(Instant::now(), window, cx);
12753        update(self, window, cx);
12754        self.end_transaction_at(Instant::now(), cx)
12755    }
12756
12757    pub fn start_transaction_at(
12758        &mut self,
12759        now: Instant,
12760        window: &mut Window,
12761        cx: &mut Context<Self>,
12762    ) {
12763        self.end_selection(window, cx);
12764        if let Some(tx_id) = self
12765            .buffer
12766            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12767        {
12768            self.selection_history
12769                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12770            cx.emit(EditorEvent::TransactionBegun {
12771                transaction_id: tx_id,
12772            })
12773        }
12774    }
12775
12776    pub fn end_transaction_at(
12777        &mut self,
12778        now: Instant,
12779        cx: &mut Context<Self>,
12780    ) -> Option<TransactionId> {
12781        if let Some(transaction_id) = self
12782            .buffer
12783            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12784        {
12785            if let Some((_, end_selections)) =
12786                self.selection_history.transaction_mut(transaction_id)
12787            {
12788                *end_selections = Some(self.selections.disjoint_anchors());
12789            } else {
12790                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12791            }
12792
12793            cx.emit(EditorEvent::Edited { transaction_id });
12794            Some(transaction_id)
12795        } else {
12796            None
12797        }
12798    }
12799
12800    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12801        if self.selection_mark_mode {
12802            self.change_selections(None, window, cx, |s| {
12803                s.move_with(|_, sel| {
12804                    sel.collapse_to(sel.head(), SelectionGoal::None);
12805                });
12806            })
12807        }
12808        self.selection_mark_mode = true;
12809        cx.notify();
12810    }
12811
12812    pub fn swap_selection_ends(
12813        &mut self,
12814        _: &actions::SwapSelectionEnds,
12815        window: &mut Window,
12816        cx: &mut Context<Self>,
12817    ) {
12818        self.change_selections(None, window, cx, |s| {
12819            s.move_with(|_, sel| {
12820                if sel.start != sel.end {
12821                    sel.reversed = !sel.reversed
12822                }
12823            });
12824        });
12825        self.request_autoscroll(Autoscroll::newest(), cx);
12826        cx.notify();
12827    }
12828
12829    pub fn toggle_fold(
12830        &mut self,
12831        _: &actions::ToggleFold,
12832        window: &mut Window,
12833        cx: &mut Context<Self>,
12834    ) {
12835        if self.is_singleton(cx) {
12836            let selection = self.selections.newest::<Point>(cx);
12837
12838            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12839            let range = if selection.is_empty() {
12840                let point = selection.head().to_display_point(&display_map);
12841                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12842                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12843                    .to_point(&display_map);
12844                start..end
12845            } else {
12846                selection.range()
12847            };
12848            if display_map.folds_in_range(range).next().is_some() {
12849                self.unfold_lines(&Default::default(), window, cx)
12850            } else {
12851                self.fold(&Default::default(), window, cx)
12852            }
12853        } else {
12854            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12855            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12856                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12857                .map(|(snapshot, _, _)| snapshot.remote_id())
12858                .collect();
12859
12860            for buffer_id in buffer_ids {
12861                if self.is_buffer_folded(buffer_id, cx) {
12862                    self.unfold_buffer(buffer_id, cx);
12863                } else {
12864                    self.fold_buffer(buffer_id, cx);
12865                }
12866            }
12867        }
12868    }
12869
12870    pub fn toggle_fold_recursive(
12871        &mut self,
12872        _: &actions::ToggleFoldRecursive,
12873        window: &mut Window,
12874        cx: &mut Context<Self>,
12875    ) {
12876        let selection = self.selections.newest::<Point>(cx);
12877
12878        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12879        let range = if selection.is_empty() {
12880            let point = selection.head().to_display_point(&display_map);
12881            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12882            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12883                .to_point(&display_map);
12884            start..end
12885        } else {
12886            selection.range()
12887        };
12888        if display_map.folds_in_range(range).next().is_some() {
12889            self.unfold_recursive(&Default::default(), window, cx)
12890        } else {
12891            self.fold_recursive(&Default::default(), window, cx)
12892        }
12893    }
12894
12895    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12896        if self.is_singleton(cx) {
12897            let mut to_fold = Vec::new();
12898            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12899            let selections = self.selections.all_adjusted(cx);
12900
12901            for selection in selections {
12902                let range = selection.range().sorted();
12903                let buffer_start_row = range.start.row;
12904
12905                if range.start.row != range.end.row {
12906                    let mut found = false;
12907                    let mut row = range.start.row;
12908                    while row <= range.end.row {
12909                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12910                        {
12911                            found = true;
12912                            row = crease.range().end.row + 1;
12913                            to_fold.push(crease);
12914                        } else {
12915                            row += 1
12916                        }
12917                    }
12918                    if found {
12919                        continue;
12920                    }
12921                }
12922
12923                for row in (0..=range.start.row).rev() {
12924                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12925                        if crease.range().end.row >= buffer_start_row {
12926                            to_fold.push(crease);
12927                            if row <= range.start.row {
12928                                break;
12929                            }
12930                        }
12931                    }
12932                }
12933            }
12934
12935            self.fold_creases(to_fold, true, window, cx);
12936        } else {
12937            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12938
12939            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12940                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12941                .map(|(snapshot, _, _)| snapshot.remote_id())
12942                .collect();
12943            for buffer_id in buffer_ids {
12944                self.fold_buffer(buffer_id, cx);
12945            }
12946        }
12947    }
12948
12949    fn fold_at_level(
12950        &mut self,
12951        fold_at: &FoldAtLevel,
12952        window: &mut Window,
12953        cx: &mut Context<Self>,
12954    ) {
12955        if !self.buffer.read(cx).is_singleton() {
12956            return;
12957        }
12958
12959        let fold_at_level = fold_at.0;
12960        let snapshot = self.buffer.read(cx).snapshot(cx);
12961        let mut to_fold = Vec::new();
12962        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12963
12964        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12965            while start_row < end_row {
12966                match self
12967                    .snapshot(window, cx)
12968                    .crease_for_buffer_row(MultiBufferRow(start_row))
12969                {
12970                    Some(crease) => {
12971                        let nested_start_row = crease.range().start.row + 1;
12972                        let nested_end_row = crease.range().end.row;
12973
12974                        if current_level < fold_at_level {
12975                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12976                        } else if current_level == fold_at_level {
12977                            to_fold.push(crease);
12978                        }
12979
12980                        start_row = nested_end_row + 1;
12981                    }
12982                    None => start_row += 1,
12983                }
12984            }
12985        }
12986
12987        self.fold_creases(to_fold, true, window, cx);
12988    }
12989
12990    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12991        if self.buffer.read(cx).is_singleton() {
12992            let mut fold_ranges = Vec::new();
12993            let snapshot = self.buffer.read(cx).snapshot(cx);
12994
12995            for row in 0..snapshot.max_row().0 {
12996                if let Some(foldable_range) = self
12997                    .snapshot(window, cx)
12998                    .crease_for_buffer_row(MultiBufferRow(row))
12999                {
13000                    fold_ranges.push(foldable_range);
13001                }
13002            }
13003
13004            self.fold_creases(fold_ranges, true, window, cx);
13005        } else {
13006            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13007                editor
13008                    .update_in(&mut cx, |editor, _, cx| {
13009                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13010                            editor.fold_buffer(buffer_id, cx);
13011                        }
13012                    })
13013                    .ok();
13014            });
13015        }
13016    }
13017
13018    pub fn fold_function_bodies(
13019        &mut self,
13020        _: &actions::FoldFunctionBodies,
13021        window: &mut Window,
13022        cx: &mut Context<Self>,
13023    ) {
13024        let snapshot = self.buffer.read(cx).snapshot(cx);
13025
13026        let ranges = snapshot
13027            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13028            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13029            .collect::<Vec<_>>();
13030
13031        let creases = ranges
13032            .into_iter()
13033            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13034            .collect();
13035
13036        self.fold_creases(creases, true, window, cx);
13037    }
13038
13039    pub fn fold_recursive(
13040        &mut self,
13041        _: &actions::FoldRecursive,
13042        window: &mut Window,
13043        cx: &mut Context<Self>,
13044    ) {
13045        let mut to_fold = Vec::new();
13046        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13047        let selections = self.selections.all_adjusted(cx);
13048
13049        for selection in selections {
13050            let range = selection.range().sorted();
13051            let buffer_start_row = range.start.row;
13052
13053            if range.start.row != range.end.row {
13054                let mut found = false;
13055                for row in range.start.row..=range.end.row {
13056                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13057                        found = true;
13058                        to_fold.push(crease);
13059                    }
13060                }
13061                if found {
13062                    continue;
13063                }
13064            }
13065
13066            for row in (0..=range.start.row).rev() {
13067                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13068                    if crease.range().end.row >= buffer_start_row {
13069                        to_fold.push(crease);
13070                    } else {
13071                        break;
13072                    }
13073                }
13074            }
13075        }
13076
13077        self.fold_creases(to_fold, true, window, cx);
13078    }
13079
13080    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13081        let buffer_row = fold_at.buffer_row;
13082        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13083
13084        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13085            let autoscroll = self
13086                .selections
13087                .all::<Point>(cx)
13088                .iter()
13089                .any(|selection| crease.range().overlaps(&selection.range()));
13090
13091            self.fold_creases(vec![crease], autoscroll, window, cx);
13092        }
13093    }
13094
13095    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13096        if self.is_singleton(cx) {
13097            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13098            let buffer = &display_map.buffer_snapshot;
13099            let selections = self.selections.all::<Point>(cx);
13100            let ranges = selections
13101                .iter()
13102                .map(|s| {
13103                    let range = s.display_range(&display_map).sorted();
13104                    let mut start = range.start.to_point(&display_map);
13105                    let mut end = range.end.to_point(&display_map);
13106                    start.column = 0;
13107                    end.column = buffer.line_len(MultiBufferRow(end.row));
13108                    start..end
13109                })
13110                .collect::<Vec<_>>();
13111
13112            self.unfold_ranges(&ranges, true, true, cx);
13113        } else {
13114            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13115            let buffer_ids: HashSet<_> = multi_buffer_snapshot
13116                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13117                .map(|(snapshot, _, _)| snapshot.remote_id())
13118                .collect();
13119            for buffer_id in buffer_ids {
13120                self.unfold_buffer(buffer_id, cx);
13121            }
13122        }
13123    }
13124
13125    pub fn unfold_recursive(
13126        &mut self,
13127        _: &UnfoldRecursive,
13128        _window: &mut Window,
13129        cx: &mut Context<Self>,
13130    ) {
13131        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13132        let selections = self.selections.all::<Point>(cx);
13133        let ranges = selections
13134            .iter()
13135            .map(|s| {
13136                let mut range = s.display_range(&display_map).sorted();
13137                *range.start.column_mut() = 0;
13138                *range.end.column_mut() = display_map.line_len(range.end.row());
13139                let start = range.start.to_point(&display_map);
13140                let end = range.end.to_point(&display_map);
13141                start..end
13142            })
13143            .collect::<Vec<_>>();
13144
13145        self.unfold_ranges(&ranges, true, true, cx);
13146    }
13147
13148    pub fn unfold_at(
13149        &mut self,
13150        unfold_at: &UnfoldAt,
13151        _window: &mut Window,
13152        cx: &mut Context<Self>,
13153    ) {
13154        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13155
13156        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13157            ..Point::new(
13158                unfold_at.buffer_row.0,
13159                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13160            );
13161
13162        let autoscroll = self
13163            .selections
13164            .all::<Point>(cx)
13165            .iter()
13166            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13167
13168        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13169    }
13170
13171    pub fn unfold_all(
13172        &mut self,
13173        _: &actions::UnfoldAll,
13174        _window: &mut Window,
13175        cx: &mut Context<Self>,
13176    ) {
13177        if self.buffer.read(cx).is_singleton() {
13178            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13179            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13180        } else {
13181            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13182                editor
13183                    .update(&mut cx, |editor, cx| {
13184                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13185                            editor.unfold_buffer(buffer_id, cx);
13186                        }
13187                    })
13188                    .ok();
13189            });
13190        }
13191    }
13192
13193    pub fn fold_selected_ranges(
13194        &mut self,
13195        _: &FoldSelectedRanges,
13196        window: &mut Window,
13197        cx: &mut Context<Self>,
13198    ) {
13199        let selections = self.selections.all::<Point>(cx);
13200        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13201        let line_mode = self.selections.line_mode;
13202        let ranges = selections
13203            .into_iter()
13204            .map(|s| {
13205                if line_mode {
13206                    let start = Point::new(s.start.row, 0);
13207                    let end = Point::new(
13208                        s.end.row,
13209                        display_map
13210                            .buffer_snapshot
13211                            .line_len(MultiBufferRow(s.end.row)),
13212                    );
13213                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13214                } else {
13215                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13216                }
13217            })
13218            .collect::<Vec<_>>();
13219        self.fold_creases(ranges, true, window, cx);
13220    }
13221
13222    pub fn fold_ranges<T: ToOffset + Clone>(
13223        &mut self,
13224        ranges: Vec<Range<T>>,
13225        auto_scroll: bool,
13226        window: &mut Window,
13227        cx: &mut Context<Self>,
13228    ) {
13229        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13230        let ranges = ranges
13231            .into_iter()
13232            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13233            .collect::<Vec<_>>();
13234        self.fold_creases(ranges, auto_scroll, window, cx);
13235    }
13236
13237    pub fn fold_creases<T: ToOffset + Clone>(
13238        &mut self,
13239        creases: Vec<Crease<T>>,
13240        auto_scroll: bool,
13241        window: &mut Window,
13242        cx: &mut Context<Self>,
13243    ) {
13244        if creases.is_empty() {
13245            return;
13246        }
13247
13248        let mut buffers_affected = HashSet::default();
13249        let multi_buffer = self.buffer().read(cx);
13250        for crease in &creases {
13251            if let Some((_, buffer, _)) =
13252                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13253            {
13254                buffers_affected.insert(buffer.read(cx).remote_id());
13255            };
13256        }
13257
13258        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13259
13260        if auto_scroll {
13261            self.request_autoscroll(Autoscroll::fit(), cx);
13262        }
13263
13264        cx.notify();
13265
13266        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13267            // Clear diagnostics block when folding a range that contains it.
13268            let snapshot = self.snapshot(window, cx);
13269            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13270                drop(snapshot);
13271                self.active_diagnostics = Some(active_diagnostics);
13272                self.dismiss_diagnostics(cx);
13273            } else {
13274                self.active_diagnostics = Some(active_diagnostics);
13275            }
13276        }
13277
13278        self.scrollbar_marker_state.dirty = true;
13279    }
13280
13281    /// Removes any folds whose ranges intersect any of the given ranges.
13282    pub fn unfold_ranges<T: ToOffset + Clone>(
13283        &mut self,
13284        ranges: &[Range<T>],
13285        inclusive: bool,
13286        auto_scroll: bool,
13287        cx: &mut Context<Self>,
13288    ) {
13289        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13290            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13291        });
13292    }
13293
13294    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13295        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13296            return;
13297        }
13298        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13299        self.display_map
13300            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13301        cx.emit(EditorEvent::BufferFoldToggled {
13302            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13303            folded: true,
13304        });
13305        cx.notify();
13306    }
13307
13308    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13309        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13310            return;
13311        }
13312        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13313        self.display_map.update(cx, |display_map, cx| {
13314            display_map.unfold_buffer(buffer_id, cx);
13315        });
13316        cx.emit(EditorEvent::BufferFoldToggled {
13317            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13318            folded: false,
13319        });
13320        cx.notify();
13321    }
13322
13323    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13324        self.display_map.read(cx).is_buffer_folded(buffer)
13325    }
13326
13327    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13328        self.display_map.read(cx).folded_buffers()
13329    }
13330
13331    /// Removes any folds with the given ranges.
13332    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13333        &mut self,
13334        ranges: &[Range<T>],
13335        type_id: TypeId,
13336        auto_scroll: bool,
13337        cx: &mut Context<Self>,
13338    ) {
13339        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13340            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13341        });
13342    }
13343
13344    fn remove_folds_with<T: ToOffset + Clone>(
13345        &mut self,
13346        ranges: &[Range<T>],
13347        auto_scroll: bool,
13348        cx: &mut Context<Self>,
13349        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13350    ) {
13351        if ranges.is_empty() {
13352            return;
13353        }
13354
13355        let mut buffers_affected = HashSet::default();
13356        let multi_buffer = self.buffer().read(cx);
13357        for range in ranges {
13358            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13359                buffers_affected.insert(buffer.read(cx).remote_id());
13360            };
13361        }
13362
13363        self.display_map.update(cx, update);
13364
13365        if auto_scroll {
13366            self.request_autoscroll(Autoscroll::fit(), cx);
13367        }
13368
13369        cx.notify();
13370        self.scrollbar_marker_state.dirty = true;
13371        self.active_indent_guides_state.dirty = true;
13372    }
13373
13374    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13375        self.display_map.read(cx).fold_placeholder.clone()
13376    }
13377
13378    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13379        self.buffer.update(cx, |buffer, cx| {
13380            buffer.set_all_diff_hunks_expanded(cx);
13381        });
13382    }
13383
13384    pub fn expand_all_diff_hunks(
13385        &mut self,
13386        _: &ExpandAllDiffHunks,
13387        _window: &mut Window,
13388        cx: &mut Context<Self>,
13389    ) {
13390        self.buffer.update(cx, |buffer, cx| {
13391            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13392        });
13393    }
13394
13395    pub fn toggle_selected_diff_hunks(
13396        &mut self,
13397        _: &ToggleSelectedDiffHunks,
13398        _window: &mut Window,
13399        cx: &mut Context<Self>,
13400    ) {
13401        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13402        self.toggle_diff_hunks_in_ranges(ranges, cx);
13403    }
13404
13405    pub fn diff_hunks_in_ranges<'a>(
13406        &'a self,
13407        ranges: &'a [Range<Anchor>],
13408        buffer: &'a MultiBufferSnapshot,
13409    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13410        ranges.iter().flat_map(move |range| {
13411            let end_excerpt_id = range.end.excerpt_id;
13412            let range = range.to_point(buffer);
13413            let mut peek_end = range.end;
13414            if range.end.row < buffer.max_row().0 {
13415                peek_end = Point::new(range.end.row + 1, 0);
13416            }
13417            buffer
13418                .diff_hunks_in_range(range.start..peek_end)
13419                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13420        })
13421    }
13422
13423    pub fn has_stageable_diff_hunks_in_ranges(
13424        &self,
13425        ranges: &[Range<Anchor>],
13426        snapshot: &MultiBufferSnapshot,
13427    ) -> bool {
13428        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13429        hunks.any(|hunk| hunk.secondary_status != DiffHunkSecondaryStatus::None)
13430    }
13431
13432    pub fn toggle_staged_selected_diff_hunks(
13433        &mut self,
13434        _: &::git::ToggleStaged,
13435        window: &mut Window,
13436        cx: &mut Context<Self>,
13437    ) {
13438        let snapshot = self.buffer.read(cx).snapshot(cx);
13439        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13440        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13441        self.stage_or_unstage_diff_hunks(stage, &ranges, window, cx);
13442    }
13443
13444    pub fn stage_and_next(
13445        &mut self,
13446        _: &::git::StageAndNext,
13447        window: &mut Window,
13448        cx: &mut Context<Self>,
13449    ) {
13450        self.do_stage_or_unstage_and_next(true, window, cx);
13451    }
13452
13453    pub fn unstage_and_next(
13454        &mut self,
13455        _: &::git::UnstageAndNext,
13456        window: &mut Window,
13457        cx: &mut Context<Self>,
13458    ) {
13459        self.do_stage_or_unstage_and_next(false, window, cx);
13460    }
13461
13462    pub fn stage_or_unstage_diff_hunks(
13463        &mut self,
13464        stage: bool,
13465        ranges: &[Range<Anchor>],
13466        window: &mut Window,
13467        cx: &mut Context<Self>,
13468    ) {
13469        let snapshot = self.buffer.read(cx).snapshot(cx);
13470        let Some(project) = &self.project else {
13471            return;
13472        };
13473
13474        let chunk_by = self
13475            .diff_hunks_in_ranges(&ranges, &snapshot)
13476            .chunk_by(|hunk| hunk.buffer_id);
13477        for (buffer_id, hunks) in &chunk_by {
13478            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, window, cx);
13479        }
13480    }
13481
13482    fn do_stage_or_unstage_and_next(
13483        &mut self,
13484        stage: bool,
13485        window: &mut Window,
13486        cx: &mut Context<Self>,
13487    ) {
13488        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13489        if ranges.iter().any(|range| range.start != range.end) {
13490            self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13491            return;
13492        }
13493
13494        if !self.buffer().read(cx).is_singleton() {
13495            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13496                if buffer.read(cx).is_empty() {
13497                    let buffer = buffer.read(cx);
13498                    let Some(file) = buffer.file() else {
13499                        return;
13500                    };
13501                    let project_path = project::ProjectPath {
13502                        worktree_id: file.worktree_id(cx),
13503                        path: file.path().clone(),
13504                    };
13505                    let Some(project) = self.project.as_ref() else {
13506                        return;
13507                    };
13508                    let project = project.read(cx);
13509
13510                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13511                        return;
13512                    };
13513
13514                    repo.update(cx, |repo, cx| {
13515                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13516                            return;
13517                        };
13518                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13519                            return;
13520                        };
13521                        if stage && status.status == FileStatus::Untracked {
13522                            repo.stage_entries(vec![repo_path], cx)
13523                                .detach_and_log_err(cx);
13524                            return;
13525                        }
13526                    })
13527                }
13528                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13529                    excerpt_id,
13530                    buffer.read(cx).remote_id(),
13531                    range,
13532                )];
13533                self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13534                let snapshot = self.buffer().read(cx).snapshot(cx);
13535                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13536                if point.row < snapshot.max_row().0 {
13537                    point.row += 1;
13538                    point.column = 0;
13539                    point = snapshot.clip_point(point, Bias::Right);
13540                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13541                        s.select_ranges([point..point]);
13542                    })
13543                }
13544                return;
13545            }
13546        }
13547        self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13548        self.go_to_next_hunk(&Default::default(), window, cx);
13549    }
13550
13551    fn do_stage_or_unstage(
13552        project: &Entity<Project>,
13553        stage: bool,
13554        buffer_id: BufferId,
13555        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13556        snapshot: &MultiBufferSnapshot,
13557        window: &mut Window,
13558        cx: &mut App,
13559    ) {
13560        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13561            log::debug!("no buffer for id");
13562            return;
13563        };
13564        let buffer_snapshot = buffer.read(cx).snapshot();
13565        let file_exists = buffer_snapshot
13566            .file()
13567            .is_some_and(|file| file.disk_state().exists());
13568        let Some((repo, path)) = project
13569            .read(cx)
13570            .repository_and_path_for_buffer_id(buffer_id, cx)
13571        else {
13572            log::debug!("no git repo for buffer id");
13573            return;
13574        };
13575        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13576            log::debug!("no diff for buffer id");
13577            return;
13578        };
13579
13580        let new_index_text = if !stage && diff.is_single_insertion || stage && !file_exists {
13581            log::debug!("removing from index");
13582            None
13583        } else {
13584            diff.new_secondary_text_for_stage_or_unstage(
13585                stage,
13586                hunks.filter_map(|hunk| {
13587                    if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13588                        return None;
13589                    } else if !stage
13590                        && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13591                    {
13592                        return None;
13593                    }
13594                    Some((hunk.buffer_range.clone(), hunk.diff_base_byte_range.clone()))
13595                }),
13596                &buffer_snapshot,
13597                cx,
13598            )
13599        };
13600        if file_exists {
13601            let buffer_store = project.read(cx).buffer_store().clone();
13602            buffer_store
13603                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13604                .detach_and_log_err(cx);
13605        }
13606        let recv = repo
13607            .read(cx)
13608            .set_index_text(&path, new_index_text.map(|rope| rope.to_string()));
13609
13610        cx.background_spawn(async move { recv.await? })
13611            .detach_and_notify_err(window, cx);
13612    }
13613
13614    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13615        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13616        self.buffer
13617            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13618    }
13619
13620    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13621        self.buffer.update(cx, |buffer, cx| {
13622            let ranges = vec![Anchor::min()..Anchor::max()];
13623            if !buffer.all_diff_hunks_expanded()
13624                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13625            {
13626                buffer.collapse_diff_hunks(ranges, cx);
13627                true
13628            } else {
13629                false
13630            }
13631        })
13632    }
13633
13634    fn toggle_diff_hunks_in_ranges(
13635        &mut self,
13636        ranges: Vec<Range<Anchor>>,
13637        cx: &mut Context<'_, Editor>,
13638    ) {
13639        self.buffer.update(cx, |buffer, cx| {
13640            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13641            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13642        })
13643    }
13644
13645    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13646        self.buffer.update(cx, |buffer, cx| {
13647            let snapshot = buffer.snapshot(cx);
13648            let excerpt_id = range.end.excerpt_id;
13649            let point_range = range.to_point(&snapshot);
13650            let expand = !buffer.single_hunk_is_expanded(range, cx);
13651            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13652        })
13653    }
13654
13655    pub(crate) fn apply_all_diff_hunks(
13656        &mut self,
13657        _: &ApplyAllDiffHunks,
13658        window: &mut Window,
13659        cx: &mut Context<Self>,
13660    ) {
13661        let buffers = self.buffer.read(cx).all_buffers();
13662        for branch_buffer in buffers {
13663            branch_buffer.update(cx, |branch_buffer, cx| {
13664                branch_buffer.merge_into_base(Vec::new(), cx);
13665            });
13666        }
13667
13668        if let Some(project) = self.project.clone() {
13669            self.save(true, project, window, cx).detach_and_log_err(cx);
13670        }
13671    }
13672
13673    pub(crate) fn apply_selected_diff_hunks(
13674        &mut self,
13675        _: &ApplyDiffHunk,
13676        window: &mut Window,
13677        cx: &mut Context<Self>,
13678    ) {
13679        let snapshot = self.snapshot(window, cx);
13680        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13681        let mut ranges_by_buffer = HashMap::default();
13682        self.transact(window, cx, |editor, _window, cx| {
13683            for hunk in hunks {
13684                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13685                    ranges_by_buffer
13686                        .entry(buffer.clone())
13687                        .or_insert_with(Vec::new)
13688                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13689                }
13690            }
13691
13692            for (buffer, ranges) in ranges_by_buffer {
13693                buffer.update(cx, |buffer, cx| {
13694                    buffer.merge_into_base(ranges, cx);
13695                });
13696            }
13697        });
13698
13699        if let Some(project) = self.project.clone() {
13700            self.save(true, project, window, cx).detach_and_log_err(cx);
13701        }
13702    }
13703
13704    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13705        if hovered != self.gutter_hovered {
13706            self.gutter_hovered = hovered;
13707            cx.notify();
13708        }
13709    }
13710
13711    pub fn insert_blocks(
13712        &mut self,
13713        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13714        autoscroll: Option<Autoscroll>,
13715        cx: &mut Context<Self>,
13716    ) -> Vec<CustomBlockId> {
13717        let blocks = self
13718            .display_map
13719            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13720        if let Some(autoscroll) = autoscroll {
13721            self.request_autoscroll(autoscroll, cx);
13722        }
13723        cx.notify();
13724        blocks
13725    }
13726
13727    pub fn resize_blocks(
13728        &mut self,
13729        heights: HashMap<CustomBlockId, u32>,
13730        autoscroll: Option<Autoscroll>,
13731        cx: &mut Context<Self>,
13732    ) {
13733        self.display_map
13734            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13735        if let Some(autoscroll) = autoscroll {
13736            self.request_autoscroll(autoscroll, cx);
13737        }
13738        cx.notify();
13739    }
13740
13741    pub fn replace_blocks(
13742        &mut self,
13743        renderers: HashMap<CustomBlockId, RenderBlock>,
13744        autoscroll: Option<Autoscroll>,
13745        cx: &mut Context<Self>,
13746    ) {
13747        self.display_map
13748            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13749        if let Some(autoscroll) = autoscroll {
13750            self.request_autoscroll(autoscroll, cx);
13751        }
13752        cx.notify();
13753    }
13754
13755    pub fn remove_blocks(
13756        &mut self,
13757        block_ids: HashSet<CustomBlockId>,
13758        autoscroll: Option<Autoscroll>,
13759        cx: &mut Context<Self>,
13760    ) {
13761        self.display_map.update(cx, |display_map, cx| {
13762            display_map.remove_blocks(block_ids, cx)
13763        });
13764        if let Some(autoscroll) = autoscroll {
13765            self.request_autoscroll(autoscroll, cx);
13766        }
13767        cx.notify();
13768    }
13769
13770    pub fn row_for_block(
13771        &self,
13772        block_id: CustomBlockId,
13773        cx: &mut Context<Self>,
13774    ) -> Option<DisplayRow> {
13775        self.display_map
13776            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13777    }
13778
13779    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13780        self.focused_block = Some(focused_block);
13781    }
13782
13783    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13784        self.focused_block.take()
13785    }
13786
13787    pub fn insert_creases(
13788        &mut self,
13789        creases: impl IntoIterator<Item = Crease<Anchor>>,
13790        cx: &mut Context<Self>,
13791    ) -> Vec<CreaseId> {
13792        self.display_map
13793            .update(cx, |map, cx| map.insert_creases(creases, cx))
13794    }
13795
13796    pub fn remove_creases(
13797        &mut self,
13798        ids: impl IntoIterator<Item = CreaseId>,
13799        cx: &mut Context<Self>,
13800    ) {
13801        self.display_map
13802            .update(cx, |map, cx| map.remove_creases(ids, cx));
13803    }
13804
13805    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13806        self.display_map
13807            .update(cx, |map, cx| map.snapshot(cx))
13808            .longest_row()
13809    }
13810
13811    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13812        self.display_map
13813            .update(cx, |map, cx| map.snapshot(cx))
13814            .max_point()
13815    }
13816
13817    pub fn text(&self, cx: &App) -> String {
13818        self.buffer.read(cx).read(cx).text()
13819    }
13820
13821    pub fn is_empty(&self, cx: &App) -> bool {
13822        self.buffer.read(cx).read(cx).is_empty()
13823    }
13824
13825    pub fn text_option(&self, cx: &App) -> Option<String> {
13826        let text = self.text(cx);
13827        let text = text.trim();
13828
13829        if text.is_empty() {
13830            return None;
13831        }
13832
13833        Some(text.to_string())
13834    }
13835
13836    pub fn set_text(
13837        &mut self,
13838        text: impl Into<Arc<str>>,
13839        window: &mut Window,
13840        cx: &mut Context<Self>,
13841    ) {
13842        self.transact(window, cx, |this, _, cx| {
13843            this.buffer
13844                .read(cx)
13845                .as_singleton()
13846                .expect("you can only call set_text on editors for singleton buffers")
13847                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13848        });
13849    }
13850
13851    pub fn display_text(&self, cx: &mut App) -> String {
13852        self.display_map
13853            .update(cx, |map, cx| map.snapshot(cx))
13854            .text()
13855    }
13856
13857    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13858        let mut wrap_guides = smallvec::smallvec![];
13859
13860        if self.show_wrap_guides == Some(false) {
13861            return wrap_guides;
13862        }
13863
13864        let settings = self.buffer.read(cx).settings_at(0, cx);
13865        if settings.show_wrap_guides {
13866            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13867                wrap_guides.push((soft_wrap as usize, true));
13868            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13869                wrap_guides.push((soft_wrap as usize, true));
13870            }
13871            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13872        }
13873
13874        wrap_guides
13875    }
13876
13877    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13878        let settings = self.buffer.read(cx).settings_at(0, cx);
13879        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13880        match mode {
13881            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13882                SoftWrap::None
13883            }
13884            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13885            language_settings::SoftWrap::PreferredLineLength => {
13886                SoftWrap::Column(settings.preferred_line_length)
13887            }
13888            language_settings::SoftWrap::Bounded => {
13889                SoftWrap::Bounded(settings.preferred_line_length)
13890            }
13891        }
13892    }
13893
13894    pub fn set_soft_wrap_mode(
13895        &mut self,
13896        mode: language_settings::SoftWrap,
13897
13898        cx: &mut Context<Self>,
13899    ) {
13900        self.soft_wrap_mode_override = Some(mode);
13901        cx.notify();
13902    }
13903
13904    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13905        self.text_style_refinement = Some(style);
13906    }
13907
13908    /// called by the Element so we know what style we were most recently rendered with.
13909    pub(crate) fn set_style(
13910        &mut self,
13911        style: EditorStyle,
13912        window: &mut Window,
13913        cx: &mut Context<Self>,
13914    ) {
13915        let rem_size = window.rem_size();
13916        self.display_map.update(cx, |map, cx| {
13917            map.set_font(
13918                style.text.font(),
13919                style.text.font_size.to_pixels(rem_size),
13920                cx,
13921            )
13922        });
13923        self.style = Some(style);
13924    }
13925
13926    pub fn style(&self) -> Option<&EditorStyle> {
13927        self.style.as_ref()
13928    }
13929
13930    // Called by the element. This method is not designed to be called outside of the editor
13931    // element's layout code because it does not notify when rewrapping is computed synchronously.
13932    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13933        self.display_map
13934            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13935    }
13936
13937    pub fn set_soft_wrap(&mut self) {
13938        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13939    }
13940
13941    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13942        if self.soft_wrap_mode_override.is_some() {
13943            self.soft_wrap_mode_override.take();
13944        } else {
13945            let soft_wrap = match self.soft_wrap_mode(cx) {
13946                SoftWrap::GitDiff => return,
13947                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13948                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13949                    language_settings::SoftWrap::None
13950                }
13951            };
13952            self.soft_wrap_mode_override = Some(soft_wrap);
13953        }
13954        cx.notify();
13955    }
13956
13957    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13958        let Some(workspace) = self.workspace() else {
13959            return;
13960        };
13961        let fs = workspace.read(cx).app_state().fs.clone();
13962        let current_show = TabBarSettings::get_global(cx).show;
13963        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13964            setting.show = Some(!current_show);
13965        });
13966    }
13967
13968    pub fn toggle_indent_guides(
13969        &mut self,
13970        _: &ToggleIndentGuides,
13971        _: &mut Window,
13972        cx: &mut Context<Self>,
13973    ) {
13974        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13975            self.buffer
13976                .read(cx)
13977                .settings_at(0, cx)
13978                .indent_guides
13979                .enabled
13980        });
13981        self.show_indent_guides = Some(!currently_enabled);
13982        cx.notify();
13983    }
13984
13985    fn should_show_indent_guides(&self) -> Option<bool> {
13986        self.show_indent_guides
13987    }
13988
13989    pub fn toggle_line_numbers(
13990        &mut self,
13991        _: &ToggleLineNumbers,
13992        _: &mut Window,
13993        cx: &mut Context<Self>,
13994    ) {
13995        let mut editor_settings = EditorSettings::get_global(cx).clone();
13996        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13997        EditorSettings::override_global(editor_settings, cx);
13998    }
13999
14000    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14001        self.use_relative_line_numbers
14002            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14003    }
14004
14005    pub fn toggle_relative_line_numbers(
14006        &mut self,
14007        _: &ToggleRelativeLineNumbers,
14008        _: &mut Window,
14009        cx: &mut Context<Self>,
14010    ) {
14011        let is_relative = self.should_use_relative_line_numbers(cx);
14012        self.set_relative_line_number(Some(!is_relative), cx)
14013    }
14014
14015    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14016        self.use_relative_line_numbers = is_relative;
14017        cx.notify();
14018    }
14019
14020    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14021        self.show_gutter = show_gutter;
14022        cx.notify();
14023    }
14024
14025    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14026        self.show_scrollbars = show_scrollbars;
14027        cx.notify();
14028    }
14029
14030    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14031        self.show_line_numbers = Some(show_line_numbers);
14032        cx.notify();
14033    }
14034
14035    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14036        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14037        cx.notify();
14038    }
14039
14040    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14041        self.show_code_actions = Some(show_code_actions);
14042        cx.notify();
14043    }
14044
14045    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14046        self.show_runnables = Some(show_runnables);
14047        cx.notify();
14048    }
14049
14050    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14051        if self.display_map.read(cx).masked != masked {
14052            self.display_map.update(cx, |map, _| map.masked = masked);
14053        }
14054        cx.notify()
14055    }
14056
14057    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14058        self.show_wrap_guides = Some(show_wrap_guides);
14059        cx.notify();
14060    }
14061
14062    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14063        self.show_indent_guides = Some(show_indent_guides);
14064        cx.notify();
14065    }
14066
14067    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14068        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14069            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14070                if let Some(dir) = file.abs_path(cx).parent() {
14071                    return Some(dir.to_owned());
14072                }
14073            }
14074
14075            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14076                return Some(project_path.path.to_path_buf());
14077            }
14078        }
14079
14080        None
14081    }
14082
14083    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14084        self.active_excerpt(cx)?
14085            .1
14086            .read(cx)
14087            .file()
14088            .and_then(|f| f.as_local())
14089    }
14090
14091    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14092        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14093            let buffer = buffer.read(cx);
14094            if let Some(project_path) = buffer.project_path(cx) {
14095                let project = self.project.as_ref()?.read(cx);
14096                project.absolute_path(&project_path, cx)
14097            } else {
14098                buffer
14099                    .file()
14100                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14101            }
14102        })
14103    }
14104
14105    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14106        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14107            let project_path = buffer.read(cx).project_path(cx)?;
14108            let project = self.project.as_ref()?.read(cx);
14109            let entry = project.entry_for_path(&project_path, cx)?;
14110            let path = entry.path.to_path_buf();
14111            Some(path)
14112        })
14113    }
14114
14115    pub fn reveal_in_finder(
14116        &mut self,
14117        _: &RevealInFileManager,
14118        _window: &mut Window,
14119        cx: &mut Context<Self>,
14120    ) {
14121        if let Some(target) = self.target_file(cx) {
14122            cx.reveal_path(&target.abs_path(cx));
14123        }
14124    }
14125
14126    pub fn copy_path(
14127        &mut self,
14128        _: &zed_actions::workspace::CopyPath,
14129        _window: &mut Window,
14130        cx: &mut Context<Self>,
14131    ) {
14132        if let Some(path) = self.target_file_abs_path(cx) {
14133            if let Some(path) = path.to_str() {
14134                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14135            }
14136        }
14137    }
14138
14139    pub fn copy_relative_path(
14140        &mut self,
14141        _: &zed_actions::workspace::CopyRelativePath,
14142        _window: &mut Window,
14143        cx: &mut Context<Self>,
14144    ) {
14145        if let Some(path) = self.target_file_path(cx) {
14146            if let Some(path) = path.to_str() {
14147                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14148            }
14149        }
14150    }
14151
14152    pub fn copy_file_name_without_extension(
14153        &mut self,
14154        _: &CopyFileNameWithoutExtension,
14155        _: &mut Window,
14156        cx: &mut Context<Self>,
14157    ) {
14158        if let Some(file) = self.target_file(cx) {
14159            if let Some(file_stem) = file.path().file_stem() {
14160                if let Some(name) = file_stem.to_str() {
14161                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14162                }
14163            }
14164        }
14165    }
14166
14167    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14168        if let Some(file) = self.target_file(cx) {
14169            if let Some(file_name) = file.path().file_name() {
14170                if let Some(name) = file_name.to_str() {
14171                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14172                }
14173            }
14174        }
14175    }
14176
14177    pub fn toggle_git_blame(
14178        &mut self,
14179        _: &ToggleGitBlame,
14180        window: &mut Window,
14181        cx: &mut Context<Self>,
14182    ) {
14183        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14184
14185        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14186            self.start_git_blame(true, window, cx);
14187        }
14188
14189        cx.notify();
14190    }
14191
14192    pub fn toggle_git_blame_inline(
14193        &mut self,
14194        _: &ToggleGitBlameInline,
14195        window: &mut Window,
14196        cx: &mut Context<Self>,
14197    ) {
14198        self.toggle_git_blame_inline_internal(true, window, cx);
14199        cx.notify();
14200    }
14201
14202    pub fn git_blame_inline_enabled(&self) -> bool {
14203        self.git_blame_inline_enabled
14204    }
14205
14206    pub fn toggle_selection_menu(
14207        &mut self,
14208        _: &ToggleSelectionMenu,
14209        _: &mut Window,
14210        cx: &mut Context<Self>,
14211    ) {
14212        self.show_selection_menu = self
14213            .show_selection_menu
14214            .map(|show_selections_menu| !show_selections_menu)
14215            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14216
14217        cx.notify();
14218    }
14219
14220    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14221        self.show_selection_menu
14222            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14223    }
14224
14225    fn start_git_blame(
14226        &mut self,
14227        user_triggered: bool,
14228        window: &mut Window,
14229        cx: &mut Context<Self>,
14230    ) {
14231        if let Some(project) = self.project.as_ref() {
14232            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14233                return;
14234            };
14235
14236            if buffer.read(cx).file().is_none() {
14237                return;
14238            }
14239
14240            let focused = self.focus_handle(cx).contains_focused(window, cx);
14241
14242            let project = project.clone();
14243            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14244            self.blame_subscription =
14245                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14246            self.blame = Some(blame);
14247        }
14248    }
14249
14250    fn toggle_git_blame_inline_internal(
14251        &mut self,
14252        user_triggered: bool,
14253        window: &mut Window,
14254        cx: &mut Context<Self>,
14255    ) {
14256        if self.git_blame_inline_enabled {
14257            self.git_blame_inline_enabled = false;
14258            self.show_git_blame_inline = false;
14259            self.show_git_blame_inline_delay_task.take();
14260        } else {
14261            self.git_blame_inline_enabled = true;
14262            self.start_git_blame_inline(user_triggered, window, cx);
14263        }
14264
14265        cx.notify();
14266    }
14267
14268    fn start_git_blame_inline(
14269        &mut self,
14270        user_triggered: bool,
14271        window: &mut Window,
14272        cx: &mut Context<Self>,
14273    ) {
14274        self.start_git_blame(user_triggered, window, cx);
14275
14276        if ProjectSettings::get_global(cx)
14277            .git
14278            .inline_blame_delay()
14279            .is_some()
14280        {
14281            self.start_inline_blame_timer(window, cx);
14282        } else {
14283            self.show_git_blame_inline = true
14284        }
14285    }
14286
14287    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14288        self.blame.as_ref()
14289    }
14290
14291    pub fn show_git_blame_gutter(&self) -> bool {
14292        self.show_git_blame_gutter
14293    }
14294
14295    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14296        self.show_git_blame_gutter && self.has_blame_entries(cx)
14297    }
14298
14299    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14300        self.show_git_blame_inline
14301            && (self.focus_handle.is_focused(window)
14302                || self
14303                    .git_blame_inline_tooltip
14304                    .as_ref()
14305                    .and_then(|t| t.upgrade())
14306                    .is_some())
14307            && !self.newest_selection_head_on_empty_line(cx)
14308            && self.has_blame_entries(cx)
14309    }
14310
14311    fn has_blame_entries(&self, cx: &App) -> bool {
14312        self.blame()
14313            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14314    }
14315
14316    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14317        let cursor_anchor = self.selections.newest_anchor().head();
14318
14319        let snapshot = self.buffer.read(cx).snapshot(cx);
14320        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14321
14322        snapshot.line_len(buffer_row) == 0
14323    }
14324
14325    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14326        let buffer_and_selection = maybe!({
14327            let selection = self.selections.newest::<Point>(cx);
14328            let selection_range = selection.range();
14329
14330            let multi_buffer = self.buffer().read(cx);
14331            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14332            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14333
14334            let (buffer, range, _) = if selection.reversed {
14335                buffer_ranges.first()
14336            } else {
14337                buffer_ranges.last()
14338            }?;
14339
14340            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14341                ..text::ToPoint::to_point(&range.end, &buffer).row;
14342            Some((
14343                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14344                selection,
14345            ))
14346        });
14347
14348        let Some((buffer, selection)) = buffer_and_selection else {
14349            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14350        };
14351
14352        let Some(project) = self.project.as_ref() else {
14353            return Task::ready(Err(anyhow!("editor does not have project")));
14354        };
14355
14356        project.update(cx, |project, cx| {
14357            project.get_permalink_to_line(&buffer, selection, cx)
14358        })
14359    }
14360
14361    pub fn copy_permalink_to_line(
14362        &mut self,
14363        _: &CopyPermalinkToLine,
14364        window: &mut Window,
14365        cx: &mut Context<Self>,
14366    ) {
14367        let permalink_task = self.get_permalink_to_line(cx);
14368        let workspace = self.workspace();
14369
14370        cx.spawn_in(window, |_, mut cx| async move {
14371            match permalink_task.await {
14372                Ok(permalink) => {
14373                    cx.update(|_, cx| {
14374                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14375                    })
14376                    .ok();
14377                }
14378                Err(err) => {
14379                    let message = format!("Failed to copy permalink: {err}");
14380
14381                    Err::<(), anyhow::Error>(err).log_err();
14382
14383                    if let Some(workspace) = workspace {
14384                        workspace
14385                            .update_in(&mut cx, |workspace, _, cx| {
14386                                struct CopyPermalinkToLine;
14387
14388                                workspace.show_toast(
14389                                    Toast::new(
14390                                        NotificationId::unique::<CopyPermalinkToLine>(),
14391                                        message,
14392                                    ),
14393                                    cx,
14394                                )
14395                            })
14396                            .ok();
14397                    }
14398                }
14399            }
14400        })
14401        .detach();
14402    }
14403
14404    pub fn copy_file_location(
14405        &mut self,
14406        _: &CopyFileLocation,
14407        _: &mut Window,
14408        cx: &mut Context<Self>,
14409    ) {
14410        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14411        if let Some(file) = self.target_file(cx) {
14412            if let Some(path) = file.path().to_str() {
14413                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14414            }
14415        }
14416    }
14417
14418    pub fn open_permalink_to_line(
14419        &mut self,
14420        _: &OpenPermalinkToLine,
14421        window: &mut Window,
14422        cx: &mut Context<Self>,
14423    ) {
14424        let permalink_task = self.get_permalink_to_line(cx);
14425        let workspace = self.workspace();
14426
14427        cx.spawn_in(window, |_, mut cx| async move {
14428            match permalink_task.await {
14429                Ok(permalink) => {
14430                    cx.update(|_, cx| {
14431                        cx.open_url(permalink.as_ref());
14432                    })
14433                    .ok();
14434                }
14435                Err(err) => {
14436                    let message = format!("Failed to open permalink: {err}");
14437
14438                    Err::<(), anyhow::Error>(err).log_err();
14439
14440                    if let Some(workspace) = workspace {
14441                        workspace
14442                            .update(&mut cx, |workspace, cx| {
14443                                struct OpenPermalinkToLine;
14444
14445                                workspace.show_toast(
14446                                    Toast::new(
14447                                        NotificationId::unique::<OpenPermalinkToLine>(),
14448                                        message,
14449                                    ),
14450                                    cx,
14451                                )
14452                            })
14453                            .ok();
14454                    }
14455                }
14456            }
14457        })
14458        .detach();
14459    }
14460
14461    pub fn insert_uuid_v4(
14462        &mut self,
14463        _: &InsertUuidV4,
14464        window: &mut Window,
14465        cx: &mut Context<Self>,
14466    ) {
14467        self.insert_uuid(UuidVersion::V4, window, cx);
14468    }
14469
14470    pub fn insert_uuid_v7(
14471        &mut self,
14472        _: &InsertUuidV7,
14473        window: &mut Window,
14474        cx: &mut Context<Self>,
14475    ) {
14476        self.insert_uuid(UuidVersion::V7, window, cx);
14477    }
14478
14479    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14480        self.transact(window, cx, |this, window, cx| {
14481            let edits = this
14482                .selections
14483                .all::<Point>(cx)
14484                .into_iter()
14485                .map(|selection| {
14486                    let uuid = match version {
14487                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14488                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14489                    };
14490
14491                    (selection.range(), uuid.to_string())
14492                });
14493            this.edit(edits, cx);
14494            this.refresh_inline_completion(true, false, window, cx);
14495        });
14496    }
14497
14498    pub fn open_selections_in_multibuffer(
14499        &mut self,
14500        _: &OpenSelectionsInMultibuffer,
14501        window: &mut Window,
14502        cx: &mut Context<Self>,
14503    ) {
14504        let multibuffer = self.buffer.read(cx);
14505
14506        let Some(buffer) = multibuffer.as_singleton() else {
14507            return;
14508        };
14509
14510        let Some(workspace) = self.workspace() else {
14511            return;
14512        };
14513
14514        let locations = self
14515            .selections
14516            .disjoint_anchors()
14517            .iter()
14518            .map(|range| Location {
14519                buffer: buffer.clone(),
14520                range: range.start.text_anchor..range.end.text_anchor,
14521            })
14522            .collect::<Vec<_>>();
14523
14524        let title = multibuffer.title(cx).to_string();
14525
14526        cx.spawn_in(window, |_, mut cx| async move {
14527            workspace.update_in(&mut cx, |workspace, window, cx| {
14528                Self::open_locations_in_multibuffer(
14529                    workspace,
14530                    locations,
14531                    format!("Selections for '{title}'"),
14532                    false,
14533                    MultibufferSelectionMode::All,
14534                    window,
14535                    cx,
14536                );
14537            })
14538        })
14539        .detach();
14540    }
14541
14542    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14543    /// last highlight added will be used.
14544    ///
14545    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14546    pub fn highlight_rows<T: 'static>(
14547        &mut self,
14548        range: Range<Anchor>,
14549        color: Hsla,
14550        should_autoscroll: bool,
14551        cx: &mut Context<Self>,
14552    ) {
14553        let snapshot = self.buffer().read(cx).snapshot(cx);
14554        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14555        let ix = row_highlights.binary_search_by(|highlight| {
14556            Ordering::Equal
14557                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14558                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14559        });
14560
14561        if let Err(mut ix) = ix {
14562            let index = post_inc(&mut self.highlight_order);
14563
14564            // If this range intersects with the preceding highlight, then merge it with
14565            // the preceding highlight. Otherwise insert a new highlight.
14566            let mut merged = false;
14567            if ix > 0 {
14568                let prev_highlight = &mut row_highlights[ix - 1];
14569                if prev_highlight
14570                    .range
14571                    .end
14572                    .cmp(&range.start, &snapshot)
14573                    .is_ge()
14574                {
14575                    ix -= 1;
14576                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14577                        prev_highlight.range.end = range.end;
14578                    }
14579                    merged = true;
14580                    prev_highlight.index = index;
14581                    prev_highlight.color = color;
14582                    prev_highlight.should_autoscroll = should_autoscroll;
14583                }
14584            }
14585
14586            if !merged {
14587                row_highlights.insert(
14588                    ix,
14589                    RowHighlight {
14590                        range: range.clone(),
14591                        index,
14592                        color,
14593                        should_autoscroll,
14594                    },
14595                );
14596            }
14597
14598            // If any of the following highlights intersect with this one, merge them.
14599            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14600                let highlight = &row_highlights[ix];
14601                if next_highlight
14602                    .range
14603                    .start
14604                    .cmp(&highlight.range.end, &snapshot)
14605                    .is_le()
14606                {
14607                    if next_highlight
14608                        .range
14609                        .end
14610                        .cmp(&highlight.range.end, &snapshot)
14611                        .is_gt()
14612                    {
14613                        row_highlights[ix].range.end = next_highlight.range.end;
14614                    }
14615                    row_highlights.remove(ix + 1);
14616                } else {
14617                    break;
14618                }
14619            }
14620        }
14621    }
14622
14623    /// Remove any highlighted row ranges of the given type that intersect the
14624    /// given ranges.
14625    pub fn remove_highlighted_rows<T: 'static>(
14626        &mut self,
14627        ranges_to_remove: Vec<Range<Anchor>>,
14628        cx: &mut Context<Self>,
14629    ) {
14630        let snapshot = self.buffer().read(cx).snapshot(cx);
14631        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14632        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14633        row_highlights.retain(|highlight| {
14634            while let Some(range_to_remove) = ranges_to_remove.peek() {
14635                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14636                    Ordering::Less | Ordering::Equal => {
14637                        ranges_to_remove.next();
14638                    }
14639                    Ordering::Greater => {
14640                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14641                            Ordering::Less | Ordering::Equal => {
14642                                return false;
14643                            }
14644                            Ordering::Greater => break,
14645                        }
14646                    }
14647                }
14648            }
14649
14650            true
14651        })
14652    }
14653
14654    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14655    pub fn clear_row_highlights<T: 'static>(&mut self) {
14656        self.highlighted_rows.remove(&TypeId::of::<T>());
14657    }
14658
14659    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14660    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14661        self.highlighted_rows
14662            .get(&TypeId::of::<T>())
14663            .map_or(&[] as &[_], |vec| vec.as_slice())
14664            .iter()
14665            .map(|highlight| (highlight.range.clone(), highlight.color))
14666    }
14667
14668    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14669    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14670    /// Allows to ignore certain kinds of highlights.
14671    pub fn highlighted_display_rows(
14672        &self,
14673        window: &mut Window,
14674        cx: &mut App,
14675    ) -> BTreeMap<DisplayRow, Background> {
14676        let snapshot = self.snapshot(window, cx);
14677        let mut used_highlight_orders = HashMap::default();
14678        self.highlighted_rows
14679            .iter()
14680            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14681            .fold(
14682                BTreeMap::<DisplayRow, Background>::new(),
14683                |mut unique_rows, highlight| {
14684                    let start = highlight.range.start.to_display_point(&snapshot);
14685                    let end = highlight.range.end.to_display_point(&snapshot);
14686                    let start_row = start.row().0;
14687                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14688                        && end.column() == 0
14689                    {
14690                        end.row().0.saturating_sub(1)
14691                    } else {
14692                        end.row().0
14693                    };
14694                    for row in start_row..=end_row {
14695                        let used_index =
14696                            used_highlight_orders.entry(row).or_insert(highlight.index);
14697                        if highlight.index >= *used_index {
14698                            *used_index = highlight.index;
14699                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14700                        }
14701                    }
14702                    unique_rows
14703                },
14704            )
14705    }
14706
14707    pub fn highlighted_display_row_for_autoscroll(
14708        &self,
14709        snapshot: &DisplaySnapshot,
14710    ) -> Option<DisplayRow> {
14711        self.highlighted_rows
14712            .values()
14713            .flat_map(|highlighted_rows| highlighted_rows.iter())
14714            .filter_map(|highlight| {
14715                if highlight.should_autoscroll {
14716                    Some(highlight.range.start.to_display_point(snapshot).row())
14717                } else {
14718                    None
14719                }
14720            })
14721            .min()
14722    }
14723
14724    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14725        self.highlight_background::<SearchWithinRange>(
14726            ranges,
14727            |colors| colors.editor_document_highlight_read_background,
14728            cx,
14729        )
14730    }
14731
14732    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14733        self.breadcrumb_header = Some(new_header);
14734    }
14735
14736    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14737        self.clear_background_highlights::<SearchWithinRange>(cx);
14738    }
14739
14740    pub fn highlight_background<T: 'static>(
14741        &mut self,
14742        ranges: &[Range<Anchor>],
14743        color_fetcher: fn(&ThemeColors) -> Hsla,
14744        cx: &mut Context<Self>,
14745    ) {
14746        self.background_highlights
14747            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14748        self.scrollbar_marker_state.dirty = true;
14749        cx.notify();
14750    }
14751
14752    pub fn clear_background_highlights<T: 'static>(
14753        &mut self,
14754        cx: &mut Context<Self>,
14755    ) -> Option<BackgroundHighlight> {
14756        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14757        if !text_highlights.1.is_empty() {
14758            self.scrollbar_marker_state.dirty = true;
14759            cx.notify();
14760        }
14761        Some(text_highlights)
14762    }
14763
14764    pub fn highlight_gutter<T: 'static>(
14765        &mut self,
14766        ranges: &[Range<Anchor>],
14767        color_fetcher: fn(&App) -> Hsla,
14768        cx: &mut Context<Self>,
14769    ) {
14770        self.gutter_highlights
14771            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14772        cx.notify();
14773    }
14774
14775    pub fn clear_gutter_highlights<T: 'static>(
14776        &mut self,
14777        cx: &mut Context<Self>,
14778    ) -> Option<GutterHighlight> {
14779        cx.notify();
14780        self.gutter_highlights.remove(&TypeId::of::<T>())
14781    }
14782
14783    #[cfg(feature = "test-support")]
14784    pub fn all_text_background_highlights(
14785        &self,
14786        window: &mut Window,
14787        cx: &mut Context<Self>,
14788    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14789        let snapshot = self.snapshot(window, cx);
14790        let buffer = &snapshot.buffer_snapshot;
14791        let start = buffer.anchor_before(0);
14792        let end = buffer.anchor_after(buffer.len());
14793        let theme = cx.theme().colors();
14794        self.background_highlights_in_range(start..end, &snapshot, theme)
14795    }
14796
14797    #[cfg(feature = "test-support")]
14798    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14799        let snapshot = self.buffer().read(cx).snapshot(cx);
14800
14801        let highlights = self
14802            .background_highlights
14803            .get(&TypeId::of::<items::BufferSearchHighlights>());
14804
14805        if let Some((_color, ranges)) = highlights {
14806            ranges
14807                .iter()
14808                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14809                .collect_vec()
14810        } else {
14811            vec![]
14812        }
14813    }
14814
14815    fn document_highlights_for_position<'a>(
14816        &'a self,
14817        position: Anchor,
14818        buffer: &'a MultiBufferSnapshot,
14819    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14820        let read_highlights = self
14821            .background_highlights
14822            .get(&TypeId::of::<DocumentHighlightRead>())
14823            .map(|h| &h.1);
14824        let write_highlights = self
14825            .background_highlights
14826            .get(&TypeId::of::<DocumentHighlightWrite>())
14827            .map(|h| &h.1);
14828        let left_position = position.bias_left(buffer);
14829        let right_position = position.bias_right(buffer);
14830        read_highlights
14831            .into_iter()
14832            .chain(write_highlights)
14833            .flat_map(move |ranges| {
14834                let start_ix = match ranges.binary_search_by(|probe| {
14835                    let cmp = probe.end.cmp(&left_position, buffer);
14836                    if cmp.is_ge() {
14837                        Ordering::Greater
14838                    } else {
14839                        Ordering::Less
14840                    }
14841                }) {
14842                    Ok(i) | Err(i) => i,
14843                };
14844
14845                ranges[start_ix..]
14846                    .iter()
14847                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14848            })
14849    }
14850
14851    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14852        self.background_highlights
14853            .get(&TypeId::of::<T>())
14854            .map_or(false, |(_, highlights)| !highlights.is_empty())
14855    }
14856
14857    pub fn background_highlights_in_range(
14858        &self,
14859        search_range: Range<Anchor>,
14860        display_snapshot: &DisplaySnapshot,
14861        theme: &ThemeColors,
14862    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14863        let mut results = Vec::new();
14864        for (color_fetcher, ranges) in self.background_highlights.values() {
14865            let color = color_fetcher(theme);
14866            let start_ix = match ranges.binary_search_by(|probe| {
14867                let cmp = probe
14868                    .end
14869                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14870                if cmp.is_gt() {
14871                    Ordering::Greater
14872                } else {
14873                    Ordering::Less
14874                }
14875            }) {
14876                Ok(i) | Err(i) => i,
14877            };
14878            for range in &ranges[start_ix..] {
14879                if range
14880                    .start
14881                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14882                    .is_ge()
14883                {
14884                    break;
14885                }
14886
14887                let start = range.start.to_display_point(display_snapshot);
14888                let end = range.end.to_display_point(display_snapshot);
14889                results.push((start..end, color))
14890            }
14891        }
14892        results
14893    }
14894
14895    pub fn background_highlight_row_ranges<T: 'static>(
14896        &self,
14897        search_range: Range<Anchor>,
14898        display_snapshot: &DisplaySnapshot,
14899        count: usize,
14900    ) -> Vec<RangeInclusive<DisplayPoint>> {
14901        let mut results = Vec::new();
14902        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14903            return vec![];
14904        };
14905
14906        let start_ix = match ranges.binary_search_by(|probe| {
14907            let cmp = probe
14908                .end
14909                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14910            if cmp.is_gt() {
14911                Ordering::Greater
14912            } else {
14913                Ordering::Less
14914            }
14915        }) {
14916            Ok(i) | Err(i) => i,
14917        };
14918        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14919            if let (Some(start_display), Some(end_display)) = (start, end) {
14920                results.push(
14921                    start_display.to_display_point(display_snapshot)
14922                        ..=end_display.to_display_point(display_snapshot),
14923                );
14924            }
14925        };
14926        let mut start_row: Option<Point> = None;
14927        let mut end_row: Option<Point> = None;
14928        if ranges.len() > count {
14929            return Vec::new();
14930        }
14931        for range in &ranges[start_ix..] {
14932            if range
14933                .start
14934                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14935                .is_ge()
14936            {
14937                break;
14938            }
14939            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14940            if let Some(current_row) = &end_row {
14941                if end.row == current_row.row {
14942                    continue;
14943                }
14944            }
14945            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14946            if start_row.is_none() {
14947                assert_eq!(end_row, None);
14948                start_row = Some(start);
14949                end_row = Some(end);
14950                continue;
14951            }
14952            if let Some(current_end) = end_row.as_mut() {
14953                if start.row > current_end.row + 1 {
14954                    push_region(start_row, end_row);
14955                    start_row = Some(start);
14956                    end_row = Some(end);
14957                } else {
14958                    // Merge two hunks.
14959                    *current_end = end;
14960                }
14961            } else {
14962                unreachable!();
14963            }
14964        }
14965        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14966        push_region(start_row, end_row);
14967        results
14968    }
14969
14970    pub fn gutter_highlights_in_range(
14971        &self,
14972        search_range: Range<Anchor>,
14973        display_snapshot: &DisplaySnapshot,
14974        cx: &App,
14975    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14976        let mut results = Vec::new();
14977        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14978            let color = color_fetcher(cx);
14979            let start_ix = match ranges.binary_search_by(|probe| {
14980                let cmp = probe
14981                    .end
14982                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14983                if cmp.is_gt() {
14984                    Ordering::Greater
14985                } else {
14986                    Ordering::Less
14987                }
14988            }) {
14989                Ok(i) | Err(i) => i,
14990            };
14991            for range in &ranges[start_ix..] {
14992                if range
14993                    .start
14994                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14995                    .is_ge()
14996                {
14997                    break;
14998                }
14999
15000                let start = range.start.to_display_point(display_snapshot);
15001                let end = range.end.to_display_point(display_snapshot);
15002                results.push((start..end, color))
15003            }
15004        }
15005        results
15006    }
15007
15008    /// Get the text ranges corresponding to the redaction query
15009    pub fn redacted_ranges(
15010        &self,
15011        search_range: Range<Anchor>,
15012        display_snapshot: &DisplaySnapshot,
15013        cx: &App,
15014    ) -> Vec<Range<DisplayPoint>> {
15015        display_snapshot
15016            .buffer_snapshot
15017            .redacted_ranges(search_range, |file| {
15018                if let Some(file) = file {
15019                    file.is_private()
15020                        && EditorSettings::get(
15021                            Some(SettingsLocation {
15022                                worktree_id: file.worktree_id(cx),
15023                                path: file.path().as_ref(),
15024                            }),
15025                            cx,
15026                        )
15027                        .redact_private_values
15028                } else {
15029                    false
15030                }
15031            })
15032            .map(|range| {
15033                range.start.to_display_point(display_snapshot)
15034                    ..range.end.to_display_point(display_snapshot)
15035            })
15036            .collect()
15037    }
15038
15039    pub fn highlight_text<T: 'static>(
15040        &mut self,
15041        ranges: Vec<Range<Anchor>>,
15042        style: HighlightStyle,
15043        cx: &mut Context<Self>,
15044    ) {
15045        self.display_map.update(cx, |map, _| {
15046            map.highlight_text(TypeId::of::<T>(), ranges, style)
15047        });
15048        cx.notify();
15049    }
15050
15051    pub(crate) fn highlight_inlays<T: 'static>(
15052        &mut self,
15053        highlights: Vec<InlayHighlight>,
15054        style: HighlightStyle,
15055        cx: &mut Context<Self>,
15056    ) {
15057        self.display_map.update(cx, |map, _| {
15058            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15059        });
15060        cx.notify();
15061    }
15062
15063    pub fn text_highlights<'a, T: 'static>(
15064        &'a self,
15065        cx: &'a App,
15066    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15067        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15068    }
15069
15070    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15071        let cleared = self
15072            .display_map
15073            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15074        if cleared {
15075            cx.notify();
15076        }
15077    }
15078
15079    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15080        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15081            && self.focus_handle.is_focused(window)
15082    }
15083
15084    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15085        self.show_cursor_when_unfocused = is_enabled;
15086        cx.notify();
15087    }
15088
15089    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15090        cx.notify();
15091    }
15092
15093    fn on_buffer_event(
15094        &mut self,
15095        multibuffer: &Entity<MultiBuffer>,
15096        event: &multi_buffer::Event,
15097        window: &mut Window,
15098        cx: &mut Context<Self>,
15099    ) {
15100        match event {
15101            multi_buffer::Event::Edited {
15102                singleton_buffer_edited,
15103                edited_buffer: buffer_edited,
15104            } => {
15105                self.scrollbar_marker_state.dirty = true;
15106                self.active_indent_guides_state.dirty = true;
15107                self.refresh_active_diagnostics(cx);
15108                self.refresh_code_actions(window, cx);
15109                if self.has_active_inline_completion() {
15110                    self.update_visible_inline_completion(window, cx);
15111                }
15112                if let Some(buffer) = buffer_edited {
15113                    let buffer_id = buffer.read(cx).remote_id();
15114                    if !self.registered_buffers.contains_key(&buffer_id) {
15115                        if let Some(project) = self.project.as_ref() {
15116                            project.update(cx, |project, cx| {
15117                                self.registered_buffers.insert(
15118                                    buffer_id,
15119                                    project.register_buffer_with_language_servers(&buffer, cx),
15120                                );
15121                            })
15122                        }
15123                    }
15124                }
15125                cx.emit(EditorEvent::BufferEdited);
15126                cx.emit(SearchEvent::MatchesInvalidated);
15127                if *singleton_buffer_edited {
15128                    if let Some(project) = &self.project {
15129                        #[allow(clippy::mutable_key_type)]
15130                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15131                            multibuffer
15132                                .all_buffers()
15133                                .into_iter()
15134                                .filter_map(|buffer| {
15135                                    buffer.update(cx, |buffer, cx| {
15136                                        let language = buffer.language()?;
15137                                        let should_discard = project.update(cx, |project, cx| {
15138                                            project.is_local()
15139                                                && !project.has_language_servers_for(buffer, cx)
15140                                        });
15141                                        should_discard.not().then_some(language.clone())
15142                                    })
15143                                })
15144                                .collect::<HashSet<_>>()
15145                        });
15146                        if !languages_affected.is_empty() {
15147                            self.refresh_inlay_hints(
15148                                InlayHintRefreshReason::BufferEdited(languages_affected),
15149                                cx,
15150                            );
15151                        }
15152                    }
15153                }
15154
15155                let Some(project) = &self.project else { return };
15156                let (telemetry, is_via_ssh) = {
15157                    let project = project.read(cx);
15158                    let telemetry = project.client().telemetry().clone();
15159                    let is_via_ssh = project.is_via_ssh();
15160                    (telemetry, is_via_ssh)
15161                };
15162                refresh_linked_ranges(self, window, cx);
15163                telemetry.log_edit_event("editor", is_via_ssh);
15164            }
15165            multi_buffer::Event::ExcerptsAdded {
15166                buffer,
15167                predecessor,
15168                excerpts,
15169            } => {
15170                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15171                let buffer_id = buffer.read(cx).remote_id();
15172                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15173                    if let Some(project) = &self.project {
15174                        get_uncommitted_diff_for_buffer(
15175                            project,
15176                            [buffer.clone()],
15177                            self.buffer.clone(),
15178                            cx,
15179                        )
15180                        .detach();
15181                    }
15182                }
15183                cx.emit(EditorEvent::ExcerptsAdded {
15184                    buffer: buffer.clone(),
15185                    predecessor: *predecessor,
15186                    excerpts: excerpts.clone(),
15187                });
15188                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15189            }
15190            multi_buffer::Event::ExcerptsRemoved { ids } => {
15191                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15192                let buffer = self.buffer.read(cx);
15193                self.registered_buffers
15194                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15195                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15196            }
15197            multi_buffer::Event::ExcerptsEdited { ids } => {
15198                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15199            }
15200            multi_buffer::Event::ExcerptsExpanded { ids } => {
15201                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15202                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15203            }
15204            multi_buffer::Event::Reparsed(buffer_id) => {
15205                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15206
15207                cx.emit(EditorEvent::Reparsed(*buffer_id));
15208            }
15209            multi_buffer::Event::DiffHunksToggled => {
15210                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15211            }
15212            multi_buffer::Event::LanguageChanged(buffer_id) => {
15213                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15214                cx.emit(EditorEvent::Reparsed(*buffer_id));
15215                cx.notify();
15216            }
15217            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15218            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15219            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15220                cx.emit(EditorEvent::TitleChanged)
15221            }
15222            // multi_buffer::Event::DiffBaseChanged => {
15223            //     self.scrollbar_marker_state.dirty = true;
15224            //     cx.emit(EditorEvent::DiffBaseChanged);
15225            //     cx.notify();
15226            // }
15227            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15228            multi_buffer::Event::DiagnosticsUpdated => {
15229                self.refresh_active_diagnostics(cx);
15230                self.refresh_inline_diagnostics(true, window, cx);
15231                self.scrollbar_marker_state.dirty = true;
15232                cx.notify();
15233            }
15234            _ => {}
15235        };
15236    }
15237
15238    fn on_display_map_changed(
15239        &mut self,
15240        _: Entity<DisplayMap>,
15241        _: &mut Window,
15242        cx: &mut Context<Self>,
15243    ) {
15244        cx.notify();
15245    }
15246
15247    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15248        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15249        self.update_edit_prediction_settings(cx);
15250        self.refresh_inline_completion(true, false, window, cx);
15251        self.refresh_inlay_hints(
15252            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15253                self.selections.newest_anchor().head(),
15254                &self.buffer.read(cx).snapshot(cx),
15255                cx,
15256            )),
15257            cx,
15258        );
15259
15260        let old_cursor_shape = self.cursor_shape;
15261
15262        {
15263            let editor_settings = EditorSettings::get_global(cx);
15264            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15265            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15266            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15267        }
15268
15269        if old_cursor_shape != self.cursor_shape {
15270            cx.emit(EditorEvent::CursorShapeChanged);
15271        }
15272
15273        let project_settings = ProjectSettings::get_global(cx);
15274        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15275
15276        if self.mode == EditorMode::Full {
15277            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15278            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15279            if self.show_inline_diagnostics != show_inline_diagnostics {
15280                self.show_inline_diagnostics = show_inline_diagnostics;
15281                self.refresh_inline_diagnostics(false, window, cx);
15282            }
15283
15284            if self.git_blame_inline_enabled != inline_blame_enabled {
15285                self.toggle_git_blame_inline_internal(false, window, cx);
15286            }
15287        }
15288
15289        cx.notify();
15290    }
15291
15292    pub fn set_searchable(&mut self, searchable: bool) {
15293        self.searchable = searchable;
15294    }
15295
15296    pub fn searchable(&self) -> bool {
15297        self.searchable
15298    }
15299
15300    fn open_proposed_changes_editor(
15301        &mut self,
15302        _: &OpenProposedChangesEditor,
15303        window: &mut Window,
15304        cx: &mut Context<Self>,
15305    ) {
15306        let Some(workspace) = self.workspace() else {
15307            cx.propagate();
15308            return;
15309        };
15310
15311        let selections = self.selections.all::<usize>(cx);
15312        let multi_buffer = self.buffer.read(cx);
15313        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15314        let mut new_selections_by_buffer = HashMap::default();
15315        for selection in selections {
15316            for (buffer, range, _) in
15317                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15318            {
15319                let mut range = range.to_point(buffer);
15320                range.start.column = 0;
15321                range.end.column = buffer.line_len(range.end.row);
15322                new_selections_by_buffer
15323                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15324                    .or_insert(Vec::new())
15325                    .push(range)
15326            }
15327        }
15328
15329        let proposed_changes_buffers = new_selections_by_buffer
15330            .into_iter()
15331            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15332            .collect::<Vec<_>>();
15333        let proposed_changes_editor = cx.new(|cx| {
15334            ProposedChangesEditor::new(
15335                "Proposed changes",
15336                proposed_changes_buffers,
15337                self.project.clone(),
15338                window,
15339                cx,
15340            )
15341        });
15342
15343        window.defer(cx, move |window, cx| {
15344            workspace.update(cx, |workspace, cx| {
15345                workspace.active_pane().update(cx, |pane, cx| {
15346                    pane.add_item(
15347                        Box::new(proposed_changes_editor),
15348                        true,
15349                        true,
15350                        None,
15351                        window,
15352                        cx,
15353                    );
15354                });
15355            });
15356        });
15357    }
15358
15359    pub fn open_excerpts_in_split(
15360        &mut self,
15361        _: &OpenExcerptsSplit,
15362        window: &mut Window,
15363        cx: &mut Context<Self>,
15364    ) {
15365        self.open_excerpts_common(None, true, window, cx)
15366    }
15367
15368    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15369        self.open_excerpts_common(None, false, window, cx)
15370    }
15371
15372    fn open_excerpts_common(
15373        &mut self,
15374        jump_data: Option<JumpData>,
15375        split: bool,
15376        window: &mut Window,
15377        cx: &mut Context<Self>,
15378    ) {
15379        let Some(workspace) = self.workspace() else {
15380            cx.propagate();
15381            return;
15382        };
15383
15384        if self.buffer.read(cx).is_singleton() {
15385            cx.propagate();
15386            return;
15387        }
15388
15389        let mut new_selections_by_buffer = HashMap::default();
15390        match &jump_data {
15391            Some(JumpData::MultiBufferPoint {
15392                excerpt_id,
15393                position,
15394                anchor,
15395                line_offset_from_top,
15396            }) => {
15397                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15398                if let Some(buffer) = multi_buffer_snapshot
15399                    .buffer_id_for_excerpt(*excerpt_id)
15400                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15401                {
15402                    let buffer_snapshot = buffer.read(cx).snapshot();
15403                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15404                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15405                    } else {
15406                        buffer_snapshot.clip_point(*position, Bias::Left)
15407                    };
15408                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15409                    new_selections_by_buffer.insert(
15410                        buffer,
15411                        (
15412                            vec![jump_to_offset..jump_to_offset],
15413                            Some(*line_offset_from_top),
15414                        ),
15415                    );
15416                }
15417            }
15418            Some(JumpData::MultiBufferRow {
15419                row,
15420                line_offset_from_top,
15421            }) => {
15422                let point = MultiBufferPoint::new(row.0, 0);
15423                if let Some((buffer, buffer_point, _)) =
15424                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15425                {
15426                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15427                    new_selections_by_buffer
15428                        .entry(buffer)
15429                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15430                        .0
15431                        .push(buffer_offset..buffer_offset)
15432                }
15433            }
15434            None => {
15435                let selections = self.selections.all::<usize>(cx);
15436                let multi_buffer = self.buffer.read(cx);
15437                for selection in selections {
15438                    for (snapshot, range, _, anchor) in multi_buffer
15439                        .snapshot(cx)
15440                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15441                    {
15442                        if let Some(anchor) = anchor {
15443                            // selection is in a deleted hunk
15444                            let Some(buffer_id) = anchor.buffer_id else {
15445                                continue;
15446                            };
15447                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15448                                continue;
15449                            };
15450                            let offset = text::ToOffset::to_offset(
15451                                &anchor.text_anchor,
15452                                &buffer_handle.read(cx).snapshot(),
15453                            );
15454                            let range = offset..offset;
15455                            new_selections_by_buffer
15456                                .entry(buffer_handle)
15457                                .or_insert((Vec::new(), None))
15458                                .0
15459                                .push(range)
15460                        } else {
15461                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15462                            else {
15463                                continue;
15464                            };
15465                            new_selections_by_buffer
15466                                .entry(buffer_handle)
15467                                .or_insert((Vec::new(), None))
15468                                .0
15469                                .push(range)
15470                        }
15471                    }
15472                }
15473            }
15474        }
15475
15476        if new_selections_by_buffer.is_empty() {
15477            return;
15478        }
15479
15480        // We defer the pane interaction because we ourselves are a workspace item
15481        // and activating a new item causes the pane to call a method on us reentrantly,
15482        // which panics if we're on the stack.
15483        window.defer(cx, move |window, cx| {
15484            workspace.update(cx, |workspace, cx| {
15485                let pane = if split {
15486                    workspace.adjacent_pane(window, cx)
15487                } else {
15488                    workspace.active_pane().clone()
15489                };
15490
15491                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15492                    let editor = buffer
15493                        .read(cx)
15494                        .file()
15495                        .is_none()
15496                        .then(|| {
15497                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15498                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15499                            // Instead, we try to activate the existing editor in the pane first.
15500                            let (editor, pane_item_index) =
15501                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15502                                    let editor = item.downcast::<Editor>()?;
15503                                    let singleton_buffer =
15504                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15505                                    if singleton_buffer == buffer {
15506                                        Some((editor, i))
15507                                    } else {
15508                                        None
15509                                    }
15510                                })?;
15511                            pane.update(cx, |pane, cx| {
15512                                pane.activate_item(pane_item_index, true, true, window, cx)
15513                            });
15514                            Some(editor)
15515                        })
15516                        .flatten()
15517                        .unwrap_or_else(|| {
15518                            workspace.open_project_item::<Self>(
15519                                pane.clone(),
15520                                buffer,
15521                                true,
15522                                true,
15523                                window,
15524                                cx,
15525                            )
15526                        });
15527
15528                    editor.update(cx, |editor, cx| {
15529                        let autoscroll = match scroll_offset {
15530                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15531                            None => Autoscroll::newest(),
15532                        };
15533                        let nav_history = editor.nav_history.take();
15534                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15535                            s.select_ranges(ranges);
15536                        });
15537                        editor.nav_history = nav_history;
15538                    });
15539                }
15540            })
15541        });
15542    }
15543
15544    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15545        let snapshot = self.buffer.read(cx).read(cx);
15546        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15547        Some(
15548            ranges
15549                .iter()
15550                .map(move |range| {
15551                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15552                })
15553                .collect(),
15554        )
15555    }
15556
15557    fn selection_replacement_ranges(
15558        &self,
15559        range: Range<OffsetUtf16>,
15560        cx: &mut App,
15561    ) -> Vec<Range<OffsetUtf16>> {
15562        let selections = self.selections.all::<OffsetUtf16>(cx);
15563        let newest_selection = selections
15564            .iter()
15565            .max_by_key(|selection| selection.id)
15566            .unwrap();
15567        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15568        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15569        let snapshot = self.buffer.read(cx).read(cx);
15570        selections
15571            .into_iter()
15572            .map(|mut selection| {
15573                selection.start.0 =
15574                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15575                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15576                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15577                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15578            })
15579            .collect()
15580    }
15581
15582    fn report_editor_event(
15583        &self,
15584        event_type: &'static str,
15585        file_extension: Option<String>,
15586        cx: &App,
15587    ) {
15588        if cfg!(any(test, feature = "test-support")) {
15589            return;
15590        }
15591
15592        let Some(project) = &self.project else { return };
15593
15594        // If None, we are in a file without an extension
15595        let file = self
15596            .buffer
15597            .read(cx)
15598            .as_singleton()
15599            .and_then(|b| b.read(cx).file());
15600        let file_extension = file_extension.or(file
15601            .as_ref()
15602            .and_then(|file| Path::new(file.file_name(cx)).extension())
15603            .and_then(|e| e.to_str())
15604            .map(|a| a.to_string()));
15605
15606        let vim_mode = cx
15607            .global::<SettingsStore>()
15608            .raw_user_settings()
15609            .get("vim_mode")
15610            == Some(&serde_json::Value::Bool(true));
15611
15612        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15613        let copilot_enabled = edit_predictions_provider
15614            == language::language_settings::EditPredictionProvider::Copilot;
15615        let copilot_enabled_for_language = self
15616            .buffer
15617            .read(cx)
15618            .settings_at(0, cx)
15619            .show_edit_predictions;
15620
15621        let project = project.read(cx);
15622        telemetry::event!(
15623            event_type,
15624            file_extension,
15625            vim_mode,
15626            copilot_enabled,
15627            copilot_enabled_for_language,
15628            edit_predictions_provider,
15629            is_via_ssh = project.is_via_ssh(),
15630        );
15631    }
15632
15633    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15634    /// with each line being an array of {text, highlight} objects.
15635    fn copy_highlight_json(
15636        &mut self,
15637        _: &CopyHighlightJson,
15638        window: &mut Window,
15639        cx: &mut Context<Self>,
15640    ) {
15641        #[derive(Serialize)]
15642        struct Chunk<'a> {
15643            text: String,
15644            highlight: Option<&'a str>,
15645        }
15646
15647        let snapshot = self.buffer.read(cx).snapshot(cx);
15648        let range = self
15649            .selected_text_range(false, window, cx)
15650            .and_then(|selection| {
15651                if selection.range.is_empty() {
15652                    None
15653                } else {
15654                    Some(selection.range)
15655                }
15656            })
15657            .unwrap_or_else(|| 0..snapshot.len());
15658
15659        let chunks = snapshot.chunks(range, true);
15660        let mut lines = Vec::new();
15661        let mut line: VecDeque<Chunk> = VecDeque::new();
15662
15663        let Some(style) = self.style.as_ref() else {
15664            return;
15665        };
15666
15667        for chunk in chunks {
15668            let highlight = chunk
15669                .syntax_highlight_id
15670                .and_then(|id| id.name(&style.syntax));
15671            let mut chunk_lines = chunk.text.split('\n').peekable();
15672            while let Some(text) = chunk_lines.next() {
15673                let mut merged_with_last_token = false;
15674                if let Some(last_token) = line.back_mut() {
15675                    if last_token.highlight == highlight {
15676                        last_token.text.push_str(text);
15677                        merged_with_last_token = true;
15678                    }
15679                }
15680
15681                if !merged_with_last_token {
15682                    line.push_back(Chunk {
15683                        text: text.into(),
15684                        highlight,
15685                    });
15686                }
15687
15688                if chunk_lines.peek().is_some() {
15689                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15690                        line.pop_front();
15691                    }
15692                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15693                        line.pop_back();
15694                    }
15695
15696                    lines.push(mem::take(&mut line));
15697                }
15698            }
15699        }
15700
15701        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15702            return;
15703        };
15704        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15705    }
15706
15707    pub fn open_context_menu(
15708        &mut self,
15709        _: &OpenContextMenu,
15710        window: &mut Window,
15711        cx: &mut Context<Self>,
15712    ) {
15713        self.request_autoscroll(Autoscroll::newest(), cx);
15714        let position = self.selections.newest_display(cx).start;
15715        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15716    }
15717
15718    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15719        &self.inlay_hint_cache
15720    }
15721
15722    pub fn replay_insert_event(
15723        &mut self,
15724        text: &str,
15725        relative_utf16_range: Option<Range<isize>>,
15726        window: &mut Window,
15727        cx: &mut Context<Self>,
15728    ) {
15729        if !self.input_enabled {
15730            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15731            return;
15732        }
15733        if let Some(relative_utf16_range) = relative_utf16_range {
15734            let selections = self.selections.all::<OffsetUtf16>(cx);
15735            self.change_selections(None, window, cx, |s| {
15736                let new_ranges = selections.into_iter().map(|range| {
15737                    let start = OffsetUtf16(
15738                        range
15739                            .head()
15740                            .0
15741                            .saturating_add_signed(relative_utf16_range.start),
15742                    );
15743                    let end = OffsetUtf16(
15744                        range
15745                            .head()
15746                            .0
15747                            .saturating_add_signed(relative_utf16_range.end),
15748                    );
15749                    start..end
15750                });
15751                s.select_ranges(new_ranges);
15752            });
15753        }
15754
15755        self.handle_input(text, window, cx);
15756    }
15757
15758    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15759        let Some(provider) = self.semantics_provider.as_ref() else {
15760            return false;
15761        };
15762
15763        let mut supports = false;
15764        self.buffer().update(cx, |this, cx| {
15765            this.for_each_buffer(|buffer| {
15766                supports |= provider.supports_inlay_hints(buffer, cx);
15767            });
15768        });
15769
15770        supports
15771    }
15772
15773    pub fn is_focused(&self, window: &Window) -> bool {
15774        self.focus_handle.is_focused(window)
15775    }
15776
15777    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15778        cx.emit(EditorEvent::Focused);
15779
15780        if let Some(descendant) = self
15781            .last_focused_descendant
15782            .take()
15783            .and_then(|descendant| descendant.upgrade())
15784        {
15785            window.focus(&descendant);
15786        } else {
15787            if let Some(blame) = self.blame.as_ref() {
15788                blame.update(cx, GitBlame::focus)
15789            }
15790
15791            self.blink_manager.update(cx, BlinkManager::enable);
15792            self.show_cursor_names(window, cx);
15793            self.buffer.update(cx, |buffer, cx| {
15794                buffer.finalize_last_transaction(cx);
15795                if self.leader_peer_id.is_none() {
15796                    buffer.set_active_selections(
15797                        &self.selections.disjoint_anchors(),
15798                        self.selections.line_mode,
15799                        self.cursor_shape,
15800                        cx,
15801                    );
15802                }
15803            });
15804        }
15805    }
15806
15807    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15808        cx.emit(EditorEvent::FocusedIn)
15809    }
15810
15811    fn handle_focus_out(
15812        &mut self,
15813        event: FocusOutEvent,
15814        _window: &mut Window,
15815        _cx: &mut Context<Self>,
15816    ) {
15817        if event.blurred != self.focus_handle {
15818            self.last_focused_descendant = Some(event.blurred);
15819        }
15820    }
15821
15822    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15823        self.blink_manager.update(cx, BlinkManager::disable);
15824        self.buffer
15825            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15826
15827        if let Some(blame) = self.blame.as_ref() {
15828            blame.update(cx, GitBlame::blur)
15829        }
15830        if !self.hover_state.focused(window, cx) {
15831            hide_hover(self, cx);
15832        }
15833        if !self
15834            .context_menu
15835            .borrow()
15836            .as_ref()
15837            .is_some_and(|context_menu| context_menu.focused(window, cx))
15838        {
15839            self.hide_context_menu(window, cx);
15840        }
15841        self.discard_inline_completion(false, cx);
15842        cx.emit(EditorEvent::Blurred);
15843        cx.notify();
15844    }
15845
15846    pub fn register_action<A: Action>(
15847        &mut self,
15848        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15849    ) -> Subscription {
15850        let id = self.next_editor_action_id.post_inc();
15851        let listener = Arc::new(listener);
15852        self.editor_actions.borrow_mut().insert(
15853            id,
15854            Box::new(move |window, _| {
15855                let listener = listener.clone();
15856                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15857                    let action = action.downcast_ref().unwrap();
15858                    if phase == DispatchPhase::Bubble {
15859                        listener(action, window, cx)
15860                    }
15861                })
15862            }),
15863        );
15864
15865        let editor_actions = self.editor_actions.clone();
15866        Subscription::new(move || {
15867            editor_actions.borrow_mut().remove(&id);
15868        })
15869    }
15870
15871    pub fn file_header_size(&self) -> u32 {
15872        FILE_HEADER_HEIGHT
15873    }
15874
15875    pub fn revert(
15876        &mut self,
15877        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15878        window: &mut Window,
15879        cx: &mut Context<Self>,
15880    ) {
15881        self.buffer().update(cx, |multi_buffer, cx| {
15882            for (buffer_id, changes) in revert_changes {
15883                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15884                    buffer.update(cx, |buffer, cx| {
15885                        buffer.edit(
15886                            changes.into_iter().map(|(range, text)| {
15887                                (range, text.to_string().map(Arc::<str>::from))
15888                            }),
15889                            None,
15890                            cx,
15891                        );
15892                    });
15893                }
15894            }
15895        });
15896        self.change_selections(None, window, cx, |selections| selections.refresh());
15897    }
15898
15899    pub fn to_pixel_point(
15900        &self,
15901        source: multi_buffer::Anchor,
15902        editor_snapshot: &EditorSnapshot,
15903        window: &mut Window,
15904    ) -> Option<gpui::Point<Pixels>> {
15905        let source_point = source.to_display_point(editor_snapshot);
15906        self.display_to_pixel_point(source_point, editor_snapshot, window)
15907    }
15908
15909    pub fn display_to_pixel_point(
15910        &self,
15911        source: DisplayPoint,
15912        editor_snapshot: &EditorSnapshot,
15913        window: &mut Window,
15914    ) -> Option<gpui::Point<Pixels>> {
15915        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15916        let text_layout_details = self.text_layout_details(window);
15917        let scroll_top = text_layout_details
15918            .scroll_anchor
15919            .scroll_position(editor_snapshot)
15920            .y;
15921
15922        if source.row().as_f32() < scroll_top.floor() {
15923            return None;
15924        }
15925        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15926        let source_y = line_height * (source.row().as_f32() - scroll_top);
15927        Some(gpui::Point::new(source_x, source_y))
15928    }
15929
15930    pub fn has_visible_completions_menu(&self) -> bool {
15931        !self.edit_prediction_preview_is_active()
15932            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15933                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15934            })
15935    }
15936
15937    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15938        self.addons
15939            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15940    }
15941
15942    pub fn unregister_addon<T: Addon>(&mut self) {
15943        self.addons.remove(&std::any::TypeId::of::<T>());
15944    }
15945
15946    pub fn addon<T: Addon>(&self) -> Option<&T> {
15947        let type_id = std::any::TypeId::of::<T>();
15948        self.addons
15949            .get(&type_id)
15950            .and_then(|item| item.to_any().downcast_ref::<T>())
15951    }
15952
15953    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15954        let text_layout_details = self.text_layout_details(window);
15955        let style = &text_layout_details.editor_style;
15956        let font_id = window.text_system().resolve_font(&style.text.font());
15957        let font_size = style.text.font_size.to_pixels(window.rem_size());
15958        let line_height = style.text.line_height_in_pixels(window.rem_size());
15959        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15960
15961        gpui::Size::new(em_width, line_height)
15962    }
15963
15964    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15965        self.load_diff_task.clone()
15966    }
15967
15968    fn read_selections_from_db(
15969        &mut self,
15970        item_id: u64,
15971        workspace_id: WorkspaceId,
15972        window: &mut Window,
15973        cx: &mut Context<Editor>,
15974    ) {
15975        if !self.is_singleton(cx)
15976            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15977        {
15978            return;
15979        }
15980        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15981            return;
15982        };
15983        if selections.is_empty() {
15984            return;
15985        }
15986
15987        let snapshot = self.buffer.read(cx).snapshot(cx);
15988        self.change_selections(None, window, cx, |s| {
15989            s.select_ranges(selections.into_iter().map(|(start, end)| {
15990                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15991            }));
15992        });
15993    }
15994}
15995
15996fn insert_extra_newline_brackets(
15997    buffer: &MultiBufferSnapshot,
15998    range: Range<usize>,
15999    language: &language::LanguageScope,
16000) -> bool {
16001    let leading_whitespace_len = buffer
16002        .reversed_chars_at(range.start)
16003        .take_while(|c| c.is_whitespace() && *c != '\n')
16004        .map(|c| c.len_utf8())
16005        .sum::<usize>();
16006    let trailing_whitespace_len = buffer
16007        .chars_at(range.end)
16008        .take_while(|c| c.is_whitespace() && *c != '\n')
16009        .map(|c| c.len_utf8())
16010        .sum::<usize>();
16011    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16012
16013    language.brackets().any(|(pair, enabled)| {
16014        let pair_start = pair.start.trim_end();
16015        let pair_end = pair.end.trim_start();
16016
16017        enabled
16018            && pair.newline
16019            && buffer.contains_str_at(range.end, pair_end)
16020            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16021    })
16022}
16023
16024fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16025    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16026        [(buffer, range, _)] => (*buffer, range.clone()),
16027        _ => return false,
16028    };
16029    let pair = {
16030        let mut result: Option<BracketMatch> = None;
16031
16032        for pair in buffer
16033            .all_bracket_ranges(range.clone())
16034            .filter(move |pair| {
16035                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16036            })
16037        {
16038            let len = pair.close_range.end - pair.open_range.start;
16039
16040            if let Some(existing) = &result {
16041                let existing_len = existing.close_range.end - existing.open_range.start;
16042                if len > existing_len {
16043                    continue;
16044                }
16045            }
16046
16047            result = Some(pair);
16048        }
16049
16050        result
16051    };
16052    let Some(pair) = pair else {
16053        return false;
16054    };
16055    pair.newline_only
16056        && buffer
16057            .chars_for_range(pair.open_range.end..range.start)
16058            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16059            .all(|c| c.is_whitespace() && c != '\n')
16060}
16061
16062fn get_uncommitted_diff_for_buffer(
16063    project: &Entity<Project>,
16064    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16065    buffer: Entity<MultiBuffer>,
16066    cx: &mut App,
16067) -> Task<()> {
16068    let mut tasks = Vec::new();
16069    project.update(cx, |project, cx| {
16070        for buffer in buffers {
16071            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16072        }
16073    });
16074    cx.spawn(|mut cx| async move {
16075        let diffs = futures::future::join_all(tasks).await;
16076        buffer
16077            .update(&mut cx, |buffer, cx| {
16078                for diff in diffs.into_iter().flatten() {
16079                    buffer.add_diff(diff, cx);
16080                }
16081            })
16082            .ok();
16083    })
16084}
16085
16086fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16087    let tab_size = tab_size.get() as usize;
16088    let mut width = offset;
16089
16090    for ch in text.chars() {
16091        width += if ch == '\t' {
16092            tab_size - (width % tab_size)
16093        } else {
16094            1
16095        };
16096    }
16097
16098    width - offset
16099}
16100
16101#[cfg(test)]
16102mod tests {
16103    use super::*;
16104
16105    #[test]
16106    fn test_string_size_with_expanded_tabs() {
16107        let nz = |val| NonZeroU32::new(val).unwrap();
16108        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16109        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16110        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16111        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16112        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16113        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16114        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16115        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16116    }
16117}
16118
16119/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16120struct WordBreakingTokenizer<'a> {
16121    input: &'a str,
16122}
16123
16124impl<'a> WordBreakingTokenizer<'a> {
16125    fn new(input: &'a str) -> Self {
16126        Self { input }
16127    }
16128}
16129
16130fn is_char_ideographic(ch: char) -> bool {
16131    use unicode_script::Script::*;
16132    use unicode_script::UnicodeScript;
16133    matches!(ch.script(), Han | Tangut | Yi)
16134}
16135
16136fn is_grapheme_ideographic(text: &str) -> bool {
16137    text.chars().any(is_char_ideographic)
16138}
16139
16140fn is_grapheme_whitespace(text: &str) -> bool {
16141    text.chars().any(|x| x.is_whitespace())
16142}
16143
16144fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16145    text.chars().next().map_or(false, |ch| {
16146        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16147    })
16148}
16149
16150#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16151struct WordBreakToken<'a> {
16152    token: &'a str,
16153    grapheme_len: usize,
16154    is_whitespace: bool,
16155}
16156
16157impl<'a> Iterator for WordBreakingTokenizer<'a> {
16158    /// Yields a span, the count of graphemes in the token, and whether it was
16159    /// whitespace. Note that it also breaks at word boundaries.
16160    type Item = WordBreakToken<'a>;
16161
16162    fn next(&mut self) -> Option<Self::Item> {
16163        use unicode_segmentation::UnicodeSegmentation;
16164        if self.input.is_empty() {
16165            return None;
16166        }
16167
16168        let mut iter = self.input.graphemes(true).peekable();
16169        let mut offset = 0;
16170        let mut graphemes = 0;
16171        if let Some(first_grapheme) = iter.next() {
16172            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16173            offset += first_grapheme.len();
16174            graphemes += 1;
16175            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16176                if let Some(grapheme) = iter.peek().copied() {
16177                    if should_stay_with_preceding_ideograph(grapheme) {
16178                        offset += grapheme.len();
16179                        graphemes += 1;
16180                    }
16181                }
16182            } else {
16183                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16184                let mut next_word_bound = words.peek().copied();
16185                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16186                    next_word_bound = words.next();
16187                }
16188                while let Some(grapheme) = iter.peek().copied() {
16189                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16190                        break;
16191                    };
16192                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16193                        break;
16194                    };
16195                    offset += grapheme.len();
16196                    graphemes += 1;
16197                    iter.next();
16198                }
16199            }
16200            let token = &self.input[..offset];
16201            self.input = &self.input[offset..];
16202            if is_whitespace {
16203                Some(WordBreakToken {
16204                    token: " ",
16205                    grapheme_len: 1,
16206                    is_whitespace: true,
16207                })
16208            } else {
16209                Some(WordBreakToken {
16210                    token,
16211                    grapheme_len: graphemes,
16212                    is_whitespace: false,
16213                })
16214            }
16215        } else {
16216            None
16217        }
16218    }
16219}
16220
16221#[test]
16222fn test_word_breaking_tokenizer() {
16223    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16224        ("", &[]),
16225        ("  ", &[(" ", 1, true)]),
16226        ("Ʒ", &[("Ʒ", 1, false)]),
16227        ("Ǽ", &[("Ǽ", 1, false)]),
16228        ("", &[("", 1, false)]),
16229        ("⋑⋑", &[("⋑⋑", 2, false)]),
16230        (
16231            "原理,进而",
16232            &[
16233                ("", 1, false),
16234                ("理,", 2, false),
16235                ("", 1, false),
16236                ("", 1, false),
16237            ],
16238        ),
16239        (
16240            "hello world",
16241            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16242        ),
16243        (
16244            "hello, world",
16245            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16246        ),
16247        (
16248            "  hello world",
16249            &[
16250                (" ", 1, true),
16251                ("hello", 5, false),
16252                (" ", 1, true),
16253                ("world", 5, false),
16254            ],
16255        ),
16256        (
16257            "这是什么 \n 钢笔",
16258            &[
16259                ("", 1, false),
16260                ("", 1, false),
16261                ("", 1, false),
16262                ("", 1, false),
16263                (" ", 1, true),
16264                ("", 1, false),
16265                ("", 1, false),
16266            ],
16267        ),
16268        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16269    ];
16270
16271    for (input, result) in tests {
16272        assert_eq!(
16273            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16274            result
16275                .iter()
16276                .copied()
16277                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16278                    token,
16279                    grapheme_len,
16280                    is_whitespace,
16281                })
16282                .collect::<Vec<_>>()
16283        );
16284    }
16285}
16286
16287fn wrap_with_prefix(
16288    line_prefix: String,
16289    unwrapped_text: String,
16290    wrap_column: usize,
16291    tab_size: NonZeroU32,
16292) -> String {
16293    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16294    let mut wrapped_text = String::new();
16295    let mut current_line = line_prefix.clone();
16296
16297    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16298    let mut current_line_len = line_prefix_len;
16299    for WordBreakToken {
16300        token,
16301        grapheme_len,
16302        is_whitespace,
16303    } in tokenizer
16304    {
16305        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16306            wrapped_text.push_str(current_line.trim_end());
16307            wrapped_text.push('\n');
16308            current_line.truncate(line_prefix.len());
16309            current_line_len = line_prefix_len;
16310            if !is_whitespace {
16311                current_line.push_str(token);
16312                current_line_len += grapheme_len;
16313            }
16314        } else if !is_whitespace {
16315            current_line.push_str(token);
16316            current_line_len += grapheme_len;
16317        } else if current_line_len != line_prefix_len {
16318            current_line.push(' ');
16319            current_line_len += 1;
16320        }
16321    }
16322
16323    if !current_line.is_empty() {
16324        wrapped_text.push_str(&current_line);
16325    }
16326    wrapped_text
16327}
16328
16329#[test]
16330fn test_wrap_with_prefix() {
16331    assert_eq!(
16332        wrap_with_prefix(
16333            "# ".to_string(),
16334            "abcdefg".to_string(),
16335            4,
16336            NonZeroU32::new(4).unwrap()
16337        ),
16338        "# abcdefg"
16339    );
16340    assert_eq!(
16341        wrap_with_prefix(
16342            "".to_string(),
16343            "\thello world".to_string(),
16344            8,
16345            NonZeroU32::new(4).unwrap()
16346        ),
16347        "hello\nworld"
16348    );
16349    assert_eq!(
16350        wrap_with_prefix(
16351            "// ".to_string(),
16352            "xx \nyy zz aa bb cc".to_string(),
16353            12,
16354            NonZeroU32::new(4).unwrap()
16355        ),
16356        "// xx yy zz\n// aa bb cc"
16357    );
16358    assert_eq!(
16359        wrap_with_prefix(
16360            String::new(),
16361            "这是什么 \n 钢笔".to_string(),
16362            3,
16363            NonZeroU32::new(4).unwrap()
16364        ),
16365        "这是什\n么 钢\n"
16366    );
16367}
16368
16369pub trait CollaborationHub {
16370    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16371    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16372    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16373}
16374
16375impl CollaborationHub for Entity<Project> {
16376    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16377        self.read(cx).collaborators()
16378    }
16379
16380    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16381        self.read(cx).user_store().read(cx).participant_indices()
16382    }
16383
16384    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16385        let this = self.read(cx);
16386        let user_ids = this.collaborators().values().map(|c| c.user_id);
16387        this.user_store().read_with(cx, |user_store, cx| {
16388            user_store.participant_names(user_ids, cx)
16389        })
16390    }
16391}
16392
16393pub trait SemanticsProvider {
16394    fn hover(
16395        &self,
16396        buffer: &Entity<Buffer>,
16397        position: text::Anchor,
16398        cx: &mut App,
16399    ) -> Option<Task<Vec<project::Hover>>>;
16400
16401    fn inlay_hints(
16402        &self,
16403        buffer_handle: Entity<Buffer>,
16404        range: Range<text::Anchor>,
16405        cx: &mut App,
16406    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16407
16408    fn resolve_inlay_hint(
16409        &self,
16410        hint: InlayHint,
16411        buffer_handle: Entity<Buffer>,
16412        server_id: LanguageServerId,
16413        cx: &mut App,
16414    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16415
16416    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16417
16418    fn document_highlights(
16419        &self,
16420        buffer: &Entity<Buffer>,
16421        position: text::Anchor,
16422        cx: &mut App,
16423    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16424
16425    fn definitions(
16426        &self,
16427        buffer: &Entity<Buffer>,
16428        position: text::Anchor,
16429        kind: GotoDefinitionKind,
16430        cx: &mut App,
16431    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16432
16433    fn range_for_rename(
16434        &self,
16435        buffer: &Entity<Buffer>,
16436        position: text::Anchor,
16437        cx: &mut App,
16438    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16439
16440    fn perform_rename(
16441        &self,
16442        buffer: &Entity<Buffer>,
16443        position: text::Anchor,
16444        new_name: String,
16445        cx: &mut App,
16446    ) -> Option<Task<Result<ProjectTransaction>>>;
16447}
16448
16449pub trait CompletionProvider {
16450    fn completions(
16451        &self,
16452        buffer: &Entity<Buffer>,
16453        buffer_position: text::Anchor,
16454        trigger: CompletionContext,
16455        window: &mut Window,
16456        cx: &mut Context<Editor>,
16457    ) -> Task<Result<Vec<Completion>>>;
16458
16459    fn resolve_completions(
16460        &self,
16461        buffer: Entity<Buffer>,
16462        completion_indices: Vec<usize>,
16463        completions: Rc<RefCell<Box<[Completion]>>>,
16464        cx: &mut Context<Editor>,
16465    ) -> Task<Result<bool>>;
16466
16467    fn apply_additional_edits_for_completion(
16468        &self,
16469        _buffer: Entity<Buffer>,
16470        _completions: Rc<RefCell<Box<[Completion]>>>,
16471        _completion_index: usize,
16472        _push_to_history: bool,
16473        _cx: &mut Context<Editor>,
16474    ) -> Task<Result<Option<language::Transaction>>> {
16475        Task::ready(Ok(None))
16476    }
16477
16478    fn is_completion_trigger(
16479        &self,
16480        buffer: &Entity<Buffer>,
16481        position: language::Anchor,
16482        text: &str,
16483        trigger_in_words: bool,
16484        cx: &mut Context<Editor>,
16485    ) -> bool;
16486
16487    fn sort_completions(&self) -> bool {
16488        true
16489    }
16490}
16491
16492pub trait CodeActionProvider {
16493    fn id(&self) -> Arc<str>;
16494
16495    fn code_actions(
16496        &self,
16497        buffer: &Entity<Buffer>,
16498        range: Range<text::Anchor>,
16499        window: &mut Window,
16500        cx: &mut App,
16501    ) -> Task<Result<Vec<CodeAction>>>;
16502
16503    fn apply_code_action(
16504        &self,
16505        buffer_handle: Entity<Buffer>,
16506        action: CodeAction,
16507        excerpt_id: ExcerptId,
16508        push_to_history: bool,
16509        window: &mut Window,
16510        cx: &mut App,
16511    ) -> Task<Result<ProjectTransaction>>;
16512}
16513
16514impl CodeActionProvider for Entity<Project> {
16515    fn id(&self) -> Arc<str> {
16516        "project".into()
16517    }
16518
16519    fn code_actions(
16520        &self,
16521        buffer: &Entity<Buffer>,
16522        range: Range<text::Anchor>,
16523        _window: &mut Window,
16524        cx: &mut App,
16525    ) -> Task<Result<Vec<CodeAction>>> {
16526        self.update(cx, |project, cx| {
16527            project.code_actions(buffer, range, None, cx)
16528        })
16529    }
16530
16531    fn apply_code_action(
16532        &self,
16533        buffer_handle: Entity<Buffer>,
16534        action: CodeAction,
16535        _excerpt_id: ExcerptId,
16536        push_to_history: bool,
16537        _window: &mut Window,
16538        cx: &mut App,
16539    ) -> Task<Result<ProjectTransaction>> {
16540        self.update(cx, |project, cx| {
16541            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16542        })
16543    }
16544}
16545
16546fn snippet_completions(
16547    project: &Project,
16548    buffer: &Entity<Buffer>,
16549    buffer_position: text::Anchor,
16550    cx: &mut App,
16551) -> Task<Result<Vec<Completion>>> {
16552    let language = buffer.read(cx).language_at(buffer_position);
16553    let language_name = language.as_ref().map(|language| language.lsp_id());
16554    let snippet_store = project.snippets().read(cx);
16555    let snippets = snippet_store.snippets_for(language_name, cx);
16556
16557    if snippets.is_empty() {
16558        return Task::ready(Ok(vec![]));
16559    }
16560    let snapshot = buffer.read(cx).text_snapshot();
16561    let chars: String = snapshot
16562        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16563        .collect();
16564
16565    let scope = language.map(|language| language.default_scope());
16566    let executor = cx.background_executor().clone();
16567
16568    cx.background_spawn(async move {
16569        let classifier = CharClassifier::new(scope).for_completion(true);
16570        let mut last_word = chars
16571            .chars()
16572            .take_while(|c| classifier.is_word(*c))
16573            .collect::<String>();
16574        last_word = last_word.chars().rev().collect();
16575
16576        if last_word.is_empty() {
16577            return Ok(vec![]);
16578        }
16579
16580        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16581        let to_lsp = |point: &text::Anchor| {
16582            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16583            point_to_lsp(end)
16584        };
16585        let lsp_end = to_lsp(&buffer_position);
16586
16587        let candidates = snippets
16588            .iter()
16589            .enumerate()
16590            .flat_map(|(ix, snippet)| {
16591                snippet
16592                    .prefix
16593                    .iter()
16594                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16595            })
16596            .collect::<Vec<StringMatchCandidate>>();
16597
16598        let mut matches = fuzzy::match_strings(
16599            &candidates,
16600            &last_word,
16601            last_word.chars().any(|c| c.is_uppercase()),
16602            100,
16603            &Default::default(),
16604            executor,
16605        )
16606        .await;
16607
16608        // Remove all candidates where the query's start does not match the start of any word in the candidate
16609        if let Some(query_start) = last_word.chars().next() {
16610            matches.retain(|string_match| {
16611                split_words(&string_match.string).any(|word| {
16612                    // Check that the first codepoint of the word as lowercase matches the first
16613                    // codepoint of the query as lowercase
16614                    word.chars()
16615                        .flat_map(|codepoint| codepoint.to_lowercase())
16616                        .zip(query_start.to_lowercase())
16617                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16618                })
16619            });
16620        }
16621
16622        let matched_strings = matches
16623            .into_iter()
16624            .map(|m| m.string)
16625            .collect::<HashSet<_>>();
16626
16627        let result: Vec<Completion> = snippets
16628            .into_iter()
16629            .filter_map(|snippet| {
16630                let matching_prefix = snippet
16631                    .prefix
16632                    .iter()
16633                    .find(|prefix| matched_strings.contains(*prefix))?;
16634                let start = as_offset - last_word.len();
16635                let start = snapshot.anchor_before(start);
16636                let range = start..buffer_position;
16637                let lsp_start = to_lsp(&start);
16638                let lsp_range = lsp::Range {
16639                    start: lsp_start,
16640                    end: lsp_end,
16641                };
16642                Some(Completion {
16643                    old_range: range,
16644                    new_text: snippet.body.clone(),
16645                    resolved: false,
16646                    label: CodeLabel {
16647                        text: matching_prefix.clone(),
16648                        runs: vec![],
16649                        filter_range: 0..matching_prefix.len(),
16650                    },
16651                    server_id: LanguageServerId(usize::MAX),
16652                    documentation: snippet
16653                        .description
16654                        .clone()
16655                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16656                    lsp_completion: lsp::CompletionItem {
16657                        label: snippet.prefix.first().unwrap().clone(),
16658                        kind: Some(CompletionItemKind::SNIPPET),
16659                        label_details: snippet.description.as_ref().map(|description| {
16660                            lsp::CompletionItemLabelDetails {
16661                                detail: Some(description.clone()),
16662                                description: None,
16663                            }
16664                        }),
16665                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16666                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16667                            lsp::InsertReplaceEdit {
16668                                new_text: snippet.body.clone(),
16669                                insert: lsp_range,
16670                                replace: lsp_range,
16671                            },
16672                        )),
16673                        filter_text: Some(snippet.body.clone()),
16674                        sort_text: Some(char::MAX.to_string()),
16675                        ..Default::default()
16676                    },
16677                    confirm: None,
16678                })
16679            })
16680            .collect();
16681
16682        Ok(result)
16683    })
16684}
16685
16686impl CompletionProvider for Entity<Project> {
16687    fn completions(
16688        &self,
16689        buffer: &Entity<Buffer>,
16690        buffer_position: text::Anchor,
16691        options: CompletionContext,
16692        _window: &mut Window,
16693        cx: &mut Context<Editor>,
16694    ) -> Task<Result<Vec<Completion>>> {
16695        self.update(cx, |project, cx| {
16696            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16697            let project_completions = project.completions(buffer, buffer_position, options, cx);
16698            cx.background_spawn(async move {
16699                let mut completions = project_completions.await?;
16700                let snippets_completions = snippets.await?;
16701                completions.extend(snippets_completions);
16702                Ok(completions)
16703            })
16704        })
16705    }
16706
16707    fn resolve_completions(
16708        &self,
16709        buffer: Entity<Buffer>,
16710        completion_indices: Vec<usize>,
16711        completions: Rc<RefCell<Box<[Completion]>>>,
16712        cx: &mut Context<Editor>,
16713    ) -> Task<Result<bool>> {
16714        self.update(cx, |project, cx| {
16715            project.lsp_store().update(cx, |lsp_store, cx| {
16716                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16717            })
16718        })
16719    }
16720
16721    fn apply_additional_edits_for_completion(
16722        &self,
16723        buffer: Entity<Buffer>,
16724        completions: Rc<RefCell<Box<[Completion]>>>,
16725        completion_index: usize,
16726        push_to_history: bool,
16727        cx: &mut Context<Editor>,
16728    ) -> Task<Result<Option<language::Transaction>>> {
16729        self.update(cx, |project, cx| {
16730            project.lsp_store().update(cx, |lsp_store, cx| {
16731                lsp_store.apply_additional_edits_for_completion(
16732                    buffer,
16733                    completions,
16734                    completion_index,
16735                    push_to_history,
16736                    cx,
16737                )
16738            })
16739        })
16740    }
16741
16742    fn is_completion_trigger(
16743        &self,
16744        buffer: &Entity<Buffer>,
16745        position: language::Anchor,
16746        text: &str,
16747        trigger_in_words: bool,
16748        cx: &mut Context<Editor>,
16749    ) -> bool {
16750        let mut chars = text.chars();
16751        let char = if let Some(char) = chars.next() {
16752            char
16753        } else {
16754            return false;
16755        };
16756        if chars.next().is_some() {
16757            return false;
16758        }
16759
16760        let buffer = buffer.read(cx);
16761        let snapshot = buffer.snapshot();
16762        if !snapshot.settings_at(position, cx).show_completions_on_input {
16763            return false;
16764        }
16765        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16766        if trigger_in_words && classifier.is_word(char) {
16767            return true;
16768        }
16769
16770        buffer.completion_triggers().contains(text)
16771    }
16772}
16773
16774impl SemanticsProvider for Entity<Project> {
16775    fn hover(
16776        &self,
16777        buffer: &Entity<Buffer>,
16778        position: text::Anchor,
16779        cx: &mut App,
16780    ) -> Option<Task<Vec<project::Hover>>> {
16781        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16782    }
16783
16784    fn document_highlights(
16785        &self,
16786        buffer: &Entity<Buffer>,
16787        position: text::Anchor,
16788        cx: &mut App,
16789    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16790        Some(self.update(cx, |project, cx| {
16791            project.document_highlights(buffer, position, cx)
16792        }))
16793    }
16794
16795    fn definitions(
16796        &self,
16797        buffer: &Entity<Buffer>,
16798        position: text::Anchor,
16799        kind: GotoDefinitionKind,
16800        cx: &mut App,
16801    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16802        Some(self.update(cx, |project, cx| match kind {
16803            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16804            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16805            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16806            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16807        }))
16808    }
16809
16810    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16811        // TODO: make this work for remote projects
16812        self.update(cx, |this, cx| {
16813            buffer.update(cx, |buffer, cx| {
16814                this.any_language_server_supports_inlay_hints(buffer, cx)
16815            })
16816        })
16817    }
16818
16819    fn inlay_hints(
16820        &self,
16821        buffer_handle: Entity<Buffer>,
16822        range: Range<text::Anchor>,
16823        cx: &mut App,
16824    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16825        Some(self.update(cx, |project, cx| {
16826            project.inlay_hints(buffer_handle, range, cx)
16827        }))
16828    }
16829
16830    fn resolve_inlay_hint(
16831        &self,
16832        hint: InlayHint,
16833        buffer_handle: Entity<Buffer>,
16834        server_id: LanguageServerId,
16835        cx: &mut App,
16836    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16837        Some(self.update(cx, |project, cx| {
16838            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16839        }))
16840    }
16841
16842    fn range_for_rename(
16843        &self,
16844        buffer: &Entity<Buffer>,
16845        position: text::Anchor,
16846        cx: &mut App,
16847    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16848        Some(self.update(cx, |project, cx| {
16849            let buffer = buffer.clone();
16850            let task = project.prepare_rename(buffer.clone(), position, cx);
16851            cx.spawn(|_, mut cx| async move {
16852                Ok(match task.await? {
16853                    PrepareRenameResponse::Success(range) => Some(range),
16854                    PrepareRenameResponse::InvalidPosition => None,
16855                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16856                        // Fallback on using TreeSitter info to determine identifier range
16857                        buffer.update(&mut cx, |buffer, _| {
16858                            let snapshot = buffer.snapshot();
16859                            let (range, kind) = snapshot.surrounding_word(position);
16860                            if kind != Some(CharKind::Word) {
16861                                return None;
16862                            }
16863                            Some(
16864                                snapshot.anchor_before(range.start)
16865                                    ..snapshot.anchor_after(range.end),
16866                            )
16867                        })?
16868                    }
16869                })
16870            })
16871        }))
16872    }
16873
16874    fn perform_rename(
16875        &self,
16876        buffer: &Entity<Buffer>,
16877        position: text::Anchor,
16878        new_name: String,
16879        cx: &mut App,
16880    ) -> Option<Task<Result<ProjectTransaction>>> {
16881        Some(self.update(cx, |project, cx| {
16882            project.perform_rename(buffer.clone(), position, new_name, cx)
16883        }))
16884    }
16885}
16886
16887fn inlay_hint_settings(
16888    location: Anchor,
16889    snapshot: &MultiBufferSnapshot,
16890    cx: &mut Context<Editor>,
16891) -> InlayHintSettings {
16892    let file = snapshot.file_at(location);
16893    let language = snapshot.language_at(location).map(|l| l.name());
16894    language_settings(language, file, cx).inlay_hints
16895}
16896
16897fn consume_contiguous_rows(
16898    contiguous_row_selections: &mut Vec<Selection<Point>>,
16899    selection: &Selection<Point>,
16900    display_map: &DisplaySnapshot,
16901    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16902) -> (MultiBufferRow, MultiBufferRow) {
16903    contiguous_row_selections.push(selection.clone());
16904    let start_row = MultiBufferRow(selection.start.row);
16905    let mut end_row = ending_row(selection, display_map);
16906
16907    while let Some(next_selection) = selections.peek() {
16908        if next_selection.start.row <= end_row.0 {
16909            end_row = ending_row(next_selection, display_map);
16910            contiguous_row_selections.push(selections.next().unwrap().clone());
16911        } else {
16912            break;
16913        }
16914    }
16915    (start_row, end_row)
16916}
16917
16918fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16919    if next_selection.end.column > 0 || next_selection.is_empty() {
16920        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16921    } else {
16922        MultiBufferRow(next_selection.end.row)
16923    }
16924}
16925
16926impl EditorSnapshot {
16927    pub fn remote_selections_in_range<'a>(
16928        &'a self,
16929        range: &'a Range<Anchor>,
16930        collaboration_hub: &dyn CollaborationHub,
16931        cx: &'a App,
16932    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16933        let participant_names = collaboration_hub.user_names(cx);
16934        let participant_indices = collaboration_hub.user_participant_indices(cx);
16935        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16936        let collaborators_by_replica_id = collaborators_by_peer_id
16937            .iter()
16938            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16939            .collect::<HashMap<_, _>>();
16940        self.buffer_snapshot
16941            .selections_in_range(range, false)
16942            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16943                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16944                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16945                let user_name = participant_names.get(&collaborator.user_id).cloned();
16946                Some(RemoteSelection {
16947                    replica_id,
16948                    selection,
16949                    cursor_shape,
16950                    line_mode,
16951                    participant_index,
16952                    peer_id: collaborator.peer_id,
16953                    user_name,
16954                })
16955            })
16956    }
16957
16958    pub fn hunks_for_ranges(
16959        &self,
16960        ranges: impl Iterator<Item = Range<Point>>,
16961    ) -> Vec<MultiBufferDiffHunk> {
16962        let mut hunks = Vec::new();
16963        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16964            HashMap::default();
16965        for query_range in ranges {
16966            let query_rows =
16967                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16968            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16969                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16970            ) {
16971                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16972                // when the caret is just above or just below the deleted hunk.
16973                let allow_adjacent = hunk.status().is_deleted();
16974                let related_to_selection = if allow_adjacent {
16975                    hunk.row_range.overlaps(&query_rows)
16976                        || hunk.row_range.start == query_rows.end
16977                        || hunk.row_range.end == query_rows.start
16978                } else {
16979                    hunk.row_range.overlaps(&query_rows)
16980                };
16981                if related_to_selection {
16982                    if !processed_buffer_rows
16983                        .entry(hunk.buffer_id)
16984                        .or_default()
16985                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16986                    {
16987                        continue;
16988                    }
16989                    hunks.push(hunk);
16990                }
16991            }
16992        }
16993
16994        hunks
16995    }
16996
16997    fn display_diff_hunks_for_rows<'a>(
16998        &'a self,
16999        display_rows: Range<DisplayRow>,
17000        folded_buffers: &'a HashSet<BufferId>,
17001    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17002        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17003        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17004
17005        self.buffer_snapshot
17006            .diff_hunks_in_range(buffer_start..buffer_end)
17007            .filter_map(|hunk| {
17008                if folded_buffers.contains(&hunk.buffer_id) {
17009                    return None;
17010                }
17011
17012                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17013                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17014
17015                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17016                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17017
17018                let display_hunk = if hunk_display_start.column() != 0 {
17019                    DisplayDiffHunk::Folded {
17020                        display_row: hunk_display_start.row(),
17021                    }
17022                } else {
17023                    let mut end_row = hunk_display_end.row();
17024                    if hunk_display_end.column() > 0 {
17025                        end_row.0 += 1;
17026                    }
17027                    DisplayDiffHunk::Unfolded {
17028                        status: hunk.status(),
17029                        diff_base_byte_range: hunk.diff_base_byte_range,
17030                        display_row_range: hunk_display_start.row()..end_row,
17031                        multi_buffer_range: Anchor::range_in_buffer(
17032                            hunk.excerpt_id,
17033                            hunk.buffer_id,
17034                            hunk.buffer_range,
17035                        ),
17036                    }
17037                };
17038
17039                Some(display_hunk)
17040            })
17041    }
17042
17043    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17044        self.display_snapshot.buffer_snapshot.language_at(position)
17045    }
17046
17047    pub fn is_focused(&self) -> bool {
17048        self.is_focused
17049    }
17050
17051    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17052        self.placeholder_text.as_ref()
17053    }
17054
17055    pub fn scroll_position(&self) -> gpui::Point<f32> {
17056        self.scroll_anchor.scroll_position(&self.display_snapshot)
17057    }
17058
17059    fn gutter_dimensions(
17060        &self,
17061        font_id: FontId,
17062        font_size: Pixels,
17063        max_line_number_width: Pixels,
17064        cx: &App,
17065    ) -> Option<GutterDimensions> {
17066        if !self.show_gutter {
17067            return None;
17068        }
17069
17070        let descent = cx.text_system().descent(font_id, font_size);
17071        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17072        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17073
17074        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17075            matches!(
17076                ProjectSettings::get_global(cx).git.git_gutter,
17077                Some(GitGutterSetting::TrackedFiles)
17078            )
17079        });
17080        let gutter_settings = EditorSettings::get_global(cx).gutter;
17081        let show_line_numbers = self
17082            .show_line_numbers
17083            .unwrap_or(gutter_settings.line_numbers);
17084        let line_gutter_width = if show_line_numbers {
17085            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17086            let min_width_for_number_on_gutter = em_advance * 4.0;
17087            max_line_number_width.max(min_width_for_number_on_gutter)
17088        } else {
17089            0.0.into()
17090        };
17091
17092        let show_code_actions = self
17093            .show_code_actions
17094            .unwrap_or(gutter_settings.code_actions);
17095
17096        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17097
17098        let git_blame_entries_width =
17099            self.git_blame_gutter_max_author_length
17100                .map(|max_author_length| {
17101                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17102
17103                    /// The number of characters to dedicate to gaps and margins.
17104                    const SPACING_WIDTH: usize = 4;
17105
17106                    let max_char_count = max_author_length
17107                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17108                        + ::git::SHORT_SHA_LENGTH
17109                        + MAX_RELATIVE_TIMESTAMP.len()
17110                        + SPACING_WIDTH;
17111
17112                    em_advance * max_char_count
17113                });
17114
17115        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17116        left_padding += if show_code_actions || show_runnables {
17117            em_width * 3.0
17118        } else if show_git_gutter && show_line_numbers {
17119            em_width * 2.0
17120        } else if show_git_gutter || show_line_numbers {
17121            em_width
17122        } else {
17123            px(0.)
17124        };
17125
17126        let right_padding = if gutter_settings.folds && show_line_numbers {
17127            em_width * 4.0
17128        } else if gutter_settings.folds {
17129            em_width * 3.0
17130        } else if show_line_numbers {
17131            em_width
17132        } else {
17133            px(0.)
17134        };
17135
17136        Some(GutterDimensions {
17137            left_padding,
17138            right_padding,
17139            width: line_gutter_width + left_padding + right_padding,
17140            margin: -descent,
17141            git_blame_entries_width,
17142        })
17143    }
17144
17145    pub fn render_crease_toggle(
17146        &self,
17147        buffer_row: MultiBufferRow,
17148        row_contains_cursor: bool,
17149        editor: Entity<Editor>,
17150        window: &mut Window,
17151        cx: &mut App,
17152    ) -> Option<AnyElement> {
17153        let folded = self.is_line_folded(buffer_row);
17154        let mut is_foldable = false;
17155
17156        if let Some(crease) = self
17157            .crease_snapshot
17158            .query_row(buffer_row, &self.buffer_snapshot)
17159        {
17160            is_foldable = true;
17161            match crease {
17162                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17163                    if let Some(render_toggle) = render_toggle {
17164                        let toggle_callback =
17165                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17166                                if folded {
17167                                    editor.update(cx, |editor, cx| {
17168                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17169                                    });
17170                                } else {
17171                                    editor.update(cx, |editor, cx| {
17172                                        editor.unfold_at(
17173                                            &crate::UnfoldAt { buffer_row },
17174                                            window,
17175                                            cx,
17176                                        )
17177                                    });
17178                                }
17179                            });
17180                        return Some((render_toggle)(
17181                            buffer_row,
17182                            folded,
17183                            toggle_callback,
17184                            window,
17185                            cx,
17186                        ));
17187                    }
17188                }
17189            }
17190        }
17191
17192        is_foldable |= self.starts_indent(buffer_row);
17193
17194        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17195            Some(
17196                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17197                    .toggle_state(folded)
17198                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17199                        if folded {
17200                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17201                        } else {
17202                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17203                        }
17204                    }))
17205                    .into_any_element(),
17206            )
17207        } else {
17208            None
17209        }
17210    }
17211
17212    pub fn render_crease_trailer(
17213        &self,
17214        buffer_row: MultiBufferRow,
17215        window: &mut Window,
17216        cx: &mut App,
17217    ) -> Option<AnyElement> {
17218        let folded = self.is_line_folded(buffer_row);
17219        if let Crease::Inline { render_trailer, .. } = self
17220            .crease_snapshot
17221            .query_row(buffer_row, &self.buffer_snapshot)?
17222        {
17223            let render_trailer = render_trailer.as_ref()?;
17224            Some(render_trailer(buffer_row, folded, window, cx))
17225        } else {
17226            None
17227        }
17228    }
17229}
17230
17231impl Deref for EditorSnapshot {
17232    type Target = DisplaySnapshot;
17233
17234    fn deref(&self) -> &Self::Target {
17235        &self.display_snapshot
17236    }
17237}
17238
17239#[derive(Clone, Debug, PartialEq, Eq)]
17240pub enum EditorEvent {
17241    InputIgnored {
17242        text: Arc<str>,
17243    },
17244    InputHandled {
17245        utf16_range_to_replace: Option<Range<isize>>,
17246        text: Arc<str>,
17247    },
17248    ExcerptsAdded {
17249        buffer: Entity<Buffer>,
17250        predecessor: ExcerptId,
17251        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17252    },
17253    ExcerptsRemoved {
17254        ids: Vec<ExcerptId>,
17255    },
17256    BufferFoldToggled {
17257        ids: Vec<ExcerptId>,
17258        folded: bool,
17259    },
17260    ExcerptsEdited {
17261        ids: Vec<ExcerptId>,
17262    },
17263    ExcerptsExpanded {
17264        ids: Vec<ExcerptId>,
17265    },
17266    BufferEdited,
17267    Edited {
17268        transaction_id: clock::Lamport,
17269    },
17270    Reparsed(BufferId),
17271    Focused,
17272    FocusedIn,
17273    Blurred,
17274    DirtyChanged,
17275    Saved,
17276    TitleChanged,
17277    DiffBaseChanged,
17278    SelectionsChanged {
17279        local: bool,
17280    },
17281    ScrollPositionChanged {
17282        local: bool,
17283        autoscroll: bool,
17284    },
17285    Closed,
17286    TransactionUndone {
17287        transaction_id: clock::Lamport,
17288    },
17289    TransactionBegun {
17290        transaction_id: clock::Lamport,
17291    },
17292    Reloaded,
17293    CursorShapeChanged,
17294}
17295
17296impl EventEmitter<EditorEvent> for Editor {}
17297
17298impl Focusable for Editor {
17299    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17300        self.focus_handle.clone()
17301    }
17302}
17303
17304impl Render for Editor {
17305    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17306        let settings = ThemeSettings::get_global(cx);
17307
17308        let mut text_style = match self.mode {
17309            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17310                color: cx.theme().colors().editor_foreground,
17311                font_family: settings.ui_font.family.clone(),
17312                font_features: settings.ui_font.features.clone(),
17313                font_fallbacks: settings.ui_font.fallbacks.clone(),
17314                font_size: rems(0.875).into(),
17315                font_weight: settings.ui_font.weight,
17316                line_height: relative(settings.buffer_line_height.value()),
17317                ..Default::default()
17318            },
17319            EditorMode::Full => TextStyle {
17320                color: cx.theme().colors().editor_foreground,
17321                font_family: settings.buffer_font.family.clone(),
17322                font_features: settings.buffer_font.features.clone(),
17323                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17324                font_size: settings.buffer_font_size(cx).into(),
17325                font_weight: settings.buffer_font.weight,
17326                line_height: relative(settings.buffer_line_height.value()),
17327                ..Default::default()
17328            },
17329        };
17330        if let Some(text_style_refinement) = &self.text_style_refinement {
17331            text_style.refine(text_style_refinement)
17332        }
17333
17334        let background = match self.mode {
17335            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17336            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17337            EditorMode::Full => cx.theme().colors().editor_background,
17338        };
17339
17340        EditorElement::new(
17341            &cx.entity(),
17342            EditorStyle {
17343                background,
17344                local_player: cx.theme().players().local(),
17345                text: text_style,
17346                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17347                syntax: cx.theme().syntax().clone(),
17348                status: cx.theme().status().clone(),
17349                inlay_hints_style: make_inlay_hints_style(cx),
17350                inline_completion_styles: make_suggestion_styles(cx),
17351                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17352            },
17353        )
17354    }
17355}
17356
17357impl EntityInputHandler for Editor {
17358    fn text_for_range(
17359        &mut self,
17360        range_utf16: Range<usize>,
17361        adjusted_range: &mut Option<Range<usize>>,
17362        _: &mut Window,
17363        cx: &mut Context<Self>,
17364    ) -> Option<String> {
17365        let snapshot = self.buffer.read(cx).read(cx);
17366        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17367        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17368        if (start.0..end.0) != range_utf16 {
17369            adjusted_range.replace(start.0..end.0);
17370        }
17371        Some(snapshot.text_for_range(start..end).collect())
17372    }
17373
17374    fn selected_text_range(
17375        &mut self,
17376        ignore_disabled_input: bool,
17377        _: &mut Window,
17378        cx: &mut Context<Self>,
17379    ) -> Option<UTF16Selection> {
17380        // Prevent the IME menu from appearing when holding down an alphabetic key
17381        // while input is disabled.
17382        if !ignore_disabled_input && !self.input_enabled {
17383            return None;
17384        }
17385
17386        let selection = self.selections.newest::<OffsetUtf16>(cx);
17387        let range = selection.range();
17388
17389        Some(UTF16Selection {
17390            range: range.start.0..range.end.0,
17391            reversed: selection.reversed,
17392        })
17393    }
17394
17395    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17396        let snapshot = self.buffer.read(cx).read(cx);
17397        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17398        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17399    }
17400
17401    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17402        self.clear_highlights::<InputComposition>(cx);
17403        self.ime_transaction.take();
17404    }
17405
17406    fn replace_text_in_range(
17407        &mut self,
17408        range_utf16: Option<Range<usize>>,
17409        text: &str,
17410        window: &mut Window,
17411        cx: &mut Context<Self>,
17412    ) {
17413        if !self.input_enabled {
17414            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17415            return;
17416        }
17417
17418        self.transact(window, cx, |this, window, cx| {
17419            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17420                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17421                Some(this.selection_replacement_ranges(range_utf16, cx))
17422            } else {
17423                this.marked_text_ranges(cx)
17424            };
17425
17426            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17427                let newest_selection_id = this.selections.newest_anchor().id;
17428                this.selections
17429                    .all::<OffsetUtf16>(cx)
17430                    .iter()
17431                    .zip(ranges_to_replace.iter())
17432                    .find_map(|(selection, range)| {
17433                        if selection.id == newest_selection_id {
17434                            Some(
17435                                (range.start.0 as isize - selection.head().0 as isize)
17436                                    ..(range.end.0 as isize - selection.head().0 as isize),
17437                            )
17438                        } else {
17439                            None
17440                        }
17441                    })
17442            });
17443
17444            cx.emit(EditorEvent::InputHandled {
17445                utf16_range_to_replace: range_to_replace,
17446                text: text.into(),
17447            });
17448
17449            if let Some(new_selected_ranges) = new_selected_ranges {
17450                this.change_selections(None, window, cx, |selections| {
17451                    selections.select_ranges(new_selected_ranges)
17452                });
17453                this.backspace(&Default::default(), window, cx);
17454            }
17455
17456            this.handle_input(text, window, cx);
17457        });
17458
17459        if let Some(transaction) = self.ime_transaction {
17460            self.buffer.update(cx, |buffer, cx| {
17461                buffer.group_until_transaction(transaction, cx);
17462            });
17463        }
17464
17465        self.unmark_text(window, cx);
17466    }
17467
17468    fn replace_and_mark_text_in_range(
17469        &mut self,
17470        range_utf16: Option<Range<usize>>,
17471        text: &str,
17472        new_selected_range_utf16: Option<Range<usize>>,
17473        window: &mut Window,
17474        cx: &mut Context<Self>,
17475    ) {
17476        if !self.input_enabled {
17477            return;
17478        }
17479
17480        let transaction = self.transact(window, cx, |this, window, cx| {
17481            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17482                let snapshot = this.buffer.read(cx).read(cx);
17483                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17484                    for marked_range in &mut marked_ranges {
17485                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17486                        marked_range.start.0 += relative_range_utf16.start;
17487                        marked_range.start =
17488                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17489                        marked_range.end =
17490                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17491                    }
17492                }
17493                Some(marked_ranges)
17494            } else if let Some(range_utf16) = range_utf16 {
17495                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17496                Some(this.selection_replacement_ranges(range_utf16, cx))
17497            } else {
17498                None
17499            };
17500
17501            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17502                let newest_selection_id = this.selections.newest_anchor().id;
17503                this.selections
17504                    .all::<OffsetUtf16>(cx)
17505                    .iter()
17506                    .zip(ranges_to_replace.iter())
17507                    .find_map(|(selection, range)| {
17508                        if selection.id == newest_selection_id {
17509                            Some(
17510                                (range.start.0 as isize - selection.head().0 as isize)
17511                                    ..(range.end.0 as isize - selection.head().0 as isize),
17512                            )
17513                        } else {
17514                            None
17515                        }
17516                    })
17517            });
17518
17519            cx.emit(EditorEvent::InputHandled {
17520                utf16_range_to_replace: range_to_replace,
17521                text: text.into(),
17522            });
17523
17524            if let Some(ranges) = ranges_to_replace {
17525                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17526            }
17527
17528            let marked_ranges = {
17529                let snapshot = this.buffer.read(cx).read(cx);
17530                this.selections
17531                    .disjoint_anchors()
17532                    .iter()
17533                    .map(|selection| {
17534                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17535                    })
17536                    .collect::<Vec<_>>()
17537            };
17538
17539            if text.is_empty() {
17540                this.unmark_text(window, cx);
17541            } else {
17542                this.highlight_text::<InputComposition>(
17543                    marked_ranges.clone(),
17544                    HighlightStyle {
17545                        underline: Some(UnderlineStyle {
17546                            thickness: px(1.),
17547                            color: None,
17548                            wavy: false,
17549                        }),
17550                        ..Default::default()
17551                    },
17552                    cx,
17553                );
17554            }
17555
17556            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17557            let use_autoclose = this.use_autoclose;
17558            let use_auto_surround = this.use_auto_surround;
17559            this.set_use_autoclose(false);
17560            this.set_use_auto_surround(false);
17561            this.handle_input(text, window, cx);
17562            this.set_use_autoclose(use_autoclose);
17563            this.set_use_auto_surround(use_auto_surround);
17564
17565            if let Some(new_selected_range) = new_selected_range_utf16 {
17566                let snapshot = this.buffer.read(cx).read(cx);
17567                let new_selected_ranges = marked_ranges
17568                    .into_iter()
17569                    .map(|marked_range| {
17570                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17571                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17572                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17573                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17574                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17575                    })
17576                    .collect::<Vec<_>>();
17577
17578                drop(snapshot);
17579                this.change_selections(None, window, cx, |selections| {
17580                    selections.select_ranges(new_selected_ranges)
17581                });
17582            }
17583        });
17584
17585        self.ime_transaction = self.ime_transaction.or(transaction);
17586        if let Some(transaction) = self.ime_transaction {
17587            self.buffer.update(cx, |buffer, cx| {
17588                buffer.group_until_transaction(transaction, cx);
17589            });
17590        }
17591
17592        if self.text_highlights::<InputComposition>(cx).is_none() {
17593            self.ime_transaction.take();
17594        }
17595    }
17596
17597    fn bounds_for_range(
17598        &mut self,
17599        range_utf16: Range<usize>,
17600        element_bounds: gpui::Bounds<Pixels>,
17601        window: &mut Window,
17602        cx: &mut Context<Self>,
17603    ) -> Option<gpui::Bounds<Pixels>> {
17604        let text_layout_details = self.text_layout_details(window);
17605        let gpui::Size {
17606            width: em_width,
17607            height: line_height,
17608        } = self.character_size(window);
17609
17610        let snapshot = self.snapshot(window, cx);
17611        let scroll_position = snapshot.scroll_position();
17612        let scroll_left = scroll_position.x * em_width;
17613
17614        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17615        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17616            + self.gutter_dimensions.width
17617            + self.gutter_dimensions.margin;
17618        let y = line_height * (start.row().as_f32() - scroll_position.y);
17619
17620        Some(Bounds {
17621            origin: element_bounds.origin + point(x, y),
17622            size: size(em_width, line_height),
17623        })
17624    }
17625
17626    fn character_index_for_point(
17627        &mut self,
17628        point: gpui::Point<Pixels>,
17629        _window: &mut Window,
17630        _cx: &mut Context<Self>,
17631    ) -> Option<usize> {
17632        let position_map = self.last_position_map.as_ref()?;
17633        if !position_map.text_hitbox.contains(&point) {
17634            return None;
17635        }
17636        let display_point = position_map.point_for_position(point).previous_valid;
17637        let anchor = position_map
17638            .snapshot
17639            .display_point_to_anchor(display_point, Bias::Left);
17640        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17641        Some(utf16_offset.0)
17642    }
17643}
17644
17645trait SelectionExt {
17646    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17647    fn spanned_rows(
17648        &self,
17649        include_end_if_at_line_start: bool,
17650        map: &DisplaySnapshot,
17651    ) -> Range<MultiBufferRow>;
17652}
17653
17654impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17655    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17656        let start = self
17657            .start
17658            .to_point(&map.buffer_snapshot)
17659            .to_display_point(map);
17660        let end = self
17661            .end
17662            .to_point(&map.buffer_snapshot)
17663            .to_display_point(map);
17664        if self.reversed {
17665            end..start
17666        } else {
17667            start..end
17668        }
17669    }
17670
17671    fn spanned_rows(
17672        &self,
17673        include_end_if_at_line_start: bool,
17674        map: &DisplaySnapshot,
17675    ) -> Range<MultiBufferRow> {
17676        let start = self.start.to_point(&map.buffer_snapshot);
17677        let mut end = self.end.to_point(&map.buffer_snapshot);
17678        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17679            end.row -= 1;
17680        }
17681
17682        let buffer_start = map.prev_line_boundary(start).0;
17683        let buffer_end = map.next_line_boundary(end).0;
17684        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17685    }
17686}
17687
17688impl<T: InvalidationRegion> InvalidationStack<T> {
17689    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17690    where
17691        S: Clone + ToOffset,
17692    {
17693        while let Some(region) = self.last() {
17694            let all_selections_inside_invalidation_ranges =
17695                if selections.len() == region.ranges().len() {
17696                    selections
17697                        .iter()
17698                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17699                        .all(|(selection, invalidation_range)| {
17700                            let head = selection.head().to_offset(buffer);
17701                            invalidation_range.start <= head && invalidation_range.end >= head
17702                        })
17703                } else {
17704                    false
17705                };
17706
17707            if all_selections_inside_invalidation_ranges {
17708                break;
17709            } else {
17710                self.pop();
17711            }
17712        }
17713    }
17714}
17715
17716impl<T> Default for InvalidationStack<T> {
17717    fn default() -> Self {
17718        Self(Default::default())
17719    }
17720}
17721
17722impl<T> Deref for InvalidationStack<T> {
17723    type Target = Vec<T>;
17724
17725    fn deref(&self) -> &Self::Target {
17726        &self.0
17727    }
17728}
17729
17730impl<T> DerefMut for InvalidationStack<T> {
17731    fn deref_mut(&mut self) -> &mut Self::Target {
17732        &mut self.0
17733    }
17734}
17735
17736impl InvalidationRegion for SnippetState {
17737    fn ranges(&self) -> &[Range<Anchor>] {
17738        &self.ranges[self.active_index]
17739    }
17740}
17741
17742pub fn diagnostic_block_renderer(
17743    diagnostic: Diagnostic,
17744    max_message_rows: Option<u8>,
17745    allow_closing: bool,
17746    _is_valid: bool,
17747) -> RenderBlock {
17748    let (text_without_backticks, code_ranges) =
17749        highlight_diagnostic_message(&diagnostic, max_message_rows);
17750
17751    Arc::new(move |cx: &mut BlockContext| {
17752        let group_id: SharedString = cx.block_id.to_string().into();
17753
17754        let mut text_style = cx.window.text_style().clone();
17755        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17756        let theme_settings = ThemeSettings::get_global(cx);
17757        text_style.font_family = theme_settings.buffer_font.family.clone();
17758        text_style.font_style = theme_settings.buffer_font.style;
17759        text_style.font_features = theme_settings.buffer_font.features.clone();
17760        text_style.font_weight = theme_settings.buffer_font.weight;
17761
17762        let multi_line_diagnostic = diagnostic.message.contains('\n');
17763
17764        let buttons = |diagnostic: &Diagnostic| {
17765            if multi_line_diagnostic {
17766                v_flex()
17767            } else {
17768                h_flex()
17769            }
17770            .when(allow_closing, |div| {
17771                div.children(diagnostic.is_primary.then(|| {
17772                    IconButton::new("close-block", IconName::XCircle)
17773                        .icon_color(Color::Muted)
17774                        .size(ButtonSize::Compact)
17775                        .style(ButtonStyle::Transparent)
17776                        .visible_on_hover(group_id.clone())
17777                        .on_click(move |_click, window, cx| {
17778                            window.dispatch_action(Box::new(Cancel), cx)
17779                        })
17780                        .tooltip(|window, cx| {
17781                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17782                        })
17783                }))
17784            })
17785            .child(
17786                IconButton::new("copy-block", IconName::Copy)
17787                    .icon_color(Color::Muted)
17788                    .size(ButtonSize::Compact)
17789                    .style(ButtonStyle::Transparent)
17790                    .visible_on_hover(group_id.clone())
17791                    .on_click({
17792                        let message = diagnostic.message.clone();
17793                        move |_click, _, cx| {
17794                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17795                        }
17796                    })
17797                    .tooltip(Tooltip::text("Copy diagnostic message")),
17798            )
17799        };
17800
17801        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17802            AvailableSpace::min_size(),
17803            cx.window,
17804            cx.app,
17805        );
17806
17807        h_flex()
17808            .id(cx.block_id)
17809            .group(group_id.clone())
17810            .relative()
17811            .size_full()
17812            .block_mouse_down()
17813            .pl(cx.gutter_dimensions.width)
17814            .w(cx.max_width - cx.gutter_dimensions.full_width())
17815            .child(
17816                div()
17817                    .flex()
17818                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17819                    .flex_shrink(),
17820            )
17821            .child(buttons(&diagnostic))
17822            .child(div().flex().flex_shrink_0().child(
17823                StyledText::new(text_without_backticks.clone()).with_highlights(
17824                    &text_style,
17825                    code_ranges.iter().map(|range| {
17826                        (
17827                            range.clone(),
17828                            HighlightStyle {
17829                                font_weight: Some(FontWeight::BOLD),
17830                                ..Default::default()
17831                            },
17832                        )
17833                    }),
17834                ),
17835            ))
17836            .into_any_element()
17837    })
17838}
17839
17840fn inline_completion_edit_text(
17841    current_snapshot: &BufferSnapshot,
17842    edits: &[(Range<Anchor>, String)],
17843    edit_preview: &EditPreview,
17844    include_deletions: bool,
17845    cx: &App,
17846) -> HighlightedText {
17847    let edits = edits
17848        .iter()
17849        .map(|(anchor, text)| {
17850            (
17851                anchor.start.text_anchor..anchor.end.text_anchor,
17852                text.clone(),
17853            )
17854        })
17855        .collect::<Vec<_>>();
17856
17857    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17858}
17859
17860pub fn highlight_diagnostic_message(
17861    diagnostic: &Diagnostic,
17862    mut max_message_rows: Option<u8>,
17863) -> (SharedString, Vec<Range<usize>>) {
17864    let mut text_without_backticks = String::new();
17865    let mut code_ranges = Vec::new();
17866
17867    if let Some(source) = &diagnostic.source {
17868        text_without_backticks.push_str(source);
17869        code_ranges.push(0..source.len());
17870        text_without_backticks.push_str(": ");
17871    }
17872
17873    let mut prev_offset = 0;
17874    let mut in_code_block = false;
17875    let has_row_limit = max_message_rows.is_some();
17876    let mut newline_indices = diagnostic
17877        .message
17878        .match_indices('\n')
17879        .filter(|_| has_row_limit)
17880        .map(|(ix, _)| ix)
17881        .fuse()
17882        .peekable();
17883
17884    for (quote_ix, _) in diagnostic
17885        .message
17886        .match_indices('`')
17887        .chain([(diagnostic.message.len(), "")])
17888    {
17889        let mut first_newline_ix = None;
17890        let mut last_newline_ix = None;
17891        while let Some(newline_ix) = newline_indices.peek() {
17892            if *newline_ix < quote_ix {
17893                if first_newline_ix.is_none() {
17894                    first_newline_ix = Some(*newline_ix);
17895                }
17896                last_newline_ix = Some(*newline_ix);
17897
17898                if let Some(rows_left) = &mut max_message_rows {
17899                    if *rows_left == 0 {
17900                        break;
17901                    } else {
17902                        *rows_left -= 1;
17903                    }
17904                }
17905                let _ = newline_indices.next();
17906            } else {
17907                break;
17908            }
17909        }
17910        let prev_len = text_without_backticks.len();
17911        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17912        text_without_backticks.push_str(new_text);
17913        if in_code_block {
17914            code_ranges.push(prev_len..text_without_backticks.len());
17915        }
17916        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17917        in_code_block = !in_code_block;
17918        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17919            text_without_backticks.push_str("...");
17920            break;
17921        }
17922    }
17923
17924    (text_without_backticks.into(), code_ranges)
17925}
17926
17927fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17928    match severity {
17929        DiagnosticSeverity::ERROR => colors.error,
17930        DiagnosticSeverity::WARNING => colors.warning,
17931        DiagnosticSeverity::INFORMATION => colors.info,
17932        DiagnosticSeverity::HINT => colors.info,
17933        _ => colors.ignored,
17934    }
17935}
17936
17937pub fn styled_runs_for_code_label<'a>(
17938    label: &'a CodeLabel,
17939    syntax_theme: &'a theme::SyntaxTheme,
17940) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17941    let fade_out = HighlightStyle {
17942        fade_out: Some(0.35),
17943        ..Default::default()
17944    };
17945
17946    let mut prev_end = label.filter_range.end;
17947    label
17948        .runs
17949        .iter()
17950        .enumerate()
17951        .flat_map(move |(ix, (range, highlight_id))| {
17952            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17953                style
17954            } else {
17955                return Default::default();
17956            };
17957            let mut muted_style = style;
17958            muted_style.highlight(fade_out);
17959
17960            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17961            if range.start >= label.filter_range.end {
17962                if range.start > prev_end {
17963                    runs.push((prev_end..range.start, fade_out));
17964                }
17965                runs.push((range.clone(), muted_style));
17966            } else if range.end <= label.filter_range.end {
17967                runs.push((range.clone(), style));
17968            } else {
17969                runs.push((range.start..label.filter_range.end, style));
17970                runs.push((label.filter_range.end..range.end, muted_style));
17971            }
17972            prev_end = cmp::max(prev_end, range.end);
17973
17974            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17975                runs.push((prev_end..label.text.len(), fade_out));
17976            }
17977
17978            runs
17979        })
17980}
17981
17982pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17983    let mut prev_index = 0;
17984    let mut prev_codepoint: Option<char> = None;
17985    text.char_indices()
17986        .chain([(text.len(), '\0')])
17987        .filter_map(move |(index, codepoint)| {
17988            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17989            let is_boundary = index == text.len()
17990                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17991                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17992            if is_boundary {
17993                let chunk = &text[prev_index..index];
17994                prev_index = index;
17995                Some(chunk)
17996            } else {
17997                None
17998            }
17999        })
18000}
18001
18002pub trait RangeToAnchorExt: Sized {
18003    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18004
18005    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18006        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18007        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18008    }
18009}
18010
18011impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18012    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18013        let start_offset = self.start.to_offset(snapshot);
18014        let end_offset = self.end.to_offset(snapshot);
18015        if start_offset == end_offset {
18016            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18017        } else {
18018            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18019        }
18020    }
18021}
18022
18023pub trait RowExt {
18024    fn as_f32(&self) -> f32;
18025
18026    fn next_row(&self) -> Self;
18027
18028    fn previous_row(&self) -> Self;
18029
18030    fn minus(&self, other: Self) -> u32;
18031}
18032
18033impl RowExt for DisplayRow {
18034    fn as_f32(&self) -> f32 {
18035        self.0 as f32
18036    }
18037
18038    fn next_row(&self) -> Self {
18039        Self(self.0 + 1)
18040    }
18041
18042    fn previous_row(&self) -> Self {
18043        Self(self.0.saturating_sub(1))
18044    }
18045
18046    fn minus(&self, other: Self) -> u32 {
18047        self.0 - other.0
18048    }
18049}
18050
18051impl RowExt for MultiBufferRow {
18052    fn as_f32(&self) -> f32 {
18053        self.0 as f32
18054    }
18055
18056    fn next_row(&self) -> Self {
18057        Self(self.0 + 1)
18058    }
18059
18060    fn previous_row(&self) -> Self {
18061        Self(self.0.saturating_sub(1))
18062    }
18063
18064    fn minus(&self, other: Self) -> u32 {
18065        self.0 - other.0
18066    }
18067}
18068
18069trait RowRangeExt {
18070    type Row;
18071
18072    fn len(&self) -> usize;
18073
18074    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18075}
18076
18077impl RowRangeExt for Range<MultiBufferRow> {
18078    type Row = MultiBufferRow;
18079
18080    fn len(&self) -> usize {
18081        (self.end.0 - self.start.0) as usize
18082    }
18083
18084    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18085        (self.start.0..self.end.0).map(MultiBufferRow)
18086    }
18087}
18088
18089impl RowRangeExt for Range<DisplayRow> {
18090    type Row = DisplayRow;
18091
18092    fn len(&self) -> usize {
18093        (self.end.0 - self.start.0) as usize
18094    }
18095
18096    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18097        (self.start.0..self.end.0).map(DisplayRow)
18098    }
18099}
18100
18101/// If select range has more than one line, we
18102/// just point the cursor to range.start.
18103fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18104    if range.start.row == range.end.row {
18105        range
18106    } else {
18107        range.start..range.start
18108    }
18109}
18110pub struct KillRing(ClipboardItem);
18111impl Global for KillRing {}
18112
18113const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18114
18115fn all_edits_insertions_or_deletions(
18116    edits: &Vec<(Range<Anchor>, String)>,
18117    snapshot: &MultiBufferSnapshot,
18118) -> bool {
18119    let mut all_insertions = true;
18120    let mut all_deletions = true;
18121
18122    for (range, new_text) in edits.iter() {
18123        let range_is_empty = range.to_offset(&snapshot).is_empty();
18124        let text_is_empty = new_text.is_empty();
18125
18126        if range_is_empty != text_is_empty {
18127            if range_is_empty {
18128                all_deletions = false;
18129            } else {
18130                all_insertions = false;
18131            }
18132        } else {
18133            return false;
18134        }
18135
18136        if !all_insertions && !all_deletions {
18137            return false;
18138        }
18139    }
18140    all_insertions || all_deletions
18141}