editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod jsx_tag_auto_close;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51pub(crate) use actions::*;
   52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{Context as _, Result, anyhow};
   55use blink_manager::BlinkManager;
   56use buffer_diff::DiffHunkStatus;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63use editor_settings::GoToDefinitionFallback;
   64pub use editor_settings::{
   65    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   66    ShowScrollbar,
   67};
   68pub use editor_settings_controls::*;
   69use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   70pub use element::{
   71    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   72};
   73use feature_flags::{Debugger, FeatureFlagAppExt};
   74use futures::{
   75    FutureExt,
   76    future::{self, Shared, join},
   77};
   78use fuzzy::StringMatchCandidate;
   79
   80use ::git::Restore;
   81use code_context_menus::{
   82    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   83    CompletionsMenu, ContextMenuOrigin,
   84};
   85use git::blame::GitBlame;
   86use gpui::{
   87    Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
   88    AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
   89    DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   90    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
   91    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size,
   92    Stateful, Styled, StyledText, Subscription, Task, TextStyle, TextStyleRefinement,
   93    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   94    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   95};
   96use highlight_matching_bracket::refresh_matching_bracket_highlights;
   97use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   98use hover_popover::{HoverState, hide_hover};
   99use indent_guides::ActiveIndentGuidesState;
  100use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  101pub use inline_completion::Direction;
  102use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  103pub use items::MAX_TAB_TITLE_LEN;
  104use itertools::Itertools;
  105use language::{
  106    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  107    CursorShape, Diagnostic, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  108    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  109    TransactionId, TreeSitterOptions, WordsQuery,
  110    language_settings::{
  111        self, InlayHintSettings, RewrapBehavior, WordsCompletionMode, all_language_settings,
  112        language_settings,
  113    },
  114    point_from_lsp, text_diff_with_options,
  115};
  116use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  117use linked_editing_ranges::refresh_linked_ranges;
  118use mouse_context_menu::MouseContextMenu;
  119use persistence::DB;
  120use project::{
  121    ProjectPath,
  122    debugger::breakpoint_store::{
  123        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  124    },
  125};
  126
  127pub use proposed_changes_editor::{
  128    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  129};
  130use smallvec::smallvec;
  131use std::{cell::OnceCell, iter::Peekable};
  132use task::{ResolvedTask, TaskTemplate, TaskVariables};
  133
  134pub use lsp::CompletionContext;
  135use lsp::{
  136    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  137    InsertTextFormat, LanguageServerId, LanguageServerName,
  138};
  139
  140use language::BufferSnapshot;
  141use movement::TextLayoutDetails;
  142pub use multi_buffer::{
  143    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  144    ToOffset, ToPoint,
  145};
  146use multi_buffer::{
  147    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  148    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  149};
  150use parking_lot::Mutex;
  151use project::{
  152    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  153    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  154    TaskSourceKind,
  155    debugger::breakpoint_store::Breakpoint,
  156    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  157    project_settings::{GitGutterSetting, ProjectSettings},
  158};
  159use rand::prelude::*;
  160use rpc::{ErrorExt, proto::*};
  161use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  162use selections_collection::{
  163    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  164};
  165use serde::{Deserialize, Serialize};
  166use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  167use smallvec::SmallVec;
  168use snippet::Snippet;
  169use std::sync::Arc;
  170use std::{
  171    any::TypeId,
  172    borrow::Cow,
  173    cell::RefCell,
  174    cmp::{self, Ordering, Reverse},
  175    mem,
  176    num::NonZeroU32,
  177    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  178    path::{Path, PathBuf},
  179    rc::Rc,
  180    time::{Duration, Instant},
  181};
  182pub use sum_tree::Bias;
  183use sum_tree::TreeMap;
  184use text::{BufferId, OffsetUtf16, Rope};
  185use theme::{
  186    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  187    observe_buffer_font_size_adjustment,
  188};
  189use ui::{
  190    ButtonSize, ButtonStyle, Disclosure, IconButton, IconButtonShape, IconName, IconSize, Key,
  191    Tooltip, h_flex, prelude::*,
  192};
  193use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  194use workspace::{
  195    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  196    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  197    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  198    item::{ItemHandle, PreviewTabsSettings},
  199    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  200    searchable::SearchEvent,
  201};
  202
  203use crate::hover_links::{find_url, find_url_from_range};
  204use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  205
  206pub const FILE_HEADER_HEIGHT: u32 = 2;
  207pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  208pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  209const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  210const MAX_LINE_LEN: usize = 1024;
  211const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  212const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  213pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  214#[doc(hidden)]
  215pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  216
  217pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  218pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  219pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  220
  221pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  222pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  223pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  224
  225pub type RenderDiffHunkControlsFn = Arc<
  226    dyn Fn(
  227        u32,
  228        &DiffHunkStatus,
  229        Range<Anchor>,
  230        bool,
  231        Pixels,
  232        &Entity<Editor>,
  233        &mut Window,
  234        &mut App,
  235    ) -> AnyElement,
  236>;
  237
  238const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  239    alt: true,
  240    shift: true,
  241    control: false,
  242    platform: false,
  243    function: false,
  244};
  245
  246#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  247pub enum InlayId {
  248    InlineCompletion(usize),
  249    Hint(usize),
  250}
  251
  252impl InlayId {
  253    fn id(&self) -> usize {
  254        match self {
  255            Self::InlineCompletion(id) => *id,
  256            Self::Hint(id) => *id,
  257        }
  258    }
  259}
  260
  261pub enum DebugCurrentRowHighlight {}
  262enum DocumentHighlightRead {}
  263enum DocumentHighlightWrite {}
  264enum InputComposition {}
  265enum SelectedTextHighlight {}
  266
  267#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  268pub enum Navigated {
  269    Yes,
  270    No,
  271}
  272
  273impl Navigated {
  274    pub fn from_bool(yes: bool) -> Navigated {
  275        if yes { Navigated::Yes } else { Navigated::No }
  276    }
  277}
  278
  279#[derive(Debug, Clone, PartialEq, Eq)]
  280enum DisplayDiffHunk {
  281    Folded {
  282        display_row: DisplayRow,
  283    },
  284    Unfolded {
  285        is_created_file: bool,
  286        diff_base_byte_range: Range<usize>,
  287        display_row_range: Range<DisplayRow>,
  288        multi_buffer_range: Range<Anchor>,
  289        status: DiffHunkStatus,
  290    },
  291}
  292
  293pub enum HideMouseCursorOrigin {
  294    TypingAction,
  295    MovementAction,
  296}
  297
  298pub fn init_settings(cx: &mut App) {
  299    EditorSettings::register(cx);
  300}
  301
  302pub fn init(cx: &mut App) {
  303    init_settings(cx);
  304
  305    workspace::register_project_item::<Editor>(cx);
  306    workspace::FollowableViewRegistry::register::<Editor>(cx);
  307    workspace::register_serializable_item::<Editor>(cx);
  308
  309    cx.observe_new(
  310        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  311            workspace.register_action(Editor::new_file);
  312            workspace.register_action(Editor::new_file_vertical);
  313            workspace.register_action(Editor::new_file_horizontal);
  314            workspace.register_action(Editor::cancel_language_server_work);
  315        },
  316    )
  317    .detach();
  318
  319    cx.on_action(move |_: &workspace::NewFile, cx| {
  320        let app_state = workspace::AppState::global(cx);
  321        if let Some(app_state) = app_state.upgrade() {
  322            workspace::open_new(
  323                Default::default(),
  324                app_state,
  325                cx,
  326                |workspace, window, cx| {
  327                    Editor::new_file(workspace, &Default::default(), window, cx)
  328                },
  329            )
  330            .detach();
  331        }
  332    });
  333    cx.on_action(move |_: &workspace::NewWindow, cx| {
  334        let app_state = workspace::AppState::global(cx);
  335        if let Some(app_state) = app_state.upgrade() {
  336            workspace::open_new(
  337                Default::default(),
  338                app_state,
  339                cx,
  340                |workspace, window, cx| {
  341                    cx.activate(true);
  342                    Editor::new_file(workspace, &Default::default(), window, cx)
  343                },
  344            )
  345            .detach();
  346        }
  347    });
  348}
  349
  350pub struct SearchWithinRange;
  351
  352trait InvalidationRegion {
  353    fn ranges(&self) -> &[Range<Anchor>];
  354}
  355
  356#[derive(Clone, Debug, PartialEq)]
  357pub enum SelectPhase {
  358    Begin {
  359        position: DisplayPoint,
  360        add: bool,
  361        click_count: usize,
  362    },
  363    BeginColumnar {
  364        position: DisplayPoint,
  365        reset: bool,
  366        goal_column: u32,
  367    },
  368    Extend {
  369        position: DisplayPoint,
  370        click_count: usize,
  371    },
  372    Update {
  373        position: DisplayPoint,
  374        goal_column: u32,
  375        scroll_delta: gpui::Point<f32>,
  376    },
  377    End,
  378}
  379
  380#[derive(Clone, Debug)]
  381pub enum SelectMode {
  382    Character,
  383    Word(Range<Anchor>),
  384    Line(Range<Anchor>),
  385    All,
  386}
  387
  388#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  389pub enum EditorMode {
  390    SingleLine { auto_width: bool },
  391    AutoHeight { max_lines: usize },
  392    Full,
  393}
  394
  395#[derive(Copy, Clone, Debug)]
  396pub enum SoftWrap {
  397    /// Prefer not to wrap at all.
  398    ///
  399    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  400    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  401    GitDiff,
  402    /// Prefer a single line generally, unless an overly long line is encountered.
  403    None,
  404    /// Soft wrap lines that exceed the editor width.
  405    EditorWidth,
  406    /// Soft wrap lines at the preferred line length.
  407    Column(u32),
  408    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  409    Bounded(u32),
  410}
  411
  412#[derive(Clone)]
  413pub struct EditorStyle {
  414    pub background: Hsla,
  415    pub local_player: PlayerColor,
  416    pub text: TextStyle,
  417    pub scrollbar_width: Pixels,
  418    pub syntax: Arc<SyntaxTheme>,
  419    pub status: StatusColors,
  420    pub inlay_hints_style: HighlightStyle,
  421    pub inline_completion_styles: InlineCompletionStyles,
  422    pub unnecessary_code_fade: f32,
  423}
  424
  425impl Default for EditorStyle {
  426    fn default() -> Self {
  427        Self {
  428            background: Hsla::default(),
  429            local_player: PlayerColor::default(),
  430            text: TextStyle::default(),
  431            scrollbar_width: Pixels::default(),
  432            syntax: Default::default(),
  433            // HACK: Status colors don't have a real default.
  434            // We should look into removing the status colors from the editor
  435            // style and retrieve them directly from the theme.
  436            status: StatusColors::dark(),
  437            inlay_hints_style: HighlightStyle::default(),
  438            inline_completion_styles: InlineCompletionStyles {
  439                insertion: HighlightStyle::default(),
  440                whitespace: HighlightStyle::default(),
  441            },
  442            unnecessary_code_fade: Default::default(),
  443        }
  444    }
  445}
  446
  447pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  448    let show_background = language_settings::language_settings(None, None, cx)
  449        .inlay_hints
  450        .show_background;
  451
  452    HighlightStyle {
  453        color: Some(cx.theme().status().hint),
  454        background_color: show_background.then(|| cx.theme().status().hint_background),
  455        ..HighlightStyle::default()
  456    }
  457}
  458
  459pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  460    InlineCompletionStyles {
  461        insertion: HighlightStyle {
  462            color: Some(cx.theme().status().predictive),
  463            ..HighlightStyle::default()
  464        },
  465        whitespace: HighlightStyle {
  466            background_color: Some(cx.theme().status().created_background),
  467            ..HighlightStyle::default()
  468        },
  469    }
  470}
  471
  472type CompletionId = usize;
  473
  474pub(crate) enum EditDisplayMode {
  475    TabAccept,
  476    DiffPopover,
  477    Inline,
  478}
  479
  480enum InlineCompletion {
  481    Edit {
  482        edits: Vec<(Range<Anchor>, String)>,
  483        edit_preview: Option<EditPreview>,
  484        display_mode: EditDisplayMode,
  485        snapshot: BufferSnapshot,
  486    },
  487    Move {
  488        target: Anchor,
  489        snapshot: BufferSnapshot,
  490    },
  491}
  492
  493struct InlineCompletionState {
  494    inlay_ids: Vec<InlayId>,
  495    completion: InlineCompletion,
  496    completion_id: Option<SharedString>,
  497    invalidation_range: Range<Anchor>,
  498}
  499
  500enum EditPredictionSettings {
  501    Disabled,
  502    Enabled {
  503        show_in_menu: bool,
  504        preview_requires_modifier: bool,
  505    },
  506}
  507
  508enum InlineCompletionHighlight {}
  509
  510#[derive(Debug, Clone)]
  511struct InlineDiagnostic {
  512    message: SharedString,
  513    group_id: usize,
  514    is_primary: bool,
  515    start: Point,
  516    severity: DiagnosticSeverity,
  517}
  518
  519pub enum MenuInlineCompletionsPolicy {
  520    Never,
  521    ByProvider,
  522}
  523
  524pub enum EditPredictionPreview {
  525    /// Modifier is not pressed
  526    Inactive { released_too_fast: bool },
  527    /// Modifier pressed
  528    Active {
  529        since: Instant,
  530        previous_scroll_position: Option<ScrollAnchor>,
  531    },
  532}
  533
  534impl EditPredictionPreview {
  535    pub fn released_too_fast(&self) -> bool {
  536        match self {
  537            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  538            EditPredictionPreview::Active { .. } => false,
  539        }
  540    }
  541
  542    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  543        if let EditPredictionPreview::Active {
  544            previous_scroll_position,
  545            ..
  546        } = self
  547        {
  548            *previous_scroll_position = scroll_position;
  549        }
  550    }
  551}
  552
  553pub struct ContextMenuOptions {
  554    pub min_entries_visible: usize,
  555    pub max_entries_visible: usize,
  556    pub placement: Option<ContextMenuPlacement>,
  557}
  558
  559#[derive(Debug, Clone, PartialEq, Eq)]
  560pub enum ContextMenuPlacement {
  561    Above,
  562    Below,
  563}
  564
  565#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  566struct EditorActionId(usize);
  567
  568impl EditorActionId {
  569    pub fn post_inc(&mut self) -> Self {
  570        let answer = self.0;
  571
  572        *self = Self(answer + 1);
  573
  574        Self(answer)
  575    }
  576}
  577
  578// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  579// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  580
  581type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  582type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  583
  584#[derive(Default)]
  585struct ScrollbarMarkerState {
  586    scrollbar_size: Size<Pixels>,
  587    dirty: bool,
  588    markers: Arc<[PaintQuad]>,
  589    pending_refresh: Option<Task<Result<()>>>,
  590}
  591
  592impl ScrollbarMarkerState {
  593    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  594        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  595    }
  596}
  597
  598#[derive(Clone, Debug)]
  599struct RunnableTasks {
  600    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  601    offset: multi_buffer::Anchor,
  602    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  603    column: u32,
  604    // Values of all named captures, including those starting with '_'
  605    extra_variables: HashMap<String, String>,
  606    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  607    context_range: Range<BufferOffset>,
  608}
  609
  610impl RunnableTasks {
  611    fn resolve<'a>(
  612        &'a self,
  613        cx: &'a task::TaskContext,
  614    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  615        self.templates.iter().filter_map(|(kind, template)| {
  616            template
  617                .resolve_task(&kind.to_id_base(), cx)
  618                .map(|task| (kind.clone(), task))
  619        })
  620    }
  621}
  622
  623#[derive(Clone)]
  624struct ResolvedTasks {
  625    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  626    position: Anchor,
  627}
  628
  629#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  630struct BufferOffset(usize);
  631
  632// Addons allow storing per-editor state in other crates (e.g. Vim)
  633pub trait Addon: 'static {
  634    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  635
  636    fn render_buffer_header_controls(
  637        &self,
  638        _: &ExcerptInfo,
  639        _: &Window,
  640        _: &App,
  641    ) -> Option<AnyElement> {
  642        None
  643    }
  644
  645    fn to_any(&self) -> &dyn std::any::Any;
  646}
  647
  648/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  649///
  650/// See the [module level documentation](self) for more information.
  651pub struct Editor {
  652    focus_handle: FocusHandle,
  653    last_focused_descendant: Option<WeakFocusHandle>,
  654    /// The text buffer being edited
  655    buffer: Entity<MultiBuffer>,
  656    /// Map of how text in the buffer should be displayed.
  657    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  658    pub display_map: Entity<DisplayMap>,
  659    pub selections: SelectionsCollection,
  660    pub scroll_manager: ScrollManager,
  661    /// When inline assist editors are linked, they all render cursors because
  662    /// typing enters text into each of them, even the ones that aren't focused.
  663    pub(crate) show_cursor_when_unfocused: bool,
  664    columnar_selection_tail: Option<Anchor>,
  665    add_selections_state: Option<AddSelectionsState>,
  666    select_next_state: Option<SelectNextState>,
  667    select_prev_state: Option<SelectNextState>,
  668    selection_history: SelectionHistory,
  669    autoclose_regions: Vec<AutocloseRegion>,
  670    snippet_stack: InvalidationStack<SnippetState>,
  671    select_syntax_node_history: SelectSyntaxNodeHistory,
  672    ime_transaction: Option<TransactionId>,
  673    active_diagnostics: Option<ActiveDiagnosticGroup>,
  674    show_inline_diagnostics: bool,
  675    inline_diagnostics_update: Task<()>,
  676    inline_diagnostics_enabled: bool,
  677    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  678    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  679    hard_wrap: Option<usize>,
  680
  681    // TODO: make this a access method
  682    pub project: Option<Entity<Project>>,
  683    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  684    completion_provider: Option<Box<dyn CompletionProvider>>,
  685    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  686    blink_manager: Entity<BlinkManager>,
  687    show_cursor_names: bool,
  688    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  689    pub show_local_selections: bool,
  690    mode: EditorMode,
  691    show_breadcrumbs: bool,
  692    show_gutter: bool,
  693    show_scrollbars: bool,
  694    show_line_numbers: Option<bool>,
  695    use_relative_line_numbers: Option<bool>,
  696    show_git_diff_gutter: Option<bool>,
  697    show_code_actions: Option<bool>,
  698    show_runnables: Option<bool>,
  699    show_breakpoints: Option<bool>,
  700    show_wrap_guides: Option<bool>,
  701    show_indent_guides: Option<bool>,
  702    placeholder_text: Option<Arc<str>>,
  703    highlight_order: usize,
  704    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  705    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  706    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  707    scrollbar_marker_state: ScrollbarMarkerState,
  708    active_indent_guides_state: ActiveIndentGuidesState,
  709    nav_history: Option<ItemNavHistory>,
  710    context_menu: RefCell<Option<CodeContextMenu>>,
  711    context_menu_options: Option<ContextMenuOptions>,
  712    mouse_context_menu: Option<MouseContextMenu>,
  713    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  714    signature_help_state: SignatureHelpState,
  715    auto_signature_help: Option<bool>,
  716    find_all_references_task_sources: Vec<Anchor>,
  717    next_completion_id: CompletionId,
  718    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  719    code_actions_task: Option<Task<Result<()>>>,
  720    selection_highlight_task: Option<Task<()>>,
  721    document_highlights_task: Option<Task<()>>,
  722    linked_editing_range_task: Option<Task<Option<()>>>,
  723    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  724    pending_rename: Option<RenameState>,
  725    searchable: bool,
  726    cursor_shape: CursorShape,
  727    current_line_highlight: Option<CurrentLineHighlight>,
  728    collapse_matches: bool,
  729    autoindent_mode: Option<AutoindentMode>,
  730    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  731    input_enabled: bool,
  732    use_modal_editing: bool,
  733    read_only: bool,
  734    leader_peer_id: Option<PeerId>,
  735    remote_id: Option<ViewId>,
  736    hover_state: HoverState,
  737    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  738    gutter_hovered: bool,
  739    hovered_link_state: Option<HoveredLinkState>,
  740    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  741    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  742    active_inline_completion: Option<InlineCompletionState>,
  743    /// Used to prevent flickering as the user types while the menu is open
  744    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  745    edit_prediction_settings: EditPredictionSettings,
  746    inline_completions_hidden_for_vim_mode: bool,
  747    show_inline_completions_override: Option<bool>,
  748    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  749    edit_prediction_preview: EditPredictionPreview,
  750    edit_prediction_indent_conflict: bool,
  751    edit_prediction_requires_modifier_in_indent_conflict: bool,
  752    inlay_hint_cache: InlayHintCache,
  753    next_inlay_id: usize,
  754    _subscriptions: Vec<Subscription>,
  755    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  756    gutter_dimensions: GutterDimensions,
  757    style: Option<EditorStyle>,
  758    text_style_refinement: Option<TextStyleRefinement>,
  759    next_editor_action_id: EditorActionId,
  760    editor_actions:
  761        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  762    use_autoclose: bool,
  763    use_auto_surround: bool,
  764    auto_replace_emoji_shortcode: bool,
  765    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  766    show_git_blame_gutter: bool,
  767    show_git_blame_inline: bool,
  768    show_git_blame_inline_delay_task: Option<Task<()>>,
  769    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  770    git_blame_inline_enabled: bool,
  771    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  772    serialize_dirty_buffers: bool,
  773    show_selection_menu: Option<bool>,
  774    blame: Option<Entity<GitBlame>>,
  775    blame_subscription: Option<Subscription>,
  776    custom_context_menu: Option<
  777        Box<
  778            dyn 'static
  779                + Fn(
  780                    &mut Self,
  781                    DisplayPoint,
  782                    &mut Window,
  783                    &mut Context<Self>,
  784                ) -> Option<Entity<ui::ContextMenu>>,
  785        >,
  786    >,
  787    last_bounds: Option<Bounds<Pixels>>,
  788    last_position_map: Option<Rc<PositionMap>>,
  789    expect_bounds_change: Option<Bounds<Pixels>>,
  790    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  791    tasks_update_task: Option<Task<()>>,
  792    breakpoint_store: Option<Entity<BreakpointStore>>,
  793    /// Allow's a user to create a breakpoint by selecting this indicator
  794    /// It should be None while a user is not hovering over the gutter
  795    /// Otherwise it represents the point that the breakpoint will be shown
  796    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  797    in_project_search: bool,
  798    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  799    breadcrumb_header: Option<String>,
  800    focused_block: Option<FocusedBlock>,
  801    next_scroll_position: NextScrollCursorCenterTopBottom,
  802    addons: HashMap<TypeId, Box<dyn Addon>>,
  803    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  804    load_diff_task: Option<Shared<Task<()>>>,
  805    selection_mark_mode: bool,
  806    toggle_fold_multiple_buffers: Task<()>,
  807    _scroll_cursor_center_top_bottom_task: Task<()>,
  808    serialize_selections: Task<()>,
  809    serialize_folds: Task<()>,
  810    mouse_cursor_hidden: bool,
  811    hide_mouse_mode: HideMouseMode,
  812}
  813
  814#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  815enum NextScrollCursorCenterTopBottom {
  816    #[default]
  817    Center,
  818    Top,
  819    Bottom,
  820}
  821
  822impl NextScrollCursorCenterTopBottom {
  823    fn next(&self) -> Self {
  824        match self {
  825            Self::Center => Self::Top,
  826            Self::Top => Self::Bottom,
  827            Self::Bottom => Self::Center,
  828        }
  829    }
  830}
  831
  832#[derive(Clone)]
  833pub struct EditorSnapshot {
  834    pub mode: EditorMode,
  835    show_gutter: bool,
  836    show_line_numbers: Option<bool>,
  837    show_git_diff_gutter: Option<bool>,
  838    show_code_actions: Option<bool>,
  839    show_runnables: Option<bool>,
  840    show_breakpoints: Option<bool>,
  841    git_blame_gutter_max_author_length: Option<usize>,
  842    pub display_snapshot: DisplaySnapshot,
  843    pub placeholder_text: Option<Arc<str>>,
  844    is_focused: bool,
  845    scroll_anchor: ScrollAnchor,
  846    ongoing_scroll: OngoingScroll,
  847    current_line_highlight: CurrentLineHighlight,
  848    gutter_hovered: bool,
  849}
  850
  851const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  852
  853#[derive(Default, Debug, Clone, Copy)]
  854pub struct GutterDimensions {
  855    pub left_padding: Pixels,
  856    pub right_padding: Pixels,
  857    pub width: Pixels,
  858    pub margin: Pixels,
  859    pub git_blame_entries_width: Option<Pixels>,
  860}
  861
  862impl GutterDimensions {
  863    /// The full width of the space taken up by the gutter.
  864    pub fn full_width(&self) -> Pixels {
  865        self.margin + self.width
  866    }
  867
  868    /// The width of the space reserved for the fold indicators,
  869    /// use alongside 'justify_end' and `gutter_width` to
  870    /// right align content with the line numbers
  871    pub fn fold_area_width(&self) -> Pixels {
  872        self.margin + self.right_padding
  873    }
  874}
  875
  876#[derive(Debug)]
  877pub struct RemoteSelection {
  878    pub replica_id: ReplicaId,
  879    pub selection: Selection<Anchor>,
  880    pub cursor_shape: CursorShape,
  881    pub peer_id: PeerId,
  882    pub line_mode: bool,
  883    pub participant_index: Option<ParticipantIndex>,
  884    pub user_name: Option<SharedString>,
  885}
  886
  887#[derive(Clone, Debug)]
  888struct SelectionHistoryEntry {
  889    selections: Arc<[Selection<Anchor>]>,
  890    select_next_state: Option<SelectNextState>,
  891    select_prev_state: Option<SelectNextState>,
  892    add_selections_state: Option<AddSelectionsState>,
  893}
  894
  895enum SelectionHistoryMode {
  896    Normal,
  897    Undoing,
  898    Redoing,
  899}
  900
  901#[derive(Clone, PartialEq, Eq, Hash)]
  902struct HoveredCursor {
  903    replica_id: u16,
  904    selection_id: usize,
  905}
  906
  907impl Default for SelectionHistoryMode {
  908    fn default() -> Self {
  909        Self::Normal
  910    }
  911}
  912
  913#[derive(Default)]
  914struct SelectionHistory {
  915    #[allow(clippy::type_complexity)]
  916    selections_by_transaction:
  917        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  918    mode: SelectionHistoryMode,
  919    undo_stack: VecDeque<SelectionHistoryEntry>,
  920    redo_stack: VecDeque<SelectionHistoryEntry>,
  921}
  922
  923impl SelectionHistory {
  924    fn insert_transaction(
  925        &mut self,
  926        transaction_id: TransactionId,
  927        selections: Arc<[Selection<Anchor>]>,
  928    ) {
  929        self.selections_by_transaction
  930            .insert(transaction_id, (selections, None));
  931    }
  932
  933    #[allow(clippy::type_complexity)]
  934    fn transaction(
  935        &self,
  936        transaction_id: TransactionId,
  937    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  938        self.selections_by_transaction.get(&transaction_id)
  939    }
  940
  941    #[allow(clippy::type_complexity)]
  942    fn transaction_mut(
  943        &mut self,
  944        transaction_id: TransactionId,
  945    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  946        self.selections_by_transaction.get_mut(&transaction_id)
  947    }
  948
  949    fn push(&mut self, entry: SelectionHistoryEntry) {
  950        if !entry.selections.is_empty() {
  951            match self.mode {
  952                SelectionHistoryMode::Normal => {
  953                    self.push_undo(entry);
  954                    self.redo_stack.clear();
  955                }
  956                SelectionHistoryMode::Undoing => self.push_redo(entry),
  957                SelectionHistoryMode::Redoing => self.push_undo(entry),
  958            }
  959        }
  960    }
  961
  962    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  963        if self
  964            .undo_stack
  965            .back()
  966            .map_or(true, |e| e.selections != entry.selections)
  967        {
  968            self.undo_stack.push_back(entry);
  969            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  970                self.undo_stack.pop_front();
  971            }
  972        }
  973    }
  974
  975    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  976        if self
  977            .redo_stack
  978            .back()
  979            .map_or(true, |e| e.selections != entry.selections)
  980        {
  981            self.redo_stack.push_back(entry);
  982            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  983                self.redo_stack.pop_front();
  984            }
  985        }
  986    }
  987}
  988
  989struct RowHighlight {
  990    index: usize,
  991    range: Range<Anchor>,
  992    color: Hsla,
  993    should_autoscroll: bool,
  994}
  995
  996#[derive(Clone, Debug)]
  997struct AddSelectionsState {
  998    above: bool,
  999    stack: Vec<usize>,
 1000}
 1001
 1002#[derive(Clone)]
 1003struct SelectNextState {
 1004    query: AhoCorasick,
 1005    wordwise: bool,
 1006    done: bool,
 1007}
 1008
 1009impl std::fmt::Debug for SelectNextState {
 1010    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1011        f.debug_struct(std::any::type_name::<Self>())
 1012            .field("wordwise", &self.wordwise)
 1013            .field("done", &self.done)
 1014            .finish()
 1015    }
 1016}
 1017
 1018#[derive(Debug)]
 1019struct AutocloseRegion {
 1020    selection_id: usize,
 1021    range: Range<Anchor>,
 1022    pair: BracketPair,
 1023}
 1024
 1025#[derive(Debug)]
 1026struct SnippetState {
 1027    ranges: Vec<Vec<Range<Anchor>>>,
 1028    active_index: usize,
 1029    choices: Vec<Option<Vec<String>>>,
 1030}
 1031
 1032#[doc(hidden)]
 1033pub struct RenameState {
 1034    pub range: Range<Anchor>,
 1035    pub old_name: Arc<str>,
 1036    pub editor: Entity<Editor>,
 1037    block_id: CustomBlockId,
 1038}
 1039
 1040struct InvalidationStack<T>(Vec<T>);
 1041
 1042struct RegisteredInlineCompletionProvider {
 1043    provider: Arc<dyn InlineCompletionProviderHandle>,
 1044    _subscription: Subscription,
 1045}
 1046
 1047#[derive(Debug, PartialEq, Eq)]
 1048struct ActiveDiagnosticGroup {
 1049    primary_range: Range<Anchor>,
 1050    primary_message: String,
 1051    group_id: usize,
 1052    blocks: HashMap<CustomBlockId, Diagnostic>,
 1053    is_valid: bool,
 1054}
 1055
 1056#[derive(Serialize, Deserialize, Clone, Debug)]
 1057pub struct ClipboardSelection {
 1058    /// The number of bytes in this selection.
 1059    pub len: usize,
 1060    /// Whether this was a full-line selection.
 1061    pub is_entire_line: bool,
 1062    /// The indentation of the first line when this content was originally copied.
 1063    pub first_line_indent: u32,
 1064}
 1065
 1066// selections, scroll behavior, was newest selection reversed
 1067type SelectSyntaxNodeHistoryState = (
 1068    Box<[Selection<usize>]>,
 1069    SelectSyntaxNodeScrollBehavior,
 1070    bool,
 1071);
 1072
 1073#[derive(Default)]
 1074struct SelectSyntaxNodeHistory {
 1075    stack: Vec<SelectSyntaxNodeHistoryState>,
 1076    // disable temporarily to allow changing selections without losing the stack
 1077    pub disable_clearing: bool,
 1078}
 1079
 1080impl SelectSyntaxNodeHistory {
 1081    pub fn try_clear(&mut self) {
 1082        if !self.disable_clearing {
 1083            self.stack.clear();
 1084        }
 1085    }
 1086
 1087    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1088        self.stack.push(selection);
 1089    }
 1090
 1091    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1092        self.stack.pop()
 1093    }
 1094}
 1095
 1096enum SelectSyntaxNodeScrollBehavior {
 1097    CursorTop,
 1098    CenterSelection,
 1099    CursorBottom,
 1100}
 1101
 1102#[derive(Debug)]
 1103pub(crate) struct NavigationData {
 1104    cursor_anchor: Anchor,
 1105    cursor_position: Point,
 1106    scroll_anchor: ScrollAnchor,
 1107    scroll_top_row: u32,
 1108}
 1109
 1110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1111pub enum GotoDefinitionKind {
 1112    Symbol,
 1113    Declaration,
 1114    Type,
 1115    Implementation,
 1116}
 1117
 1118#[derive(Debug, Clone)]
 1119enum InlayHintRefreshReason {
 1120    ModifiersChanged(bool),
 1121    Toggle(bool),
 1122    SettingsChange(InlayHintSettings),
 1123    NewLinesShown,
 1124    BufferEdited(HashSet<Arc<Language>>),
 1125    RefreshRequested,
 1126    ExcerptsRemoved(Vec<ExcerptId>),
 1127}
 1128
 1129impl InlayHintRefreshReason {
 1130    fn description(&self) -> &'static str {
 1131        match self {
 1132            Self::ModifiersChanged(_) => "modifiers changed",
 1133            Self::Toggle(_) => "toggle",
 1134            Self::SettingsChange(_) => "settings change",
 1135            Self::NewLinesShown => "new lines shown",
 1136            Self::BufferEdited(_) => "buffer edited",
 1137            Self::RefreshRequested => "refresh requested",
 1138            Self::ExcerptsRemoved(_) => "excerpts removed",
 1139        }
 1140    }
 1141}
 1142
 1143pub enum FormatTarget {
 1144    Buffers,
 1145    Ranges(Vec<Range<MultiBufferPoint>>),
 1146}
 1147
 1148pub(crate) struct FocusedBlock {
 1149    id: BlockId,
 1150    focus_handle: WeakFocusHandle,
 1151}
 1152
 1153#[derive(Clone)]
 1154enum JumpData {
 1155    MultiBufferRow {
 1156        row: MultiBufferRow,
 1157        line_offset_from_top: u32,
 1158    },
 1159    MultiBufferPoint {
 1160        excerpt_id: ExcerptId,
 1161        position: Point,
 1162        anchor: text::Anchor,
 1163        line_offset_from_top: u32,
 1164    },
 1165}
 1166
 1167pub enum MultibufferSelectionMode {
 1168    First,
 1169    All,
 1170}
 1171
 1172#[derive(Clone, Copy, Debug, Default)]
 1173pub struct RewrapOptions {
 1174    pub override_language_settings: bool,
 1175    pub preserve_existing_whitespace: bool,
 1176}
 1177
 1178impl Editor {
 1179    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1180        let buffer = cx.new(|cx| Buffer::local("", cx));
 1181        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1182        Self::new(
 1183            EditorMode::SingleLine { auto_width: false },
 1184            buffer,
 1185            None,
 1186            window,
 1187            cx,
 1188        )
 1189    }
 1190
 1191    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1192        let buffer = cx.new(|cx| Buffer::local("", cx));
 1193        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1194        Self::new(EditorMode::Full, buffer, None, window, cx)
 1195    }
 1196
 1197    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1198        let buffer = cx.new(|cx| Buffer::local("", cx));
 1199        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1200        Self::new(
 1201            EditorMode::SingleLine { auto_width: true },
 1202            buffer,
 1203            None,
 1204            window,
 1205            cx,
 1206        )
 1207    }
 1208
 1209    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1210        let buffer = cx.new(|cx| Buffer::local("", cx));
 1211        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1212        Self::new(
 1213            EditorMode::AutoHeight { max_lines },
 1214            buffer,
 1215            None,
 1216            window,
 1217            cx,
 1218        )
 1219    }
 1220
 1221    pub fn for_buffer(
 1222        buffer: Entity<Buffer>,
 1223        project: Option<Entity<Project>>,
 1224        window: &mut Window,
 1225        cx: &mut Context<Self>,
 1226    ) -> Self {
 1227        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1228        Self::new(EditorMode::Full, buffer, project, window, cx)
 1229    }
 1230
 1231    pub fn for_multibuffer(
 1232        buffer: Entity<MultiBuffer>,
 1233        project: Option<Entity<Project>>,
 1234        window: &mut Window,
 1235        cx: &mut Context<Self>,
 1236    ) -> Self {
 1237        Self::new(EditorMode::Full, buffer, project, window, cx)
 1238    }
 1239
 1240    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1241        let mut clone = Self::new(
 1242            self.mode,
 1243            self.buffer.clone(),
 1244            self.project.clone(),
 1245            window,
 1246            cx,
 1247        );
 1248        self.display_map.update(cx, |display_map, cx| {
 1249            let snapshot = display_map.snapshot(cx);
 1250            clone.display_map.update(cx, |display_map, cx| {
 1251                display_map.set_state(&snapshot, cx);
 1252            });
 1253        });
 1254        clone.folds_did_change(cx);
 1255        clone.selections.clone_state(&self.selections);
 1256        clone.scroll_manager.clone_state(&self.scroll_manager);
 1257        clone.searchable = self.searchable;
 1258        clone
 1259    }
 1260
 1261    pub fn new(
 1262        mode: EditorMode,
 1263        buffer: Entity<MultiBuffer>,
 1264        project: Option<Entity<Project>>,
 1265        window: &mut Window,
 1266        cx: &mut Context<Self>,
 1267    ) -> Self {
 1268        let style = window.text_style();
 1269        let font_size = style.font_size.to_pixels(window.rem_size());
 1270        let editor = cx.entity().downgrade();
 1271        let fold_placeholder = FoldPlaceholder {
 1272            constrain_width: true,
 1273            render: Arc::new(move |fold_id, fold_range, cx| {
 1274                let editor = editor.clone();
 1275                div()
 1276                    .id(fold_id)
 1277                    .bg(cx.theme().colors().ghost_element_background)
 1278                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1279                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1280                    .rounded_xs()
 1281                    .size_full()
 1282                    .cursor_pointer()
 1283                    .child("")
 1284                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1285                    .on_click(move |_, _window, cx| {
 1286                        editor
 1287                            .update(cx, |editor, cx| {
 1288                                editor.unfold_ranges(
 1289                                    &[fold_range.start..fold_range.end],
 1290                                    true,
 1291                                    false,
 1292                                    cx,
 1293                                );
 1294                                cx.stop_propagation();
 1295                            })
 1296                            .ok();
 1297                    })
 1298                    .into_any()
 1299            }),
 1300            merge_adjacent: true,
 1301            ..Default::default()
 1302        };
 1303        let display_map = cx.new(|cx| {
 1304            DisplayMap::new(
 1305                buffer.clone(),
 1306                style.font(),
 1307                font_size,
 1308                None,
 1309                FILE_HEADER_HEIGHT,
 1310                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1311                fold_placeholder,
 1312                cx,
 1313            )
 1314        });
 1315
 1316        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1317
 1318        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1319
 1320        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1321            .then(|| language_settings::SoftWrap::None);
 1322
 1323        let mut project_subscriptions = Vec::new();
 1324        if mode == EditorMode::Full {
 1325            if let Some(project) = project.as_ref() {
 1326                project_subscriptions.push(cx.subscribe_in(
 1327                    project,
 1328                    window,
 1329                    |editor, _, event, window, cx| match event {
 1330                        project::Event::RefreshCodeLens => {
 1331                            // we always query lens with actions, without storing them, always refreshing them
 1332                        }
 1333                        project::Event::RefreshInlayHints => {
 1334                            editor
 1335                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1336                        }
 1337                        project::Event::SnippetEdit(id, snippet_edits) => {
 1338                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1339                                let focus_handle = editor.focus_handle(cx);
 1340                                if focus_handle.is_focused(window) {
 1341                                    let snapshot = buffer.read(cx).snapshot();
 1342                                    for (range, snippet) in snippet_edits {
 1343                                        let editor_range =
 1344                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1345                                        editor
 1346                                            .insert_snippet(
 1347                                                &[editor_range],
 1348                                                snippet.clone(),
 1349                                                window,
 1350                                                cx,
 1351                                            )
 1352                                            .ok();
 1353                                    }
 1354                                }
 1355                            }
 1356                        }
 1357                        _ => {}
 1358                    },
 1359                ));
 1360                if let Some(task_inventory) = project
 1361                    .read(cx)
 1362                    .task_store()
 1363                    .read(cx)
 1364                    .task_inventory()
 1365                    .cloned()
 1366                {
 1367                    project_subscriptions.push(cx.observe_in(
 1368                        &task_inventory,
 1369                        window,
 1370                        |editor, _, window, cx| {
 1371                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1372                        },
 1373                    ));
 1374                };
 1375
 1376                project_subscriptions.push(cx.subscribe_in(
 1377                    &project.read(cx).breakpoint_store(),
 1378                    window,
 1379                    |editor, _, event, window, cx| match event {
 1380                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1381                            editor.go_to_active_debug_line(window, cx);
 1382                        }
 1383                        _ => {}
 1384                    },
 1385                ));
 1386            }
 1387        }
 1388
 1389        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1390
 1391        let inlay_hint_settings =
 1392            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1393        let focus_handle = cx.focus_handle();
 1394        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1395            .detach();
 1396        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1397            .detach();
 1398        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1399            .detach();
 1400        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1401            .detach();
 1402
 1403        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1404            Some(false)
 1405        } else {
 1406            None
 1407        };
 1408
 1409        let breakpoint_store = match (mode, project.as_ref()) {
 1410            (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1411            _ => None,
 1412        };
 1413
 1414        let mut code_action_providers = Vec::new();
 1415        let mut load_uncommitted_diff = None;
 1416        if let Some(project) = project.clone() {
 1417            load_uncommitted_diff = Some(
 1418                get_uncommitted_diff_for_buffer(
 1419                    &project,
 1420                    buffer.read(cx).all_buffers(),
 1421                    buffer.clone(),
 1422                    cx,
 1423                )
 1424                .shared(),
 1425            );
 1426            code_action_providers.push(Rc::new(project) as Rc<_>);
 1427        }
 1428
 1429        let mut this = Self {
 1430            focus_handle,
 1431            show_cursor_when_unfocused: false,
 1432            last_focused_descendant: None,
 1433            buffer: buffer.clone(),
 1434            display_map: display_map.clone(),
 1435            selections,
 1436            scroll_manager: ScrollManager::new(cx),
 1437            columnar_selection_tail: None,
 1438            add_selections_state: None,
 1439            select_next_state: None,
 1440            select_prev_state: None,
 1441            selection_history: Default::default(),
 1442            autoclose_regions: Default::default(),
 1443            snippet_stack: Default::default(),
 1444            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1445            ime_transaction: Default::default(),
 1446            active_diagnostics: None,
 1447            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1448            inline_diagnostics_update: Task::ready(()),
 1449            inline_diagnostics: Vec::new(),
 1450            soft_wrap_mode_override,
 1451            hard_wrap: None,
 1452            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1453            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1454            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1455            project,
 1456            blink_manager: blink_manager.clone(),
 1457            show_local_selections: true,
 1458            show_scrollbars: true,
 1459            mode,
 1460            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1461            show_gutter: mode == EditorMode::Full,
 1462            show_line_numbers: None,
 1463            use_relative_line_numbers: None,
 1464            show_git_diff_gutter: None,
 1465            show_code_actions: None,
 1466            show_runnables: None,
 1467            show_breakpoints: None,
 1468            show_wrap_guides: None,
 1469            show_indent_guides,
 1470            placeholder_text: None,
 1471            highlight_order: 0,
 1472            highlighted_rows: HashMap::default(),
 1473            background_highlights: Default::default(),
 1474            gutter_highlights: TreeMap::default(),
 1475            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1476            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1477            nav_history: None,
 1478            context_menu: RefCell::new(None),
 1479            context_menu_options: None,
 1480            mouse_context_menu: None,
 1481            completion_tasks: Default::default(),
 1482            signature_help_state: SignatureHelpState::default(),
 1483            auto_signature_help: None,
 1484            find_all_references_task_sources: Vec::new(),
 1485            next_completion_id: 0,
 1486            next_inlay_id: 0,
 1487            code_action_providers,
 1488            available_code_actions: Default::default(),
 1489            code_actions_task: Default::default(),
 1490            selection_highlight_task: Default::default(),
 1491            document_highlights_task: Default::default(),
 1492            linked_editing_range_task: Default::default(),
 1493            pending_rename: Default::default(),
 1494            searchable: true,
 1495            cursor_shape: EditorSettings::get_global(cx)
 1496                .cursor_shape
 1497                .unwrap_or_default(),
 1498            current_line_highlight: None,
 1499            autoindent_mode: Some(AutoindentMode::EachLine),
 1500            collapse_matches: false,
 1501            workspace: None,
 1502            input_enabled: true,
 1503            use_modal_editing: mode == EditorMode::Full,
 1504            read_only: false,
 1505            use_autoclose: true,
 1506            use_auto_surround: true,
 1507            auto_replace_emoji_shortcode: false,
 1508            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1509            leader_peer_id: None,
 1510            remote_id: None,
 1511            hover_state: Default::default(),
 1512            pending_mouse_down: None,
 1513            hovered_link_state: Default::default(),
 1514            edit_prediction_provider: None,
 1515            active_inline_completion: None,
 1516            stale_inline_completion_in_menu: None,
 1517            edit_prediction_preview: EditPredictionPreview::Inactive {
 1518                released_too_fast: false,
 1519            },
 1520            inline_diagnostics_enabled: mode == EditorMode::Full,
 1521            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1522
 1523            gutter_hovered: false,
 1524            pixel_position_of_newest_cursor: None,
 1525            last_bounds: None,
 1526            last_position_map: None,
 1527            expect_bounds_change: None,
 1528            gutter_dimensions: GutterDimensions::default(),
 1529            style: None,
 1530            show_cursor_names: false,
 1531            hovered_cursors: Default::default(),
 1532            next_editor_action_id: EditorActionId::default(),
 1533            editor_actions: Rc::default(),
 1534            inline_completions_hidden_for_vim_mode: false,
 1535            show_inline_completions_override: None,
 1536            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1537            edit_prediction_settings: EditPredictionSettings::Disabled,
 1538            edit_prediction_indent_conflict: false,
 1539            edit_prediction_requires_modifier_in_indent_conflict: true,
 1540            custom_context_menu: None,
 1541            show_git_blame_gutter: false,
 1542            show_git_blame_inline: false,
 1543            show_selection_menu: None,
 1544            show_git_blame_inline_delay_task: None,
 1545            git_blame_inline_tooltip: None,
 1546            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1547            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1548            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1549                .session
 1550                .restore_unsaved_buffers,
 1551            blame: None,
 1552            blame_subscription: None,
 1553            tasks: Default::default(),
 1554
 1555            breakpoint_store,
 1556            gutter_breakpoint_indicator: (None, None),
 1557            _subscriptions: vec![
 1558                cx.observe(&buffer, Self::on_buffer_changed),
 1559                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1560                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1561                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1562                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1563                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1564                cx.observe_window_activation(window, |editor, window, cx| {
 1565                    let active = window.is_window_active();
 1566                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1567                        if active {
 1568                            blink_manager.enable(cx);
 1569                        } else {
 1570                            blink_manager.disable(cx);
 1571                        }
 1572                    });
 1573                }),
 1574            ],
 1575            tasks_update_task: None,
 1576            linked_edit_ranges: Default::default(),
 1577            in_project_search: false,
 1578            previous_search_ranges: None,
 1579            breadcrumb_header: None,
 1580            focused_block: None,
 1581            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1582            addons: HashMap::default(),
 1583            registered_buffers: HashMap::default(),
 1584            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1585            selection_mark_mode: false,
 1586            toggle_fold_multiple_buffers: Task::ready(()),
 1587            serialize_selections: Task::ready(()),
 1588            serialize_folds: Task::ready(()),
 1589            text_style_refinement: None,
 1590            load_diff_task: load_uncommitted_diff,
 1591            mouse_cursor_hidden: false,
 1592            hide_mouse_mode: EditorSettings::get_global(cx)
 1593                .hide_mouse
 1594                .unwrap_or_default(),
 1595        };
 1596        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1597            this._subscriptions
 1598                .push(cx.observe(breakpoints, |_, _, cx| {
 1599                    cx.notify();
 1600                }));
 1601        }
 1602        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1603        this._subscriptions.extend(project_subscriptions);
 1604        this._subscriptions
 1605            .push(cx.subscribe_self(|editor, e: &EditorEvent, cx| {
 1606                if let EditorEvent::SelectionsChanged { local } = e {
 1607                    if *local {
 1608                        let new_anchor = editor.scroll_manager.anchor();
 1609                        editor.update_restoration_data(cx, move |data| {
 1610                            data.scroll_anchor = new_anchor;
 1611                        });
 1612                    }
 1613                }
 1614            }));
 1615
 1616        this.end_selection(window, cx);
 1617        this.scroll_manager.show_scrollbars(window, cx);
 1618        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1619
 1620        if mode == EditorMode::Full {
 1621            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1622            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1623
 1624            if this.git_blame_inline_enabled {
 1625                this.git_blame_inline_enabled = true;
 1626                this.start_git_blame_inline(false, window, cx);
 1627            }
 1628
 1629            this.go_to_active_debug_line(window, cx);
 1630
 1631            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1632                if let Some(project) = this.project.as_ref() {
 1633                    let handle = project.update(cx, |project, cx| {
 1634                        project.register_buffer_with_language_servers(&buffer, cx)
 1635                    });
 1636                    this.registered_buffers
 1637                        .insert(buffer.read(cx).remote_id(), handle);
 1638                }
 1639            }
 1640        }
 1641
 1642        this.report_editor_event("Editor Opened", None, cx);
 1643        this
 1644    }
 1645
 1646    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1647        self.mouse_context_menu
 1648            .as_ref()
 1649            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1650    }
 1651
 1652    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1653        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1654    }
 1655
 1656    fn key_context_internal(
 1657        &self,
 1658        has_active_edit_prediction: bool,
 1659        window: &Window,
 1660        cx: &App,
 1661    ) -> KeyContext {
 1662        let mut key_context = KeyContext::new_with_defaults();
 1663        key_context.add("Editor");
 1664        let mode = match self.mode {
 1665            EditorMode::SingleLine { .. } => "single_line",
 1666            EditorMode::AutoHeight { .. } => "auto_height",
 1667            EditorMode::Full => "full",
 1668        };
 1669
 1670        if EditorSettings::jupyter_enabled(cx) {
 1671            key_context.add("jupyter");
 1672        }
 1673
 1674        key_context.set("mode", mode);
 1675        if self.pending_rename.is_some() {
 1676            key_context.add("renaming");
 1677        }
 1678
 1679        match self.context_menu.borrow().as_ref() {
 1680            Some(CodeContextMenu::Completions(_)) => {
 1681                key_context.add("menu");
 1682                key_context.add("showing_completions");
 1683            }
 1684            Some(CodeContextMenu::CodeActions(_)) => {
 1685                key_context.add("menu");
 1686                key_context.add("showing_code_actions")
 1687            }
 1688            None => {}
 1689        }
 1690
 1691        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1692        if !self.focus_handle(cx).contains_focused(window, cx)
 1693            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1694        {
 1695            for addon in self.addons.values() {
 1696                addon.extend_key_context(&mut key_context, cx)
 1697            }
 1698        }
 1699
 1700        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1701            if let Some(extension) = singleton_buffer
 1702                .read(cx)
 1703                .file()
 1704                .and_then(|file| file.path().extension()?.to_str())
 1705            {
 1706                key_context.set("extension", extension.to_string());
 1707            }
 1708        } else {
 1709            key_context.add("multibuffer");
 1710        }
 1711
 1712        if has_active_edit_prediction {
 1713            if self.edit_prediction_in_conflict() {
 1714                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1715            } else {
 1716                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1717                key_context.add("copilot_suggestion");
 1718            }
 1719        }
 1720
 1721        if self.selection_mark_mode {
 1722            key_context.add("selection_mode");
 1723        }
 1724
 1725        key_context
 1726    }
 1727
 1728    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1729        self.mouse_cursor_hidden = match origin {
 1730            HideMouseCursorOrigin::TypingAction => {
 1731                matches!(
 1732                    self.hide_mouse_mode,
 1733                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1734                )
 1735            }
 1736            HideMouseCursorOrigin::MovementAction => {
 1737                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1738            }
 1739        };
 1740    }
 1741
 1742    pub fn edit_prediction_in_conflict(&self) -> bool {
 1743        if !self.show_edit_predictions_in_menu() {
 1744            return false;
 1745        }
 1746
 1747        let showing_completions = self
 1748            .context_menu
 1749            .borrow()
 1750            .as_ref()
 1751            .map_or(false, |context| {
 1752                matches!(context, CodeContextMenu::Completions(_))
 1753            });
 1754
 1755        showing_completions
 1756            || self.edit_prediction_requires_modifier()
 1757            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1758            // bindings to insert tab characters.
 1759            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1760    }
 1761
 1762    pub fn accept_edit_prediction_keybind(
 1763        &self,
 1764        window: &Window,
 1765        cx: &App,
 1766    ) -> AcceptEditPredictionBinding {
 1767        let key_context = self.key_context_internal(true, window, cx);
 1768        let in_conflict = self.edit_prediction_in_conflict();
 1769
 1770        AcceptEditPredictionBinding(
 1771            window
 1772                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1773                .into_iter()
 1774                .filter(|binding| {
 1775                    !in_conflict
 1776                        || binding
 1777                            .keystrokes()
 1778                            .first()
 1779                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1780                })
 1781                .rev()
 1782                .min_by_key(|binding| {
 1783                    binding
 1784                        .keystrokes()
 1785                        .first()
 1786                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1787                }),
 1788        )
 1789    }
 1790
 1791    pub fn new_file(
 1792        workspace: &mut Workspace,
 1793        _: &workspace::NewFile,
 1794        window: &mut Window,
 1795        cx: &mut Context<Workspace>,
 1796    ) {
 1797        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1798            "Failed to create buffer",
 1799            window,
 1800            cx,
 1801            |e, _, _| match e.error_code() {
 1802                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1803                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1804                e.error_tag("required").unwrap_or("the latest version")
 1805            )),
 1806                _ => None,
 1807            },
 1808        );
 1809    }
 1810
 1811    pub fn new_in_workspace(
 1812        workspace: &mut Workspace,
 1813        window: &mut Window,
 1814        cx: &mut Context<Workspace>,
 1815    ) -> Task<Result<Entity<Editor>>> {
 1816        let project = workspace.project().clone();
 1817        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1818
 1819        cx.spawn_in(window, async move |workspace, cx| {
 1820            let buffer = create.await?;
 1821            workspace.update_in(cx, |workspace, window, cx| {
 1822                let editor =
 1823                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1824                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1825                editor
 1826            })
 1827        })
 1828    }
 1829
 1830    fn new_file_vertical(
 1831        workspace: &mut Workspace,
 1832        _: &workspace::NewFileSplitVertical,
 1833        window: &mut Window,
 1834        cx: &mut Context<Workspace>,
 1835    ) {
 1836        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1837    }
 1838
 1839    fn new_file_horizontal(
 1840        workspace: &mut Workspace,
 1841        _: &workspace::NewFileSplitHorizontal,
 1842        window: &mut Window,
 1843        cx: &mut Context<Workspace>,
 1844    ) {
 1845        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1846    }
 1847
 1848    fn new_file_in_direction(
 1849        workspace: &mut Workspace,
 1850        direction: SplitDirection,
 1851        window: &mut Window,
 1852        cx: &mut Context<Workspace>,
 1853    ) {
 1854        let project = workspace.project().clone();
 1855        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1856
 1857        cx.spawn_in(window, async move |workspace, cx| {
 1858            let buffer = create.await?;
 1859            workspace.update_in(cx, move |workspace, window, cx| {
 1860                workspace.split_item(
 1861                    direction,
 1862                    Box::new(
 1863                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1864                    ),
 1865                    window,
 1866                    cx,
 1867                )
 1868            })?;
 1869            anyhow::Ok(())
 1870        })
 1871        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1872            match e.error_code() {
 1873                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1874                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1875                e.error_tag("required").unwrap_or("the latest version")
 1876            )),
 1877                _ => None,
 1878            }
 1879        });
 1880    }
 1881
 1882    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1883        self.leader_peer_id
 1884    }
 1885
 1886    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1887        &self.buffer
 1888    }
 1889
 1890    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1891        self.workspace.as_ref()?.0.upgrade()
 1892    }
 1893
 1894    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1895        self.buffer().read(cx).title(cx)
 1896    }
 1897
 1898    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1899        let git_blame_gutter_max_author_length = self
 1900            .render_git_blame_gutter(cx)
 1901            .then(|| {
 1902                if let Some(blame) = self.blame.as_ref() {
 1903                    let max_author_length =
 1904                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1905                    Some(max_author_length)
 1906                } else {
 1907                    None
 1908                }
 1909            })
 1910            .flatten();
 1911
 1912        EditorSnapshot {
 1913            mode: self.mode,
 1914            show_gutter: self.show_gutter,
 1915            show_line_numbers: self.show_line_numbers,
 1916            show_git_diff_gutter: self.show_git_diff_gutter,
 1917            show_code_actions: self.show_code_actions,
 1918            show_runnables: self.show_runnables,
 1919            show_breakpoints: self.show_breakpoints,
 1920            git_blame_gutter_max_author_length,
 1921            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1922            scroll_anchor: self.scroll_manager.anchor(),
 1923            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1924            placeholder_text: self.placeholder_text.clone(),
 1925            is_focused: self.focus_handle.is_focused(window),
 1926            current_line_highlight: self
 1927                .current_line_highlight
 1928                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1929            gutter_hovered: self.gutter_hovered,
 1930        }
 1931    }
 1932
 1933    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1934        self.buffer.read(cx).language_at(point, cx)
 1935    }
 1936
 1937    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1938        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1939    }
 1940
 1941    pub fn active_excerpt(
 1942        &self,
 1943        cx: &App,
 1944    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1945        self.buffer
 1946            .read(cx)
 1947            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1948    }
 1949
 1950    pub fn mode(&self) -> EditorMode {
 1951        self.mode
 1952    }
 1953
 1954    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1955        self.collaboration_hub.as_deref()
 1956    }
 1957
 1958    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1959        self.collaboration_hub = Some(hub);
 1960    }
 1961
 1962    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1963        self.in_project_search = in_project_search;
 1964    }
 1965
 1966    pub fn set_custom_context_menu(
 1967        &mut self,
 1968        f: impl 'static
 1969        + Fn(
 1970            &mut Self,
 1971            DisplayPoint,
 1972            &mut Window,
 1973            &mut Context<Self>,
 1974        ) -> Option<Entity<ui::ContextMenu>>,
 1975    ) {
 1976        self.custom_context_menu = Some(Box::new(f))
 1977    }
 1978
 1979    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1980        self.completion_provider = provider;
 1981    }
 1982
 1983    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1984        self.semantics_provider.clone()
 1985    }
 1986
 1987    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1988        self.semantics_provider = provider;
 1989    }
 1990
 1991    pub fn set_edit_prediction_provider<T>(
 1992        &mut self,
 1993        provider: Option<Entity<T>>,
 1994        window: &mut Window,
 1995        cx: &mut Context<Self>,
 1996    ) where
 1997        T: EditPredictionProvider,
 1998    {
 1999        self.edit_prediction_provider =
 2000            provider.map(|provider| RegisteredInlineCompletionProvider {
 2001                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2002                    if this.focus_handle.is_focused(window) {
 2003                        this.update_visible_inline_completion(window, cx);
 2004                    }
 2005                }),
 2006                provider: Arc::new(provider),
 2007            });
 2008        self.update_edit_prediction_settings(cx);
 2009        self.refresh_inline_completion(false, false, window, cx);
 2010    }
 2011
 2012    pub fn placeholder_text(&self) -> Option<&str> {
 2013        self.placeholder_text.as_deref()
 2014    }
 2015
 2016    pub fn set_placeholder_text(
 2017        &mut self,
 2018        placeholder_text: impl Into<Arc<str>>,
 2019        cx: &mut Context<Self>,
 2020    ) {
 2021        let placeholder_text = Some(placeholder_text.into());
 2022        if self.placeholder_text != placeholder_text {
 2023            self.placeholder_text = placeholder_text;
 2024            cx.notify();
 2025        }
 2026    }
 2027
 2028    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2029        self.cursor_shape = cursor_shape;
 2030
 2031        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2032        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2033
 2034        cx.notify();
 2035    }
 2036
 2037    pub fn set_current_line_highlight(
 2038        &mut self,
 2039        current_line_highlight: Option<CurrentLineHighlight>,
 2040    ) {
 2041        self.current_line_highlight = current_line_highlight;
 2042    }
 2043
 2044    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2045        self.collapse_matches = collapse_matches;
 2046    }
 2047
 2048    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2049        let buffers = self.buffer.read(cx).all_buffers();
 2050        let Some(project) = self.project.as_ref() else {
 2051            return;
 2052        };
 2053        project.update(cx, |project, cx| {
 2054            for buffer in buffers {
 2055                self.registered_buffers
 2056                    .entry(buffer.read(cx).remote_id())
 2057                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2058            }
 2059        })
 2060    }
 2061
 2062    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2063        if self.collapse_matches {
 2064            return range.start..range.start;
 2065        }
 2066        range.clone()
 2067    }
 2068
 2069    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2070        if self.display_map.read(cx).clip_at_line_ends != clip {
 2071            self.display_map
 2072                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2073        }
 2074    }
 2075
 2076    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2077        self.input_enabled = input_enabled;
 2078    }
 2079
 2080    pub fn set_inline_completions_hidden_for_vim_mode(
 2081        &mut self,
 2082        hidden: bool,
 2083        window: &mut Window,
 2084        cx: &mut Context<Self>,
 2085    ) {
 2086        if hidden != self.inline_completions_hidden_for_vim_mode {
 2087            self.inline_completions_hidden_for_vim_mode = hidden;
 2088            if hidden {
 2089                self.update_visible_inline_completion(window, cx);
 2090            } else {
 2091                self.refresh_inline_completion(true, false, window, cx);
 2092            }
 2093        }
 2094    }
 2095
 2096    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2097        self.menu_inline_completions_policy = value;
 2098    }
 2099
 2100    pub fn set_autoindent(&mut self, autoindent: bool) {
 2101        if autoindent {
 2102            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2103        } else {
 2104            self.autoindent_mode = None;
 2105        }
 2106    }
 2107
 2108    pub fn read_only(&self, cx: &App) -> bool {
 2109        self.read_only || self.buffer.read(cx).read_only()
 2110    }
 2111
 2112    pub fn set_read_only(&mut self, read_only: bool) {
 2113        self.read_only = read_only;
 2114    }
 2115
 2116    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2117        self.use_autoclose = autoclose;
 2118    }
 2119
 2120    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2121        self.use_auto_surround = auto_surround;
 2122    }
 2123
 2124    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2125        self.auto_replace_emoji_shortcode = auto_replace;
 2126    }
 2127
 2128    pub fn toggle_edit_predictions(
 2129        &mut self,
 2130        _: &ToggleEditPrediction,
 2131        window: &mut Window,
 2132        cx: &mut Context<Self>,
 2133    ) {
 2134        if self.show_inline_completions_override.is_some() {
 2135            self.set_show_edit_predictions(None, window, cx);
 2136        } else {
 2137            let show_edit_predictions = !self.edit_predictions_enabled();
 2138            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2139        }
 2140    }
 2141
 2142    pub fn set_show_edit_predictions(
 2143        &mut self,
 2144        show_edit_predictions: Option<bool>,
 2145        window: &mut Window,
 2146        cx: &mut Context<Self>,
 2147    ) {
 2148        self.show_inline_completions_override = show_edit_predictions;
 2149        self.update_edit_prediction_settings(cx);
 2150
 2151        if let Some(false) = show_edit_predictions {
 2152            self.discard_inline_completion(false, cx);
 2153        } else {
 2154            self.refresh_inline_completion(false, true, window, cx);
 2155        }
 2156    }
 2157
 2158    fn inline_completions_disabled_in_scope(
 2159        &self,
 2160        buffer: &Entity<Buffer>,
 2161        buffer_position: language::Anchor,
 2162        cx: &App,
 2163    ) -> bool {
 2164        let snapshot = buffer.read(cx).snapshot();
 2165        let settings = snapshot.settings_at(buffer_position, cx);
 2166
 2167        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2168            return false;
 2169        };
 2170
 2171        scope.override_name().map_or(false, |scope_name| {
 2172            settings
 2173                .edit_predictions_disabled_in
 2174                .iter()
 2175                .any(|s| s == scope_name)
 2176        })
 2177    }
 2178
 2179    pub fn set_use_modal_editing(&mut self, to: bool) {
 2180        self.use_modal_editing = to;
 2181    }
 2182
 2183    pub fn use_modal_editing(&self) -> bool {
 2184        self.use_modal_editing
 2185    }
 2186
 2187    fn selections_did_change(
 2188        &mut self,
 2189        local: bool,
 2190        old_cursor_position: &Anchor,
 2191        show_completions: bool,
 2192        window: &mut Window,
 2193        cx: &mut Context<Self>,
 2194    ) {
 2195        window.invalidate_character_coordinates();
 2196
 2197        // Copy selections to primary selection buffer
 2198        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2199        if local {
 2200            let selections = self.selections.all::<usize>(cx);
 2201            let buffer_handle = self.buffer.read(cx).read(cx);
 2202
 2203            let mut text = String::new();
 2204            for (index, selection) in selections.iter().enumerate() {
 2205                let text_for_selection = buffer_handle
 2206                    .text_for_range(selection.start..selection.end)
 2207                    .collect::<String>();
 2208
 2209                text.push_str(&text_for_selection);
 2210                if index != selections.len() - 1 {
 2211                    text.push('\n');
 2212                }
 2213            }
 2214
 2215            if !text.is_empty() {
 2216                cx.write_to_primary(ClipboardItem::new_string(text));
 2217            }
 2218        }
 2219
 2220        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2221            self.buffer.update(cx, |buffer, cx| {
 2222                buffer.set_active_selections(
 2223                    &self.selections.disjoint_anchors(),
 2224                    self.selections.line_mode,
 2225                    self.cursor_shape,
 2226                    cx,
 2227                )
 2228            });
 2229        }
 2230        let display_map = self
 2231            .display_map
 2232            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2233        let buffer = &display_map.buffer_snapshot;
 2234        self.add_selections_state = None;
 2235        self.select_next_state = None;
 2236        self.select_prev_state = None;
 2237        self.select_syntax_node_history.try_clear();
 2238        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2239        self.snippet_stack
 2240            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2241        self.take_rename(false, window, cx);
 2242
 2243        let new_cursor_position = self.selections.newest_anchor().head();
 2244
 2245        self.push_to_nav_history(
 2246            *old_cursor_position,
 2247            Some(new_cursor_position.to_point(buffer)),
 2248            false,
 2249            cx,
 2250        );
 2251
 2252        if local {
 2253            let new_cursor_position = self.selections.newest_anchor().head();
 2254            let mut context_menu = self.context_menu.borrow_mut();
 2255            let completion_menu = match context_menu.as_ref() {
 2256                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2257                _ => {
 2258                    *context_menu = None;
 2259                    None
 2260                }
 2261            };
 2262            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2263                if !self.registered_buffers.contains_key(&buffer_id) {
 2264                    if let Some(project) = self.project.as_ref() {
 2265                        project.update(cx, |project, cx| {
 2266                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2267                                return;
 2268                            };
 2269                            self.registered_buffers.insert(
 2270                                buffer_id,
 2271                                project.register_buffer_with_language_servers(&buffer, cx),
 2272                            );
 2273                        })
 2274                    }
 2275                }
 2276            }
 2277
 2278            if let Some(completion_menu) = completion_menu {
 2279                let cursor_position = new_cursor_position.to_offset(buffer);
 2280                let (word_range, kind) =
 2281                    buffer.surrounding_word(completion_menu.initial_position, true);
 2282                if kind == Some(CharKind::Word)
 2283                    && word_range.to_inclusive().contains(&cursor_position)
 2284                {
 2285                    let mut completion_menu = completion_menu.clone();
 2286                    drop(context_menu);
 2287
 2288                    let query = Self::completion_query(buffer, cursor_position);
 2289                    cx.spawn(async move |this, cx| {
 2290                        completion_menu
 2291                            .filter(query.as_deref(), cx.background_executor().clone())
 2292                            .await;
 2293
 2294                        this.update(cx, |this, cx| {
 2295                            let mut context_menu = this.context_menu.borrow_mut();
 2296                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2297                            else {
 2298                                return;
 2299                            };
 2300
 2301                            if menu.id > completion_menu.id {
 2302                                return;
 2303                            }
 2304
 2305                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2306                            drop(context_menu);
 2307                            cx.notify();
 2308                        })
 2309                    })
 2310                    .detach();
 2311
 2312                    if show_completions {
 2313                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2314                    }
 2315                } else {
 2316                    drop(context_menu);
 2317                    self.hide_context_menu(window, cx);
 2318                }
 2319            } else {
 2320                drop(context_menu);
 2321            }
 2322
 2323            hide_hover(self, cx);
 2324
 2325            if old_cursor_position.to_display_point(&display_map).row()
 2326                != new_cursor_position.to_display_point(&display_map).row()
 2327            {
 2328                self.available_code_actions.take();
 2329            }
 2330            self.refresh_code_actions(window, cx);
 2331            self.refresh_document_highlights(cx);
 2332            self.refresh_selected_text_highlights(window, cx);
 2333            refresh_matching_bracket_highlights(self, window, cx);
 2334            self.update_visible_inline_completion(window, cx);
 2335            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2336            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2337            if self.git_blame_inline_enabled {
 2338                self.start_inline_blame_timer(window, cx);
 2339            }
 2340        }
 2341
 2342        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2343        cx.emit(EditorEvent::SelectionsChanged { local });
 2344
 2345        let selections = &self.selections.disjoint;
 2346        if selections.len() == 1 {
 2347            cx.emit(SearchEvent::ActiveMatchChanged)
 2348        }
 2349        if local && self.is_singleton(cx) {
 2350            let inmemory_selections = selections.iter().map(|s| s.range()).collect();
 2351            self.update_restoration_data(cx, |data| {
 2352                data.selections = inmemory_selections;
 2353            });
 2354
 2355            if WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2356            {
 2357                if let Some(workspace_id) =
 2358                    self.workspace.as_ref().and_then(|workspace| workspace.1)
 2359                {
 2360                    let snapshot = self.buffer().read(cx).snapshot(cx);
 2361                    let selections = selections.clone();
 2362                    let background_executor = cx.background_executor().clone();
 2363                    let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2364                    self.serialize_selections = cx.background_spawn(async move {
 2365                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2366                    let db_selections = selections
 2367                        .iter()
 2368                        .map(|selection| {
 2369                            (
 2370                                selection.start.to_offset(&snapshot),
 2371                                selection.end.to_offset(&snapshot),
 2372                            )
 2373                        })
 2374                        .collect();
 2375
 2376                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2377                        .await
 2378                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2379                        .log_err();
 2380                });
 2381                }
 2382            }
 2383        }
 2384
 2385        cx.notify();
 2386    }
 2387
 2388    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2389        if !self.is_singleton(cx)
 2390            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
 2391        {
 2392            return;
 2393        }
 2394
 2395        let snapshot = self.buffer().read(cx).snapshot(cx);
 2396        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2397            display_map
 2398                .snapshot(cx)
 2399                .folds_in_range(0..snapshot.len())
 2400                .map(|fold| fold.range.deref().clone())
 2401                .collect()
 2402        });
 2403        self.update_restoration_data(cx, |data| {
 2404            data.folds = inmemory_folds;
 2405        });
 2406
 2407        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2408            return;
 2409        };
 2410        let background_executor = cx.background_executor().clone();
 2411        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2412        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2413            display_map
 2414                .snapshot(cx)
 2415                .folds_in_range(0..snapshot.len())
 2416                .map(|fold| {
 2417                    (
 2418                        fold.range.start.to_offset(&snapshot),
 2419                        fold.range.end.to_offset(&snapshot),
 2420                    )
 2421                })
 2422                .collect()
 2423        });
 2424        self.serialize_folds = cx.background_spawn(async move {
 2425            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2426            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2427                .await
 2428                .with_context(|| {
 2429                    format!(
 2430                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2431                    )
 2432                })
 2433                .log_err();
 2434        });
 2435    }
 2436
 2437    pub fn sync_selections(
 2438        &mut self,
 2439        other: Entity<Editor>,
 2440        cx: &mut Context<Self>,
 2441    ) -> gpui::Subscription {
 2442        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2443        self.selections.change_with(cx, |selections| {
 2444            selections.select_anchors(other_selections);
 2445        });
 2446
 2447        let other_subscription =
 2448            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2449                EditorEvent::SelectionsChanged { local: true } => {
 2450                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2451                    if other_selections.is_empty() {
 2452                        return;
 2453                    }
 2454                    this.selections.change_with(cx, |selections| {
 2455                        selections.select_anchors(other_selections);
 2456                    });
 2457                }
 2458                _ => {}
 2459            });
 2460
 2461        let this_subscription =
 2462            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2463                EditorEvent::SelectionsChanged { local: true } => {
 2464                    let these_selections = this.selections.disjoint.to_vec();
 2465                    if these_selections.is_empty() {
 2466                        return;
 2467                    }
 2468                    other.update(cx, |other_editor, cx| {
 2469                        other_editor.selections.change_with(cx, |selections| {
 2470                            selections.select_anchors(these_selections);
 2471                        })
 2472                    });
 2473                }
 2474                _ => {}
 2475            });
 2476
 2477        Subscription::join(other_subscription, this_subscription)
 2478    }
 2479
 2480    pub fn change_selections<R>(
 2481        &mut self,
 2482        autoscroll: Option<Autoscroll>,
 2483        window: &mut Window,
 2484        cx: &mut Context<Self>,
 2485        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2486    ) -> R {
 2487        self.change_selections_inner(autoscroll, true, window, cx, change)
 2488    }
 2489
 2490    fn change_selections_inner<R>(
 2491        &mut self,
 2492        autoscroll: Option<Autoscroll>,
 2493        request_completions: bool,
 2494        window: &mut Window,
 2495        cx: &mut Context<Self>,
 2496        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2497    ) -> R {
 2498        let old_cursor_position = self.selections.newest_anchor().head();
 2499        self.push_to_selection_history();
 2500
 2501        let (changed, result) = self.selections.change_with(cx, change);
 2502
 2503        if changed {
 2504            if let Some(autoscroll) = autoscroll {
 2505                self.request_autoscroll(autoscroll, cx);
 2506            }
 2507            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2508
 2509            if self.should_open_signature_help_automatically(
 2510                &old_cursor_position,
 2511                self.signature_help_state.backspace_pressed(),
 2512                cx,
 2513            ) {
 2514                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2515            }
 2516            self.signature_help_state.set_backspace_pressed(false);
 2517        }
 2518
 2519        result
 2520    }
 2521
 2522    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2523    where
 2524        I: IntoIterator<Item = (Range<S>, T)>,
 2525        S: ToOffset,
 2526        T: Into<Arc<str>>,
 2527    {
 2528        if self.read_only(cx) {
 2529            return;
 2530        }
 2531
 2532        self.buffer
 2533            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2534    }
 2535
 2536    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2537    where
 2538        I: IntoIterator<Item = (Range<S>, T)>,
 2539        S: ToOffset,
 2540        T: Into<Arc<str>>,
 2541    {
 2542        if self.read_only(cx) {
 2543            return;
 2544        }
 2545
 2546        self.buffer.update(cx, |buffer, cx| {
 2547            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2548        });
 2549    }
 2550
 2551    pub fn edit_with_block_indent<I, S, T>(
 2552        &mut self,
 2553        edits: I,
 2554        original_indent_columns: Vec<Option<u32>>,
 2555        cx: &mut Context<Self>,
 2556    ) where
 2557        I: IntoIterator<Item = (Range<S>, T)>,
 2558        S: ToOffset,
 2559        T: Into<Arc<str>>,
 2560    {
 2561        if self.read_only(cx) {
 2562            return;
 2563        }
 2564
 2565        self.buffer.update(cx, |buffer, cx| {
 2566            buffer.edit(
 2567                edits,
 2568                Some(AutoindentMode::Block {
 2569                    original_indent_columns,
 2570                }),
 2571                cx,
 2572            )
 2573        });
 2574    }
 2575
 2576    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2577        self.hide_context_menu(window, cx);
 2578
 2579        match phase {
 2580            SelectPhase::Begin {
 2581                position,
 2582                add,
 2583                click_count,
 2584            } => self.begin_selection(position, add, click_count, window, cx),
 2585            SelectPhase::BeginColumnar {
 2586                position,
 2587                goal_column,
 2588                reset,
 2589            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2590            SelectPhase::Extend {
 2591                position,
 2592                click_count,
 2593            } => self.extend_selection(position, click_count, window, cx),
 2594            SelectPhase::Update {
 2595                position,
 2596                goal_column,
 2597                scroll_delta,
 2598            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2599            SelectPhase::End => self.end_selection(window, cx),
 2600        }
 2601    }
 2602
 2603    fn extend_selection(
 2604        &mut self,
 2605        position: DisplayPoint,
 2606        click_count: usize,
 2607        window: &mut Window,
 2608        cx: &mut Context<Self>,
 2609    ) {
 2610        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2611        let tail = self.selections.newest::<usize>(cx).tail();
 2612        self.begin_selection(position, false, click_count, window, cx);
 2613
 2614        let position = position.to_offset(&display_map, Bias::Left);
 2615        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2616
 2617        let mut pending_selection = self
 2618            .selections
 2619            .pending_anchor()
 2620            .expect("extend_selection not called with pending selection");
 2621        if position >= tail {
 2622            pending_selection.start = tail_anchor;
 2623        } else {
 2624            pending_selection.end = tail_anchor;
 2625            pending_selection.reversed = true;
 2626        }
 2627
 2628        let mut pending_mode = self.selections.pending_mode().unwrap();
 2629        match &mut pending_mode {
 2630            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2631            _ => {}
 2632        }
 2633
 2634        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2635            s.set_pending(pending_selection, pending_mode)
 2636        });
 2637    }
 2638
 2639    fn begin_selection(
 2640        &mut self,
 2641        position: DisplayPoint,
 2642        add: bool,
 2643        click_count: usize,
 2644        window: &mut Window,
 2645        cx: &mut Context<Self>,
 2646    ) {
 2647        if !self.focus_handle.is_focused(window) {
 2648            self.last_focused_descendant = None;
 2649            window.focus(&self.focus_handle);
 2650        }
 2651
 2652        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2653        let buffer = &display_map.buffer_snapshot;
 2654        let newest_selection = self.selections.newest_anchor().clone();
 2655        let position = display_map.clip_point(position, Bias::Left);
 2656
 2657        let start;
 2658        let end;
 2659        let mode;
 2660        let mut auto_scroll;
 2661        match click_count {
 2662            1 => {
 2663                start = buffer.anchor_before(position.to_point(&display_map));
 2664                end = start;
 2665                mode = SelectMode::Character;
 2666                auto_scroll = true;
 2667            }
 2668            2 => {
 2669                let range = movement::surrounding_word(&display_map, position);
 2670                start = buffer.anchor_before(range.start.to_point(&display_map));
 2671                end = buffer.anchor_before(range.end.to_point(&display_map));
 2672                mode = SelectMode::Word(start..end);
 2673                auto_scroll = true;
 2674            }
 2675            3 => {
 2676                let position = display_map
 2677                    .clip_point(position, Bias::Left)
 2678                    .to_point(&display_map);
 2679                let line_start = display_map.prev_line_boundary(position).0;
 2680                let next_line_start = buffer.clip_point(
 2681                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2682                    Bias::Left,
 2683                );
 2684                start = buffer.anchor_before(line_start);
 2685                end = buffer.anchor_before(next_line_start);
 2686                mode = SelectMode::Line(start..end);
 2687                auto_scroll = true;
 2688            }
 2689            _ => {
 2690                start = buffer.anchor_before(0);
 2691                end = buffer.anchor_before(buffer.len());
 2692                mode = SelectMode::All;
 2693                auto_scroll = false;
 2694            }
 2695        }
 2696        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2697
 2698        let point_to_delete: Option<usize> = {
 2699            let selected_points: Vec<Selection<Point>> =
 2700                self.selections.disjoint_in_range(start..end, cx);
 2701
 2702            if !add || click_count > 1 {
 2703                None
 2704            } else if !selected_points.is_empty() {
 2705                Some(selected_points[0].id)
 2706            } else {
 2707                let clicked_point_already_selected =
 2708                    self.selections.disjoint.iter().find(|selection| {
 2709                        selection.start.to_point(buffer) == start.to_point(buffer)
 2710                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2711                    });
 2712
 2713                clicked_point_already_selected.map(|selection| selection.id)
 2714            }
 2715        };
 2716
 2717        let selections_count = self.selections.count();
 2718
 2719        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2720            if let Some(point_to_delete) = point_to_delete {
 2721                s.delete(point_to_delete);
 2722
 2723                if selections_count == 1 {
 2724                    s.set_pending_anchor_range(start..end, mode);
 2725                }
 2726            } else {
 2727                if !add {
 2728                    s.clear_disjoint();
 2729                } else if click_count > 1 {
 2730                    s.delete(newest_selection.id)
 2731                }
 2732
 2733                s.set_pending_anchor_range(start..end, mode);
 2734            }
 2735        });
 2736    }
 2737
 2738    fn begin_columnar_selection(
 2739        &mut self,
 2740        position: DisplayPoint,
 2741        goal_column: u32,
 2742        reset: bool,
 2743        window: &mut Window,
 2744        cx: &mut Context<Self>,
 2745    ) {
 2746        if !self.focus_handle.is_focused(window) {
 2747            self.last_focused_descendant = None;
 2748            window.focus(&self.focus_handle);
 2749        }
 2750
 2751        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2752
 2753        if reset {
 2754            let pointer_position = display_map
 2755                .buffer_snapshot
 2756                .anchor_before(position.to_point(&display_map));
 2757
 2758            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2759                s.clear_disjoint();
 2760                s.set_pending_anchor_range(
 2761                    pointer_position..pointer_position,
 2762                    SelectMode::Character,
 2763                );
 2764            });
 2765        }
 2766
 2767        let tail = self.selections.newest::<Point>(cx).tail();
 2768        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2769
 2770        if !reset {
 2771            self.select_columns(
 2772                tail.to_display_point(&display_map),
 2773                position,
 2774                goal_column,
 2775                &display_map,
 2776                window,
 2777                cx,
 2778            );
 2779        }
 2780    }
 2781
 2782    fn update_selection(
 2783        &mut self,
 2784        position: DisplayPoint,
 2785        goal_column: u32,
 2786        scroll_delta: gpui::Point<f32>,
 2787        window: &mut Window,
 2788        cx: &mut Context<Self>,
 2789    ) {
 2790        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2791
 2792        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2793            let tail = tail.to_display_point(&display_map);
 2794            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2795        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2796            let buffer = self.buffer.read(cx).snapshot(cx);
 2797            let head;
 2798            let tail;
 2799            let mode = self.selections.pending_mode().unwrap();
 2800            match &mode {
 2801                SelectMode::Character => {
 2802                    head = position.to_point(&display_map);
 2803                    tail = pending.tail().to_point(&buffer);
 2804                }
 2805                SelectMode::Word(original_range) => {
 2806                    let original_display_range = original_range.start.to_display_point(&display_map)
 2807                        ..original_range.end.to_display_point(&display_map);
 2808                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2809                        ..original_display_range.end.to_point(&display_map);
 2810                    if movement::is_inside_word(&display_map, position)
 2811                        || original_display_range.contains(&position)
 2812                    {
 2813                        let word_range = movement::surrounding_word(&display_map, position);
 2814                        if word_range.start < original_display_range.start {
 2815                            head = word_range.start.to_point(&display_map);
 2816                        } else {
 2817                            head = word_range.end.to_point(&display_map);
 2818                        }
 2819                    } else {
 2820                        head = position.to_point(&display_map);
 2821                    }
 2822
 2823                    if head <= original_buffer_range.start {
 2824                        tail = original_buffer_range.end;
 2825                    } else {
 2826                        tail = original_buffer_range.start;
 2827                    }
 2828                }
 2829                SelectMode::Line(original_range) => {
 2830                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2831
 2832                    let position = display_map
 2833                        .clip_point(position, Bias::Left)
 2834                        .to_point(&display_map);
 2835                    let line_start = display_map.prev_line_boundary(position).0;
 2836                    let next_line_start = buffer.clip_point(
 2837                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2838                        Bias::Left,
 2839                    );
 2840
 2841                    if line_start < original_range.start {
 2842                        head = line_start
 2843                    } else {
 2844                        head = next_line_start
 2845                    }
 2846
 2847                    if head <= original_range.start {
 2848                        tail = original_range.end;
 2849                    } else {
 2850                        tail = original_range.start;
 2851                    }
 2852                }
 2853                SelectMode::All => {
 2854                    return;
 2855                }
 2856            };
 2857
 2858            if head < tail {
 2859                pending.start = buffer.anchor_before(head);
 2860                pending.end = buffer.anchor_before(tail);
 2861                pending.reversed = true;
 2862            } else {
 2863                pending.start = buffer.anchor_before(tail);
 2864                pending.end = buffer.anchor_before(head);
 2865                pending.reversed = false;
 2866            }
 2867
 2868            self.change_selections(None, window, cx, |s| {
 2869                s.set_pending(pending, mode);
 2870            });
 2871        } else {
 2872            log::error!("update_selection dispatched with no pending selection");
 2873            return;
 2874        }
 2875
 2876        self.apply_scroll_delta(scroll_delta, window, cx);
 2877        cx.notify();
 2878    }
 2879
 2880    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2881        self.columnar_selection_tail.take();
 2882        if self.selections.pending_anchor().is_some() {
 2883            let selections = self.selections.all::<usize>(cx);
 2884            self.change_selections(None, window, cx, |s| {
 2885                s.select(selections);
 2886                s.clear_pending();
 2887            });
 2888        }
 2889    }
 2890
 2891    fn select_columns(
 2892        &mut self,
 2893        tail: DisplayPoint,
 2894        head: DisplayPoint,
 2895        goal_column: u32,
 2896        display_map: &DisplaySnapshot,
 2897        window: &mut Window,
 2898        cx: &mut Context<Self>,
 2899    ) {
 2900        let start_row = cmp::min(tail.row(), head.row());
 2901        let end_row = cmp::max(tail.row(), head.row());
 2902        let start_column = cmp::min(tail.column(), goal_column);
 2903        let end_column = cmp::max(tail.column(), goal_column);
 2904        let reversed = start_column < tail.column();
 2905
 2906        let selection_ranges = (start_row.0..=end_row.0)
 2907            .map(DisplayRow)
 2908            .filter_map(|row| {
 2909                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2910                    let start = display_map
 2911                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2912                        .to_point(display_map);
 2913                    let end = display_map
 2914                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2915                        .to_point(display_map);
 2916                    if reversed {
 2917                        Some(end..start)
 2918                    } else {
 2919                        Some(start..end)
 2920                    }
 2921                } else {
 2922                    None
 2923                }
 2924            })
 2925            .collect::<Vec<_>>();
 2926
 2927        self.change_selections(None, window, cx, |s| {
 2928            s.select_ranges(selection_ranges);
 2929        });
 2930        cx.notify();
 2931    }
 2932
 2933    pub fn has_pending_nonempty_selection(&self) -> bool {
 2934        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2935            Some(Selection { start, end, .. }) => start != end,
 2936            None => false,
 2937        };
 2938
 2939        pending_nonempty_selection
 2940            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2941    }
 2942
 2943    pub fn has_pending_selection(&self) -> bool {
 2944        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2945    }
 2946
 2947    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2948        self.selection_mark_mode = false;
 2949
 2950        if self.clear_expanded_diff_hunks(cx) {
 2951            cx.notify();
 2952            return;
 2953        }
 2954        if self.dismiss_menus_and_popups(true, window, cx) {
 2955            return;
 2956        }
 2957
 2958        if self.mode == EditorMode::Full
 2959            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2960        {
 2961            return;
 2962        }
 2963
 2964        cx.propagate();
 2965    }
 2966
 2967    pub fn dismiss_menus_and_popups(
 2968        &mut self,
 2969        is_user_requested: bool,
 2970        window: &mut Window,
 2971        cx: &mut Context<Self>,
 2972    ) -> bool {
 2973        if self.take_rename(false, window, cx).is_some() {
 2974            return true;
 2975        }
 2976
 2977        if hide_hover(self, cx) {
 2978            return true;
 2979        }
 2980
 2981        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2982            return true;
 2983        }
 2984
 2985        if self.hide_context_menu(window, cx).is_some() {
 2986            return true;
 2987        }
 2988
 2989        if self.mouse_context_menu.take().is_some() {
 2990            return true;
 2991        }
 2992
 2993        if is_user_requested && self.discard_inline_completion(true, cx) {
 2994            return true;
 2995        }
 2996
 2997        if self.snippet_stack.pop().is_some() {
 2998            return true;
 2999        }
 3000
 3001        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3002            self.dismiss_diagnostics(cx);
 3003            return true;
 3004        }
 3005
 3006        false
 3007    }
 3008
 3009    fn linked_editing_ranges_for(
 3010        &self,
 3011        selection: Range<text::Anchor>,
 3012        cx: &App,
 3013    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3014        if self.linked_edit_ranges.is_empty() {
 3015            return None;
 3016        }
 3017        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3018            selection.end.buffer_id.and_then(|end_buffer_id| {
 3019                if selection.start.buffer_id != Some(end_buffer_id) {
 3020                    return None;
 3021                }
 3022                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3023                let snapshot = buffer.read(cx).snapshot();
 3024                self.linked_edit_ranges
 3025                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3026                    .map(|ranges| (ranges, snapshot, buffer))
 3027            })?;
 3028        use text::ToOffset as TO;
 3029        // find offset from the start of current range to current cursor position
 3030        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3031
 3032        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3033        let start_difference = start_offset - start_byte_offset;
 3034        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3035        let end_difference = end_offset - start_byte_offset;
 3036        // Current range has associated linked ranges.
 3037        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3038        for range in linked_ranges.iter() {
 3039            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3040            let end_offset = start_offset + end_difference;
 3041            let start_offset = start_offset + start_difference;
 3042            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3043                continue;
 3044            }
 3045            if self.selections.disjoint_anchor_ranges().any(|s| {
 3046                if s.start.buffer_id != selection.start.buffer_id
 3047                    || s.end.buffer_id != selection.end.buffer_id
 3048                {
 3049                    return false;
 3050                }
 3051                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3052                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3053            }) {
 3054                continue;
 3055            }
 3056            let start = buffer_snapshot.anchor_after(start_offset);
 3057            let end = buffer_snapshot.anchor_after(end_offset);
 3058            linked_edits
 3059                .entry(buffer.clone())
 3060                .or_default()
 3061                .push(start..end);
 3062        }
 3063        Some(linked_edits)
 3064    }
 3065
 3066    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3067        let text: Arc<str> = text.into();
 3068
 3069        if self.read_only(cx) {
 3070            return;
 3071        }
 3072
 3073        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3074
 3075        let selections = self.selections.all_adjusted(cx);
 3076        let mut bracket_inserted = false;
 3077        let mut edits = Vec::new();
 3078        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3079        let mut new_selections = Vec::with_capacity(selections.len());
 3080        let mut new_autoclose_regions = Vec::new();
 3081        let snapshot = self.buffer.read(cx).read(cx);
 3082
 3083        for (selection, autoclose_region) in
 3084            self.selections_with_autoclose_regions(selections, &snapshot)
 3085        {
 3086            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3087                // Determine if the inserted text matches the opening or closing
 3088                // bracket of any of this language's bracket pairs.
 3089                let mut bracket_pair = None;
 3090                let mut is_bracket_pair_start = false;
 3091                let mut is_bracket_pair_end = false;
 3092                if !text.is_empty() {
 3093                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3094                    //  and they are removing the character that triggered IME popup.
 3095                    for (pair, enabled) in scope.brackets() {
 3096                        if !pair.close && !pair.surround {
 3097                            continue;
 3098                        }
 3099
 3100                        if enabled && pair.start.ends_with(text.as_ref()) {
 3101                            let prefix_len = pair.start.len() - text.len();
 3102                            let preceding_text_matches_prefix = prefix_len == 0
 3103                                || (selection.start.column >= (prefix_len as u32)
 3104                                    && snapshot.contains_str_at(
 3105                                        Point::new(
 3106                                            selection.start.row,
 3107                                            selection.start.column - (prefix_len as u32),
 3108                                        ),
 3109                                        &pair.start[..prefix_len],
 3110                                    ));
 3111                            if preceding_text_matches_prefix {
 3112                                bracket_pair = Some(pair.clone());
 3113                                is_bracket_pair_start = true;
 3114                                break;
 3115                            }
 3116                        }
 3117                        if pair.end.as_str() == text.as_ref() {
 3118                            bracket_pair = Some(pair.clone());
 3119                            is_bracket_pair_end = true;
 3120                            break;
 3121                        }
 3122                    }
 3123                }
 3124
 3125                if let Some(bracket_pair) = bracket_pair {
 3126                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3127                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3128                    let auto_surround =
 3129                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3130                    if selection.is_empty() {
 3131                        if is_bracket_pair_start {
 3132                            // If the inserted text is a suffix of an opening bracket and the
 3133                            // selection is preceded by the rest of the opening bracket, then
 3134                            // insert the closing bracket.
 3135                            let following_text_allows_autoclose = snapshot
 3136                                .chars_at(selection.start)
 3137                                .next()
 3138                                .map_or(true, |c| scope.should_autoclose_before(c));
 3139
 3140                            let preceding_text_allows_autoclose = selection.start.column == 0
 3141                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3142                                    true,
 3143                                    |c| {
 3144                                        bracket_pair.start != bracket_pair.end
 3145                                            || !snapshot
 3146                                                .char_classifier_at(selection.start)
 3147                                                .is_word(c)
 3148                                    },
 3149                                );
 3150
 3151                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3152                                && bracket_pair.start.len() == 1
 3153                            {
 3154                                let target = bracket_pair.start.chars().next().unwrap();
 3155                                let current_line_count = snapshot
 3156                                    .reversed_chars_at(selection.start)
 3157                                    .take_while(|&c| c != '\n')
 3158                                    .filter(|&c| c == target)
 3159                                    .count();
 3160                                current_line_count % 2 == 1
 3161                            } else {
 3162                                false
 3163                            };
 3164
 3165                            if autoclose
 3166                                && bracket_pair.close
 3167                                && following_text_allows_autoclose
 3168                                && preceding_text_allows_autoclose
 3169                                && !is_closing_quote
 3170                            {
 3171                                let anchor = snapshot.anchor_before(selection.end);
 3172                                new_selections.push((selection.map(|_| anchor), text.len()));
 3173                                new_autoclose_regions.push((
 3174                                    anchor,
 3175                                    text.len(),
 3176                                    selection.id,
 3177                                    bracket_pair.clone(),
 3178                                ));
 3179                                edits.push((
 3180                                    selection.range(),
 3181                                    format!("{}{}", text, bracket_pair.end).into(),
 3182                                ));
 3183                                bracket_inserted = true;
 3184                                continue;
 3185                            }
 3186                        }
 3187
 3188                        if let Some(region) = autoclose_region {
 3189                            // If the selection is followed by an auto-inserted closing bracket,
 3190                            // then don't insert that closing bracket again; just move the selection
 3191                            // past the closing bracket.
 3192                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3193                                && text.as_ref() == region.pair.end.as_str();
 3194                            if should_skip {
 3195                                let anchor = snapshot.anchor_after(selection.end);
 3196                                new_selections
 3197                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3198                                continue;
 3199                            }
 3200                        }
 3201
 3202                        let always_treat_brackets_as_autoclosed = snapshot
 3203                            .language_settings_at(selection.start, cx)
 3204                            .always_treat_brackets_as_autoclosed;
 3205                        if always_treat_brackets_as_autoclosed
 3206                            && is_bracket_pair_end
 3207                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3208                        {
 3209                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3210                            // and the inserted text is a closing bracket and the selection is followed
 3211                            // by the closing bracket then move the selection past the closing bracket.
 3212                            let anchor = snapshot.anchor_after(selection.end);
 3213                            new_selections.push((selection.map(|_| anchor), text.len()));
 3214                            continue;
 3215                        }
 3216                    }
 3217                    // If an opening bracket is 1 character long and is typed while
 3218                    // text is selected, then surround that text with the bracket pair.
 3219                    else if auto_surround
 3220                        && bracket_pair.surround
 3221                        && is_bracket_pair_start
 3222                        && bracket_pair.start.chars().count() == 1
 3223                    {
 3224                        edits.push((selection.start..selection.start, text.clone()));
 3225                        edits.push((
 3226                            selection.end..selection.end,
 3227                            bracket_pair.end.as_str().into(),
 3228                        ));
 3229                        bracket_inserted = true;
 3230                        new_selections.push((
 3231                            Selection {
 3232                                id: selection.id,
 3233                                start: snapshot.anchor_after(selection.start),
 3234                                end: snapshot.anchor_before(selection.end),
 3235                                reversed: selection.reversed,
 3236                                goal: selection.goal,
 3237                            },
 3238                            0,
 3239                        ));
 3240                        continue;
 3241                    }
 3242                }
 3243            }
 3244
 3245            if self.auto_replace_emoji_shortcode
 3246                && selection.is_empty()
 3247                && text.as_ref().ends_with(':')
 3248            {
 3249                if let Some(possible_emoji_short_code) =
 3250                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3251                {
 3252                    if !possible_emoji_short_code.is_empty() {
 3253                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3254                            let emoji_shortcode_start = Point::new(
 3255                                selection.start.row,
 3256                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3257                            );
 3258
 3259                            // Remove shortcode from buffer
 3260                            edits.push((
 3261                                emoji_shortcode_start..selection.start,
 3262                                "".to_string().into(),
 3263                            ));
 3264                            new_selections.push((
 3265                                Selection {
 3266                                    id: selection.id,
 3267                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3268                                    end: snapshot.anchor_before(selection.start),
 3269                                    reversed: selection.reversed,
 3270                                    goal: selection.goal,
 3271                                },
 3272                                0,
 3273                            ));
 3274
 3275                            // Insert emoji
 3276                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3277                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3278                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3279
 3280                            continue;
 3281                        }
 3282                    }
 3283                }
 3284            }
 3285
 3286            // If not handling any auto-close operation, then just replace the selected
 3287            // text with the given input and move the selection to the end of the
 3288            // newly inserted text.
 3289            let anchor = snapshot.anchor_after(selection.end);
 3290            if !self.linked_edit_ranges.is_empty() {
 3291                let start_anchor = snapshot.anchor_before(selection.start);
 3292
 3293                let is_word_char = text.chars().next().map_or(true, |char| {
 3294                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3295                    classifier.is_word(char)
 3296                });
 3297
 3298                if is_word_char {
 3299                    if let Some(ranges) = self
 3300                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3301                    {
 3302                        for (buffer, edits) in ranges {
 3303                            linked_edits
 3304                                .entry(buffer.clone())
 3305                                .or_default()
 3306                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3307                        }
 3308                    }
 3309                }
 3310            }
 3311
 3312            new_selections.push((selection.map(|_| anchor), 0));
 3313            edits.push((selection.start..selection.end, text.clone()));
 3314        }
 3315
 3316        drop(snapshot);
 3317
 3318        self.transact(window, cx, |this, window, cx| {
 3319            let initial_buffer_versions =
 3320                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3321
 3322            this.buffer.update(cx, |buffer, cx| {
 3323                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3324            });
 3325            for (buffer, edits) in linked_edits {
 3326                buffer.update(cx, |buffer, cx| {
 3327                    let snapshot = buffer.snapshot();
 3328                    let edits = edits
 3329                        .into_iter()
 3330                        .map(|(range, text)| {
 3331                            use text::ToPoint as TP;
 3332                            let end_point = TP::to_point(&range.end, &snapshot);
 3333                            let start_point = TP::to_point(&range.start, &snapshot);
 3334                            (start_point..end_point, text)
 3335                        })
 3336                        .sorted_by_key(|(range, _)| range.start);
 3337                    buffer.edit(edits, None, cx);
 3338                })
 3339            }
 3340            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3341            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3342            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3343            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3344                .zip(new_selection_deltas)
 3345                .map(|(selection, delta)| Selection {
 3346                    id: selection.id,
 3347                    start: selection.start + delta,
 3348                    end: selection.end + delta,
 3349                    reversed: selection.reversed,
 3350                    goal: SelectionGoal::None,
 3351                })
 3352                .collect::<Vec<_>>();
 3353
 3354            let mut i = 0;
 3355            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3356                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3357                let start = map.buffer_snapshot.anchor_before(position);
 3358                let end = map.buffer_snapshot.anchor_after(position);
 3359                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3360                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3361                        Ordering::Less => i += 1,
 3362                        Ordering::Greater => break,
 3363                        Ordering::Equal => {
 3364                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3365                                Ordering::Less => i += 1,
 3366                                Ordering::Equal => break,
 3367                                Ordering::Greater => break,
 3368                            }
 3369                        }
 3370                    }
 3371                }
 3372                this.autoclose_regions.insert(
 3373                    i,
 3374                    AutocloseRegion {
 3375                        selection_id,
 3376                        range: start..end,
 3377                        pair,
 3378                    },
 3379                );
 3380            }
 3381
 3382            let had_active_inline_completion = this.has_active_inline_completion();
 3383            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3384                s.select(new_selections)
 3385            });
 3386
 3387            if !bracket_inserted {
 3388                if let Some(on_type_format_task) =
 3389                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3390                {
 3391                    on_type_format_task.detach_and_log_err(cx);
 3392                }
 3393            }
 3394
 3395            let editor_settings = EditorSettings::get_global(cx);
 3396            if bracket_inserted
 3397                && (editor_settings.auto_signature_help
 3398                    || editor_settings.show_signature_help_after_edits)
 3399            {
 3400                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3401            }
 3402
 3403            let trigger_in_words =
 3404                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3405            if this.hard_wrap.is_some() {
 3406                let latest: Range<Point> = this.selections.newest(cx).range();
 3407                if latest.is_empty()
 3408                    && this
 3409                        .buffer()
 3410                        .read(cx)
 3411                        .snapshot(cx)
 3412                        .line_len(MultiBufferRow(latest.start.row))
 3413                        == latest.start.column
 3414                {
 3415                    this.rewrap_impl(
 3416                        RewrapOptions {
 3417                            override_language_settings: true,
 3418                            preserve_existing_whitespace: true,
 3419                        },
 3420                        cx,
 3421                    )
 3422                }
 3423            }
 3424            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3425            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3426            this.refresh_inline_completion(true, false, window, cx);
 3427            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3428        });
 3429    }
 3430
 3431    fn find_possible_emoji_shortcode_at_position(
 3432        snapshot: &MultiBufferSnapshot,
 3433        position: Point,
 3434    ) -> Option<String> {
 3435        let mut chars = Vec::new();
 3436        let mut found_colon = false;
 3437        for char in snapshot.reversed_chars_at(position).take(100) {
 3438            // Found a possible emoji shortcode in the middle of the buffer
 3439            if found_colon {
 3440                if char.is_whitespace() {
 3441                    chars.reverse();
 3442                    return Some(chars.iter().collect());
 3443                }
 3444                // If the previous character is not a whitespace, we are in the middle of a word
 3445                // and we only want to complete the shortcode if the word is made up of other emojis
 3446                let mut containing_word = String::new();
 3447                for ch in snapshot
 3448                    .reversed_chars_at(position)
 3449                    .skip(chars.len() + 1)
 3450                    .take(100)
 3451                {
 3452                    if ch.is_whitespace() {
 3453                        break;
 3454                    }
 3455                    containing_word.push(ch);
 3456                }
 3457                let containing_word = containing_word.chars().rev().collect::<String>();
 3458                if util::word_consists_of_emojis(containing_word.as_str()) {
 3459                    chars.reverse();
 3460                    return Some(chars.iter().collect());
 3461                }
 3462            }
 3463
 3464            if char.is_whitespace() || !char.is_ascii() {
 3465                return None;
 3466            }
 3467            if char == ':' {
 3468                found_colon = true;
 3469            } else {
 3470                chars.push(char);
 3471            }
 3472        }
 3473        // Found a possible emoji shortcode at the beginning of the buffer
 3474        chars.reverse();
 3475        Some(chars.iter().collect())
 3476    }
 3477
 3478    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3479        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3480        self.transact(window, cx, |this, window, cx| {
 3481            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3482                let selections = this.selections.all::<usize>(cx);
 3483                let multi_buffer = this.buffer.read(cx);
 3484                let buffer = multi_buffer.snapshot(cx);
 3485                selections
 3486                    .iter()
 3487                    .map(|selection| {
 3488                        let start_point = selection.start.to_point(&buffer);
 3489                        let mut indent =
 3490                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3491                        indent.len = cmp::min(indent.len, start_point.column);
 3492                        let start = selection.start;
 3493                        let end = selection.end;
 3494                        let selection_is_empty = start == end;
 3495                        let language_scope = buffer.language_scope_at(start);
 3496                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3497                            &language_scope
 3498                        {
 3499                            let insert_extra_newline =
 3500                                insert_extra_newline_brackets(&buffer, start..end, language)
 3501                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3502
 3503                            // Comment extension on newline is allowed only for cursor selections
 3504                            let comment_delimiter = maybe!({
 3505                                if !selection_is_empty {
 3506                                    return None;
 3507                                }
 3508
 3509                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3510                                    return None;
 3511                                }
 3512
 3513                                let delimiters = language.line_comment_prefixes();
 3514                                let max_len_of_delimiter =
 3515                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3516                                let (snapshot, range) =
 3517                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3518
 3519                                let mut index_of_first_non_whitespace = 0;
 3520                                let comment_candidate = snapshot
 3521                                    .chars_for_range(range)
 3522                                    .skip_while(|c| {
 3523                                        let should_skip = c.is_whitespace();
 3524                                        if should_skip {
 3525                                            index_of_first_non_whitespace += 1;
 3526                                        }
 3527                                        should_skip
 3528                                    })
 3529                                    .take(max_len_of_delimiter)
 3530                                    .collect::<String>();
 3531                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3532                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3533                                })?;
 3534                                let cursor_is_placed_after_comment_marker =
 3535                                    index_of_first_non_whitespace + comment_prefix.len()
 3536                                        <= start_point.column as usize;
 3537                                if cursor_is_placed_after_comment_marker {
 3538                                    Some(comment_prefix.clone())
 3539                                } else {
 3540                                    None
 3541                                }
 3542                            });
 3543                            (comment_delimiter, insert_extra_newline)
 3544                        } else {
 3545                            (None, false)
 3546                        };
 3547
 3548                        let capacity_for_delimiter = comment_delimiter
 3549                            .as_deref()
 3550                            .map(str::len)
 3551                            .unwrap_or_default();
 3552                        let mut new_text =
 3553                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3554                        new_text.push('\n');
 3555                        new_text.extend(indent.chars());
 3556                        if let Some(delimiter) = &comment_delimiter {
 3557                            new_text.push_str(delimiter);
 3558                        }
 3559                        if insert_extra_newline {
 3560                            new_text = new_text.repeat(2);
 3561                        }
 3562
 3563                        let anchor = buffer.anchor_after(end);
 3564                        let new_selection = selection.map(|_| anchor);
 3565                        (
 3566                            (start..end, new_text),
 3567                            (insert_extra_newline, new_selection),
 3568                        )
 3569                    })
 3570                    .unzip()
 3571            };
 3572
 3573            this.edit_with_autoindent(edits, cx);
 3574            let buffer = this.buffer.read(cx).snapshot(cx);
 3575            let new_selections = selection_fixup_info
 3576                .into_iter()
 3577                .map(|(extra_newline_inserted, new_selection)| {
 3578                    let mut cursor = new_selection.end.to_point(&buffer);
 3579                    if extra_newline_inserted {
 3580                        cursor.row -= 1;
 3581                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3582                    }
 3583                    new_selection.map(|_| cursor)
 3584                })
 3585                .collect();
 3586
 3587            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3588                s.select(new_selections)
 3589            });
 3590            this.refresh_inline_completion(true, false, window, cx);
 3591        });
 3592    }
 3593
 3594    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3595        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3596
 3597        let buffer = self.buffer.read(cx);
 3598        let snapshot = buffer.snapshot(cx);
 3599
 3600        let mut edits = Vec::new();
 3601        let mut rows = Vec::new();
 3602
 3603        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3604            let cursor = selection.head();
 3605            let row = cursor.row;
 3606
 3607            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3608
 3609            let newline = "\n".to_string();
 3610            edits.push((start_of_line..start_of_line, newline));
 3611
 3612            rows.push(row + rows_inserted as u32);
 3613        }
 3614
 3615        self.transact(window, cx, |editor, window, cx| {
 3616            editor.edit(edits, cx);
 3617
 3618            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3619                let mut index = 0;
 3620                s.move_cursors_with(|map, _, _| {
 3621                    let row = rows[index];
 3622                    index += 1;
 3623
 3624                    let point = Point::new(row, 0);
 3625                    let boundary = map.next_line_boundary(point).1;
 3626                    let clipped = map.clip_point(boundary, Bias::Left);
 3627
 3628                    (clipped, SelectionGoal::None)
 3629                });
 3630            });
 3631
 3632            let mut indent_edits = Vec::new();
 3633            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3634            for row in rows {
 3635                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3636                for (row, indent) in indents {
 3637                    if indent.len == 0 {
 3638                        continue;
 3639                    }
 3640
 3641                    let text = match indent.kind {
 3642                        IndentKind::Space => " ".repeat(indent.len as usize),
 3643                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3644                    };
 3645                    let point = Point::new(row.0, 0);
 3646                    indent_edits.push((point..point, text));
 3647                }
 3648            }
 3649            editor.edit(indent_edits, cx);
 3650        });
 3651    }
 3652
 3653    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3654        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3655
 3656        let buffer = self.buffer.read(cx);
 3657        let snapshot = buffer.snapshot(cx);
 3658
 3659        let mut edits = Vec::new();
 3660        let mut rows = Vec::new();
 3661        let mut rows_inserted = 0;
 3662
 3663        for selection in self.selections.all_adjusted(cx) {
 3664            let cursor = selection.head();
 3665            let row = cursor.row;
 3666
 3667            let point = Point::new(row + 1, 0);
 3668            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3669
 3670            let newline = "\n".to_string();
 3671            edits.push((start_of_line..start_of_line, newline));
 3672
 3673            rows_inserted += 1;
 3674            rows.push(row + rows_inserted);
 3675        }
 3676
 3677        self.transact(window, cx, |editor, window, cx| {
 3678            editor.edit(edits, cx);
 3679
 3680            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3681                let mut index = 0;
 3682                s.move_cursors_with(|map, _, _| {
 3683                    let row = rows[index];
 3684                    index += 1;
 3685
 3686                    let point = Point::new(row, 0);
 3687                    let boundary = map.next_line_boundary(point).1;
 3688                    let clipped = map.clip_point(boundary, Bias::Left);
 3689
 3690                    (clipped, SelectionGoal::None)
 3691                });
 3692            });
 3693
 3694            let mut indent_edits = Vec::new();
 3695            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3696            for row in rows {
 3697                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3698                for (row, indent) in indents {
 3699                    if indent.len == 0 {
 3700                        continue;
 3701                    }
 3702
 3703                    let text = match indent.kind {
 3704                        IndentKind::Space => " ".repeat(indent.len as usize),
 3705                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3706                    };
 3707                    let point = Point::new(row.0, 0);
 3708                    indent_edits.push((point..point, text));
 3709                }
 3710            }
 3711            editor.edit(indent_edits, cx);
 3712        });
 3713    }
 3714
 3715    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3716        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3717            original_indent_columns: Vec::new(),
 3718        });
 3719        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3720    }
 3721
 3722    fn insert_with_autoindent_mode(
 3723        &mut self,
 3724        text: &str,
 3725        autoindent_mode: Option<AutoindentMode>,
 3726        window: &mut Window,
 3727        cx: &mut Context<Self>,
 3728    ) {
 3729        if self.read_only(cx) {
 3730            return;
 3731        }
 3732
 3733        let text: Arc<str> = text.into();
 3734        self.transact(window, cx, |this, window, cx| {
 3735            let old_selections = this.selections.all_adjusted(cx);
 3736            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3737                let anchors = {
 3738                    let snapshot = buffer.read(cx);
 3739                    old_selections
 3740                        .iter()
 3741                        .map(|s| {
 3742                            let anchor = snapshot.anchor_after(s.head());
 3743                            s.map(|_| anchor)
 3744                        })
 3745                        .collect::<Vec<_>>()
 3746                };
 3747                buffer.edit(
 3748                    old_selections
 3749                        .iter()
 3750                        .map(|s| (s.start..s.end, text.clone())),
 3751                    autoindent_mode,
 3752                    cx,
 3753                );
 3754                anchors
 3755            });
 3756
 3757            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3758                s.select_anchors(selection_anchors);
 3759            });
 3760
 3761            cx.notify();
 3762        });
 3763    }
 3764
 3765    fn trigger_completion_on_input(
 3766        &mut self,
 3767        text: &str,
 3768        trigger_in_words: bool,
 3769        window: &mut Window,
 3770        cx: &mut Context<Self>,
 3771    ) {
 3772        let ignore_completion_provider = self
 3773            .context_menu
 3774            .borrow()
 3775            .as_ref()
 3776            .map(|menu| match menu {
 3777                CodeContextMenu::Completions(completions_menu) => {
 3778                    completions_menu.ignore_completion_provider
 3779                }
 3780                CodeContextMenu::CodeActions(_) => false,
 3781            })
 3782            .unwrap_or(false);
 3783
 3784        if ignore_completion_provider {
 3785            self.show_word_completions(&ShowWordCompletions, window, cx);
 3786        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3787            self.show_completions(
 3788                &ShowCompletions {
 3789                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3790                },
 3791                window,
 3792                cx,
 3793            );
 3794        } else {
 3795            self.hide_context_menu(window, cx);
 3796        }
 3797    }
 3798
 3799    fn is_completion_trigger(
 3800        &self,
 3801        text: &str,
 3802        trigger_in_words: bool,
 3803        cx: &mut Context<Self>,
 3804    ) -> bool {
 3805        let position = self.selections.newest_anchor().head();
 3806        let multibuffer = self.buffer.read(cx);
 3807        let Some(buffer) = position
 3808            .buffer_id
 3809            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3810        else {
 3811            return false;
 3812        };
 3813
 3814        if let Some(completion_provider) = &self.completion_provider {
 3815            completion_provider.is_completion_trigger(
 3816                &buffer,
 3817                position.text_anchor,
 3818                text,
 3819                trigger_in_words,
 3820                cx,
 3821            )
 3822        } else {
 3823            false
 3824        }
 3825    }
 3826
 3827    /// If any empty selections is touching the start of its innermost containing autoclose
 3828    /// region, expand it to select the brackets.
 3829    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3830        let selections = self.selections.all::<usize>(cx);
 3831        let buffer = self.buffer.read(cx).read(cx);
 3832        let new_selections = self
 3833            .selections_with_autoclose_regions(selections, &buffer)
 3834            .map(|(mut selection, region)| {
 3835                if !selection.is_empty() {
 3836                    return selection;
 3837                }
 3838
 3839                if let Some(region) = region {
 3840                    let mut range = region.range.to_offset(&buffer);
 3841                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3842                        range.start -= region.pair.start.len();
 3843                        if buffer.contains_str_at(range.start, &region.pair.start)
 3844                            && buffer.contains_str_at(range.end, &region.pair.end)
 3845                        {
 3846                            range.end += region.pair.end.len();
 3847                            selection.start = range.start;
 3848                            selection.end = range.end;
 3849
 3850                            return selection;
 3851                        }
 3852                    }
 3853                }
 3854
 3855                let always_treat_brackets_as_autoclosed = buffer
 3856                    .language_settings_at(selection.start, cx)
 3857                    .always_treat_brackets_as_autoclosed;
 3858
 3859                if !always_treat_brackets_as_autoclosed {
 3860                    return selection;
 3861                }
 3862
 3863                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3864                    for (pair, enabled) in scope.brackets() {
 3865                        if !enabled || !pair.close {
 3866                            continue;
 3867                        }
 3868
 3869                        if buffer.contains_str_at(selection.start, &pair.end) {
 3870                            let pair_start_len = pair.start.len();
 3871                            if buffer.contains_str_at(
 3872                                selection.start.saturating_sub(pair_start_len),
 3873                                &pair.start,
 3874                            ) {
 3875                                selection.start -= pair_start_len;
 3876                                selection.end += pair.end.len();
 3877
 3878                                return selection;
 3879                            }
 3880                        }
 3881                    }
 3882                }
 3883
 3884                selection
 3885            })
 3886            .collect();
 3887
 3888        drop(buffer);
 3889        self.change_selections(None, window, cx, |selections| {
 3890            selections.select(new_selections)
 3891        });
 3892    }
 3893
 3894    /// Iterate the given selections, and for each one, find the smallest surrounding
 3895    /// autoclose region. This uses the ordering of the selections and the autoclose
 3896    /// regions to avoid repeated comparisons.
 3897    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3898        &'a self,
 3899        selections: impl IntoIterator<Item = Selection<D>>,
 3900        buffer: &'a MultiBufferSnapshot,
 3901    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3902        let mut i = 0;
 3903        let mut regions = self.autoclose_regions.as_slice();
 3904        selections.into_iter().map(move |selection| {
 3905            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3906
 3907            let mut enclosing = None;
 3908            while let Some(pair_state) = regions.get(i) {
 3909                if pair_state.range.end.to_offset(buffer) < range.start {
 3910                    regions = &regions[i + 1..];
 3911                    i = 0;
 3912                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3913                    break;
 3914                } else {
 3915                    if pair_state.selection_id == selection.id {
 3916                        enclosing = Some(pair_state);
 3917                    }
 3918                    i += 1;
 3919                }
 3920            }
 3921
 3922            (selection, enclosing)
 3923        })
 3924    }
 3925
 3926    /// Remove any autoclose regions that no longer contain their selection.
 3927    fn invalidate_autoclose_regions(
 3928        &mut self,
 3929        mut selections: &[Selection<Anchor>],
 3930        buffer: &MultiBufferSnapshot,
 3931    ) {
 3932        self.autoclose_regions.retain(|state| {
 3933            let mut i = 0;
 3934            while let Some(selection) = selections.get(i) {
 3935                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3936                    selections = &selections[1..];
 3937                    continue;
 3938                }
 3939                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3940                    break;
 3941                }
 3942                if selection.id == state.selection_id {
 3943                    return true;
 3944                } else {
 3945                    i += 1;
 3946                }
 3947            }
 3948            false
 3949        });
 3950    }
 3951
 3952    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3953        let offset = position.to_offset(buffer);
 3954        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3955        if offset > word_range.start && kind == Some(CharKind::Word) {
 3956            Some(
 3957                buffer
 3958                    .text_for_range(word_range.start..offset)
 3959                    .collect::<String>(),
 3960            )
 3961        } else {
 3962            None
 3963        }
 3964    }
 3965
 3966    pub fn toggle_inlay_hints(
 3967        &mut self,
 3968        _: &ToggleInlayHints,
 3969        _: &mut Window,
 3970        cx: &mut Context<Self>,
 3971    ) {
 3972        self.refresh_inlay_hints(
 3973            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3974            cx,
 3975        );
 3976    }
 3977
 3978    pub fn inlay_hints_enabled(&self) -> bool {
 3979        self.inlay_hint_cache.enabled
 3980    }
 3981
 3982    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3983        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3984            return;
 3985        }
 3986
 3987        let reason_description = reason.description();
 3988        let ignore_debounce = matches!(
 3989            reason,
 3990            InlayHintRefreshReason::SettingsChange(_)
 3991                | InlayHintRefreshReason::Toggle(_)
 3992                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3993                | InlayHintRefreshReason::ModifiersChanged(_)
 3994        );
 3995        let (invalidate_cache, required_languages) = match reason {
 3996            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3997                match self.inlay_hint_cache.modifiers_override(enabled) {
 3998                    Some(enabled) => {
 3999                        if enabled {
 4000                            (InvalidationStrategy::RefreshRequested, None)
 4001                        } else {
 4002                            self.splice_inlays(
 4003                                &self
 4004                                    .visible_inlay_hints(cx)
 4005                                    .iter()
 4006                                    .map(|inlay| inlay.id)
 4007                                    .collect::<Vec<InlayId>>(),
 4008                                Vec::new(),
 4009                                cx,
 4010                            );
 4011                            return;
 4012                        }
 4013                    }
 4014                    None => return,
 4015                }
 4016            }
 4017            InlayHintRefreshReason::Toggle(enabled) => {
 4018                if self.inlay_hint_cache.toggle(enabled) {
 4019                    if enabled {
 4020                        (InvalidationStrategy::RefreshRequested, None)
 4021                    } else {
 4022                        self.splice_inlays(
 4023                            &self
 4024                                .visible_inlay_hints(cx)
 4025                                .iter()
 4026                                .map(|inlay| inlay.id)
 4027                                .collect::<Vec<InlayId>>(),
 4028                            Vec::new(),
 4029                            cx,
 4030                        );
 4031                        return;
 4032                    }
 4033                } else {
 4034                    return;
 4035                }
 4036            }
 4037            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4038                match self.inlay_hint_cache.update_settings(
 4039                    &self.buffer,
 4040                    new_settings,
 4041                    self.visible_inlay_hints(cx),
 4042                    cx,
 4043                ) {
 4044                    ControlFlow::Break(Some(InlaySplice {
 4045                        to_remove,
 4046                        to_insert,
 4047                    })) => {
 4048                        self.splice_inlays(&to_remove, to_insert, cx);
 4049                        return;
 4050                    }
 4051                    ControlFlow::Break(None) => return,
 4052                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4053                }
 4054            }
 4055            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4056                if let Some(InlaySplice {
 4057                    to_remove,
 4058                    to_insert,
 4059                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4060                {
 4061                    self.splice_inlays(&to_remove, to_insert, cx);
 4062                }
 4063                return;
 4064            }
 4065            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4066            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4067                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4068            }
 4069            InlayHintRefreshReason::RefreshRequested => {
 4070                (InvalidationStrategy::RefreshRequested, None)
 4071            }
 4072        };
 4073
 4074        if let Some(InlaySplice {
 4075            to_remove,
 4076            to_insert,
 4077        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4078            reason_description,
 4079            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4080            invalidate_cache,
 4081            ignore_debounce,
 4082            cx,
 4083        ) {
 4084            self.splice_inlays(&to_remove, to_insert, cx);
 4085        }
 4086    }
 4087
 4088    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4089        self.display_map
 4090            .read(cx)
 4091            .current_inlays()
 4092            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4093            .cloned()
 4094            .collect()
 4095    }
 4096
 4097    pub fn excerpts_for_inlay_hints_query(
 4098        &self,
 4099        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4100        cx: &mut Context<Editor>,
 4101    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4102        let Some(project) = self.project.as_ref() else {
 4103            return HashMap::default();
 4104        };
 4105        let project = project.read(cx);
 4106        let multi_buffer = self.buffer().read(cx);
 4107        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4108        let multi_buffer_visible_start = self
 4109            .scroll_manager
 4110            .anchor()
 4111            .anchor
 4112            .to_point(&multi_buffer_snapshot);
 4113        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4114            multi_buffer_visible_start
 4115                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4116            Bias::Left,
 4117        );
 4118        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4119        multi_buffer_snapshot
 4120            .range_to_buffer_ranges(multi_buffer_visible_range)
 4121            .into_iter()
 4122            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4123            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4124                let buffer_file = project::File::from_dyn(buffer.file())?;
 4125                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4126                let worktree_entry = buffer_worktree
 4127                    .read(cx)
 4128                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4129                if worktree_entry.is_ignored {
 4130                    return None;
 4131                }
 4132
 4133                let language = buffer.language()?;
 4134                if let Some(restrict_to_languages) = restrict_to_languages {
 4135                    if !restrict_to_languages.contains(language) {
 4136                        return None;
 4137                    }
 4138                }
 4139                Some((
 4140                    excerpt_id,
 4141                    (
 4142                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4143                        buffer.version().clone(),
 4144                        excerpt_visible_range,
 4145                    ),
 4146                ))
 4147            })
 4148            .collect()
 4149    }
 4150
 4151    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4152        TextLayoutDetails {
 4153            text_system: window.text_system().clone(),
 4154            editor_style: self.style.clone().unwrap(),
 4155            rem_size: window.rem_size(),
 4156            scroll_anchor: self.scroll_manager.anchor(),
 4157            visible_rows: self.visible_line_count(),
 4158            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4159        }
 4160    }
 4161
 4162    pub fn splice_inlays(
 4163        &self,
 4164        to_remove: &[InlayId],
 4165        to_insert: Vec<Inlay>,
 4166        cx: &mut Context<Self>,
 4167    ) {
 4168        self.display_map.update(cx, |display_map, cx| {
 4169            display_map.splice_inlays(to_remove, to_insert, cx)
 4170        });
 4171        cx.notify();
 4172    }
 4173
 4174    fn trigger_on_type_formatting(
 4175        &self,
 4176        input: String,
 4177        window: &mut Window,
 4178        cx: &mut Context<Self>,
 4179    ) -> Option<Task<Result<()>>> {
 4180        if input.len() != 1 {
 4181            return None;
 4182        }
 4183
 4184        let project = self.project.as_ref()?;
 4185        let position = self.selections.newest_anchor().head();
 4186        let (buffer, buffer_position) = self
 4187            .buffer
 4188            .read(cx)
 4189            .text_anchor_for_position(position, cx)?;
 4190
 4191        let settings = language_settings::language_settings(
 4192            buffer
 4193                .read(cx)
 4194                .language_at(buffer_position)
 4195                .map(|l| l.name()),
 4196            buffer.read(cx).file(),
 4197            cx,
 4198        );
 4199        if !settings.use_on_type_format {
 4200            return None;
 4201        }
 4202
 4203        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4204        // hence we do LSP request & edit on host side only — add formats to host's history.
 4205        let push_to_lsp_host_history = true;
 4206        // If this is not the host, append its history with new edits.
 4207        let push_to_client_history = project.read(cx).is_via_collab();
 4208
 4209        let on_type_formatting = project.update(cx, |project, cx| {
 4210            project.on_type_format(
 4211                buffer.clone(),
 4212                buffer_position,
 4213                input,
 4214                push_to_lsp_host_history,
 4215                cx,
 4216            )
 4217        });
 4218        Some(cx.spawn_in(window, async move |editor, cx| {
 4219            if let Some(transaction) = on_type_formatting.await? {
 4220                if push_to_client_history {
 4221                    buffer
 4222                        .update(cx, |buffer, _| {
 4223                            buffer.push_transaction(transaction, Instant::now());
 4224                        })
 4225                        .ok();
 4226                }
 4227                editor.update(cx, |editor, cx| {
 4228                    editor.refresh_document_highlights(cx);
 4229                })?;
 4230            }
 4231            Ok(())
 4232        }))
 4233    }
 4234
 4235    pub fn show_word_completions(
 4236        &mut self,
 4237        _: &ShowWordCompletions,
 4238        window: &mut Window,
 4239        cx: &mut Context<Self>,
 4240    ) {
 4241        self.open_completions_menu(true, None, window, cx);
 4242    }
 4243
 4244    pub fn show_completions(
 4245        &mut self,
 4246        options: &ShowCompletions,
 4247        window: &mut Window,
 4248        cx: &mut Context<Self>,
 4249    ) {
 4250        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4251    }
 4252
 4253    fn open_completions_menu(
 4254        &mut self,
 4255        ignore_completion_provider: bool,
 4256        trigger: Option<&str>,
 4257        window: &mut Window,
 4258        cx: &mut Context<Self>,
 4259    ) {
 4260        if self.pending_rename.is_some() {
 4261            return;
 4262        }
 4263        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4264            return;
 4265        }
 4266
 4267        let position = self.selections.newest_anchor().head();
 4268        if position.diff_base_anchor.is_some() {
 4269            return;
 4270        }
 4271        let (buffer, buffer_position) =
 4272            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4273                output
 4274            } else {
 4275                return;
 4276            };
 4277        let buffer_snapshot = buffer.read(cx).snapshot();
 4278        let show_completion_documentation = buffer_snapshot
 4279            .settings_at(buffer_position, cx)
 4280            .show_completion_documentation;
 4281
 4282        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4283
 4284        let trigger_kind = match trigger {
 4285            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4286                CompletionTriggerKind::TRIGGER_CHARACTER
 4287            }
 4288            _ => CompletionTriggerKind::INVOKED,
 4289        };
 4290        let completion_context = CompletionContext {
 4291            trigger_character: trigger.and_then(|trigger| {
 4292                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4293                    Some(String::from(trigger))
 4294                } else {
 4295                    None
 4296                }
 4297            }),
 4298            trigger_kind,
 4299        };
 4300
 4301        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4302        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4303            let word_to_exclude = buffer_snapshot
 4304                .text_for_range(old_range.clone())
 4305                .collect::<String>();
 4306            (
 4307                buffer_snapshot.anchor_before(old_range.start)
 4308                    ..buffer_snapshot.anchor_after(old_range.end),
 4309                Some(word_to_exclude),
 4310            )
 4311        } else {
 4312            (buffer_position..buffer_position, None)
 4313        };
 4314
 4315        let completion_settings = language_settings(
 4316            buffer_snapshot
 4317                .language_at(buffer_position)
 4318                .map(|language| language.name()),
 4319            buffer_snapshot.file(),
 4320            cx,
 4321        )
 4322        .completions;
 4323
 4324        // The document can be large, so stay in reasonable bounds when searching for words,
 4325        // otherwise completion pop-up might be slow to appear.
 4326        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4327        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4328        let min_word_search = buffer_snapshot.clip_point(
 4329            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4330            Bias::Left,
 4331        );
 4332        let max_word_search = buffer_snapshot.clip_point(
 4333            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4334            Bias::Right,
 4335        );
 4336        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4337            ..buffer_snapshot.point_to_offset(max_word_search);
 4338
 4339        let provider = self
 4340            .completion_provider
 4341            .as_ref()
 4342            .filter(|_| !ignore_completion_provider);
 4343        let skip_digits = query
 4344            .as_ref()
 4345            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4346
 4347        let (mut words, provided_completions) = match provider {
 4348            Some(provider) => {
 4349                let completions = provider.completions(
 4350                    position.excerpt_id,
 4351                    &buffer,
 4352                    buffer_position,
 4353                    completion_context,
 4354                    window,
 4355                    cx,
 4356                );
 4357
 4358                let words = match completion_settings.words {
 4359                    WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
 4360                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4361                        .background_spawn(async move {
 4362                            buffer_snapshot.words_in_range(WordsQuery {
 4363                                fuzzy_contents: None,
 4364                                range: word_search_range,
 4365                                skip_digits,
 4366                            })
 4367                        }),
 4368                };
 4369
 4370                (words, completions)
 4371            }
 4372            None => (
 4373                cx.background_spawn(async move {
 4374                    buffer_snapshot.words_in_range(WordsQuery {
 4375                        fuzzy_contents: None,
 4376                        range: word_search_range,
 4377                        skip_digits,
 4378                    })
 4379                }),
 4380                Task::ready(Ok(None)),
 4381            ),
 4382        };
 4383
 4384        let sort_completions = provider
 4385            .as_ref()
 4386            .map_or(true, |provider| provider.sort_completions());
 4387
 4388        let filter_completions = provider
 4389            .as_ref()
 4390            .map_or(true, |provider| provider.filter_completions());
 4391
 4392        let id = post_inc(&mut self.next_completion_id);
 4393        let task = cx.spawn_in(window, async move |editor, cx| {
 4394            async move {
 4395                editor.update(cx, |this, _| {
 4396                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4397                })?;
 4398
 4399                let mut completions = Vec::new();
 4400                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4401                    completions.extend(provided_completions);
 4402                    if completion_settings.words == WordsCompletionMode::Fallback {
 4403                        words = Task::ready(HashMap::default());
 4404                    }
 4405                }
 4406
 4407                let mut words = words.await;
 4408                if let Some(word_to_exclude) = &word_to_exclude {
 4409                    words.remove(word_to_exclude);
 4410                }
 4411                for lsp_completion in &completions {
 4412                    words.remove(&lsp_completion.new_text);
 4413                }
 4414                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4415                    old_range: old_range.clone(),
 4416                    new_text: word.clone(),
 4417                    label: CodeLabel::plain(word, None),
 4418                    icon_path: None,
 4419                    documentation: None,
 4420                    source: CompletionSource::BufferWord {
 4421                        word_range,
 4422                        resolved: false,
 4423                    },
 4424                    confirm: None,
 4425                }));
 4426
 4427                let menu = if completions.is_empty() {
 4428                    None
 4429                } else {
 4430                    let mut menu = CompletionsMenu::new(
 4431                        id,
 4432                        sort_completions,
 4433                        show_completion_documentation,
 4434                        ignore_completion_provider,
 4435                        position,
 4436                        buffer.clone(),
 4437                        completions.into(),
 4438                    );
 4439
 4440                    menu.filter(
 4441                        if filter_completions {
 4442                            query.as_deref()
 4443                        } else {
 4444                            None
 4445                        },
 4446                        cx.background_executor().clone(),
 4447                    )
 4448                    .await;
 4449
 4450                    menu.visible().then_some(menu)
 4451                };
 4452
 4453                editor.update_in(cx, |editor, window, cx| {
 4454                    match editor.context_menu.borrow().as_ref() {
 4455                        None => {}
 4456                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4457                            if prev_menu.id > id {
 4458                                return;
 4459                            }
 4460                        }
 4461                        _ => return,
 4462                    }
 4463
 4464                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4465                        let mut menu = menu.unwrap();
 4466                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4467
 4468                        *editor.context_menu.borrow_mut() =
 4469                            Some(CodeContextMenu::Completions(menu));
 4470
 4471                        if editor.show_edit_predictions_in_menu() {
 4472                            editor.update_visible_inline_completion(window, cx);
 4473                        } else {
 4474                            editor.discard_inline_completion(false, cx);
 4475                        }
 4476
 4477                        cx.notify();
 4478                    } else if editor.completion_tasks.len() <= 1 {
 4479                        // If there are no more completion tasks and the last menu was
 4480                        // empty, we should hide it.
 4481                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4482                        // If it was already hidden and we don't show inline
 4483                        // completions in the menu, we should also show the
 4484                        // inline-completion when available.
 4485                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4486                            editor.update_visible_inline_completion(window, cx);
 4487                        }
 4488                    }
 4489                })?;
 4490
 4491                anyhow::Ok(())
 4492            }
 4493            .log_err()
 4494            .await
 4495        });
 4496
 4497        self.completion_tasks.push((id, task));
 4498    }
 4499
 4500    #[cfg(feature = "test-support")]
 4501    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4502        let menu = self.context_menu.borrow();
 4503        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4504            let completions = menu.completions.borrow();
 4505            Some(completions.to_vec())
 4506        } else {
 4507            None
 4508        }
 4509    }
 4510
 4511    pub fn confirm_completion(
 4512        &mut self,
 4513        action: &ConfirmCompletion,
 4514        window: &mut Window,
 4515        cx: &mut Context<Self>,
 4516    ) -> Option<Task<Result<()>>> {
 4517        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4518        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4519    }
 4520
 4521    pub fn compose_completion(
 4522        &mut self,
 4523        action: &ComposeCompletion,
 4524        window: &mut Window,
 4525        cx: &mut Context<Self>,
 4526    ) -> Option<Task<Result<()>>> {
 4527        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4528        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4529    }
 4530
 4531    fn do_completion(
 4532        &mut self,
 4533        item_ix: Option<usize>,
 4534        intent: CompletionIntent,
 4535        window: &mut Window,
 4536        cx: &mut Context<Editor>,
 4537    ) -> Option<Task<Result<()>>> {
 4538        use language::ToOffset as _;
 4539
 4540        let completions_menu =
 4541            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4542                menu
 4543            } else {
 4544                return None;
 4545            };
 4546
 4547        let candidate_id = {
 4548            let entries = completions_menu.entries.borrow();
 4549            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4550            if self.show_edit_predictions_in_menu() {
 4551                self.discard_inline_completion(true, cx);
 4552            }
 4553            mat.candidate_id
 4554        };
 4555
 4556        let buffer_handle = completions_menu.buffer;
 4557        let completion = completions_menu
 4558            .completions
 4559            .borrow()
 4560            .get(candidate_id)?
 4561            .clone();
 4562        cx.stop_propagation();
 4563
 4564        let snippet;
 4565        let new_text;
 4566        if completion.is_snippet() {
 4567            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4568            new_text = snippet.as_ref().unwrap().text.clone();
 4569        } else {
 4570            snippet = None;
 4571            new_text = completion.new_text.clone();
 4572        };
 4573        let selections = self.selections.all::<usize>(cx);
 4574        let buffer = buffer_handle.read(cx);
 4575        let old_range = completion.old_range.to_offset(buffer);
 4576        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4577
 4578        let newest_selection = self.selections.newest_anchor();
 4579        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4580            return None;
 4581        }
 4582
 4583        let lookbehind = newest_selection
 4584            .start
 4585            .text_anchor
 4586            .to_offset(buffer)
 4587            .saturating_sub(old_range.start);
 4588        let lookahead = old_range
 4589            .end
 4590            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4591        let mut common_prefix_len = old_text
 4592            .bytes()
 4593            .zip(new_text.bytes())
 4594            .take_while(|(a, b)| a == b)
 4595            .count();
 4596
 4597        let snapshot = self.buffer.read(cx).snapshot(cx);
 4598        let mut range_to_replace: Option<Range<isize>> = None;
 4599        let mut ranges = Vec::new();
 4600        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4601        for selection in &selections {
 4602            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4603                let start = selection.start.saturating_sub(lookbehind);
 4604                let end = selection.end + lookahead;
 4605                if selection.id == newest_selection.id {
 4606                    range_to_replace = Some(
 4607                        ((start + common_prefix_len) as isize - selection.start as isize)
 4608                            ..(end as isize - selection.start as isize),
 4609                    );
 4610                }
 4611                ranges.push(start + common_prefix_len..end);
 4612            } else {
 4613                common_prefix_len = 0;
 4614                ranges.clear();
 4615                ranges.extend(selections.iter().map(|s| {
 4616                    if s.id == newest_selection.id {
 4617                        range_to_replace = Some(
 4618                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4619                                - selection.start as isize
 4620                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4621                                    - selection.start as isize,
 4622                        );
 4623                        old_range.clone()
 4624                    } else {
 4625                        s.start..s.end
 4626                    }
 4627                }));
 4628                break;
 4629            }
 4630            if !self.linked_edit_ranges.is_empty() {
 4631                let start_anchor = snapshot.anchor_before(selection.head());
 4632                let end_anchor = snapshot.anchor_after(selection.tail());
 4633                if let Some(ranges) = self
 4634                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4635                {
 4636                    for (buffer, edits) in ranges {
 4637                        linked_edits.entry(buffer.clone()).or_default().extend(
 4638                            edits
 4639                                .into_iter()
 4640                                .map(|range| (range, new_text[common_prefix_len..].to_owned())),
 4641                        );
 4642                    }
 4643                }
 4644            }
 4645        }
 4646        let text = &new_text[common_prefix_len..];
 4647
 4648        cx.emit(EditorEvent::InputHandled {
 4649            utf16_range_to_replace: range_to_replace,
 4650            text: text.into(),
 4651        });
 4652
 4653        self.transact(window, cx, |this, window, cx| {
 4654            if let Some(mut snippet) = snippet {
 4655                snippet.text = text.to_string();
 4656                for tabstop in snippet
 4657                    .tabstops
 4658                    .iter_mut()
 4659                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4660                {
 4661                    tabstop.start -= common_prefix_len as isize;
 4662                    tabstop.end -= common_prefix_len as isize;
 4663                }
 4664
 4665                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4666            } else {
 4667                this.buffer.update(cx, |buffer, cx| {
 4668                    let edits = ranges.iter().map(|range| (range.clone(), text));
 4669                    buffer.edit(edits, this.autoindent_mode.clone(), cx);
 4670                });
 4671            }
 4672            for (buffer, edits) in linked_edits {
 4673                buffer.update(cx, |buffer, cx| {
 4674                    let snapshot = buffer.snapshot();
 4675                    let edits = edits
 4676                        .into_iter()
 4677                        .map(|(range, text)| {
 4678                            use text::ToPoint as TP;
 4679                            let end_point = TP::to_point(&range.end, &snapshot);
 4680                            let start_point = TP::to_point(&range.start, &snapshot);
 4681                            (start_point..end_point, text)
 4682                        })
 4683                        .sorted_by_key(|(range, _)| range.start);
 4684                    buffer.edit(edits, None, cx);
 4685                })
 4686            }
 4687
 4688            this.refresh_inline_completion(true, false, window, cx);
 4689        });
 4690
 4691        let show_new_completions_on_confirm = completion
 4692            .confirm
 4693            .as_ref()
 4694            .map_or(false, |confirm| confirm(intent, window, cx));
 4695        if show_new_completions_on_confirm {
 4696            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4697        }
 4698
 4699        let provider = self.completion_provider.as_ref()?;
 4700        drop(completion);
 4701        let apply_edits = provider.apply_additional_edits_for_completion(
 4702            buffer_handle,
 4703            completions_menu.completions.clone(),
 4704            candidate_id,
 4705            true,
 4706            cx,
 4707        );
 4708
 4709        let editor_settings = EditorSettings::get_global(cx);
 4710        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4711            // After the code completion is finished, users often want to know what signatures are needed.
 4712            // so we should automatically call signature_help
 4713            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4714        }
 4715
 4716        Some(cx.foreground_executor().spawn(async move {
 4717            apply_edits.await?;
 4718            Ok(())
 4719        }))
 4720    }
 4721
 4722    pub fn toggle_code_actions(
 4723        &mut self,
 4724        action: &ToggleCodeActions,
 4725        window: &mut Window,
 4726        cx: &mut Context<Self>,
 4727    ) {
 4728        let mut context_menu = self.context_menu.borrow_mut();
 4729        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4730            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4731                // Toggle if we're selecting the same one
 4732                *context_menu = None;
 4733                cx.notify();
 4734                return;
 4735            } else {
 4736                // Otherwise, clear it and start a new one
 4737                *context_menu = None;
 4738                cx.notify();
 4739            }
 4740        }
 4741        drop(context_menu);
 4742        let snapshot = self.snapshot(window, cx);
 4743        let deployed_from_indicator = action.deployed_from_indicator;
 4744        let mut task = self.code_actions_task.take();
 4745        let action = action.clone();
 4746        cx.spawn_in(window, async move |editor, cx| {
 4747            while let Some(prev_task) = task {
 4748                prev_task.await.log_err();
 4749                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4750            }
 4751
 4752            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4753                if editor.focus_handle.is_focused(window) {
 4754                    let multibuffer_point = action
 4755                        .deployed_from_indicator
 4756                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4757                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4758                    let (buffer, buffer_row) = snapshot
 4759                        .buffer_snapshot
 4760                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4761                        .and_then(|(buffer_snapshot, range)| {
 4762                            editor
 4763                                .buffer
 4764                                .read(cx)
 4765                                .buffer(buffer_snapshot.remote_id())
 4766                                .map(|buffer| (buffer, range.start.row))
 4767                        })?;
 4768                    let (_, code_actions) = editor
 4769                        .available_code_actions
 4770                        .clone()
 4771                        .and_then(|(location, code_actions)| {
 4772                            let snapshot = location.buffer.read(cx).snapshot();
 4773                            let point_range = location.range.to_point(&snapshot);
 4774                            let point_range = point_range.start.row..=point_range.end.row;
 4775                            if point_range.contains(&buffer_row) {
 4776                                Some((location, code_actions))
 4777                            } else {
 4778                                None
 4779                            }
 4780                        })
 4781                        .unzip();
 4782                    let buffer_id = buffer.read(cx).remote_id();
 4783                    let tasks = editor
 4784                        .tasks
 4785                        .get(&(buffer_id, buffer_row))
 4786                        .map(|t| Arc::new(t.to_owned()));
 4787                    if tasks.is_none() && code_actions.is_none() {
 4788                        return None;
 4789                    }
 4790
 4791                    editor.completion_tasks.clear();
 4792                    editor.discard_inline_completion(false, cx);
 4793                    let task_context =
 4794                        tasks
 4795                            .as_ref()
 4796                            .zip(editor.project.clone())
 4797                            .map(|(tasks, project)| {
 4798                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4799                            });
 4800
 4801                    Some(cx.spawn_in(window, async move |editor, cx| {
 4802                        let task_context = match task_context {
 4803                            Some(task_context) => task_context.await,
 4804                            None => None,
 4805                        };
 4806                        let resolved_tasks =
 4807                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4808                                Rc::new(ResolvedTasks {
 4809                                    templates: tasks.resolve(&task_context).collect(),
 4810                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4811                                        multibuffer_point.row,
 4812                                        tasks.column,
 4813                                    )),
 4814                                })
 4815                            });
 4816                        let spawn_straight_away = resolved_tasks
 4817                            .as_ref()
 4818                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4819                            && code_actions
 4820                                .as_ref()
 4821                                .map_or(true, |actions| actions.is_empty());
 4822                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4823                            *editor.context_menu.borrow_mut() =
 4824                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4825                                    buffer,
 4826                                    actions: CodeActionContents {
 4827                                        tasks: resolved_tasks,
 4828                                        actions: code_actions,
 4829                                    },
 4830                                    selected_item: Default::default(),
 4831                                    scroll_handle: UniformListScrollHandle::default(),
 4832                                    deployed_from_indicator,
 4833                                }));
 4834                            if spawn_straight_away {
 4835                                if let Some(task) = editor.confirm_code_action(
 4836                                    &ConfirmCodeAction { item_ix: Some(0) },
 4837                                    window,
 4838                                    cx,
 4839                                ) {
 4840                                    cx.notify();
 4841                                    return task;
 4842                                }
 4843                            }
 4844                            cx.notify();
 4845                            Task::ready(Ok(()))
 4846                        }) {
 4847                            task.await
 4848                        } else {
 4849                            Ok(())
 4850                        }
 4851                    }))
 4852                } else {
 4853                    Some(Task::ready(Ok(())))
 4854                }
 4855            })?;
 4856            if let Some(task) = spawned_test_task {
 4857                task.await?;
 4858            }
 4859
 4860            Ok::<_, anyhow::Error>(())
 4861        })
 4862        .detach_and_log_err(cx);
 4863    }
 4864
 4865    pub fn confirm_code_action(
 4866        &mut self,
 4867        action: &ConfirmCodeAction,
 4868        window: &mut Window,
 4869        cx: &mut Context<Self>,
 4870    ) -> Option<Task<Result<()>>> {
 4871        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4872
 4873        let actions_menu =
 4874            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4875                menu
 4876            } else {
 4877                return None;
 4878            };
 4879
 4880        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4881        let action = actions_menu.actions.get(action_ix)?;
 4882        let title = action.label();
 4883        let buffer = actions_menu.buffer;
 4884        let workspace = self.workspace()?;
 4885
 4886        match action {
 4887            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4888                match resolved_task.task_type() {
 4889                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 4890                        workspace::tasks::schedule_resolved_task(
 4891                            workspace,
 4892                            task_source_kind,
 4893                            resolved_task,
 4894                            false,
 4895                            cx,
 4896                        );
 4897
 4898                        Some(Task::ready(Ok(())))
 4899                    }),
 4900                    task::TaskType::Debug(debug_args) => {
 4901                        if debug_args.locator.is_some() {
 4902                            workspace.update(cx, |workspace, cx| {
 4903                                workspace::tasks::schedule_resolved_task(
 4904                                    workspace,
 4905                                    task_source_kind,
 4906                                    resolved_task,
 4907                                    false,
 4908                                    cx,
 4909                                );
 4910                            });
 4911
 4912                            return Some(Task::ready(Ok(())));
 4913                        }
 4914
 4915                        if let Some(project) = self.project.as_ref() {
 4916                            project
 4917                                .update(cx, |project, cx| {
 4918                                    project.start_debug_session(
 4919                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 4920                                        cx,
 4921                                    )
 4922                                })
 4923                                .detach_and_log_err(cx);
 4924                            Some(Task::ready(Ok(())))
 4925                        } else {
 4926                            Some(Task::ready(Ok(())))
 4927                        }
 4928                    }
 4929                }
 4930            }
 4931            CodeActionsItem::CodeAction {
 4932                excerpt_id,
 4933                action,
 4934                provider,
 4935            } => {
 4936                let apply_code_action =
 4937                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4938                let workspace = workspace.downgrade();
 4939                Some(cx.spawn_in(window, async move |editor, cx| {
 4940                    let project_transaction = apply_code_action.await?;
 4941                    Self::open_project_transaction(
 4942                        &editor,
 4943                        workspace,
 4944                        project_transaction,
 4945                        title,
 4946                        cx,
 4947                    )
 4948                    .await
 4949                }))
 4950            }
 4951        }
 4952    }
 4953
 4954    pub async fn open_project_transaction(
 4955        this: &WeakEntity<Editor>,
 4956        workspace: WeakEntity<Workspace>,
 4957        transaction: ProjectTransaction,
 4958        title: String,
 4959        cx: &mut AsyncWindowContext,
 4960    ) -> Result<()> {
 4961        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4962        cx.update(|_, cx| {
 4963            entries.sort_unstable_by_key(|(buffer, _)| {
 4964                buffer.read(cx).file().map(|f| f.path().clone())
 4965            });
 4966        })?;
 4967
 4968        // If the project transaction's edits are all contained within this editor, then
 4969        // avoid opening a new editor to display them.
 4970
 4971        if let Some((buffer, transaction)) = entries.first() {
 4972            if entries.len() == 1 {
 4973                let excerpt = this.update(cx, |editor, cx| {
 4974                    editor
 4975                        .buffer()
 4976                        .read(cx)
 4977                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4978                })?;
 4979                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4980                    if excerpted_buffer == *buffer {
 4981                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 4982                            let excerpt_range = excerpt_range.to_offset(buffer);
 4983                            buffer
 4984                                .edited_ranges_for_transaction::<usize>(transaction)
 4985                                .all(|range| {
 4986                                    excerpt_range.start <= range.start
 4987                                        && excerpt_range.end >= range.end
 4988                                })
 4989                        })?;
 4990
 4991                        if all_edits_within_excerpt {
 4992                            return Ok(());
 4993                        }
 4994                    }
 4995                }
 4996            }
 4997        } else {
 4998            return Ok(());
 4999        }
 5000
 5001        let mut ranges_to_highlight = Vec::new();
 5002        let excerpt_buffer = cx.new(|cx| {
 5003            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5004            for (buffer_handle, transaction) in &entries {
 5005                let buffer = buffer_handle.read(cx);
 5006                ranges_to_highlight.extend(
 5007                    multibuffer.push_excerpts_with_context_lines(
 5008                        buffer_handle.clone(),
 5009                        buffer
 5010                            .edited_ranges_for_transaction::<usize>(transaction)
 5011                            .collect(),
 5012                        DEFAULT_MULTIBUFFER_CONTEXT,
 5013                        cx,
 5014                    ),
 5015                );
 5016            }
 5017            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5018            multibuffer
 5019        })?;
 5020
 5021        workspace.update_in(cx, |workspace, window, cx| {
 5022            let project = workspace.project().clone();
 5023            let editor =
 5024                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5025            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5026            editor.update(cx, |editor, cx| {
 5027                editor.highlight_background::<Self>(
 5028                    &ranges_to_highlight,
 5029                    |theme| theme.editor_highlighted_line_background,
 5030                    cx,
 5031                );
 5032            });
 5033        })?;
 5034
 5035        Ok(())
 5036    }
 5037
 5038    pub fn clear_code_action_providers(&mut self) {
 5039        self.code_action_providers.clear();
 5040        self.available_code_actions.take();
 5041    }
 5042
 5043    pub fn add_code_action_provider(
 5044        &mut self,
 5045        provider: Rc<dyn CodeActionProvider>,
 5046        window: &mut Window,
 5047        cx: &mut Context<Self>,
 5048    ) {
 5049        if self
 5050            .code_action_providers
 5051            .iter()
 5052            .any(|existing_provider| existing_provider.id() == provider.id())
 5053        {
 5054            return;
 5055        }
 5056
 5057        self.code_action_providers.push(provider);
 5058        self.refresh_code_actions(window, cx);
 5059    }
 5060
 5061    pub fn remove_code_action_provider(
 5062        &mut self,
 5063        id: Arc<str>,
 5064        window: &mut Window,
 5065        cx: &mut Context<Self>,
 5066    ) {
 5067        self.code_action_providers
 5068            .retain(|provider| provider.id() != id);
 5069        self.refresh_code_actions(window, cx);
 5070    }
 5071
 5072    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5073        let buffer = self.buffer.read(cx);
 5074        let newest_selection = self.selections.newest_anchor().clone();
 5075        if newest_selection.head().diff_base_anchor.is_some() {
 5076            return None;
 5077        }
 5078        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5079        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5080        if start_buffer != end_buffer {
 5081            return None;
 5082        }
 5083
 5084        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5085            cx.background_executor()
 5086                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5087                .await;
 5088
 5089            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5090                let providers = this.code_action_providers.clone();
 5091                let tasks = this
 5092                    .code_action_providers
 5093                    .iter()
 5094                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5095                    .collect::<Vec<_>>();
 5096                (providers, tasks)
 5097            })?;
 5098
 5099            let mut actions = Vec::new();
 5100            for (provider, provider_actions) in
 5101                providers.into_iter().zip(future::join_all(tasks).await)
 5102            {
 5103                if let Some(provider_actions) = provider_actions.log_err() {
 5104                    actions.extend(provider_actions.into_iter().map(|action| {
 5105                        AvailableCodeAction {
 5106                            excerpt_id: newest_selection.start.excerpt_id,
 5107                            action,
 5108                            provider: provider.clone(),
 5109                        }
 5110                    }));
 5111                }
 5112            }
 5113
 5114            this.update(cx, |this, cx| {
 5115                this.available_code_actions = if actions.is_empty() {
 5116                    None
 5117                } else {
 5118                    Some((
 5119                        Location {
 5120                            buffer: start_buffer,
 5121                            range: start..end,
 5122                        },
 5123                        actions.into(),
 5124                    ))
 5125                };
 5126                cx.notify();
 5127            })
 5128        }));
 5129        None
 5130    }
 5131
 5132    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5133        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5134            self.show_git_blame_inline = false;
 5135
 5136            self.show_git_blame_inline_delay_task =
 5137                Some(cx.spawn_in(window, async move |this, cx| {
 5138                    cx.background_executor().timer(delay).await;
 5139
 5140                    this.update(cx, |this, cx| {
 5141                        this.show_git_blame_inline = true;
 5142                        cx.notify();
 5143                    })
 5144                    .log_err();
 5145                }));
 5146        }
 5147    }
 5148
 5149    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5150        if self.pending_rename.is_some() {
 5151            return None;
 5152        }
 5153
 5154        let provider = self.semantics_provider.clone()?;
 5155        let buffer = self.buffer.read(cx);
 5156        let newest_selection = self.selections.newest_anchor().clone();
 5157        let cursor_position = newest_selection.head();
 5158        let (cursor_buffer, cursor_buffer_position) =
 5159            buffer.text_anchor_for_position(cursor_position, cx)?;
 5160        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5161        if cursor_buffer != tail_buffer {
 5162            return None;
 5163        }
 5164        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5165        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5166            cx.background_executor()
 5167                .timer(Duration::from_millis(debounce))
 5168                .await;
 5169
 5170            let highlights = if let Some(highlights) = cx
 5171                .update(|cx| {
 5172                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5173                })
 5174                .ok()
 5175                .flatten()
 5176            {
 5177                highlights.await.log_err()
 5178            } else {
 5179                None
 5180            };
 5181
 5182            if let Some(highlights) = highlights {
 5183                this.update(cx, |this, cx| {
 5184                    if this.pending_rename.is_some() {
 5185                        return;
 5186                    }
 5187
 5188                    let buffer_id = cursor_position.buffer_id;
 5189                    let buffer = this.buffer.read(cx);
 5190                    if !buffer
 5191                        .text_anchor_for_position(cursor_position, cx)
 5192                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5193                    {
 5194                        return;
 5195                    }
 5196
 5197                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5198                    let mut write_ranges = Vec::new();
 5199                    let mut read_ranges = Vec::new();
 5200                    for highlight in highlights {
 5201                        for (excerpt_id, excerpt_range) in
 5202                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5203                        {
 5204                            let start = highlight
 5205                                .range
 5206                                .start
 5207                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5208                            let end = highlight
 5209                                .range
 5210                                .end
 5211                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5212                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5213                                continue;
 5214                            }
 5215
 5216                            let range = Anchor {
 5217                                buffer_id,
 5218                                excerpt_id,
 5219                                text_anchor: start,
 5220                                diff_base_anchor: None,
 5221                            }..Anchor {
 5222                                buffer_id,
 5223                                excerpt_id,
 5224                                text_anchor: end,
 5225                                diff_base_anchor: None,
 5226                            };
 5227                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5228                                write_ranges.push(range);
 5229                            } else {
 5230                                read_ranges.push(range);
 5231                            }
 5232                        }
 5233                    }
 5234
 5235                    this.highlight_background::<DocumentHighlightRead>(
 5236                        &read_ranges,
 5237                        |theme| theme.editor_document_highlight_read_background,
 5238                        cx,
 5239                    );
 5240                    this.highlight_background::<DocumentHighlightWrite>(
 5241                        &write_ranges,
 5242                        |theme| theme.editor_document_highlight_write_background,
 5243                        cx,
 5244                    );
 5245                    cx.notify();
 5246                })
 5247                .log_err();
 5248            }
 5249        }));
 5250        None
 5251    }
 5252
 5253    pub fn refresh_selected_text_highlights(
 5254        &mut self,
 5255        window: &mut Window,
 5256        cx: &mut Context<Editor>,
 5257    ) {
 5258        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5259            return;
 5260        }
 5261        self.selection_highlight_task.take();
 5262        if !EditorSettings::get_global(cx).selection_highlight {
 5263            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5264            return;
 5265        }
 5266        if self.selections.count() != 1 || self.selections.line_mode {
 5267            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5268            return;
 5269        }
 5270        let selection = self.selections.newest::<Point>(cx);
 5271        if selection.is_empty() || selection.start.row != selection.end.row {
 5272            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5273            return;
 5274        }
 5275        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5276        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5277            cx.background_executor()
 5278                .timer(Duration::from_millis(debounce))
 5279                .await;
 5280            let Some(Some(matches_task)) = editor
 5281                .update_in(cx, |editor, _, cx| {
 5282                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5283                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5284                        return None;
 5285                    }
 5286                    let selection = editor.selections.newest::<Point>(cx);
 5287                    if selection.is_empty() || selection.start.row != selection.end.row {
 5288                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5289                        return None;
 5290                    }
 5291                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5292                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5293                    if query.trim().is_empty() {
 5294                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5295                        return None;
 5296                    }
 5297                    Some(cx.background_spawn(async move {
 5298                        let mut ranges = Vec::new();
 5299                        let selection_anchors = selection.range().to_anchors(&buffer);
 5300                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5301                            for (search_buffer, search_range, excerpt_id) in
 5302                                buffer.range_to_buffer_ranges(range)
 5303                            {
 5304                                ranges.extend(
 5305                                    project::search::SearchQuery::text(
 5306                                        query.clone(),
 5307                                        false,
 5308                                        false,
 5309                                        false,
 5310                                        Default::default(),
 5311                                        Default::default(),
 5312                                        None,
 5313                                    )
 5314                                    .unwrap()
 5315                                    .search(search_buffer, Some(search_range.clone()))
 5316                                    .await
 5317                                    .into_iter()
 5318                                    .filter_map(
 5319                                        |match_range| {
 5320                                            let start = search_buffer.anchor_after(
 5321                                                search_range.start + match_range.start,
 5322                                            );
 5323                                            let end = search_buffer.anchor_before(
 5324                                                search_range.start + match_range.end,
 5325                                            );
 5326                                            let range = Anchor::range_in_buffer(
 5327                                                excerpt_id,
 5328                                                search_buffer.remote_id(),
 5329                                                start..end,
 5330                                            );
 5331                                            (range != selection_anchors).then_some(range)
 5332                                        },
 5333                                    ),
 5334                                );
 5335                            }
 5336                        }
 5337                        ranges
 5338                    }))
 5339                })
 5340                .log_err()
 5341            else {
 5342                return;
 5343            };
 5344            let matches = matches_task.await;
 5345            editor
 5346                .update_in(cx, |editor, _, cx| {
 5347                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5348                    if !matches.is_empty() {
 5349                        editor.highlight_background::<SelectedTextHighlight>(
 5350                            &matches,
 5351                            |theme| theme.editor_document_highlight_bracket_background,
 5352                            cx,
 5353                        )
 5354                    }
 5355                })
 5356                .log_err();
 5357        }));
 5358    }
 5359
 5360    pub fn refresh_inline_completion(
 5361        &mut self,
 5362        debounce: bool,
 5363        user_requested: bool,
 5364        window: &mut Window,
 5365        cx: &mut Context<Self>,
 5366    ) -> Option<()> {
 5367        let provider = self.edit_prediction_provider()?;
 5368        let cursor = self.selections.newest_anchor().head();
 5369        let (buffer, cursor_buffer_position) =
 5370            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5371
 5372        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5373            self.discard_inline_completion(false, cx);
 5374            return None;
 5375        }
 5376
 5377        if !user_requested
 5378            && (!self.should_show_edit_predictions()
 5379                || !self.is_focused(window)
 5380                || buffer.read(cx).is_empty())
 5381        {
 5382            self.discard_inline_completion(false, cx);
 5383            return None;
 5384        }
 5385
 5386        self.update_visible_inline_completion(window, cx);
 5387        provider.refresh(
 5388            self.project.clone(),
 5389            buffer,
 5390            cursor_buffer_position,
 5391            debounce,
 5392            cx,
 5393        );
 5394        Some(())
 5395    }
 5396
 5397    fn show_edit_predictions_in_menu(&self) -> bool {
 5398        match self.edit_prediction_settings {
 5399            EditPredictionSettings::Disabled => false,
 5400            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5401        }
 5402    }
 5403
 5404    pub fn edit_predictions_enabled(&self) -> bool {
 5405        match self.edit_prediction_settings {
 5406            EditPredictionSettings::Disabled => false,
 5407            EditPredictionSettings::Enabled { .. } => true,
 5408        }
 5409    }
 5410
 5411    fn edit_prediction_requires_modifier(&self) -> bool {
 5412        match self.edit_prediction_settings {
 5413            EditPredictionSettings::Disabled => false,
 5414            EditPredictionSettings::Enabled {
 5415                preview_requires_modifier,
 5416                ..
 5417            } => preview_requires_modifier,
 5418        }
 5419    }
 5420
 5421    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5422        if self.edit_prediction_provider.is_none() {
 5423            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5424        } else {
 5425            let selection = self.selections.newest_anchor();
 5426            let cursor = selection.head();
 5427
 5428            if let Some((buffer, cursor_buffer_position)) =
 5429                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5430            {
 5431                self.edit_prediction_settings =
 5432                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5433            }
 5434        }
 5435    }
 5436
 5437    fn edit_prediction_settings_at_position(
 5438        &self,
 5439        buffer: &Entity<Buffer>,
 5440        buffer_position: language::Anchor,
 5441        cx: &App,
 5442    ) -> EditPredictionSettings {
 5443        if self.mode != EditorMode::Full
 5444            || !self.show_inline_completions_override.unwrap_or(true)
 5445            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5446        {
 5447            return EditPredictionSettings::Disabled;
 5448        }
 5449
 5450        let buffer = buffer.read(cx);
 5451
 5452        let file = buffer.file();
 5453
 5454        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5455            return EditPredictionSettings::Disabled;
 5456        };
 5457
 5458        let by_provider = matches!(
 5459            self.menu_inline_completions_policy,
 5460            MenuInlineCompletionsPolicy::ByProvider
 5461        );
 5462
 5463        let show_in_menu = by_provider
 5464            && self
 5465                .edit_prediction_provider
 5466                .as_ref()
 5467                .map_or(false, |provider| {
 5468                    provider.provider.show_completions_in_menu()
 5469                });
 5470
 5471        let preview_requires_modifier =
 5472            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5473
 5474        EditPredictionSettings::Enabled {
 5475            show_in_menu,
 5476            preview_requires_modifier,
 5477        }
 5478    }
 5479
 5480    fn should_show_edit_predictions(&self) -> bool {
 5481        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5482    }
 5483
 5484    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5485        matches!(
 5486            self.edit_prediction_preview,
 5487            EditPredictionPreview::Active { .. }
 5488        )
 5489    }
 5490
 5491    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5492        let cursor = self.selections.newest_anchor().head();
 5493        if let Some((buffer, cursor_position)) =
 5494            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5495        {
 5496            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5497        } else {
 5498            false
 5499        }
 5500    }
 5501
 5502    fn edit_predictions_enabled_in_buffer(
 5503        &self,
 5504        buffer: &Entity<Buffer>,
 5505        buffer_position: language::Anchor,
 5506        cx: &App,
 5507    ) -> bool {
 5508        maybe!({
 5509            if self.read_only(cx) {
 5510                return Some(false);
 5511            }
 5512            let provider = self.edit_prediction_provider()?;
 5513            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5514                return Some(false);
 5515            }
 5516            let buffer = buffer.read(cx);
 5517            let Some(file) = buffer.file() else {
 5518                return Some(true);
 5519            };
 5520            let settings = all_language_settings(Some(file), cx);
 5521            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5522        })
 5523        .unwrap_or(false)
 5524    }
 5525
 5526    fn cycle_inline_completion(
 5527        &mut self,
 5528        direction: Direction,
 5529        window: &mut Window,
 5530        cx: &mut Context<Self>,
 5531    ) -> Option<()> {
 5532        let provider = self.edit_prediction_provider()?;
 5533        let cursor = self.selections.newest_anchor().head();
 5534        let (buffer, cursor_buffer_position) =
 5535            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5536        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5537            return None;
 5538        }
 5539
 5540        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5541        self.update_visible_inline_completion(window, cx);
 5542
 5543        Some(())
 5544    }
 5545
 5546    pub fn show_inline_completion(
 5547        &mut self,
 5548        _: &ShowEditPrediction,
 5549        window: &mut Window,
 5550        cx: &mut Context<Self>,
 5551    ) {
 5552        if !self.has_active_inline_completion() {
 5553            self.refresh_inline_completion(false, true, window, cx);
 5554            return;
 5555        }
 5556
 5557        self.update_visible_inline_completion(window, cx);
 5558    }
 5559
 5560    pub fn display_cursor_names(
 5561        &mut self,
 5562        _: &DisplayCursorNames,
 5563        window: &mut Window,
 5564        cx: &mut Context<Self>,
 5565    ) {
 5566        self.show_cursor_names(window, cx);
 5567    }
 5568
 5569    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5570        self.show_cursor_names = true;
 5571        cx.notify();
 5572        cx.spawn_in(window, async move |this, cx| {
 5573            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5574            this.update(cx, |this, cx| {
 5575                this.show_cursor_names = false;
 5576                cx.notify()
 5577            })
 5578            .ok()
 5579        })
 5580        .detach();
 5581    }
 5582
 5583    pub fn next_edit_prediction(
 5584        &mut self,
 5585        _: &NextEditPrediction,
 5586        window: &mut Window,
 5587        cx: &mut Context<Self>,
 5588    ) {
 5589        if self.has_active_inline_completion() {
 5590            self.cycle_inline_completion(Direction::Next, window, cx);
 5591        } else {
 5592            let is_copilot_disabled = self
 5593                .refresh_inline_completion(false, true, window, cx)
 5594                .is_none();
 5595            if is_copilot_disabled {
 5596                cx.propagate();
 5597            }
 5598        }
 5599    }
 5600
 5601    pub fn previous_edit_prediction(
 5602        &mut self,
 5603        _: &PreviousEditPrediction,
 5604        window: &mut Window,
 5605        cx: &mut Context<Self>,
 5606    ) {
 5607        if self.has_active_inline_completion() {
 5608            self.cycle_inline_completion(Direction::Prev, window, cx);
 5609        } else {
 5610            let is_copilot_disabled = self
 5611                .refresh_inline_completion(false, true, window, cx)
 5612                .is_none();
 5613            if is_copilot_disabled {
 5614                cx.propagate();
 5615            }
 5616        }
 5617    }
 5618
 5619    pub fn accept_edit_prediction(
 5620        &mut self,
 5621        _: &AcceptEditPrediction,
 5622        window: &mut Window,
 5623        cx: &mut Context<Self>,
 5624    ) {
 5625        if self.show_edit_predictions_in_menu() {
 5626            self.hide_context_menu(window, cx);
 5627        }
 5628
 5629        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5630            return;
 5631        };
 5632
 5633        self.report_inline_completion_event(
 5634            active_inline_completion.completion_id.clone(),
 5635            true,
 5636            cx,
 5637        );
 5638
 5639        match &active_inline_completion.completion {
 5640            InlineCompletion::Move { target, .. } => {
 5641                let target = *target;
 5642
 5643                if let Some(position_map) = &self.last_position_map {
 5644                    if position_map
 5645                        .visible_row_range
 5646                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5647                        || !self.edit_prediction_requires_modifier()
 5648                    {
 5649                        self.unfold_ranges(&[target..target], true, false, cx);
 5650                        // Note that this is also done in vim's handler of the Tab action.
 5651                        self.change_selections(
 5652                            Some(Autoscroll::newest()),
 5653                            window,
 5654                            cx,
 5655                            |selections| {
 5656                                selections.select_anchor_ranges([target..target]);
 5657                            },
 5658                        );
 5659                        self.clear_row_highlights::<EditPredictionPreview>();
 5660
 5661                        self.edit_prediction_preview
 5662                            .set_previous_scroll_position(None);
 5663                    } else {
 5664                        self.edit_prediction_preview
 5665                            .set_previous_scroll_position(Some(
 5666                                position_map.snapshot.scroll_anchor,
 5667                            ));
 5668
 5669                        self.highlight_rows::<EditPredictionPreview>(
 5670                            target..target,
 5671                            cx.theme().colors().editor_highlighted_line_background,
 5672                            true,
 5673                            cx,
 5674                        );
 5675                        self.request_autoscroll(Autoscroll::fit(), cx);
 5676                    }
 5677                }
 5678            }
 5679            InlineCompletion::Edit { edits, .. } => {
 5680                if let Some(provider) = self.edit_prediction_provider() {
 5681                    provider.accept(cx);
 5682                }
 5683
 5684                let snapshot = self.buffer.read(cx).snapshot(cx);
 5685                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5686
 5687                self.buffer.update(cx, |buffer, cx| {
 5688                    buffer.edit(edits.iter().cloned(), None, cx)
 5689                });
 5690
 5691                self.change_selections(None, window, cx, |s| {
 5692                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5693                });
 5694
 5695                self.update_visible_inline_completion(window, cx);
 5696                if self.active_inline_completion.is_none() {
 5697                    self.refresh_inline_completion(true, true, window, cx);
 5698                }
 5699
 5700                cx.notify();
 5701            }
 5702        }
 5703
 5704        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5705    }
 5706
 5707    pub fn accept_partial_inline_completion(
 5708        &mut self,
 5709        _: &AcceptPartialEditPrediction,
 5710        window: &mut Window,
 5711        cx: &mut Context<Self>,
 5712    ) {
 5713        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5714            return;
 5715        };
 5716        if self.selections.count() != 1 {
 5717            return;
 5718        }
 5719
 5720        self.report_inline_completion_event(
 5721            active_inline_completion.completion_id.clone(),
 5722            true,
 5723            cx,
 5724        );
 5725
 5726        match &active_inline_completion.completion {
 5727            InlineCompletion::Move { target, .. } => {
 5728                let target = *target;
 5729                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5730                    selections.select_anchor_ranges([target..target]);
 5731                });
 5732            }
 5733            InlineCompletion::Edit { edits, .. } => {
 5734                // Find an insertion that starts at the cursor position.
 5735                let snapshot = self.buffer.read(cx).snapshot(cx);
 5736                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5737                let insertion = edits.iter().find_map(|(range, text)| {
 5738                    let range = range.to_offset(&snapshot);
 5739                    if range.is_empty() && range.start == cursor_offset {
 5740                        Some(text)
 5741                    } else {
 5742                        None
 5743                    }
 5744                });
 5745
 5746                if let Some(text) = insertion {
 5747                    let mut partial_completion = text
 5748                        .chars()
 5749                        .by_ref()
 5750                        .take_while(|c| c.is_alphabetic())
 5751                        .collect::<String>();
 5752                    if partial_completion.is_empty() {
 5753                        partial_completion = text
 5754                            .chars()
 5755                            .by_ref()
 5756                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5757                            .collect::<String>();
 5758                    }
 5759
 5760                    cx.emit(EditorEvent::InputHandled {
 5761                        utf16_range_to_replace: None,
 5762                        text: partial_completion.clone().into(),
 5763                    });
 5764
 5765                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5766
 5767                    self.refresh_inline_completion(true, true, window, cx);
 5768                    cx.notify();
 5769                } else {
 5770                    self.accept_edit_prediction(&Default::default(), window, cx);
 5771                }
 5772            }
 5773        }
 5774    }
 5775
 5776    fn discard_inline_completion(
 5777        &mut self,
 5778        should_report_inline_completion_event: bool,
 5779        cx: &mut Context<Self>,
 5780    ) -> bool {
 5781        if should_report_inline_completion_event {
 5782            let completion_id = self
 5783                .active_inline_completion
 5784                .as_ref()
 5785                .and_then(|active_completion| active_completion.completion_id.clone());
 5786
 5787            self.report_inline_completion_event(completion_id, false, cx);
 5788        }
 5789
 5790        if let Some(provider) = self.edit_prediction_provider() {
 5791            provider.discard(cx);
 5792        }
 5793
 5794        self.take_active_inline_completion(cx)
 5795    }
 5796
 5797    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5798        let Some(provider) = self.edit_prediction_provider() else {
 5799            return;
 5800        };
 5801
 5802        let Some((_, buffer, _)) = self
 5803            .buffer
 5804            .read(cx)
 5805            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5806        else {
 5807            return;
 5808        };
 5809
 5810        let extension = buffer
 5811            .read(cx)
 5812            .file()
 5813            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5814
 5815        let event_type = match accepted {
 5816            true => "Edit Prediction Accepted",
 5817            false => "Edit Prediction Discarded",
 5818        };
 5819        telemetry::event!(
 5820            event_type,
 5821            provider = provider.name(),
 5822            prediction_id = id,
 5823            suggestion_accepted = accepted,
 5824            file_extension = extension,
 5825        );
 5826    }
 5827
 5828    pub fn has_active_inline_completion(&self) -> bool {
 5829        self.active_inline_completion.is_some()
 5830    }
 5831
 5832    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5833        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5834            return false;
 5835        };
 5836
 5837        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5838        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5839        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5840        true
 5841    }
 5842
 5843    /// Returns true when we're displaying the edit prediction popover below the cursor
 5844    /// like we are not previewing and the LSP autocomplete menu is visible
 5845    /// or we are in `when_holding_modifier` mode.
 5846    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5847        if self.edit_prediction_preview_is_active()
 5848            || !self.show_edit_predictions_in_menu()
 5849            || !self.edit_predictions_enabled()
 5850        {
 5851            return false;
 5852        }
 5853
 5854        if self.has_visible_completions_menu() {
 5855            return true;
 5856        }
 5857
 5858        has_completion && self.edit_prediction_requires_modifier()
 5859    }
 5860
 5861    fn handle_modifiers_changed(
 5862        &mut self,
 5863        modifiers: Modifiers,
 5864        position_map: &PositionMap,
 5865        window: &mut Window,
 5866        cx: &mut Context<Self>,
 5867    ) {
 5868        if self.show_edit_predictions_in_menu() {
 5869            self.update_edit_prediction_preview(&modifiers, window, cx);
 5870        }
 5871
 5872        self.update_selection_mode(&modifiers, position_map, window, cx);
 5873
 5874        let mouse_position = window.mouse_position();
 5875        if !position_map.text_hitbox.is_hovered(window) {
 5876            return;
 5877        }
 5878
 5879        self.update_hovered_link(
 5880            position_map.point_for_position(mouse_position),
 5881            &position_map.snapshot,
 5882            modifiers,
 5883            window,
 5884            cx,
 5885        )
 5886    }
 5887
 5888    fn update_selection_mode(
 5889        &mut self,
 5890        modifiers: &Modifiers,
 5891        position_map: &PositionMap,
 5892        window: &mut Window,
 5893        cx: &mut Context<Self>,
 5894    ) {
 5895        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5896            return;
 5897        }
 5898
 5899        let mouse_position = window.mouse_position();
 5900        let point_for_position = position_map.point_for_position(mouse_position);
 5901        let position = point_for_position.previous_valid;
 5902
 5903        self.select(
 5904            SelectPhase::BeginColumnar {
 5905                position,
 5906                reset: false,
 5907                goal_column: point_for_position.exact_unclipped.column(),
 5908            },
 5909            window,
 5910            cx,
 5911        );
 5912    }
 5913
 5914    fn update_edit_prediction_preview(
 5915        &mut self,
 5916        modifiers: &Modifiers,
 5917        window: &mut Window,
 5918        cx: &mut Context<Self>,
 5919    ) {
 5920        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5921        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5922            return;
 5923        };
 5924
 5925        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5926            if matches!(
 5927                self.edit_prediction_preview,
 5928                EditPredictionPreview::Inactive { .. }
 5929            ) {
 5930                self.edit_prediction_preview = EditPredictionPreview::Active {
 5931                    previous_scroll_position: None,
 5932                    since: Instant::now(),
 5933                };
 5934
 5935                self.update_visible_inline_completion(window, cx);
 5936                cx.notify();
 5937            }
 5938        } else if let EditPredictionPreview::Active {
 5939            previous_scroll_position,
 5940            since,
 5941        } = self.edit_prediction_preview
 5942        {
 5943            if let (Some(previous_scroll_position), Some(position_map)) =
 5944                (previous_scroll_position, self.last_position_map.as_ref())
 5945            {
 5946                self.set_scroll_position(
 5947                    previous_scroll_position
 5948                        .scroll_position(&position_map.snapshot.display_snapshot),
 5949                    window,
 5950                    cx,
 5951                );
 5952            }
 5953
 5954            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5955                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5956            };
 5957            self.clear_row_highlights::<EditPredictionPreview>();
 5958            self.update_visible_inline_completion(window, cx);
 5959            cx.notify();
 5960        }
 5961    }
 5962
 5963    fn update_visible_inline_completion(
 5964        &mut self,
 5965        _window: &mut Window,
 5966        cx: &mut Context<Self>,
 5967    ) -> Option<()> {
 5968        let selection = self.selections.newest_anchor();
 5969        let cursor = selection.head();
 5970        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5971        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5972        let excerpt_id = cursor.excerpt_id;
 5973
 5974        let show_in_menu = self.show_edit_predictions_in_menu();
 5975        let completions_menu_has_precedence = !show_in_menu
 5976            && (self.context_menu.borrow().is_some()
 5977                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5978
 5979        if completions_menu_has_precedence
 5980            || !offset_selection.is_empty()
 5981            || self
 5982                .active_inline_completion
 5983                .as_ref()
 5984                .map_or(false, |completion| {
 5985                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5986                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5987                    !invalidation_range.contains(&offset_selection.head())
 5988                })
 5989        {
 5990            self.discard_inline_completion(false, cx);
 5991            return None;
 5992        }
 5993
 5994        self.take_active_inline_completion(cx);
 5995        let Some(provider) = self.edit_prediction_provider() else {
 5996            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5997            return None;
 5998        };
 5999
 6000        let (buffer, cursor_buffer_position) =
 6001            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6002
 6003        self.edit_prediction_settings =
 6004            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6005
 6006        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6007
 6008        if self.edit_prediction_indent_conflict {
 6009            let cursor_point = cursor.to_point(&multibuffer);
 6010
 6011            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6012
 6013            if let Some((_, indent)) = indents.iter().next() {
 6014                if indent.len == cursor_point.column {
 6015                    self.edit_prediction_indent_conflict = false;
 6016                }
 6017            }
 6018        }
 6019
 6020        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6021        let edits = inline_completion
 6022            .edits
 6023            .into_iter()
 6024            .flat_map(|(range, new_text)| {
 6025                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6026                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6027                Some((start..end, new_text))
 6028            })
 6029            .collect::<Vec<_>>();
 6030        if edits.is_empty() {
 6031            return None;
 6032        }
 6033
 6034        let first_edit_start = edits.first().unwrap().0.start;
 6035        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6036        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6037
 6038        let last_edit_end = edits.last().unwrap().0.end;
 6039        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6040        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6041
 6042        let cursor_row = cursor.to_point(&multibuffer).row;
 6043
 6044        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6045
 6046        let mut inlay_ids = Vec::new();
 6047        let invalidation_row_range;
 6048        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6049            Some(cursor_row..edit_end_row)
 6050        } else if cursor_row > edit_end_row {
 6051            Some(edit_start_row..cursor_row)
 6052        } else {
 6053            None
 6054        };
 6055        let is_move =
 6056            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6057        let completion = if is_move {
 6058            invalidation_row_range =
 6059                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6060            let target = first_edit_start;
 6061            InlineCompletion::Move { target, snapshot }
 6062        } else {
 6063            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6064                && !self.inline_completions_hidden_for_vim_mode;
 6065
 6066            if show_completions_in_buffer {
 6067                if edits
 6068                    .iter()
 6069                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6070                {
 6071                    let mut inlays = Vec::new();
 6072                    for (range, new_text) in &edits {
 6073                        let inlay = Inlay::inline_completion(
 6074                            post_inc(&mut self.next_inlay_id),
 6075                            range.start,
 6076                            new_text.as_str(),
 6077                        );
 6078                        inlay_ids.push(inlay.id);
 6079                        inlays.push(inlay);
 6080                    }
 6081
 6082                    self.splice_inlays(&[], inlays, cx);
 6083                } else {
 6084                    let background_color = cx.theme().status().deleted_background;
 6085                    self.highlight_text::<InlineCompletionHighlight>(
 6086                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6087                        HighlightStyle {
 6088                            background_color: Some(background_color),
 6089                            ..Default::default()
 6090                        },
 6091                        cx,
 6092                    );
 6093                }
 6094            }
 6095
 6096            invalidation_row_range = edit_start_row..edit_end_row;
 6097
 6098            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6099                if provider.show_tab_accept_marker() {
 6100                    EditDisplayMode::TabAccept
 6101                } else {
 6102                    EditDisplayMode::Inline
 6103                }
 6104            } else {
 6105                EditDisplayMode::DiffPopover
 6106            };
 6107
 6108            InlineCompletion::Edit {
 6109                edits,
 6110                edit_preview: inline_completion.edit_preview,
 6111                display_mode,
 6112                snapshot,
 6113            }
 6114        };
 6115
 6116        let invalidation_range = multibuffer
 6117            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6118            ..multibuffer.anchor_after(Point::new(
 6119                invalidation_row_range.end,
 6120                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6121            ));
 6122
 6123        self.stale_inline_completion_in_menu = None;
 6124        self.active_inline_completion = Some(InlineCompletionState {
 6125            inlay_ids,
 6126            completion,
 6127            completion_id: inline_completion.id,
 6128            invalidation_range,
 6129        });
 6130
 6131        cx.notify();
 6132
 6133        Some(())
 6134    }
 6135
 6136    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6137        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6138    }
 6139
 6140    fn render_code_actions_indicator(
 6141        &self,
 6142        _style: &EditorStyle,
 6143        row: DisplayRow,
 6144        is_active: bool,
 6145        breakpoint: Option<&(Anchor, Breakpoint)>,
 6146        cx: &mut Context<Self>,
 6147    ) -> Option<IconButton> {
 6148        let color = Color::Muted;
 6149        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6150
 6151        if self.available_code_actions.is_some() {
 6152            Some(
 6153                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6154                    .shape(ui::IconButtonShape::Square)
 6155                    .icon_size(IconSize::XSmall)
 6156                    .icon_color(color)
 6157                    .toggle_state(is_active)
 6158                    .tooltip({
 6159                        let focus_handle = self.focus_handle.clone();
 6160                        move |window, cx| {
 6161                            Tooltip::for_action_in(
 6162                                "Toggle Code Actions",
 6163                                &ToggleCodeActions {
 6164                                    deployed_from_indicator: None,
 6165                                },
 6166                                &focus_handle,
 6167                                window,
 6168                                cx,
 6169                            )
 6170                        }
 6171                    })
 6172                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6173                        window.focus(&editor.focus_handle(cx));
 6174                        editor.toggle_code_actions(
 6175                            &ToggleCodeActions {
 6176                                deployed_from_indicator: Some(row),
 6177                            },
 6178                            window,
 6179                            cx,
 6180                        );
 6181                    }))
 6182                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6183                        editor.set_breakpoint_context_menu(
 6184                            row,
 6185                            position,
 6186                            event.down.position,
 6187                            window,
 6188                            cx,
 6189                        );
 6190                    })),
 6191            )
 6192        } else {
 6193            None
 6194        }
 6195    }
 6196
 6197    fn clear_tasks(&mut self) {
 6198        self.tasks.clear()
 6199    }
 6200
 6201    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6202        if self.tasks.insert(key, value).is_some() {
 6203            // This case should hopefully be rare, but just in case...
 6204            log::error!(
 6205                "multiple different run targets found on a single line, only the last target will be rendered"
 6206            )
 6207        }
 6208    }
 6209
 6210    /// Get all display points of breakpoints that will be rendered within editor
 6211    ///
 6212    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6213    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6214    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6215    fn active_breakpoints(
 6216        &mut self,
 6217        range: Range<DisplayRow>,
 6218        window: &mut Window,
 6219        cx: &mut Context<Self>,
 6220    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6221        let mut breakpoint_display_points = HashMap::default();
 6222
 6223        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6224            return breakpoint_display_points;
 6225        };
 6226
 6227        let snapshot = self.snapshot(window, cx);
 6228
 6229        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6230        let Some(project) = self.project.as_ref() else {
 6231            return breakpoint_display_points;
 6232        };
 6233
 6234        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6235            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6236
 6237        for (buffer_snapshot, range, excerpt_id) in
 6238            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6239        {
 6240            let Some(buffer) = project.read_with(cx, |this, cx| {
 6241                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6242            }) else {
 6243                continue;
 6244            };
 6245            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6246                &buffer,
 6247                Some(
 6248                    buffer_snapshot.anchor_before(range.start)
 6249                        ..buffer_snapshot.anchor_after(range.end),
 6250                ),
 6251                buffer_snapshot,
 6252                cx,
 6253            );
 6254            for (anchor, breakpoint) in breakpoints {
 6255                let multi_buffer_anchor =
 6256                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6257                let position = multi_buffer_anchor
 6258                    .to_point(&multi_buffer_snapshot)
 6259                    .to_display_point(&snapshot);
 6260
 6261                breakpoint_display_points
 6262                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6263            }
 6264        }
 6265
 6266        breakpoint_display_points
 6267    }
 6268
 6269    fn breakpoint_context_menu(
 6270        &self,
 6271        anchor: Anchor,
 6272        window: &mut Window,
 6273        cx: &mut Context<Self>,
 6274    ) -> Entity<ui::ContextMenu> {
 6275        let weak_editor = cx.weak_entity();
 6276        let focus_handle = self.focus_handle(cx);
 6277
 6278        let row = self
 6279            .buffer
 6280            .read(cx)
 6281            .snapshot(cx)
 6282            .summary_for_anchor::<Point>(&anchor)
 6283            .row;
 6284
 6285        let breakpoint = self
 6286            .breakpoint_at_row(row, window, cx)
 6287            .map(|(_, bp)| Arc::from(bp));
 6288
 6289        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.message.is_some()) {
 6290            "Edit Log Breakpoint"
 6291        } else {
 6292            "Set Log Breakpoint"
 6293        };
 6294
 6295        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6296            "Unset Breakpoint"
 6297        } else {
 6298            "Set Breakpoint"
 6299        };
 6300
 6301        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.state {
 6302            BreakpointState::Enabled => Some("Disable"),
 6303            BreakpointState::Disabled => Some("Enable"),
 6304        });
 6305
 6306        let breakpoint = breakpoint.unwrap_or_else(|| {
 6307            Arc::new(Breakpoint {
 6308                state: BreakpointState::Enabled,
 6309                message: None,
 6310            })
 6311        });
 6312
 6313        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6314            menu.on_blur_subscription(Subscription::new(|| {}))
 6315                .context(focus_handle)
 6316                .when_some(toggle_state_msg, |this, msg| {
 6317                    this.entry(msg, None, {
 6318                        let weak_editor = weak_editor.clone();
 6319                        let breakpoint = breakpoint.clone();
 6320                        move |_window, cx| {
 6321                            weak_editor
 6322                                .update(cx, |this, cx| {
 6323                                    this.edit_breakpoint_at_anchor(
 6324                                        anchor,
 6325                                        breakpoint.as_ref().clone(),
 6326                                        BreakpointEditAction::InvertState,
 6327                                        cx,
 6328                                    );
 6329                                })
 6330                                .log_err();
 6331                        }
 6332                    })
 6333                })
 6334                .entry(set_breakpoint_msg, None, {
 6335                    let weak_editor = weak_editor.clone();
 6336                    let breakpoint = breakpoint.clone();
 6337                    move |_window, cx| {
 6338                        weak_editor
 6339                            .update(cx, |this, cx| {
 6340                                this.edit_breakpoint_at_anchor(
 6341                                    anchor,
 6342                                    breakpoint.as_ref().clone(),
 6343                                    BreakpointEditAction::Toggle,
 6344                                    cx,
 6345                                );
 6346                            })
 6347                            .log_err();
 6348                    }
 6349                })
 6350                .entry(log_breakpoint_msg, None, move |window, cx| {
 6351                    weak_editor
 6352                        .update(cx, |this, cx| {
 6353                            this.add_edit_breakpoint_block(anchor, breakpoint.as_ref(), window, cx);
 6354                        })
 6355                        .log_err();
 6356                })
 6357        })
 6358    }
 6359
 6360    fn render_breakpoint(
 6361        &self,
 6362        position: Anchor,
 6363        row: DisplayRow,
 6364        breakpoint: &Breakpoint,
 6365        cx: &mut Context<Self>,
 6366    ) -> IconButton {
 6367        let (color, icon) = {
 6368            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6369                (false, false) => ui::IconName::DebugBreakpoint,
 6370                (true, false) => ui::IconName::DebugLogBreakpoint,
 6371                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6372                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6373            };
 6374
 6375            let color = if self
 6376                .gutter_breakpoint_indicator
 6377                .0
 6378                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6379            {
 6380                Color::Hint
 6381            } else {
 6382                Color::Debugger
 6383            };
 6384
 6385            (color, icon)
 6386        };
 6387
 6388        let breakpoint = Arc::from(breakpoint.clone());
 6389
 6390        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6391            .icon_size(IconSize::XSmall)
 6392            .size(ui::ButtonSize::None)
 6393            .icon_color(color)
 6394            .style(ButtonStyle::Transparent)
 6395            .on_click(cx.listener({
 6396                let breakpoint = breakpoint.clone();
 6397
 6398                move |editor, event: &ClickEvent, window, cx| {
 6399                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6400                        BreakpointEditAction::InvertState
 6401                    } else {
 6402                        BreakpointEditAction::Toggle
 6403                    };
 6404
 6405                    window.focus(&editor.focus_handle(cx));
 6406                    editor.edit_breakpoint_at_anchor(
 6407                        position,
 6408                        breakpoint.as_ref().clone(),
 6409                        edit_action,
 6410                        cx,
 6411                    );
 6412                }
 6413            }))
 6414            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6415                editor.set_breakpoint_context_menu(
 6416                    row,
 6417                    Some(position),
 6418                    event.down.position,
 6419                    window,
 6420                    cx,
 6421                );
 6422            }))
 6423    }
 6424
 6425    fn build_tasks_context(
 6426        project: &Entity<Project>,
 6427        buffer: &Entity<Buffer>,
 6428        buffer_row: u32,
 6429        tasks: &Arc<RunnableTasks>,
 6430        cx: &mut Context<Self>,
 6431    ) -> Task<Option<task::TaskContext>> {
 6432        let position = Point::new(buffer_row, tasks.column);
 6433        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6434        let location = Location {
 6435            buffer: buffer.clone(),
 6436            range: range_start..range_start,
 6437        };
 6438        // Fill in the environmental variables from the tree-sitter captures
 6439        let mut captured_task_variables = TaskVariables::default();
 6440        for (capture_name, value) in tasks.extra_variables.clone() {
 6441            captured_task_variables.insert(
 6442                task::VariableName::Custom(capture_name.into()),
 6443                value.clone(),
 6444            );
 6445        }
 6446        project.update(cx, |project, cx| {
 6447            project.task_store().update(cx, |task_store, cx| {
 6448                task_store.task_context_for_location(captured_task_variables, location, cx)
 6449            })
 6450        })
 6451    }
 6452
 6453    pub fn spawn_nearest_task(
 6454        &mut self,
 6455        action: &SpawnNearestTask,
 6456        window: &mut Window,
 6457        cx: &mut Context<Self>,
 6458    ) {
 6459        let Some((workspace, _)) = self.workspace.clone() else {
 6460            return;
 6461        };
 6462        let Some(project) = self.project.clone() else {
 6463            return;
 6464        };
 6465
 6466        // Try to find a closest, enclosing node using tree-sitter that has a
 6467        // task
 6468        let Some((buffer, buffer_row, tasks)) = self
 6469            .find_enclosing_node_task(cx)
 6470            // Or find the task that's closest in row-distance.
 6471            .or_else(|| self.find_closest_task(cx))
 6472        else {
 6473            return;
 6474        };
 6475
 6476        let reveal_strategy = action.reveal;
 6477        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6478        cx.spawn_in(window, async move |_, cx| {
 6479            let context = task_context.await?;
 6480            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6481
 6482            let resolved = resolved_task.resolved.as_mut()?;
 6483            resolved.reveal = reveal_strategy;
 6484
 6485            workspace
 6486                .update(cx, |workspace, cx| {
 6487                    workspace::tasks::schedule_resolved_task(
 6488                        workspace,
 6489                        task_source_kind,
 6490                        resolved_task,
 6491                        false,
 6492                        cx,
 6493                    );
 6494                })
 6495                .ok()
 6496        })
 6497        .detach();
 6498    }
 6499
 6500    fn find_closest_task(
 6501        &mut self,
 6502        cx: &mut Context<Self>,
 6503    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6504        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6505
 6506        let ((buffer_id, row), tasks) = self
 6507            .tasks
 6508            .iter()
 6509            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6510
 6511        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6512        let tasks = Arc::new(tasks.to_owned());
 6513        Some((buffer, *row, tasks))
 6514    }
 6515
 6516    fn find_enclosing_node_task(
 6517        &mut self,
 6518        cx: &mut Context<Self>,
 6519    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6520        let snapshot = self.buffer.read(cx).snapshot(cx);
 6521        let offset = self.selections.newest::<usize>(cx).head();
 6522        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6523        let buffer_id = excerpt.buffer().remote_id();
 6524
 6525        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6526        let mut cursor = layer.node().walk();
 6527
 6528        while cursor.goto_first_child_for_byte(offset).is_some() {
 6529            if cursor.node().end_byte() == offset {
 6530                cursor.goto_next_sibling();
 6531            }
 6532        }
 6533
 6534        // Ascend to the smallest ancestor that contains the range and has a task.
 6535        loop {
 6536            let node = cursor.node();
 6537            let node_range = node.byte_range();
 6538            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6539
 6540            // Check if this node contains our offset
 6541            if node_range.start <= offset && node_range.end >= offset {
 6542                // If it contains offset, check for task
 6543                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6544                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6545                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6546                }
 6547            }
 6548
 6549            if !cursor.goto_parent() {
 6550                break;
 6551            }
 6552        }
 6553        None
 6554    }
 6555
 6556    fn render_run_indicator(
 6557        &self,
 6558        _style: &EditorStyle,
 6559        is_active: bool,
 6560        row: DisplayRow,
 6561        breakpoint: Option<(Anchor, Breakpoint)>,
 6562        cx: &mut Context<Self>,
 6563    ) -> IconButton {
 6564        let color = Color::Muted;
 6565        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6566
 6567        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6568            .shape(ui::IconButtonShape::Square)
 6569            .icon_size(IconSize::XSmall)
 6570            .icon_color(color)
 6571            .toggle_state(is_active)
 6572            .on_click(cx.listener(move |editor, _e, window, cx| {
 6573                window.focus(&editor.focus_handle(cx));
 6574                editor.toggle_code_actions(
 6575                    &ToggleCodeActions {
 6576                        deployed_from_indicator: Some(row),
 6577                    },
 6578                    window,
 6579                    cx,
 6580                );
 6581            }))
 6582            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6583                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6584            }))
 6585    }
 6586
 6587    pub fn context_menu_visible(&self) -> bool {
 6588        !self.edit_prediction_preview_is_active()
 6589            && self
 6590                .context_menu
 6591                .borrow()
 6592                .as_ref()
 6593                .map_or(false, |menu| menu.visible())
 6594    }
 6595
 6596    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6597        self.context_menu
 6598            .borrow()
 6599            .as_ref()
 6600            .map(|menu| menu.origin())
 6601    }
 6602
 6603    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6604        self.context_menu_options = Some(options);
 6605    }
 6606
 6607    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6608    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6609
 6610    fn render_edit_prediction_popover(
 6611        &mut self,
 6612        text_bounds: &Bounds<Pixels>,
 6613        content_origin: gpui::Point<Pixels>,
 6614        editor_snapshot: &EditorSnapshot,
 6615        visible_row_range: Range<DisplayRow>,
 6616        scroll_top: f32,
 6617        scroll_bottom: f32,
 6618        line_layouts: &[LineWithInvisibles],
 6619        line_height: Pixels,
 6620        scroll_pixel_position: gpui::Point<Pixels>,
 6621        newest_selection_head: Option<DisplayPoint>,
 6622        editor_width: Pixels,
 6623        style: &EditorStyle,
 6624        window: &mut Window,
 6625        cx: &mut App,
 6626    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6627        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6628
 6629        if self.edit_prediction_visible_in_cursor_popover(true) {
 6630            return None;
 6631        }
 6632
 6633        match &active_inline_completion.completion {
 6634            InlineCompletion::Move { target, .. } => {
 6635                let target_display_point = target.to_display_point(editor_snapshot);
 6636
 6637                if self.edit_prediction_requires_modifier() {
 6638                    if !self.edit_prediction_preview_is_active() {
 6639                        return None;
 6640                    }
 6641
 6642                    self.render_edit_prediction_modifier_jump_popover(
 6643                        text_bounds,
 6644                        content_origin,
 6645                        visible_row_range,
 6646                        line_layouts,
 6647                        line_height,
 6648                        scroll_pixel_position,
 6649                        newest_selection_head,
 6650                        target_display_point,
 6651                        window,
 6652                        cx,
 6653                    )
 6654                } else {
 6655                    self.render_edit_prediction_eager_jump_popover(
 6656                        text_bounds,
 6657                        content_origin,
 6658                        editor_snapshot,
 6659                        visible_row_range,
 6660                        scroll_top,
 6661                        scroll_bottom,
 6662                        line_height,
 6663                        scroll_pixel_position,
 6664                        target_display_point,
 6665                        editor_width,
 6666                        window,
 6667                        cx,
 6668                    )
 6669                }
 6670            }
 6671            InlineCompletion::Edit {
 6672                display_mode: EditDisplayMode::Inline,
 6673                ..
 6674            } => None,
 6675            InlineCompletion::Edit {
 6676                display_mode: EditDisplayMode::TabAccept,
 6677                edits,
 6678                ..
 6679            } => {
 6680                let range = &edits.first()?.0;
 6681                let target_display_point = range.end.to_display_point(editor_snapshot);
 6682
 6683                self.render_edit_prediction_end_of_line_popover(
 6684                    "Accept",
 6685                    editor_snapshot,
 6686                    visible_row_range,
 6687                    target_display_point,
 6688                    line_height,
 6689                    scroll_pixel_position,
 6690                    content_origin,
 6691                    editor_width,
 6692                    window,
 6693                    cx,
 6694                )
 6695            }
 6696            InlineCompletion::Edit {
 6697                edits,
 6698                edit_preview,
 6699                display_mode: EditDisplayMode::DiffPopover,
 6700                snapshot,
 6701            } => self.render_edit_prediction_diff_popover(
 6702                text_bounds,
 6703                content_origin,
 6704                editor_snapshot,
 6705                visible_row_range,
 6706                line_layouts,
 6707                line_height,
 6708                scroll_pixel_position,
 6709                newest_selection_head,
 6710                editor_width,
 6711                style,
 6712                edits,
 6713                edit_preview,
 6714                snapshot,
 6715                window,
 6716                cx,
 6717            ),
 6718        }
 6719    }
 6720
 6721    fn render_edit_prediction_modifier_jump_popover(
 6722        &mut self,
 6723        text_bounds: &Bounds<Pixels>,
 6724        content_origin: gpui::Point<Pixels>,
 6725        visible_row_range: Range<DisplayRow>,
 6726        line_layouts: &[LineWithInvisibles],
 6727        line_height: Pixels,
 6728        scroll_pixel_position: gpui::Point<Pixels>,
 6729        newest_selection_head: Option<DisplayPoint>,
 6730        target_display_point: DisplayPoint,
 6731        window: &mut Window,
 6732        cx: &mut App,
 6733    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6734        let scrolled_content_origin =
 6735            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6736
 6737        const SCROLL_PADDING_Y: Pixels = px(12.);
 6738
 6739        if target_display_point.row() < visible_row_range.start {
 6740            return self.render_edit_prediction_scroll_popover(
 6741                |_| SCROLL_PADDING_Y,
 6742                IconName::ArrowUp,
 6743                visible_row_range,
 6744                line_layouts,
 6745                newest_selection_head,
 6746                scrolled_content_origin,
 6747                window,
 6748                cx,
 6749            );
 6750        } else if target_display_point.row() >= visible_row_range.end {
 6751            return self.render_edit_prediction_scroll_popover(
 6752                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6753                IconName::ArrowDown,
 6754                visible_row_range,
 6755                line_layouts,
 6756                newest_selection_head,
 6757                scrolled_content_origin,
 6758                window,
 6759                cx,
 6760            );
 6761        }
 6762
 6763        const POLE_WIDTH: Pixels = px(2.);
 6764
 6765        let line_layout =
 6766            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6767        let target_column = target_display_point.column() as usize;
 6768
 6769        let target_x = line_layout.x_for_index(target_column);
 6770        let target_y =
 6771            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6772
 6773        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6774
 6775        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6776        border_color.l += 0.001;
 6777
 6778        let mut element = v_flex()
 6779            .items_end()
 6780            .when(flag_on_right, |el| el.items_start())
 6781            .child(if flag_on_right {
 6782                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6783                    .rounded_bl(px(0.))
 6784                    .rounded_tl(px(0.))
 6785                    .border_l_2()
 6786                    .border_color(border_color)
 6787            } else {
 6788                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6789                    .rounded_br(px(0.))
 6790                    .rounded_tr(px(0.))
 6791                    .border_r_2()
 6792                    .border_color(border_color)
 6793            })
 6794            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6795            .into_any();
 6796
 6797        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6798
 6799        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6800            - point(
 6801                if flag_on_right {
 6802                    POLE_WIDTH
 6803                } else {
 6804                    size.width - POLE_WIDTH
 6805                },
 6806                size.height - line_height,
 6807            );
 6808
 6809        origin.x = origin.x.max(content_origin.x);
 6810
 6811        element.prepaint_at(origin, window, cx);
 6812
 6813        Some((element, origin))
 6814    }
 6815
 6816    fn render_edit_prediction_scroll_popover(
 6817        &mut self,
 6818        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6819        scroll_icon: IconName,
 6820        visible_row_range: Range<DisplayRow>,
 6821        line_layouts: &[LineWithInvisibles],
 6822        newest_selection_head: Option<DisplayPoint>,
 6823        scrolled_content_origin: gpui::Point<Pixels>,
 6824        window: &mut Window,
 6825        cx: &mut App,
 6826    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6827        let mut element = self
 6828            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6829            .into_any();
 6830
 6831        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6832
 6833        let cursor = newest_selection_head?;
 6834        let cursor_row_layout =
 6835            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6836        let cursor_column = cursor.column() as usize;
 6837
 6838        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6839
 6840        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6841
 6842        element.prepaint_at(origin, window, cx);
 6843        Some((element, origin))
 6844    }
 6845
 6846    fn render_edit_prediction_eager_jump_popover(
 6847        &mut self,
 6848        text_bounds: &Bounds<Pixels>,
 6849        content_origin: gpui::Point<Pixels>,
 6850        editor_snapshot: &EditorSnapshot,
 6851        visible_row_range: Range<DisplayRow>,
 6852        scroll_top: f32,
 6853        scroll_bottom: f32,
 6854        line_height: Pixels,
 6855        scroll_pixel_position: gpui::Point<Pixels>,
 6856        target_display_point: DisplayPoint,
 6857        editor_width: Pixels,
 6858        window: &mut Window,
 6859        cx: &mut App,
 6860    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6861        if target_display_point.row().as_f32() < scroll_top {
 6862            let mut element = self
 6863                .render_edit_prediction_line_popover(
 6864                    "Jump to Edit",
 6865                    Some(IconName::ArrowUp),
 6866                    window,
 6867                    cx,
 6868                )?
 6869                .into_any();
 6870
 6871            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6872            let offset = point(
 6873                (text_bounds.size.width - size.width) / 2.,
 6874                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6875            );
 6876
 6877            let origin = text_bounds.origin + offset;
 6878            element.prepaint_at(origin, window, cx);
 6879            Some((element, origin))
 6880        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6881            let mut element = self
 6882                .render_edit_prediction_line_popover(
 6883                    "Jump to Edit",
 6884                    Some(IconName::ArrowDown),
 6885                    window,
 6886                    cx,
 6887                )?
 6888                .into_any();
 6889
 6890            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6891            let offset = point(
 6892                (text_bounds.size.width - size.width) / 2.,
 6893                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6894            );
 6895
 6896            let origin = text_bounds.origin + offset;
 6897            element.prepaint_at(origin, window, cx);
 6898            Some((element, origin))
 6899        } else {
 6900            self.render_edit_prediction_end_of_line_popover(
 6901                "Jump to Edit",
 6902                editor_snapshot,
 6903                visible_row_range,
 6904                target_display_point,
 6905                line_height,
 6906                scroll_pixel_position,
 6907                content_origin,
 6908                editor_width,
 6909                window,
 6910                cx,
 6911            )
 6912        }
 6913    }
 6914
 6915    fn render_edit_prediction_end_of_line_popover(
 6916        self: &mut Editor,
 6917        label: &'static str,
 6918        editor_snapshot: &EditorSnapshot,
 6919        visible_row_range: Range<DisplayRow>,
 6920        target_display_point: DisplayPoint,
 6921        line_height: Pixels,
 6922        scroll_pixel_position: gpui::Point<Pixels>,
 6923        content_origin: gpui::Point<Pixels>,
 6924        editor_width: Pixels,
 6925        window: &mut Window,
 6926        cx: &mut App,
 6927    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6928        let target_line_end = DisplayPoint::new(
 6929            target_display_point.row(),
 6930            editor_snapshot.line_len(target_display_point.row()),
 6931        );
 6932
 6933        let mut element = self
 6934            .render_edit_prediction_line_popover(label, None, window, cx)?
 6935            .into_any();
 6936
 6937        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6938
 6939        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6940
 6941        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6942        let mut origin = start_point
 6943            + line_origin
 6944            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6945        origin.x = origin.x.max(content_origin.x);
 6946
 6947        let max_x = content_origin.x + editor_width - size.width;
 6948
 6949        if origin.x > max_x {
 6950            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6951
 6952            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6953                origin.y += offset;
 6954                IconName::ArrowUp
 6955            } else {
 6956                origin.y -= offset;
 6957                IconName::ArrowDown
 6958            };
 6959
 6960            element = self
 6961                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6962                .into_any();
 6963
 6964            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6965
 6966            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6967        }
 6968
 6969        element.prepaint_at(origin, window, cx);
 6970        Some((element, origin))
 6971    }
 6972
 6973    fn render_edit_prediction_diff_popover(
 6974        self: &Editor,
 6975        text_bounds: &Bounds<Pixels>,
 6976        content_origin: gpui::Point<Pixels>,
 6977        editor_snapshot: &EditorSnapshot,
 6978        visible_row_range: Range<DisplayRow>,
 6979        line_layouts: &[LineWithInvisibles],
 6980        line_height: Pixels,
 6981        scroll_pixel_position: gpui::Point<Pixels>,
 6982        newest_selection_head: Option<DisplayPoint>,
 6983        editor_width: Pixels,
 6984        style: &EditorStyle,
 6985        edits: &Vec<(Range<Anchor>, String)>,
 6986        edit_preview: &Option<language::EditPreview>,
 6987        snapshot: &language::BufferSnapshot,
 6988        window: &mut Window,
 6989        cx: &mut App,
 6990    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6991        let edit_start = edits
 6992            .first()
 6993            .unwrap()
 6994            .0
 6995            .start
 6996            .to_display_point(editor_snapshot);
 6997        let edit_end = edits
 6998            .last()
 6999            .unwrap()
 7000            .0
 7001            .end
 7002            .to_display_point(editor_snapshot);
 7003
 7004        let is_visible = visible_row_range.contains(&edit_start.row())
 7005            || visible_row_range.contains(&edit_end.row());
 7006        if !is_visible {
 7007            return None;
 7008        }
 7009
 7010        let highlighted_edits =
 7011            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7012
 7013        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7014        let line_count = highlighted_edits.text.lines().count();
 7015
 7016        const BORDER_WIDTH: Pixels = px(1.);
 7017
 7018        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7019        let has_keybind = keybind.is_some();
 7020
 7021        let mut element = h_flex()
 7022            .items_start()
 7023            .child(
 7024                h_flex()
 7025                    .bg(cx.theme().colors().editor_background)
 7026                    .border(BORDER_WIDTH)
 7027                    .shadow_sm()
 7028                    .border_color(cx.theme().colors().border)
 7029                    .rounded_l_lg()
 7030                    .when(line_count > 1, |el| el.rounded_br_lg())
 7031                    .pr_1()
 7032                    .child(styled_text),
 7033            )
 7034            .child(
 7035                h_flex()
 7036                    .h(line_height + BORDER_WIDTH * 2.)
 7037                    .px_1p5()
 7038                    .gap_1()
 7039                    // Workaround: For some reason, there's a gap if we don't do this
 7040                    .ml(-BORDER_WIDTH)
 7041                    .shadow(smallvec![gpui::BoxShadow {
 7042                        color: gpui::black().opacity(0.05),
 7043                        offset: point(px(1.), px(1.)),
 7044                        blur_radius: px(2.),
 7045                        spread_radius: px(0.),
 7046                    }])
 7047                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7048                    .border(BORDER_WIDTH)
 7049                    .border_color(cx.theme().colors().border)
 7050                    .rounded_r_lg()
 7051                    .id("edit_prediction_diff_popover_keybind")
 7052                    .when(!has_keybind, |el| {
 7053                        let status_colors = cx.theme().status();
 7054
 7055                        el.bg(status_colors.error_background)
 7056                            .border_color(status_colors.error.opacity(0.6))
 7057                            .child(Icon::new(IconName::Info).color(Color::Error))
 7058                            .cursor_default()
 7059                            .hoverable_tooltip(move |_window, cx| {
 7060                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7061                            })
 7062                    })
 7063                    .children(keybind),
 7064            )
 7065            .into_any();
 7066
 7067        let longest_row =
 7068            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7069        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7070            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7071        } else {
 7072            layout_line(
 7073                longest_row,
 7074                editor_snapshot,
 7075                style,
 7076                editor_width,
 7077                |_| false,
 7078                window,
 7079                cx,
 7080            )
 7081            .width
 7082        };
 7083
 7084        let viewport_bounds =
 7085            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7086                right: -EditorElement::SCROLLBAR_WIDTH,
 7087                ..Default::default()
 7088            });
 7089
 7090        let x_after_longest =
 7091            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7092                - scroll_pixel_position.x;
 7093
 7094        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7095
 7096        // Fully visible if it can be displayed within the window (allow overlapping other
 7097        // panes). However, this is only allowed if the popover starts within text_bounds.
 7098        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7099            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7100
 7101        let mut origin = if can_position_to_the_right {
 7102            point(
 7103                x_after_longest,
 7104                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7105                    - scroll_pixel_position.y,
 7106            )
 7107        } else {
 7108            let cursor_row = newest_selection_head.map(|head| head.row());
 7109            let above_edit = edit_start
 7110                .row()
 7111                .0
 7112                .checked_sub(line_count as u32)
 7113                .map(DisplayRow);
 7114            let below_edit = Some(edit_end.row() + 1);
 7115            let above_cursor =
 7116                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7117            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7118
 7119            // Place the edit popover adjacent to the edit if there is a location
 7120            // available that is onscreen and does not obscure the cursor. Otherwise,
 7121            // place it adjacent to the cursor.
 7122            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7123                .into_iter()
 7124                .flatten()
 7125                .find(|&start_row| {
 7126                    let end_row = start_row + line_count as u32;
 7127                    visible_row_range.contains(&start_row)
 7128                        && visible_row_range.contains(&end_row)
 7129                        && cursor_row.map_or(true, |cursor_row| {
 7130                            !((start_row..end_row).contains(&cursor_row))
 7131                        })
 7132                })?;
 7133
 7134            content_origin
 7135                + point(
 7136                    -scroll_pixel_position.x,
 7137                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7138                )
 7139        };
 7140
 7141        origin.x -= BORDER_WIDTH;
 7142
 7143        window.defer_draw(element, origin, 1);
 7144
 7145        // Do not return an element, since it will already be drawn due to defer_draw.
 7146        None
 7147    }
 7148
 7149    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7150        px(30.)
 7151    }
 7152
 7153    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7154        if self.read_only(cx) {
 7155            cx.theme().players().read_only()
 7156        } else {
 7157            self.style.as_ref().unwrap().local_player
 7158        }
 7159    }
 7160
 7161    fn render_edit_prediction_accept_keybind(
 7162        &self,
 7163        window: &mut Window,
 7164        cx: &App,
 7165    ) -> Option<AnyElement> {
 7166        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7167        let accept_keystroke = accept_binding.keystroke()?;
 7168
 7169        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7170
 7171        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7172            Color::Accent
 7173        } else {
 7174            Color::Muted
 7175        };
 7176
 7177        h_flex()
 7178            .px_0p5()
 7179            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7180            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7181            .text_size(TextSize::XSmall.rems(cx))
 7182            .child(h_flex().children(ui::render_modifiers(
 7183                &accept_keystroke.modifiers,
 7184                PlatformStyle::platform(),
 7185                Some(modifiers_color),
 7186                Some(IconSize::XSmall.rems().into()),
 7187                true,
 7188            )))
 7189            .when(is_platform_style_mac, |parent| {
 7190                parent.child(accept_keystroke.key.clone())
 7191            })
 7192            .when(!is_platform_style_mac, |parent| {
 7193                parent.child(
 7194                    Key::new(
 7195                        util::capitalize(&accept_keystroke.key),
 7196                        Some(Color::Default),
 7197                    )
 7198                    .size(Some(IconSize::XSmall.rems().into())),
 7199                )
 7200            })
 7201            .into_any()
 7202            .into()
 7203    }
 7204
 7205    fn render_edit_prediction_line_popover(
 7206        &self,
 7207        label: impl Into<SharedString>,
 7208        icon: Option<IconName>,
 7209        window: &mut Window,
 7210        cx: &App,
 7211    ) -> Option<Stateful<Div>> {
 7212        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7213
 7214        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7215        let has_keybind = keybind.is_some();
 7216
 7217        let result = h_flex()
 7218            .id("ep-line-popover")
 7219            .py_0p5()
 7220            .pl_1()
 7221            .pr(padding_right)
 7222            .gap_1()
 7223            .rounded_md()
 7224            .border_1()
 7225            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7226            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7227            .shadow_sm()
 7228            .when(!has_keybind, |el| {
 7229                let status_colors = cx.theme().status();
 7230
 7231                el.bg(status_colors.error_background)
 7232                    .border_color(status_colors.error.opacity(0.6))
 7233                    .pl_2()
 7234                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7235                    .cursor_default()
 7236                    .hoverable_tooltip(move |_window, cx| {
 7237                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7238                    })
 7239            })
 7240            .children(keybind)
 7241            .child(
 7242                Label::new(label)
 7243                    .size(LabelSize::Small)
 7244                    .when(!has_keybind, |el| {
 7245                        el.color(cx.theme().status().error.into()).strikethrough()
 7246                    }),
 7247            )
 7248            .when(!has_keybind, |el| {
 7249                el.child(
 7250                    h_flex().ml_1().child(
 7251                        Icon::new(IconName::Info)
 7252                            .size(IconSize::Small)
 7253                            .color(cx.theme().status().error.into()),
 7254                    ),
 7255                )
 7256            })
 7257            .when_some(icon, |element, icon| {
 7258                element.child(
 7259                    div()
 7260                        .mt(px(1.5))
 7261                        .child(Icon::new(icon).size(IconSize::Small)),
 7262                )
 7263            });
 7264
 7265        Some(result)
 7266    }
 7267
 7268    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7269        let accent_color = cx.theme().colors().text_accent;
 7270        let editor_bg_color = cx.theme().colors().editor_background;
 7271        editor_bg_color.blend(accent_color.opacity(0.1))
 7272    }
 7273
 7274    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7275        let accent_color = cx.theme().colors().text_accent;
 7276        let editor_bg_color = cx.theme().colors().editor_background;
 7277        editor_bg_color.blend(accent_color.opacity(0.6))
 7278    }
 7279
 7280    fn render_edit_prediction_cursor_popover(
 7281        &self,
 7282        min_width: Pixels,
 7283        max_width: Pixels,
 7284        cursor_point: Point,
 7285        style: &EditorStyle,
 7286        accept_keystroke: Option<&gpui::Keystroke>,
 7287        _window: &Window,
 7288        cx: &mut Context<Editor>,
 7289    ) -> Option<AnyElement> {
 7290        let provider = self.edit_prediction_provider.as_ref()?;
 7291
 7292        if provider.provider.needs_terms_acceptance(cx) {
 7293            return Some(
 7294                h_flex()
 7295                    .min_w(min_width)
 7296                    .flex_1()
 7297                    .px_2()
 7298                    .py_1()
 7299                    .gap_3()
 7300                    .elevation_2(cx)
 7301                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7302                    .id("accept-terms")
 7303                    .cursor_pointer()
 7304                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7305                    .on_click(cx.listener(|this, _event, window, cx| {
 7306                        cx.stop_propagation();
 7307                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7308                        window.dispatch_action(
 7309                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7310                            cx,
 7311                        );
 7312                    }))
 7313                    .child(
 7314                        h_flex()
 7315                            .flex_1()
 7316                            .gap_2()
 7317                            .child(Icon::new(IconName::ZedPredict))
 7318                            .child(Label::new("Accept Terms of Service"))
 7319                            .child(div().w_full())
 7320                            .child(
 7321                                Icon::new(IconName::ArrowUpRight)
 7322                                    .color(Color::Muted)
 7323                                    .size(IconSize::Small),
 7324                            )
 7325                            .into_any_element(),
 7326                    )
 7327                    .into_any(),
 7328            );
 7329        }
 7330
 7331        let is_refreshing = provider.provider.is_refreshing(cx);
 7332
 7333        fn pending_completion_container() -> Div {
 7334            h_flex()
 7335                .h_full()
 7336                .flex_1()
 7337                .gap_2()
 7338                .child(Icon::new(IconName::ZedPredict))
 7339        }
 7340
 7341        let completion = match &self.active_inline_completion {
 7342            Some(prediction) => {
 7343                if !self.has_visible_completions_menu() {
 7344                    const RADIUS: Pixels = px(6.);
 7345                    const BORDER_WIDTH: Pixels = px(1.);
 7346
 7347                    return Some(
 7348                        h_flex()
 7349                            .elevation_2(cx)
 7350                            .border(BORDER_WIDTH)
 7351                            .border_color(cx.theme().colors().border)
 7352                            .when(accept_keystroke.is_none(), |el| {
 7353                                el.border_color(cx.theme().status().error)
 7354                            })
 7355                            .rounded(RADIUS)
 7356                            .rounded_tl(px(0.))
 7357                            .overflow_hidden()
 7358                            .child(div().px_1p5().child(match &prediction.completion {
 7359                                InlineCompletion::Move { target, snapshot } => {
 7360                                    use text::ToPoint as _;
 7361                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7362                                    {
 7363                                        Icon::new(IconName::ZedPredictDown)
 7364                                    } else {
 7365                                        Icon::new(IconName::ZedPredictUp)
 7366                                    }
 7367                                }
 7368                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7369                            }))
 7370                            .child(
 7371                                h_flex()
 7372                                    .gap_1()
 7373                                    .py_1()
 7374                                    .px_2()
 7375                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7376                                    .border_l_1()
 7377                                    .border_color(cx.theme().colors().border)
 7378                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7379                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7380                                        el.child(
 7381                                            Label::new("Hold")
 7382                                                .size(LabelSize::Small)
 7383                                                .when(accept_keystroke.is_none(), |el| {
 7384                                                    el.strikethrough()
 7385                                                })
 7386                                                .line_height_style(LineHeightStyle::UiLabel),
 7387                                        )
 7388                                    })
 7389                                    .id("edit_prediction_cursor_popover_keybind")
 7390                                    .when(accept_keystroke.is_none(), |el| {
 7391                                        let status_colors = cx.theme().status();
 7392
 7393                                        el.bg(status_colors.error_background)
 7394                                            .border_color(status_colors.error.opacity(0.6))
 7395                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7396                                            .cursor_default()
 7397                                            .hoverable_tooltip(move |_window, cx| {
 7398                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7399                                                    .into()
 7400                                            })
 7401                                    })
 7402                                    .when_some(
 7403                                        accept_keystroke.as_ref(),
 7404                                        |el, accept_keystroke| {
 7405                                            el.child(h_flex().children(ui::render_modifiers(
 7406                                                &accept_keystroke.modifiers,
 7407                                                PlatformStyle::platform(),
 7408                                                Some(Color::Default),
 7409                                                Some(IconSize::XSmall.rems().into()),
 7410                                                false,
 7411                                            )))
 7412                                        },
 7413                                    ),
 7414                            )
 7415                            .into_any(),
 7416                    );
 7417                }
 7418
 7419                self.render_edit_prediction_cursor_popover_preview(
 7420                    prediction,
 7421                    cursor_point,
 7422                    style,
 7423                    cx,
 7424                )?
 7425            }
 7426
 7427            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7428                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7429                    stale_completion,
 7430                    cursor_point,
 7431                    style,
 7432                    cx,
 7433                )?,
 7434
 7435                None => {
 7436                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7437                }
 7438            },
 7439
 7440            None => pending_completion_container().child(Label::new("No Prediction")),
 7441        };
 7442
 7443        let completion = if is_refreshing {
 7444            completion
 7445                .with_animation(
 7446                    "loading-completion",
 7447                    Animation::new(Duration::from_secs(2))
 7448                        .repeat()
 7449                        .with_easing(pulsating_between(0.4, 0.8)),
 7450                    |label, delta| label.opacity(delta),
 7451                )
 7452                .into_any_element()
 7453        } else {
 7454            completion.into_any_element()
 7455        };
 7456
 7457        let has_completion = self.active_inline_completion.is_some();
 7458
 7459        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7460        Some(
 7461            h_flex()
 7462                .min_w(min_width)
 7463                .max_w(max_width)
 7464                .flex_1()
 7465                .elevation_2(cx)
 7466                .border_color(cx.theme().colors().border)
 7467                .child(
 7468                    div()
 7469                        .flex_1()
 7470                        .py_1()
 7471                        .px_2()
 7472                        .overflow_hidden()
 7473                        .child(completion),
 7474                )
 7475                .when_some(accept_keystroke, |el, accept_keystroke| {
 7476                    if !accept_keystroke.modifiers.modified() {
 7477                        return el;
 7478                    }
 7479
 7480                    el.child(
 7481                        h_flex()
 7482                            .h_full()
 7483                            .border_l_1()
 7484                            .rounded_r_lg()
 7485                            .border_color(cx.theme().colors().border)
 7486                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7487                            .gap_1()
 7488                            .py_1()
 7489                            .px_2()
 7490                            .child(
 7491                                h_flex()
 7492                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7493                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7494                                    .child(h_flex().children(ui::render_modifiers(
 7495                                        &accept_keystroke.modifiers,
 7496                                        PlatformStyle::platform(),
 7497                                        Some(if !has_completion {
 7498                                            Color::Muted
 7499                                        } else {
 7500                                            Color::Default
 7501                                        }),
 7502                                        None,
 7503                                        false,
 7504                                    ))),
 7505                            )
 7506                            .child(Label::new("Preview").into_any_element())
 7507                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7508                    )
 7509                })
 7510                .into_any(),
 7511        )
 7512    }
 7513
 7514    fn render_edit_prediction_cursor_popover_preview(
 7515        &self,
 7516        completion: &InlineCompletionState,
 7517        cursor_point: Point,
 7518        style: &EditorStyle,
 7519        cx: &mut Context<Editor>,
 7520    ) -> Option<Div> {
 7521        use text::ToPoint as _;
 7522
 7523        fn render_relative_row_jump(
 7524            prefix: impl Into<String>,
 7525            current_row: u32,
 7526            target_row: u32,
 7527        ) -> Div {
 7528            let (row_diff, arrow) = if target_row < current_row {
 7529                (current_row - target_row, IconName::ArrowUp)
 7530            } else {
 7531                (target_row - current_row, IconName::ArrowDown)
 7532            };
 7533
 7534            h_flex()
 7535                .child(
 7536                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7537                        .color(Color::Muted)
 7538                        .size(LabelSize::Small),
 7539                )
 7540                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7541        }
 7542
 7543        match &completion.completion {
 7544            InlineCompletion::Move {
 7545                target, snapshot, ..
 7546            } => Some(
 7547                h_flex()
 7548                    .px_2()
 7549                    .gap_2()
 7550                    .flex_1()
 7551                    .child(
 7552                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7553                            Icon::new(IconName::ZedPredictDown)
 7554                        } else {
 7555                            Icon::new(IconName::ZedPredictUp)
 7556                        },
 7557                    )
 7558                    .child(Label::new("Jump to Edit")),
 7559            ),
 7560
 7561            InlineCompletion::Edit {
 7562                edits,
 7563                edit_preview,
 7564                snapshot,
 7565                display_mode: _,
 7566            } => {
 7567                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7568
 7569                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7570                    &snapshot,
 7571                    &edits,
 7572                    edit_preview.as_ref()?,
 7573                    true,
 7574                    cx,
 7575                )
 7576                .first_line_preview();
 7577
 7578                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7579                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7580
 7581                let preview = h_flex()
 7582                    .gap_1()
 7583                    .min_w_16()
 7584                    .child(styled_text)
 7585                    .when(has_more_lines, |parent| parent.child(""));
 7586
 7587                let left = if first_edit_row != cursor_point.row {
 7588                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7589                        .into_any_element()
 7590                } else {
 7591                    Icon::new(IconName::ZedPredict).into_any_element()
 7592                };
 7593
 7594                Some(
 7595                    h_flex()
 7596                        .h_full()
 7597                        .flex_1()
 7598                        .gap_2()
 7599                        .pr_1()
 7600                        .overflow_x_hidden()
 7601                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7602                        .child(left)
 7603                        .child(preview),
 7604                )
 7605            }
 7606        }
 7607    }
 7608
 7609    fn render_context_menu(
 7610        &self,
 7611        style: &EditorStyle,
 7612        max_height_in_lines: u32,
 7613        y_flipped: bool,
 7614        window: &mut Window,
 7615        cx: &mut Context<Editor>,
 7616    ) -> Option<AnyElement> {
 7617        let menu = self.context_menu.borrow();
 7618        let menu = menu.as_ref()?;
 7619        if !menu.visible() {
 7620            return None;
 7621        };
 7622        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 7623    }
 7624
 7625    fn render_context_menu_aside(
 7626        &mut self,
 7627        max_size: Size<Pixels>,
 7628        window: &mut Window,
 7629        cx: &mut Context<Editor>,
 7630    ) -> Option<AnyElement> {
 7631        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7632            if menu.visible() {
 7633                menu.render_aside(self, max_size, window, cx)
 7634            } else {
 7635                None
 7636            }
 7637        })
 7638    }
 7639
 7640    fn hide_context_menu(
 7641        &mut self,
 7642        window: &mut Window,
 7643        cx: &mut Context<Self>,
 7644    ) -> Option<CodeContextMenu> {
 7645        cx.notify();
 7646        self.completion_tasks.clear();
 7647        let context_menu = self.context_menu.borrow_mut().take();
 7648        self.stale_inline_completion_in_menu.take();
 7649        self.update_visible_inline_completion(window, cx);
 7650        context_menu
 7651    }
 7652
 7653    fn show_snippet_choices(
 7654        &mut self,
 7655        choices: &Vec<String>,
 7656        selection: Range<Anchor>,
 7657        cx: &mut Context<Self>,
 7658    ) {
 7659        if selection.start.buffer_id.is_none() {
 7660            return;
 7661        }
 7662        let buffer_id = selection.start.buffer_id.unwrap();
 7663        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7664        let id = post_inc(&mut self.next_completion_id);
 7665
 7666        if let Some(buffer) = buffer {
 7667            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7668                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7669            ));
 7670        }
 7671    }
 7672
 7673    pub fn insert_snippet(
 7674        &mut self,
 7675        insertion_ranges: &[Range<usize>],
 7676        snippet: Snippet,
 7677        window: &mut Window,
 7678        cx: &mut Context<Self>,
 7679    ) -> Result<()> {
 7680        struct Tabstop<T> {
 7681            is_end_tabstop: bool,
 7682            ranges: Vec<Range<T>>,
 7683            choices: Option<Vec<String>>,
 7684        }
 7685
 7686        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7687            let snippet_text: Arc<str> = snippet.text.clone().into();
 7688            let edits = insertion_ranges
 7689                .iter()
 7690                .cloned()
 7691                .map(|range| (range, snippet_text.clone()));
 7692            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7693
 7694            let snapshot = &*buffer.read(cx);
 7695            let snippet = &snippet;
 7696            snippet
 7697                .tabstops
 7698                .iter()
 7699                .map(|tabstop| {
 7700                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7701                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7702                    });
 7703                    let mut tabstop_ranges = tabstop
 7704                        .ranges
 7705                        .iter()
 7706                        .flat_map(|tabstop_range| {
 7707                            let mut delta = 0_isize;
 7708                            insertion_ranges.iter().map(move |insertion_range| {
 7709                                let insertion_start = insertion_range.start as isize + delta;
 7710                                delta +=
 7711                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7712
 7713                                let start = ((insertion_start + tabstop_range.start) as usize)
 7714                                    .min(snapshot.len());
 7715                                let end = ((insertion_start + tabstop_range.end) as usize)
 7716                                    .min(snapshot.len());
 7717                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7718                            })
 7719                        })
 7720                        .collect::<Vec<_>>();
 7721                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7722
 7723                    Tabstop {
 7724                        is_end_tabstop,
 7725                        ranges: tabstop_ranges,
 7726                        choices: tabstop.choices.clone(),
 7727                    }
 7728                })
 7729                .collect::<Vec<_>>()
 7730        });
 7731        if let Some(tabstop) = tabstops.first() {
 7732            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7733                s.select_ranges(tabstop.ranges.iter().cloned());
 7734            });
 7735
 7736            if let Some(choices) = &tabstop.choices {
 7737                if let Some(selection) = tabstop.ranges.first() {
 7738                    self.show_snippet_choices(choices, selection.clone(), cx)
 7739                }
 7740            }
 7741
 7742            // If we're already at the last tabstop and it's at the end of the snippet,
 7743            // we're done, we don't need to keep the state around.
 7744            if !tabstop.is_end_tabstop {
 7745                let choices = tabstops
 7746                    .iter()
 7747                    .map(|tabstop| tabstop.choices.clone())
 7748                    .collect();
 7749
 7750                let ranges = tabstops
 7751                    .into_iter()
 7752                    .map(|tabstop| tabstop.ranges)
 7753                    .collect::<Vec<_>>();
 7754
 7755                self.snippet_stack.push(SnippetState {
 7756                    active_index: 0,
 7757                    ranges,
 7758                    choices,
 7759                });
 7760            }
 7761
 7762            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7763            if self.autoclose_regions.is_empty() {
 7764                let snapshot = self.buffer.read(cx).snapshot(cx);
 7765                for selection in &mut self.selections.all::<Point>(cx) {
 7766                    let selection_head = selection.head();
 7767                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7768                        continue;
 7769                    };
 7770
 7771                    let mut bracket_pair = None;
 7772                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7773                    let prev_chars = snapshot
 7774                        .reversed_chars_at(selection_head)
 7775                        .collect::<String>();
 7776                    for (pair, enabled) in scope.brackets() {
 7777                        if enabled
 7778                            && pair.close
 7779                            && prev_chars.starts_with(pair.start.as_str())
 7780                            && next_chars.starts_with(pair.end.as_str())
 7781                        {
 7782                            bracket_pair = Some(pair.clone());
 7783                            break;
 7784                        }
 7785                    }
 7786                    if let Some(pair) = bracket_pair {
 7787                        let start = snapshot.anchor_after(selection_head);
 7788                        let end = snapshot.anchor_after(selection_head);
 7789                        self.autoclose_regions.push(AutocloseRegion {
 7790                            selection_id: selection.id,
 7791                            range: start..end,
 7792                            pair,
 7793                        });
 7794                    }
 7795                }
 7796            }
 7797        }
 7798        Ok(())
 7799    }
 7800
 7801    pub fn move_to_next_snippet_tabstop(
 7802        &mut self,
 7803        window: &mut Window,
 7804        cx: &mut Context<Self>,
 7805    ) -> bool {
 7806        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7807    }
 7808
 7809    pub fn move_to_prev_snippet_tabstop(
 7810        &mut self,
 7811        window: &mut Window,
 7812        cx: &mut Context<Self>,
 7813    ) -> bool {
 7814        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7815    }
 7816
 7817    pub fn move_to_snippet_tabstop(
 7818        &mut self,
 7819        bias: Bias,
 7820        window: &mut Window,
 7821        cx: &mut Context<Self>,
 7822    ) -> bool {
 7823        if let Some(mut snippet) = self.snippet_stack.pop() {
 7824            match bias {
 7825                Bias::Left => {
 7826                    if snippet.active_index > 0 {
 7827                        snippet.active_index -= 1;
 7828                    } else {
 7829                        self.snippet_stack.push(snippet);
 7830                        return false;
 7831                    }
 7832                }
 7833                Bias::Right => {
 7834                    if snippet.active_index + 1 < snippet.ranges.len() {
 7835                        snippet.active_index += 1;
 7836                    } else {
 7837                        self.snippet_stack.push(snippet);
 7838                        return false;
 7839                    }
 7840                }
 7841            }
 7842            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7843                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7844                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7845                });
 7846
 7847                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7848                    if let Some(selection) = current_ranges.first() {
 7849                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7850                    }
 7851                }
 7852
 7853                // If snippet state is not at the last tabstop, push it back on the stack
 7854                if snippet.active_index + 1 < snippet.ranges.len() {
 7855                    self.snippet_stack.push(snippet);
 7856                }
 7857                return true;
 7858            }
 7859        }
 7860
 7861        false
 7862    }
 7863
 7864    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7865        self.transact(window, cx, |this, window, cx| {
 7866            this.select_all(&SelectAll, window, cx);
 7867            this.insert("", window, cx);
 7868        });
 7869    }
 7870
 7871    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7872        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 7873        self.transact(window, cx, |this, window, cx| {
 7874            this.select_autoclose_pair(window, cx);
 7875            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7876            if !this.linked_edit_ranges.is_empty() {
 7877                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7878                let snapshot = this.buffer.read(cx).snapshot(cx);
 7879
 7880                for selection in selections.iter() {
 7881                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7882                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7883                    if selection_start.buffer_id != selection_end.buffer_id {
 7884                        continue;
 7885                    }
 7886                    if let Some(ranges) =
 7887                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7888                    {
 7889                        for (buffer, entries) in ranges {
 7890                            linked_ranges.entry(buffer).or_default().extend(entries);
 7891                        }
 7892                    }
 7893                }
 7894            }
 7895
 7896            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7897            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7898            for selection in &mut selections {
 7899                if selection.is_empty() {
 7900                    let old_head = selection.head();
 7901                    let mut new_head =
 7902                        movement::left(&display_map, old_head.to_display_point(&display_map))
 7903                            .to_point(&display_map);
 7904                    if let Some((buffer, line_buffer_range)) = display_map
 7905                        .buffer_snapshot
 7906                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 7907                    {
 7908                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 7909                        let indent_len = match indent_size.kind {
 7910                            IndentKind::Space => {
 7911                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 7912                            }
 7913                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7914                        };
 7915                        if old_head.column <= indent_size.len && old_head.column > 0 {
 7916                            let indent_len = indent_len.get();
 7917                            new_head = cmp::min(
 7918                                new_head,
 7919                                MultiBufferPoint::new(
 7920                                    old_head.row,
 7921                                    ((old_head.column - 1) / indent_len) * indent_len,
 7922                                ),
 7923                            );
 7924                        }
 7925                    }
 7926
 7927                    selection.set_head(new_head, SelectionGoal::None);
 7928                }
 7929            }
 7930
 7931            this.signature_help_state.set_backspace_pressed(true);
 7932            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7933                s.select(selections)
 7934            });
 7935            this.insert("", window, cx);
 7936            let empty_str: Arc<str> = Arc::from("");
 7937            for (buffer, edits) in linked_ranges {
 7938                let snapshot = buffer.read(cx).snapshot();
 7939                use text::ToPoint as TP;
 7940
 7941                let edits = edits
 7942                    .into_iter()
 7943                    .map(|range| {
 7944                        let end_point = TP::to_point(&range.end, &snapshot);
 7945                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7946
 7947                        if end_point == start_point {
 7948                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7949                                .saturating_sub(1);
 7950                            start_point =
 7951                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7952                        };
 7953
 7954                        (start_point..end_point, empty_str.clone())
 7955                    })
 7956                    .sorted_by_key(|(range, _)| range.start)
 7957                    .collect::<Vec<_>>();
 7958                buffer.update(cx, |this, cx| {
 7959                    this.edit(edits, None, cx);
 7960                })
 7961            }
 7962            this.refresh_inline_completion(true, false, window, cx);
 7963            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7964        });
 7965    }
 7966
 7967    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7968        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 7969        self.transact(window, cx, |this, window, cx| {
 7970            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7971                s.move_with(|map, selection| {
 7972                    if selection.is_empty() {
 7973                        let cursor = movement::right(map, selection.head());
 7974                        selection.end = cursor;
 7975                        selection.reversed = true;
 7976                        selection.goal = SelectionGoal::None;
 7977                    }
 7978                })
 7979            });
 7980            this.insert("", window, cx);
 7981            this.refresh_inline_completion(true, false, window, cx);
 7982        });
 7983    }
 7984
 7985    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7986        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 7987        if self.move_to_prev_snippet_tabstop(window, cx) {
 7988            return;
 7989        }
 7990        self.outdent(&Outdent, window, cx);
 7991    }
 7992
 7993    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7994        if self.move_to_next_snippet_tabstop(window, cx) {
 7995            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 7996            return;
 7997        }
 7998        if self.read_only(cx) {
 7999            return;
 8000        }
 8001        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8002        let mut selections = self.selections.all_adjusted(cx);
 8003        let buffer = self.buffer.read(cx);
 8004        let snapshot = buffer.snapshot(cx);
 8005        let rows_iter = selections.iter().map(|s| s.head().row);
 8006        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8007
 8008        let mut edits = Vec::new();
 8009        let mut prev_edited_row = 0;
 8010        let mut row_delta = 0;
 8011        for selection in &mut selections {
 8012            if selection.start.row != prev_edited_row {
 8013                row_delta = 0;
 8014            }
 8015            prev_edited_row = selection.end.row;
 8016
 8017            // If the selection is non-empty, then increase the indentation of the selected lines.
 8018            if !selection.is_empty() {
 8019                row_delta =
 8020                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8021                continue;
 8022            }
 8023
 8024            // If the selection is empty and the cursor is in the leading whitespace before the
 8025            // suggested indentation, then auto-indent the line.
 8026            let cursor = selection.head();
 8027            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8028            if let Some(suggested_indent) =
 8029                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8030            {
 8031                if cursor.column < suggested_indent.len
 8032                    && cursor.column <= current_indent.len
 8033                    && current_indent.len <= suggested_indent.len
 8034                {
 8035                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8036                    selection.end = selection.start;
 8037                    if row_delta == 0 {
 8038                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8039                            cursor.row,
 8040                            current_indent,
 8041                            suggested_indent,
 8042                        ));
 8043                        row_delta = suggested_indent.len - current_indent.len;
 8044                    }
 8045                    continue;
 8046                }
 8047            }
 8048
 8049            // Otherwise, insert a hard or soft tab.
 8050            let settings = buffer.language_settings_at(cursor, cx);
 8051            let tab_size = if settings.hard_tabs {
 8052                IndentSize::tab()
 8053            } else {
 8054                let tab_size = settings.tab_size.get();
 8055                let char_column = snapshot
 8056                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8057                    .flat_map(str::chars)
 8058                    .count()
 8059                    + row_delta as usize;
 8060                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 8061                IndentSize::spaces(chars_to_next_tab_stop)
 8062            };
 8063            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8064            selection.end = selection.start;
 8065            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8066            row_delta += tab_size.len;
 8067        }
 8068
 8069        self.transact(window, cx, |this, window, cx| {
 8070            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8071            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8072                s.select(selections)
 8073            });
 8074            this.refresh_inline_completion(true, false, window, cx);
 8075        });
 8076    }
 8077
 8078    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8079        if self.read_only(cx) {
 8080            return;
 8081        }
 8082        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8083        let mut selections = self.selections.all::<Point>(cx);
 8084        let mut prev_edited_row = 0;
 8085        let mut row_delta = 0;
 8086        let mut edits = Vec::new();
 8087        let buffer = self.buffer.read(cx);
 8088        let snapshot = buffer.snapshot(cx);
 8089        for selection in &mut selections {
 8090            if selection.start.row != prev_edited_row {
 8091                row_delta = 0;
 8092            }
 8093            prev_edited_row = selection.end.row;
 8094
 8095            row_delta =
 8096                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8097        }
 8098
 8099        self.transact(window, cx, |this, window, cx| {
 8100            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8101            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8102                s.select(selections)
 8103            });
 8104        });
 8105    }
 8106
 8107    fn indent_selection(
 8108        buffer: &MultiBuffer,
 8109        snapshot: &MultiBufferSnapshot,
 8110        selection: &mut Selection<Point>,
 8111        edits: &mut Vec<(Range<Point>, String)>,
 8112        delta_for_start_row: u32,
 8113        cx: &App,
 8114    ) -> u32 {
 8115        let settings = buffer.language_settings_at(selection.start, cx);
 8116        let tab_size = settings.tab_size.get();
 8117        let indent_kind = if settings.hard_tabs {
 8118            IndentKind::Tab
 8119        } else {
 8120            IndentKind::Space
 8121        };
 8122        let mut start_row = selection.start.row;
 8123        let mut end_row = selection.end.row + 1;
 8124
 8125        // If a selection ends at the beginning of a line, don't indent
 8126        // that last line.
 8127        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8128            end_row -= 1;
 8129        }
 8130
 8131        // Avoid re-indenting a row that has already been indented by a
 8132        // previous selection, but still update this selection's column
 8133        // to reflect that indentation.
 8134        if delta_for_start_row > 0 {
 8135            start_row += 1;
 8136            selection.start.column += delta_for_start_row;
 8137            if selection.end.row == selection.start.row {
 8138                selection.end.column += delta_for_start_row;
 8139            }
 8140        }
 8141
 8142        let mut delta_for_end_row = 0;
 8143        let has_multiple_rows = start_row + 1 != end_row;
 8144        for row in start_row..end_row {
 8145            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8146            let indent_delta = match (current_indent.kind, indent_kind) {
 8147                (IndentKind::Space, IndentKind::Space) => {
 8148                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8149                    IndentSize::spaces(columns_to_next_tab_stop)
 8150                }
 8151                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8152                (_, IndentKind::Tab) => IndentSize::tab(),
 8153            };
 8154
 8155            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8156                0
 8157            } else {
 8158                selection.start.column
 8159            };
 8160            let row_start = Point::new(row, start);
 8161            edits.push((
 8162                row_start..row_start,
 8163                indent_delta.chars().collect::<String>(),
 8164            ));
 8165
 8166            // Update this selection's endpoints to reflect the indentation.
 8167            if row == selection.start.row {
 8168                selection.start.column += indent_delta.len;
 8169            }
 8170            if row == selection.end.row {
 8171                selection.end.column += indent_delta.len;
 8172                delta_for_end_row = indent_delta.len;
 8173            }
 8174        }
 8175
 8176        if selection.start.row == selection.end.row {
 8177            delta_for_start_row + delta_for_end_row
 8178        } else {
 8179            delta_for_end_row
 8180        }
 8181    }
 8182
 8183    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8184        if self.read_only(cx) {
 8185            return;
 8186        }
 8187        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8188        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8189        let selections = self.selections.all::<Point>(cx);
 8190        let mut deletion_ranges = Vec::new();
 8191        let mut last_outdent = None;
 8192        {
 8193            let buffer = self.buffer.read(cx);
 8194            let snapshot = buffer.snapshot(cx);
 8195            for selection in &selections {
 8196                let settings = buffer.language_settings_at(selection.start, cx);
 8197                let tab_size = settings.tab_size.get();
 8198                let mut rows = selection.spanned_rows(false, &display_map);
 8199
 8200                // Avoid re-outdenting a row that has already been outdented by a
 8201                // previous selection.
 8202                if let Some(last_row) = last_outdent {
 8203                    if last_row == rows.start {
 8204                        rows.start = rows.start.next_row();
 8205                    }
 8206                }
 8207                let has_multiple_rows = rows.len() > 1;
 8208                for row in rows.iter_rows() {
 8209                    let indent_size = snapshot.indent_size_for_line(row);
 8210                    if indent_size.len > 0 {
 8211                        let deletion_len = match indent_size.kind {
 8212                            IndentKind::Space => {
 8213                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8214                                if columns_to_prev_tab_stop == 0 {
 8215                                    tab_size
 8216                                } else {
 8217                                    columns_to_prev_tab_stop
 8218                                }
 8219                            }
 8220                            IndentKind::Tab => 1,
 8221                        };
 8222                        let start = if has_multiple_rows
 8223                            || deletion_len > selection.start.column
 8224                            || indent_size.len < selection.start.column
 8225                        {
 8226                            0
 8227                        } else {
 8228                            selection.start.column - deletion_len
 8229                        };
 8230                        deletion_ranges.push(
 8231                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8232                        );
 8233                        last_outdent = Some(row);
 8234                    }
 8235                }
 8236            }
 8237        }
 8238
 8239        self.transact(window, cx, |this, window, cx| {
 8240            this.buffer.update(cx, |buffer, cx| {
 8241                let empty_str: Arc<str> = Arc::default();
 8242                buffer.edit(
 8243                    deletion_ranges
 8244                        .into_iter()
 8245                        .map(|range| (range, empty_str.clone())),
 8246                    None,
 8247                    cx,
 8248                );
 8249            });
 8250            let selections = this.selections.all::<usize>(cx);
 8251            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8252                s.select(selections)
 8253            });
 8254        });
 8255    }
 8256
 8257    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8258        if self.read_only(cx) {
 8259            return;
 8260        }
 8261        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8262        let selections = self
 8263            .selections
 8264            .all::<usize>(cx)
 8265            .into_iter()
 8266            .map(|s| s.range());
 8267
 8268        self.transact(window, cx, |this, window, cx| {
 8269            this.buffer.update(cx, |buffer, cx| {
 8270                buffer.autoindent_ranges(selections, cx);
 8271            });
 8272            let selections = this.selections.all::<usize>(cx);
 8273            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8274                s.select(selections)
 8275            });
 8276        });
 8277    }
 8278
 8279    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8280        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8281        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8282        let selections = self.selections.all::<Point>(cx);
 8283
 8284        let mut new_cursors = Vec::new();
 8285        let mut edit_ranges = Vec::new();
 8286        let mut selections = selections.iter().peekable();
 8287        while let Some(selection) = selections.next() {
 8288            let mut rows = selection.spanned_rows(false, &display_map);
 8289            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8290
 8291            // Accumulate contiguous regions of rows that we want to delete.
 8292            while let Some(next_selection) = selections.peek() {
 8293                let next_rows = next_selection.spanned_rows(false, &display_map);
 8294                if next_rows.start <= rows.end {
 8295                    rows.end = next_rows.end;
 8296                    selections.next().unwrap();
 8297                } else {
 8298                    break;
 8299                }
 8300            }
 8301
 8302            let buffer = &display_map.buffer_snapshot;
 8303            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8304            let edit_end;
 8305            let cursor_buffer_row;
 8306            if buffer.max_point().row >= rows.end.0 {
 8307                // If there's a line after the range, delete the \n from the end of the row range
 8308                // and position the cursor on the next line.
 8309                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8310                cursor_buffer_row = rows.end;
 8311            } else {
 8312                // If there isn't a line after the range, delete the \n from the line before the
 8313                // start of the row range and position the cursor there.
 8314                edit_start = edit_start.saturating_sub(1);
 8315                edit_end = buffer.len();
 8316                cursor_buffer_row = rows.start.previous_row();
 8317            }
 8318
 8319            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8320            *cursor.column_mut() =
 8321                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8322
 8323            new_cursors.push((
 8324                selection.id,
 8325                buffer.anchor_after(cursor.to_point(&display_map)),
 8326            ));
 8327            edit_ranges.push(edit_start..edit_end);
 8328        }
 8329
 8330        self.transact(window, cx, |this, window, cx| {
 8331            let buffer = this.buffer.update(cx, |buffer, cx| {
 8332                let empty_str: Arc<str> = Arc::default();
 8333                buffer.edit(
 8334                    edit_ranges
 8335                        .into_iter()
 8336                        .map(|range| (range, empty_str.clone())),
 8337                    None,
 8338                    cx,
 8339                );
 8340                buffer.snapshot(cx)
 8341            });
 8342            let new_selections = new_cursors
 8343                .into_iter()
 8344                .map(|(id, cursor)| {
 8345                    let cursor = cursor.to_point(&buffer);
 8346                    Selection {
 8347                        id,
 8348                        start: cursor,
 8349                        end: cursor,
 8350                        reversed: false,
 8351                        goal: SelectionGoal::None,
 8352                    }
 8353                })
 8354                .collect();
 8355
 8356            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8357                s.select(new_selections);
 8358            });
 8359        });
 8360    }
 8361
 8362    pub fn join_lines_impl(
 8363        &mut self,
 8364        insert_whitespace: bool,
 8365        window: &mut Window,
 8366        cx: &mut Context<Self>,
 8367    ) {
 8368        if self.read_only(cx) {
 8369            return;
 8370        }
 8371        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8372        for selection in self.selections.all::<Point>(cx) {
 8373            let start = MultiBufferRow(selection.start.row);
 8374            // Treat single line selections as if they include the next line. Otherwise this action
 8375            // would do nothing for single line selections individual cursors.
 8376            let end = if selection.start.row == selection.end.row {
 8377                MultiBufferRow(selection.start.row + 1)
 8378            } else {
 8379                MultiBufferRow(selection.end.row)
 8380            };
 8381
 8382            if let Some(last_row_range) = row_ranges.last_mut() {
 8383                if start <= last_row_range.end {
 8384                    last_row_range.end = end;
 8385                    continue;
 8386                }
 8387            }
 8388            row_ranges.push(start..end);
 8389        }
 8390
 8391        let snapshot = self.buffer.read(cx).snapshot(cx);
 8392        let mut cursor_positions = Vec::new();
 8393        for row_range in &row_ranges {
 8394            let anchor = snapshot.anchor_before(Point::new(
 8395                row_range.end.previous_row().0,
 8396                snapshot.line_len(row_range.end.previous_row()),
 8397            ));
 8398            cursor_positions.push(anchor..anchor);
 8399        }
 8400
 8401        self.transact(window, cx, |this, window, cx| {
 8402            for row_range in row_ranges.into_iter().rev() {
 8403                for row in row_range.iter_rows().rev() {
 8404                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8405                    let next_line_row = row.next_row();
 8406                    let indent = snapshot.indent_size_for_line(next_line_row);
 8407                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8408
 8409                    let replace =
 8410                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8411                            " "
 8412                        } else {
 8413                            ""
 8414                        };
 8415
 8416                    this.buffer.update(cx, |buffer, cx| {
 8417                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8418                    });
 8419                }
 8420            }
 8421
 8422            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8423                s.select_anchor_ranges(cursor_positions)
 8424            });
 8425        });
 8426    }
 8427
 8428    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8429        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8430        self.join_lines_impl(true, window, cx);
 8431    }
 8432
 8433    pub fn sort_lines_case_sensitive(
 8434        &mut self,
 8435        _: &SortLinesCaseSensitive,
 8436        window: &mut Window,
 8437        cx: &mut Context<Self>,
 8438    ) {
 8439        self.manipulate_lines(window, cx, |lines| lines.sort())
 8440    }
 8441
 8442    pub fn sort_lines_case_insensitive(
 8443        &mut self,
 8444        _: &SortLinesCaseInsensitive,
 8445        window: &mut Window,
 8446        cx: &mut Context<Self>,
 8447    ) {
 8448        self.manipulate_lines(window, cx, |lines| {
 8449            lines.sort_by_key(|line| line.to_lowercase())
 8450        })
 8451    }
 8452
 8453    pub fn unique_lines_case_insensitive(
 8454        &mut self,
 8455        _: &UniqueLinesCaseInsensitive,
 8456        window: &mut Window,
 8457        cx: &mut Context<Self>,
 8458    ) {
 8459        self.manipulate_lines(window, cx, |lines| {
 8460            let mut seen = HashSet::default();
 8461            lines.retain(|line| seen.insert(line.to_lowercase()));
 8462        })
 8463    }
 8464
 8465    pub fn unique_lines_case_sensitive(
 8466        &mut self,
 8467        _: &UniqueLinesCaseSensitive,
 8468        window: &mut Window,
 8469        cx: &mut Context<Self>,
 8470    ) {
 8471        self.manipulate_lines(window, cx, |lines| {
 8472            let mut seen = HashSet::default();
 8473            lines.retain(|line| seen.insert(*line));
 8474        })
 8475    }
 8476
 8477    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8478        let Some(project) = self.project.clone() else {
 8479            return;
 8480        };
 8481        self.reload(project, window, cx)
 8482            .detach_and_notify_err(window, cx);
 8483    }
 8484
 8485    pub fn restore_file(
 8486        &mut self,
 8487        _: &::git::RestoreFile,
 8488        window: &mut Window,
 8489        cx: &mut Context<Self>,
 8490    ) {
 8491        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8492        let mut buffer_ids = HashSet::default();
 8493        let snapshot = self.buffer().read(cx).snapshot(cx);
 8494        for selection in self.selections.all::<usize>(cx) {
 8495            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8496        }
 8497
 8498        let buffer = self.buffer().read(cx);
 8499        let ranges = buffer_ids
 8500            .into_iter()
 8501            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8502            .collect::<Vec<_>>();
 8503
 8504        self.restore_hunks_in_ranges(ranges, window, cx);
 8505    }
 8506
 8507    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8508        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8509        let selections = self
 8510            .selections
 8511            .all(cx)
 8512            .into_iter()
 8513            .map(|s| s.range())
 8514            .collect();
 8515        self.restore_hunks_in_ranges(selections, window, cx);
 8516    }
 8517
 8518    pub fn restore_hunks_in_ranges(
 8519        &mut self,
 8520        ranges: Vec<Range<Point>>,
 8521        window: &mut Window,
 8522        cx: &mut Context<Editor>,
 8523    ) {
 8524        let mut revert_changes = HashMap::default();
 8525        let chunk_by = self
 8526            .snapshot(window, cx)
 8527            .hunks_for_ranges(ranges)
 8528            .into_iter()
 8529            .chunk_by(|hunk| hunk.buffer_id);
 8530        for (buffer_id, hunks) in &chunk_by {
 8531            let hunks = hunks.collect::<Vec<_>>();
 8532            for hunk in &hunks {
 8533                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8534            }
 8535            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8536        }
 8537        drop(chunk_by);
 8538        if !revert_changes.is_empty() {
 8539            self.transact(window, cx, |editor, window, cx| {
 8540                editor.restore(revert_changes, window, cx);
 8541            });
 8542        }
 8543    }
 8544
 8545    pub fn open_active_item_in_terminal(
 8546        &mut self,
 8547        _: &OpenInTerminal,
 8548        window: &mut Window,
 8549        cx: &mut Context<Self>,
 8550    ) {
 8551        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8552            let project_path = buffer.read(cx).project_path(cx)?;
 8553            let project = self.project.as_ref()?.read(cx);
 8554            let entry = project.entry_for_path(&project_path, cx)?;
 8555            let parent = match &entry.canonical_path {
 8556                Some(canonical_path) => canonical_path.to_path_buf(),
 8557                None => project.absolute_path(&project_path, cx)?,
 8558            }
 8559            .parent()?
 8560            .to_path_buf();
 8561            Some(parent)
 8562        }) {
 8563            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8564        }
 8565    }
 8566
 8567    fn set_breakpoint_context_menu(
 8568        &mut self,
 8569        display_row: DisplayRow,
 8570        position: Option<Anchor>,
 8571        clicked_point: gpui::Point<Pixels>,
 8572        window: &mut Window,
 8573        cx: &mut Context<Self>,
 8574    ) {
 8575        if !cx.has_flag::<Debugger>() {
 8576            return;
 8577        }
 8578        let source = self
 8579            .buffer
 8580            .read(cx)
 8581            .snapshot(cx)
 8582            .anchor_before(Point::new(display_row.0, 0u32));
 8583
 8584        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8585
 8586        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8587            self,
 8588            source,
 8589            clicked_point,
 8590            context_menu,
 8591            window,
 8592            cx,
 8593        );
 8594    }
 8595
 8596    fn add_edit_breakpoint_block(
 8597        &mut self,
 8598        anchor: Anchor,
 8599        breakpoint: &Breakpoint,
 8600        window: &mut Window,
 8601        cx: &mut Context<Self>,
 8602    ) {
 8603        let weak_editor = cx.weak_entity();
 8604        let bp_prompt = cx.new(|cx| {
 8605            BreakpointPromptEditor::new(weak_editor, anchor, breakpoint.clone(), window, cx)
 8606        });
 8607
 8608        let height = bp_prompt.update(cx, |this, cx| {
 8609            this.prompt
 8610                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8611        });
 8612        let cloned_prompt = bp_prompt.clone();
 8613        let blocks = vec![BlockProperties {
 8614            style: BlockStyle::Sticky,
 8615            placement: BlockPlacement::Above(anchor),
 8616            height,
 8617            render: Arc::new(move |cx| {
 8618                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8619                cloned_prompt.clone().into_any_element()
 8620            }),
 8621            priority: 0,
 8622        }];
 8623
 8624        let focus_handle = bp_prompt.focus_handle(cx);
 8625        window.focus(&focus_handle);
 8626
 8627        let block_ids = self.insert_blocks(blocks, None, cx);
 8628        bp_prompt.update(cx, |prompt, _| {
 8629            prompt.add_block_ids(block_ids);
 8630        });
 8631    }
 8632
 8633    fn breakpoint_at_cursor_head(
 8634        &self,
 8635        window: &mut Window,
 8636        cx: &mut Context<Self>,
 8637    ) -> Option<(Anchor, Breakpoint)> {
 8638        let cursor_position: Point = self.selections.newest(cx).head();
 8639        self.breakpoint_at_row(cursor_position.row, window, cx)
 8640    }
 8641
 8642    pub(crate) fn breakpoint_at_row(
 8643        &self,
 8644        row: u32,
 8645        window: &mut Window,
 8646        cx: &mut Context<Self>,
 8647    ) -> Option<(Anchor, Breakpoint)> {
 8648        let snapshot = self.snapshot(window, cx);
 8649        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8650
 8651        let project = self.project.clone()?;
 8652
 8653        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8654            snapshot
 8655                .buffer_snapshot
 8656                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8657        })?;
 8658
 8659        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8660        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8661        let buffer_snapshot = buffer.read(cx).snapshot();
 8662
 8663        let row = buffer_snapshot
 8664            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8665            .row;
 8666
 8667        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8668        let anchor_end = snapshot
 8669            .buffer_snapshot
 8670            .anchor_after(Point::new(row, line_len));
 8671
 8672        let bp = self
 8673            .breakpoint_store
 8674            .as_ref()?
 8675            .read_with(cx, |breakpoint_store, cx| {
 8676                breakpoint_store
 8677                    .breakpoints(
 8678                        &buffer,
 8679                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8680                        &buffer_snapshot,
 8681                        cx,
 8682                    )
 8683                    .next()
 8684                    .and_then(|(anchor, bp)| {
 8685                        let breakpoint_row = buffer_snapshot
 8686                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8687                            .row;
 8688
 8689                        if breakpoint_row == row {
 8690                            snapshot
 8691                                .buffer_snapshot
 8692                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8693                                .map(|anchor| (anchor, bp.clone()))
 8694                        } else {
 8695                            None
 8696                        }
 8697                    })
 8698            });
 8699        bp
 8700    }
 8701
 8702    pub fn edit_log_breakpoint(
 8703        &mut self,
 8704        _: &EditLogBreakpoint,
 8705        window: &mut Window,
 8706        cx: &mut Context<Self>,
 8707    ) {
 8708        let (anchor, bp) = self
 8709            .breakpoint_at_cursor_head(window, cx)
 8710            .unwrap_or_else(|| {
 8711                let cursor_position: Point = self.selections.newest(cx).head();
 8712
 8713                let breakpoint_position = self
 8714                    .snapshot(window, cx)
 8715                    .display_snapshot
 8716                    .buffer_snapshot
 8717                    .anchor_after(Point::new(cursor_position.row, 0));
 8718
 8719                (
 8720                    breakpoint_position,
 8721                    Breakpoint {
 8722                        message: None,
 8723                        state: BreakpointState::Enabled,
 8724                    },
 8725                )
 8726            });
 8727
 8728        self.add_edit_breakpoint_block(anchor, &bp, window, cx);
 8729    }
 8730
 8731    pub fn enable_breakpoint(
 8732        &mut self,
 8733        _: &crate::actions::EnableBreakpoint,
 8734        window: &mut Window,
 8735        cx: &mut Context<Self>,
 8736    ) {
 8737        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8738            if breakpoint.is_disabled() {
 8739                self.edit_breakpoint_at_anchor(
 8740                    anchor,
 8741                    breakpoint,
 8742                    BreakpointEditAction::InvertState,
 8743                    cx,
 8744                );
 8745            }
 8746        }
 8747    }
 8748
 8749    pub fn disable_breakpoint(
 8750        &mut self,
 8751        _: &crate::actions::DisableBreakpoint,
 8752        window: &mut Window,
 8753        cx: &mut Context<Self>,
 8754    ) {
 8755        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8756            if breakpoint.is_enabled() {
 8757                self.edit_breakpoint_at_anchor(
 8758                    anchor,
 8759                    breakpoint,
 8760                    BreakpointEditAction::InvertState,
 8761                    cx,
 8762                );
 8763            }
 8764        }
 8765    }
 8766
 8767    pub fn toggle_breakpoint(
 8768        &mut self,
 8769        _: &crate::actions::ToggleBreakpoint,
 8770        window: &mut Window,
 8771        cx: &mut Context<Self>,
 8772    ) {
 8773        let edit_action = BreakpointEditAction::Toggle;
 8774
 8775        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8776            self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
 8777        } else {
 8778            let cursor_position: Point = self.selections.newest(cx).head();
 8779
 8780            let breakpoint_position = self
 8781                .snapshot(window, cx)
 8782                .display_snapshot
 8783                .buffer_snapshot
 8784                .anchor_after(Point::new(cursor_position.row, 0));
 8785
 8786            self.edit_breakpoint_at_anchor(
 8787                breakpoint_position,
 8788                Breakpoint::new_standard(),
 8789                edit_action,
 8790                cx,
 8791            );
 8792        }
 8793    }
 8794
 8795    pub fn edit_breakpoint_at_anchor(
 8796        &mut self,
 8797        breakpoint_position: Anchor,
 8798        breakpoint: Breakpoint,
 8799        edit_action: BreakpointEditAction,
 8800        cx: &mut Context<Self>,
 8801    ) {
 8802        let Some(breakpoint_store) = &self.breakpoint_store else {
 8803            return;
 8804        };
 8805
 8806        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 8807            if breakpoint_position == Anchor::min() {
 8808                self.buffer()
 8809                    .read(cx)
 8810                    .excerpt_buffer_ids()
 8811                    .into_iter()
 8812                    .next()
 8813            } else {
 8814                None
 8815            }
 8816        }) else {
 8817            return;
 8818        };
 8819
 8820        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 8821            return;
 8822        };
 8823
 8824        breakpoint_store.update(cx, |breakpoint_store, cx| {
 8825            breakpoint_store.toggle_breakpoint(
 8826                buffer,
 8827                (breakpoint_position.text_anchor, breakpoint),
 8828                edit_action,
 8829                cx,
 8830            );
 8831        });
 8832
 8833        cx.notify();
 8834    }
 8835
 8836    #[cfg(any(test, feature = "test-support"))]
 8837    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 8838        self.breakpoint_store.clone()
 8839    }
 8840
 8841    pub fn prepare_restore_change(
 8842        &self,
 8843        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 8844        hunk: &MultiBufferDiffHunk,
 8845        cx: &mut App,
 8846    ) -> Option<()> {
 8847        if hunk.is_created_file() {
 8848            return None;
 8849        }
 8850        let buffer = self.buffer.read(cx);
 8851        let diff = buffer.diff_for(hunk.buffer_id)?;
 8852        let buffer = buffer.buffer(hunk.buffer_id)?;
 8853        let buffer = buffer.read(cx);
 8854        let original_text = diff
 8855            .read(cx)
 8856            .base_text()
 8857            .as_rope()
 8858            .slice(hunk.diff_base_byte_range.clone());
 8859        let buffer_snapshot = buffer.snapshot();
 8860        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 8861        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 8862            probe
 8863                .0
 8864                .start
 8865                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 8866                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 8867        }) {
 8868            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 8869            Some(())
 8870        } else {
 8871            None
 8872        }
 8873    }
 8874
 8875    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 8876        self.manipulate_lines(window, cx, |lines| lines.reverse())
 8877    }
 8878
 8879    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 8880        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 8881    }
 8882
 8883    fn manipulate_lines<Fn>(
 8884        &mut self,
 8885        window: &mut Window,
 8886        cx: &mut Context<Self>,
 8887        mut callback: Fn,
 8888    ) where
 8889        Fn: FnMut(&mut Vec<&str>),
 8890    {
 8891        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8892
 8893        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8894        let buffer = self.buffer.read(cx).snapshot(cx);
 8895
 8896        let mut edits = Vec::new();
 8897
 8898        let selections = self.selections.all::<Point>(cx);
 8899        let mut selections = selections.iter().peekable();
 8900        let mut contiguous_row_selections = Vec::new();
 8901        let mut new_selections = Vec::new();
 8902        let mut added_lines = 0;
 8903        let mut removed_lines = 0;
 8904
 8905        while let Some(selection) = selections.next() {
 8906            let (start_row, end_row) = consume_contiguous_rows(
 8907                &mut contiguous_row_selections,
 8908                selection,
 8909                &display_map,
 8910                &mut selections,
 8911            );
 8912
 8913            let start_point = Point::new(start_row.0, 0);
 8914            let end_point = Point::new(
 8915                end_row.previous_row().0,
 8916                buffer.line_len(end_row.previous_row()),
 8917            );
 8918            let text = buffer
 8919                .text_for_range(start_point..end_point)
 8920                .collect::<String>();
 8921
 8922            let mut lines = text.split('\n').collect_vec();
 8923
 8924            let lines_before = lines.len();
 8925            callback(&mut lines);
 8926            let lines_after = lines.len();
 8927
 8928            edits.push((start_point..end_point, lines.join("\n")));
 8929
 8930            // Selections must change based on added and removed line count
 8931            let start_row =
 8932                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 8933            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 8934            new_selections.push(Selection {
 8935                id: selection.id,
 8936                start: start_row,
 8937                end: end_row,
 8938                goal: SelectionGoal::None,
 8939                reversed: selection.reversed,
 8940            });
 8941
 8942            if lines_after > lines_before {
 8943                added_lines += lines_after - lines_before;
 8944            } else if lines_before > lines_after {
 8945                removed_lines += lines_before - lines_after;
 8946            }
 8947        }
 8948
 8949        self.transact(window, cx, |this, window, cx| {
 8950            let buffer = this.buffer.update(cx, |buffer, cx| {
 8951                buffer.edit(edits, None, cx);
 8952                buffer.snapshot(cx)
 8953            });
 8954
 8955            // Recalculate offsets on newly edited buffer
 8956            let new_selections = new_selections
 8957                .iter()
 8958                .map(|s| {
 8959                    let start_point = Point::new(s.start.0, 0);
 8960                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 8961                    Selection {
 8962                        id: s.id,
 8963                        start: buffer.point_to_offset(start_point),
 8964                        end: buffer.point_to_offset(end_point),
 8965                        goal: s.goal,
 8966                        reversed: s.reversed,
 8967                    }
 8968                })
 8969                .collect();
 8970
 8971            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8972                s.select(new_selections);
 8973            });
 8974
 8975            this.request_autoscroll(Autoscroll::fit(), cx);
 8976        });
 8977    }
 8978
 8979    pub fn convert_to_upper_case(
 8980        &mut self,
 8981        _: &ConvertToUpperCase,
 8982        window: &mut Window,
 8983        cx: &mut Context<Self>,
 8984    ) {
 8985        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8986    }
 8987
 8988    pub fn convert_to_lower_case(
 8989        &mut self,
 8990        _: &ConvertToLowerCase,
 8991        window: &mut Window,
 8992        cx: &mut Context<Self>,
 8993    ) {
 8994        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8995    }
 8996
 8997    pub fn convert_to_title_case(
 8998        &mut self,
 8999        _: &ConvertToTitleCase,
 9000        window: &mut Window,
 9001        cx: &mut Context<Self>,
 9002    ) {
 9003        self.manipulate_text(window, cx, |text| {
 9004            text.split('\n')
 9005                .map(|line| line.to_case(Case::Title))
 9006                .join("\n")
 9007        })
 9008    }
 9009
 9010    pub fn convert_to_snake_case(
 9011        &mut self,
 9012        _: &ConvertToSnakeCase,
 9013        window: &mut Window,
 9014        cx: &mut Context<Self>,
 9015    ) {
 9016        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9017    }
 9018
 9019    pub fn convert_to_kebab_case(
 9020        &mut self,
 9021        _: &ConvertToKebabCase,
 9022        window: &mut Window,
 9023        cx: &mut Context<Self>,
 9024    ) {
 9025        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9026    }
 9027
 9028    pub fn convert_to_upper_camel_case(
 9029        &mut self,
 9030        _: &ConvertToUpperCamelCase,
 9031        window: &mut Window,
 9032        cx: &mut Context<Self>,
 9033    ) {
 9034        self.manipulate_text(window, cx, |text| {
 9035            text.split('\n')
 9036                .map(|line| line.to_case(Case::UpperCamel))
 9037                .join("\n")
 9038        })
 9039    }
 9040
 9041    pub fn convert_to_lower_camel_case(
 9042        &mut self,
 9043        _: &ConvertToLowerCamelCase,
 9044        window: &mut Window,
 9045        cx: &mut Context<Self>,
 9046    ) {
 9047        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9048    }
 9049
 9050    pub fn convert_to_opposite_case(
 9051        &mut self,
 9052        _: &ConvertToOppositeCase,
 9053        window: &mut Window,
 9054        cx: &mut Context<Self>,
 9055    ) {
 9056        self.manipulate_text(window, cx, |text| {
 9057            text.chars()
 9058                .fold(String::with_capacity(text.len()), |mut t, c| {
 9059                    if c.is_uppercase() {
 9060                        t.extend(c.to_lowercase());
 9061                    } else {
 9062                        t.extend(c.to_uppercase());
 9063                    }
 9064                    t
 9065                })
 9066        })
 9067    }
 9068
 9069    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9070    where
 9071        Fn: FnMut(&str) -> String,
 9072    {
 9073        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9074        let buffer = self.buffer.read(cx).snapshot(cx);
 9075
 9076        let mut new_selections = Vec::new();
 9077        let mut edits = Vec::new();
 9078        let mut selection_adjustment = 0i32;
 9079
 9080        for selection in self.selections.all::<usize>(cx) {
 9081            let selection_is_empty = selection.is_empty();
 9082
 9083            let (start, end) = if selection_is_empty {
 9084                let word_range = movement::surrounding_word(
 9085                    &display_map,
 9086                    selection.start.to_display_point(&display_map),
 9087                );
 9088                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9089                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9090                (start, end)
 9091            } else {
 9092                (selection.start, selection.end)
 9093            };
 9094
 9095            let text = buffer.text_for_range(start..end).collect::<String>();
 9096            let old_length = text.len() as i32;
 9097            let text = callback(&text);
 9098
 9099            new_selections.push(Selection {
 9100                start: (start as i32 - selection_adjustment) as usize,
 9101                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9102                goal: SelectionGoal::None,
 9103                ..selection
 9104            });
 9105
 9106            selection_adjustment += old_length - text.len() as i32;
 9107
 9108            edits.push((start..end, text));
 9109        }
 9110
 9111        self.transact(window, cx, |this, window, cx| {
 9112            this.buffer.update(cx, |buffer, cx| {
 9113                buffer.edit(edits, None, cx);
 9114            });
 9115
 9116            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9117                s.select(new_selections);
 9118            });
 9119
 9120            this.request_autoscroll(Autoscroll::fit(), cx);
 9121        });
 9122    }
 9123
 9124    pub fn duplicate(
 9125        &mut self,
 9126        upwards: bool,
 9127        whole_lines: bool,
 9128        window: &mut Window,
 9129        cx: &mut Context<Self>,
 9130    ) {
 9131        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9132
 9133        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9134        let buffer = &display_map.buffer_snapshot;
 9135        let selections = self.selections.all::<Point>(cx);
 9136
 9137        let mut edits = Vec::new();
 9138        let mut selections_iter = selections.iter().peekable();
 9139        while let Some(selection) = selections_iter.next() {
 9140            let mut rows = selection.spanned_rows(false, &display_map);
 9141            // duplicate line-wise
 9142            if whole_lines || selection.start == selection.end {
 9143                // Avoid duplicating the same lines twice.
 9144                while let Some(next_selection) = selections_iter.peek() {
 9145                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9146                    if next_rows.start < rows.end {
 9147                        rows.end = next_rows.end;
 9148                        selections_iter.next().unwrap();
 9149                    } else {
 9150                        break;
 9151                    }
 9152                }
 9153
 9154                // Copy the text from the selected row region and splice it either at the start
 9155                // or end of the region.
 9156                let start = Point::new(rows.start.0, 0);
 9157                let end = Point::new(
 9158                    rows.end.previous_row().0,
 9159                    buffer.line_len(rows.end.previous_row()),
 9160                );
 9161                let text = buffer
 9162                    .text_for_range(start..end)
 9163                    .chain(Some("\n"))
 9164                    .collect::<String>();
 9165                let insert_location = if upwards {
 9166                    Point::new(rows.end.0, 0)
 9167                } else {
 9168                    start
 9169                };
 9170                edits.push((insert_location..insert_location, text));
 9171            } else {
 9172                // duplicate character-wise
 9173                let start = selection.start;
 9174                let end = selection.end;
 9175                let text = buffer.text_for_range(start..end).collect::<String>();
 9176                edits.push((selection.end..selection.end, text));
 9177            }
 9178        }
 9179
 9180        self.transact(window, cx, |this, _, cx| {
 9181            this.buffer.update(cx, |buffer, cx| {
 9182                buffer.edit(edits, None, cx);
 9183            });
 9184
 9185            this.request_autoscroll(Autoscroll::fit(), cx);
 9186        });
 9187    }
 9188
 9189    pub fn duplicate_line_up(
 9190        &mut self,
 9191        _: &DuplicateLineUp,
 9192        window: &mut Window,
 9193        cx: &mut Context<Self>,
 9194    ) {
 9195        self.duplicate(true, true, window, cx);
 9196    }
 9197
 9198    pub fn duplicate_line_down(
 9199        &mut self,
 9200        _: &DuplicateLineDown,
 9201        window: &mut Window,
 9202        cx: &mut Context<Self>,
 9203    ) {
 9204        self.duplicate(false, true, window, cx);
 9205    }
 9206
 9207    pub fn duplicate_selection(
 9208        &mut self,
 9209        _: &DuplicateSelection,
 9210        window: &mut Window,
 9211        cx: &mut Context<Self>,
 9212    ) {
 9213        self.duplicate(false, false, window, cx);
 9214    }
 9215
 9216    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9217        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9218
 9219        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9220        let buffer = self.buffer.read(cx).snapshot(cx);
 9221
 9222        let mut edits = Vec::new();
 9223        let mut unfold_ranges = Vec::new();
 9224        let mut refold_creases = Vec::new();
 9225
 9226        let selections = self.selections.all::<Point>(cx);
 9227        let mut selections = selections.iter().peekable();
 9228        let mut contiguous_row_selections = Vec::new();
 9229        let mut new_selections = Vec::new();
 9230
 9231        while let Some(selection) = selections.next() {
 9232            // Find all the selections that span a contiguous row range
 9233            let (start_row, end_row) = consume_contiguous_rows(
 9234                &mut contiguous_row_selections,
 9235                selection,
 9236                &display_map,
 9237                &mut selections,
 9238            );
 9239
 9240            // Move the text spanned by the row range to be before the line preceding the row range
 9241            if start_row.0 > 0 {
 9242                let range_to_move = Point::new(
 9243                    start_row.previous_row().0,
 9244                    buffer.line_len(start_row.previous_row()),
 9245                )
 9246                    ..Point::new(
 9247                        end_row.previous_row().0,
 9248                        buffer.line_len(end_row.previous_row()),
 9249                    );
 9250                let insertion_point = display_map
 9251                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9252                    .0;
 9253
 9254                // Don't move lines across excerpts
 9255                if buffer
 9256                    .excerpt_containing(insertion_point..range_to_move.end)
 9257                    .is_some()
 9258                {
 9259                    let text = buffer
 9260                        .text_for_range(range_to_move.clone())
 9261                        .flat_map(|s| s.chars())
 9262                        .skip(1)
 9263                        .chain(['\n'])
 9264                        .collect::<String>();
 9265
 9266                    edits.push((
 9267                        buffer.anchor_after(range_to_move.start)
 9268                            ..buffer.anchor_before(range_to_move.end),
 9269                        String::new(),
 9270                    ));
 9271                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9272                    edits.push((insertion_anchor..insertion_anchor, text));
 9273
 9274                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9275
 9276                    // Move selections up
 9277                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9278                        |mut selection| {
 9279                            selection.start.row -= row_delta;
 9280                            selection.end.row -= row_delta;
 9281                            selection
 9282                        },
 9283                    ));
 9284
 9285                    // Move folds up
 9286                    unfold_ranges.push(range_to_move.clone());
 9287                    for fold in display_map.folds_in_range(
 9288                        buffer.anchor_before(range_to_move.start)
 9289                            ..buffer.anchor_after(range_to_move.end),
 9290                    ) {
 9291                        let mut start = fold.range.start.to_point(&buffer);
 9292                        let mut end = fold.range.end.to_point(&buffer);
 9293                        start.row -= row_delta;
 9294                        end.row -= row_delta;
 9295                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9296                    }
 9297                }
 9298            }
 9299
 9300            // If we didn't move line(s), preserve the existing selections
 9301            new_selections.append(&mut contiguous_row_selections);
 9302        }
 9303
 9304        self.transact(window, cx, |this, window, cx| {
 9305            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9306            this.buffer.update(cx, |buffer, cx| {
 9307                for (range, text) in edits {
 9308                    buffer.edit([(range, text)], None, cx);
 9309                }
 9310            });
 9311            this.fold_creases(refold_creases, true, window, cx);
 9312            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9313                s.select(new_selections);
 9314            })
 9315        });
 9316    }
 9317
 9318    pub fn move_line_down(
 9319        &mut self,
 9320        _: &MoveLineDown,
 9321        window: &mut Window,
 9322        cx: &mut Context<Self>,
 9323    ) {
 9324        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9325
 9326        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9327        let buffer = self.buffer.read(cx).snapshot(cx);
 9328
 9329        let mut edits = Vec::new();
 9330        let mut unfold_ranges = Vec::new();
 9331        let mut refold_creases = Vec::new();
 9332
 9333        let selections = self.selections.all::<Point>(cx);
 9334        let mut selections = selections.iter().peekable();
 9335        let mut contiguous_row_selections = Vec::new();
 9336        let mut new_selections = Vec::new();
 9337
 9338        while let Some(selection) = selections.next() {
 9339            // Find all the selections that span a contiguous row range
 9340            let (start_row, end_row) = consume_contiguous_rows(
 9341                &mut contiguous_row_selections,
 9342                selection,
 9343                &display_map,
 9344                &mut selections,
 9345            );
 9346
 9347            // Move the text spanned by the row range to be after the last line of the row range
 9348            if end_row.0 <= buffer.max_point().row {
 9349                let range_to_move =
 9350                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9351                let insertion_point = display_map
 9352                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9353                    .0;
 9354
 9355                // Don't move lines across excerpt boundaries
 9356                if buffer
 9357                    .excerpt_containing(range_to_move.start..insertion_point)
 9358                    .is_some()
 9359                {
 9360                    let mut text = String::from("\n");
 9361                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9362                    text.pop(); // Drop trailing newline
 9363                    edits.push((
 9364                        buffer.anchor_after(range_to_move.start)
 9365                            ..buffer.anchor_before(range_to_move.end),
 9366                        String::new(),
 9367                    ));
 9368                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9369                    edits.push((insertion_anchor..insertion_anchor, text));
 9370
 9371                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9372
 9373                    // Move selections down
 9374                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9375                        |mut selection| {
 9376                            selection.start.row += row_delta;
 9377                            selection.end.row += row_delta;
 9378                            selection
 9379                        },
 9380                    ));
 9381
 9382                    // Move folds down
 9383                    unfold_ranges.push(range_to_move.clone());
 9384                    for fold in display_map.folds_in_range(
 9385                        buffer.anchor_before(range_to_move.start)
 9386                            ..buffer.anchor_after(range_to_move.end),
 9387                    ) {
 9388                        let mut start = fold.range.start.to_point(&buffer);
 9389                        let mut end = fold.range.end.to_point(&buffer);
 9390                        start.row += row_delta;
 9391                        end.row += row_delta;
 9392                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9393                    }
 9394                }
 9395            }
 9396
 9397            // If we didn't move line(s), preserve the existing selections
 9398            new_selections.append(&mut contiguous_row_selections);
 9399        }
 9400
 9401        self.transact(window, cx, |this, window, cx| {
 9402            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9403            this.buffer.update(cx, |buffer, cx| {
 9404                for (range, text) in edits {
 9405                    buffer.edit([(range, text)], None, cx);
 9406                }
 9407            });
 9408            this.fold_creases(refold_creases, true, window, cx);
 9409            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9410                s.select(new_selections)
 9411            });
 9412        });
 9413    }
 9414
 9415    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9416        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9417        let text_layout_details = &self.text_layout_details(window);
 9418        self.transact(window, cx, |this, window, cx| {
 9419            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9420                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9421                s.move_with(|display_map, selection| {
 9422                    if !selection.is_empty() {
 9423                        return;
 9424                    }
 9425
 9426                    let mut head = selection.head();
 9427                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9428                    if head.column() == display_map.line_len(head.row()) {
 9429                        transpose_offset = display_map
 9430                            .buffer_snapshot
 9431                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9432                    }
 9433
 9434                    if transpose_offset == 0 {
 9435                        return;
 9436                    }
 9437
 9438                    *head.column_mut() += 1;
 9439                    head = display_map.clip_point(head, Bias::Right);
 9440                    let goal = SelectionGoal::HorizontalPosition(
 9441                        display_map
 9442                            .x_for_display_point(head, text_layout_details)
 9443                            .into(),
 9444                    );
 9445                    selection.collapse_to(head, goal);
 9446
 9447                    let transpose_start = display_map
 9448                        .buffer_snapshot
 9449                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9450                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9451                        let transpose_end = display_map
 9452                            .buffer_snapshot
 9453                            .clip_offset(transpose_offset + 1, Bias::Right);
 9454                        if let Some(ch) =
 9455                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9456                        {
 9457                            edits.push((transpose_start..transpose_offset, String::new()));
 9458                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9459                        }
 9460                    }
 9461                });
 9462                edits
 9463            });
 9464            this.buffer
 9465                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9466            let selections = this.selections.all::<usize>(cx);
 9467            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9468                s.select(selections);
 9469            });
 9470        });
 9471    }
 9472
 9473    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9474        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9475        self.rewrap_impl(RewrapOptions::default(), cx)
 9476    }
 9477
 9478    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9479        let buffer = self.buffer.read(cx).snapshot(cx);
 9480        let selections = self.selections.all::<Point>(cx);
 9481        let mut selections = selections.iter().peekable();
 9482
 9483        let mut edits = Vec::new();
 9484        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9485
 9486        while let Some(selection) = selections.next() {
 9487            let mut start_row = selection.start.row;
 9488            let mut end_row = selection.end.row;
 9489
 9490            // Skip selections that overlap with a range that has already been rewrapped.
 9491            let selection_range = start_row..end_row;
 9492            if rewrapped_row_ranges
 9493                .iter()
 9494                .any(|range| range.overlaps(&selection_range))
 9495            {
 9496                continue;
 9497            }
 9498
 9499            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9500
 9501            // Since not all lines in the selection may be at the same indent
 9502            // level, choose the indent size that is the most common between all
 9503            // of the lines.
 9504            //
 9505            // If there is a tie, we use the deepest indent.
 9506            let (indent_size, indent_end) = {
 9507                let mut indent_size_occurrences = HashMap::default();
 9508                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9509
 9510                for row in start_row..=end_row {
 9511                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9512                    rows_by_indent_size.entry(indent).or_default().push(row);
 9513                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9514                }
 9515
 9516                let indent_size = indent_size_occurrences
 9517                    .into_iter()
 9518                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9519                    .map(|(indent, _)| indent)
 9520                    .unwrap_or_default();
 9521                let row = rows_by_indent_size[&indent_size][0];
 9522                let indent_end = Point::new(row, indent_size.len);
 9523
 9524                (indent_size, indent_end)
 9525            };
 9526
 9527            let mut line_prefix = indent_size.chars().collect::<String>();
 9528
 9529            let mut inside_comment = false;
 9530            if let Some(comment_prefix) =
 9531                buffer
 9532                    .language_scope_at(selection.head())
 9533                    .and_then(|language| {
 9534                        language
 9535                            .line_comment_prefixes()
 9536                            .iter()
 9537                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9538                            .cloned()
 9539                    })
 9540            {
 9541                line_prefix.push_str(&comment_prefix);
 9542                inside_comment = true;
 9543            }
 9544
 9545            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9546            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9547                RewrapBehavior::InComments => inside_comment,
 9548                RewrapBehavior::InSelections => !selection.is_empty(),
 9549                RewrapBehavior::Anywhere => true,
 9550            };
 9551
 9552            let should_rewrap = options.override_language_settings
 9553                || allow_rewrap_based_on_language
 9554                || self.hard_wrap.is_some();
 9555            if !should_rewrap {
 9556                continue;
 9557            }
 9558
 9559            if selection.is_empty() {
 9560                'expand_upwards: while start_row > 0 {
 9561                    let prev_row = start_row - 1;
 9562                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9563                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9564                    {
 9565                        start_row = prev_row;
 9566                    } else {
 9567                        break 'expand_upwards;
 9568                    }
 9569                }
 9570
 9571                'expand_downwards: while end_row < buffer.max_point().row {
 9572                    let next_row = end_row + 1;
 9573                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9574                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9575                    {
 9576                        end_row = next_row;
 9577                    } else {
 9578                        break 'expand_downwards;
 9579                    }
 9580                }
 9581            }
 9582
 9583            let start = Point::new(start_row, 0);
 9584            let start_offset = start.to_offset(&buffer);
 9585            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9586            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9587            let Some(lines_without_prefixes) = selection_text
 9588                .lines()
 9589                .map(|line| {
 9590                    line.strip_prefix(&line_prefix)
 9591                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9592                        .ok_or_else(|| {
 9593                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9594                        })
 9595                })
 9596                .collect::<Result<Vec<_>, _>>()
 9597                .log_err()
 9598            else {
 9599                continue;
 9600            };
 9601
 9602            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9603                buffer
 9604                    .language_settings_at(Point::new(start_row, 0), cx)
 9605                    .preferred_line_length as usize
 9606            });
 9607            let wrapped_text = wrap_with_prefix(
 9608                line_prefix,
 9609                lines_without_prefixes.join("\n"),
 9610                wrap_column,
 9611                tab_size,
 9612                options.preserve_existing_whitespace,
 9613            );
 9614
 9615            // TODO: should always use char-based diff while still supporting cursor behavior that
 9616            // matches vim.
 9617            let mut diff_options = DiffOptions::default();
 9618            if options.override_language_settings {
 9619                diff_options.max_word_diff_len = 0;
 9620                diff_options.max_word_diff_line_count = 0;
 9621            } else {
 9622                diff_options.max_word_diff_len = usize::MAX;
 9623                diff_options.max_word_diff_line_count = usize::MAX;
 9624            }
 9625
 9626            for (old_range, new_text) in
 9627                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9628            {
 9629                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9630                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9631                edits.push((edit_start..edit_end, new_text));
 9632            }
 9633
 9634            rewrapped_row_ranges.push(start_row..=end_row);
 9635        }
 9636
 9637        self.buffer
 9638            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9639    }
 9640
 9641    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9642        let mut text = String::new();
 9643        let buffer = self.buffer.read(cx).snapshot(cx);
 9644        let mut selections = self.selections.all::<Point>(cx);
 9645        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9646        {
 9647            let max_point = buffer.max_point();
 9648            let mut is_first = true;
 9649            for selection in &mut selections {
 9650                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9651                if is_entire_line {
 9652                    selection.start = Point::new(selection.start.row, 0);
 9653                    if !selection.is_empty() && selection.end.column == 0 {
 9654                        selection.end = cmp::min(max_point, selection.end);
 9655                    } else {
 9656                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9657                    }
 9658                    selection.goal = SelectionGoal::None;
 9659                }
 9660                if is_first {
 9661                    is_first = false;
 9662                } else {
 9663                    text += "\n";
 9664                }
 9665                let mut len = 0;
 9666                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9667                    text.push_str(chunk);
 9668                    len += chunk.len();
 9669                }
 9670                clipboard_selections.push(ClipboardSelection {
 9671                    len,
 9672                    is_entire_line,
 9673                    first_line_indent: buffer
 9674                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9675                        .len,
 9676                });
 9677            }
 9678        }
 9679
 9680        self.transact(window, cx, |this, window, cx| {
 9681            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9682                s.select(selections);
 9683            });
 9684            this.insert("", window, cx);
 9685        });
 9686        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9687    }
 9688
 9689    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9690        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9691        let item = self.cut_common(window, cx);
 9692        cx.write_to_clipboard(item);
 9693    }
 9694
 9695    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9696        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9697        self.change_selections(None, window, cx, |s| {
 9698            s.move_with(|snapshot, sel| {
 9699                if sel.is_empty() {
 9700                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9701                }
 9702            });
 9703        });
 9704        let item = self.cut_common(window, cx);
 9705        cx.set_global(KillRing(item))
 9706    }
 9707
 9708    pub fn kill_ring_yank(
 9709        &mut self,
 9710        _: &KillRingYank,
 9711        window: &mut Window,
 9712        cx: &mut Context<Self>,
 9713    ) {
 9714        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9715        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 9716            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 9717                (kill_ring.text().to_string(), kill_ring.metadata_json())
 9718            } else {
 9719                return;
 9720            }
 9721        } else {
 9722            return;
 9723        };
 9724        self.do_paste(&text, metadata, false, window, cx);
 9725    }
 9726
 9727    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
 9728        self.do_copy(true, cx);
 9729    }
 9730
 9731    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 9732        self.do_copy(false, cx);
 9733    }
 9734
 9735    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
 9736        let selections = self.selections.all::<Point>(cx);
 9737        let buffer = self.buffer.read(cx).read(cx);
 9738        let mut text = String::new();
 9739
 9740        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9741        {
 9742            let max_point = buffer.max_point();
 9743            let mut is_first = true;
 9744            for selection in &selections {
 9745                let mut start = selection.start;
 9746                let mut end = selection.end;
 9747                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9748                if is_entire_line {
 9749                    start = Point::new(start.row, 0);
 9750                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 9751                }
 9752
 9753                let mut trimmed_selections = Vec::new();
 9754                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
 9755                    let row = MultiBufferRow(start.row);
 9756                    let first_indent = buffer.indent_size_for_line(row);
 9757                    if first_indent.len == 0 || start.column > first_indent.len {
 9758                        trimmed_selections.push(start..end);
 9759                    } else {
 9760                        trimmed_selections.push(
 9761                            Point::new(row.0, first_indent.len)
 9762                                ..Point::new(row.0, buffer.line_len(row)),
 9763                        );
 9764                        for row in start.row + 1..=end.row {
 9765                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
 9766                            if row_indent_size.len >= first_indent.len {
 9767                                trimmed_selections.push(
 9768                                    Point::new(row, first_indent.len)
 9769                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
 9770                                );
 9771                            } else {
 9772                                trimmed_selections.clear();
 9773                                trimmed_selections.push(start..end);
 9774                                break;
 9775                            }
 9776                        }
 9777                    }
 9778                } else {
 9779                    trimmed_selections.push(start..end);
 9780                }
 9781
 9782                for trimmed_range in trimmed_selections {
 9783                    if is_first {
 9784                        is_first = false;
 9785                    } else {
 9786                        text += "\n";
 9787                    }
 9788                    let mut len = 0;
 9789                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
 9790                        text.push_str(chunk);
 9791                        len += chunk.len();
 9792                    }
 9793                    clipboard_selections.push(ClipboardSelection {
 9794                        len,
 9795                        is_entire_line,
 9796                        first_line_indent: buffer
 9797                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
 9798                            .len,
 9799                    });
 9800                }
 9801            }
 9802        }
 9803
 9804        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 9805            text,
 9806            clipboard_selections,
 9807        ));
 9808    }
 9809
 9810    pub fn do_paste(
 9811        &mut self,
 9812        text: &String,
 9813        clipboard_selections: Option<Vec<ClipboardSelection>>,
 9814        handle_entire_lines: bool,
 9815        window: &mut Window,
 9816        cx: &mut Context<Self>,
 9817    ) {
 9818        if self.read_only(cx) {
 9819            return;
 9820        }
 9821
 9822        let clipboard_text = Cow::Borrowed(text);
 9823
 9824        self.transact(window, cx, |this, window, cx| {
 9825            if let Some(mut clipboard_selections) = clipboard_selections {
 9826                let old_selections = this.selections.all::<usize>(cx);
 9827                let all_selections_were_entire_line =
 9828                    clipboard_selections.iter().all(|s| s.is_entire_line);
 9829                let first_selection_indent_column =
 9830                    clipboard_selections.first().map(|s| s.first_line_indent);
 9831                if clipboard_selections.len() != old_selections.len() {
 9832                    clipboard_selections.drain(..);
 9833                }
 9834                let cursor_offset = this.selections.last::<usize>(cx).head();
 9835                let mut auto_indent_on_paste = true;
 9836
 9837                this.buffer.update(cx, |buffer, cx| {
 9838                    let snapshot = buffer.read(cx);
 9839                    auto_indent_on_paste = snapshot
 9840                        .language_settings_at(cursor_offset, cx)
 9841                        .auto_indent_on_paste;
 9842
 9843                    let mut start_offset = 0;
 9844                    let mut edits = Vec::new();
 9845                    let mut original_indent_columns = Vec::new();
 9846                    for (ix, selection) in old_selections.iter().enumerate() {
 9847                        let to_insert;
 9848                        let entire_line;
 9849                        let original_indent_column;
 9850                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 9851                            let end_offset = start_offset + clipboard_selection.len;
 9852                            to_insert = &clipboard_text[start_offset..end_offset];
 9853                            entire_line = clipboard_selection.is_entire_line;
 9854                            start_offset = end_offset + 1;
 9855                            original_indent_column = Some(clipboard_selection.first_line_indent);
 9856                        } else {
 9857                            to_insert = clipboard_text.as_str();
 9858                            entire_line = all_selections_were_entire_line;
 9859                            original_indent_column = first_selection_indent_column
 9860                        }
 9861
 9862                        // If the corresponding selection was empty when this slice of the
 9863                        // clipboard text was written, then the entire line containing the
 9864                        // selection was copied. If this selection is also currently empty,
 9865                        // then paste the line before the current line of the buffer.
 9866                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 9867                            let column = selection.start.to_point(&snapshot).column as usize;
 9868                            let line_start = selection.start - column;
 9869                            line_start..line_start
 9870                        } else {
 9871                            selection.range()
 9872                        };
 9873
 9874                        edits.push((range, to_insert));
 9875                        original_indent_columns.push(original_indent_column);
 9876                    }
 9877                    drop(snapshot);
 9878
 9879                    buffer.edit(
 9880                        edits,
 9881                        if auto_indent_on_paste {
 9882                            Some(AutoindentMode::Block {
 9883                                original_indent_columns,
 9884                            })
 9885                        } else {
 9886                            None
 9887                        },
 9888                        cx,
 9889                    );
 9890                });
 9891
 9892                let selections = this.selections.all::<usize>(cx);
 9893                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9894                    s.select(selections)
 9895                });
 9896            } else {
 9897                this.insert(&clipboard_text, window, cx);
 9898            }
 9899        });
 9900    }
 9901
 9902    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 9903        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9904        if let Some(item) = cx.read_from_clipboard() {
 9905            let entries = item.entries();
 9906
 9907            match entries.first() {
 9908                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 9909                // of all the pasted entries.
 9910                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 9911                    .do_paste(
 9912                        clipboard_string.text(),
 9913                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 9914                        true,
 9915                        window,
 9916                        cx,
 9917                    ),
 9918                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 9919            }
 9920        }
 9921    }
 9922
 9923    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 9924        if self.read_only(cx) {
 9925            return;
 9926        }
 9927
 9928        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9929
 9930        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 9931            if let Some((selections, _)) =
 9932                self.selection_history.transaction(transaction_id).cloned()
 9933            {
 9934                self.change_selections(None, window, cx, |s| {
 9935                    s.select_anchors(selections.to_vec());
 9936                });
 9937            } else {
 9938                log::error!(
 9939                    "No entry in selection_history found for undo. \
 9940                     This may correspond to a bug where undo does not update the selection. \
 9941                     If this is occurring, please add details to \
 9942                     https://github.com/zed-industries/zed/issues/22692"
 9943                );
 9944            }
 9945            self.request_autoscroll(Autoscroll::fit(), cx);
 9946            self.unmark_text(window, cx);
 9947            self.refresh_inline_completion(true, false, window, cx);
 9948            cx.emit(EditorEvent::Edited { transaction_id });
 9949            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 9950        }
 9951    }
 9952
 9953    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 9954        if self.read_only(cx) {
 9955            return;
 9956        }
 9957
 9958        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9959
 9960        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 9961            if let Some((_, Some(selections))) =
 9962                self.selection_history.transaction(transaction_id).cloned()
 9963            {
 9964                self.change_selections(None, window, cx, |s| {
 9965                    s.select_anchors(selections.to_vec());
 9966                });
 9967            } else {
 9968                log::error!(
 9969                    "No entry in selection_history found for redo. \
 9970                     This may correspond to a bug where undo does not update the selection. \
 9971                     If this is occurring, please add details to \
 9972                     https://github.com/zed-industries/zed/issues/22692"
 9973                );
 9974            }
 9975            self.request_autoscroll(Autoscroll::fit(), cx);
 9976            self.unmark_text(window, cx);
 9977            self.refresh_inline_completion(true, false, window, cx);
 9978            cx.emit(EditorEvent::Edited { transaction_id });
 9979        }
 9980    }
 9981
 9982    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 9983        self.buffer
 9984            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 9985    }
 9986
 9987    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 9988        self.buffer
 9989            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 9990    }
 9991
 9992    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 9993        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
 9994        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9995            s.move_with(|map, selection| {
 9996                let cursor = if selection.is_empty() {
 9997                    movement::left(map, selection.start)
 9998                } else {
 9999                    selection.start
10000                };
10001                selection.collapse_to(cursor, SelectionGoal::None);
10002            });
10003        })
10004    }
10005
10006    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10007        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10008        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10009            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10010        })
10011    }
10012
10013    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10014        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10015        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10016            s.move_with(|map, selection| {
10017                let cursor = if selection.is_empty() {
10018                    movement::right(map, selection.end)
10019                } else {
10020                    selection.end
10021                };
10022                selection.collapse_to(cursor, SelectionGoal::None)
10023            });
10024        })
10025    }
10026
10027    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10028        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10029        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10030            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10031        })
10032    }
10033
10034    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10035        if self.take_rename(true, window, cx).is_some() {
10036            return;
10037        }
10038
10039        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10040            cx.propagate();
10041            return;
10042        }
10043
10044        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10045
10046        let text_layout_details = &self.text_layout_details(window);
10047        let selection_count = self.selections.count();
10048        let first_selection = self.selections.first_anchor();
10049
10050        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10051            s.move_with(|map, selection| {
10052                if !selection.is_empty() {
10053                    selection.goal = SelectionGoal::None;
10054                }
10055                let (cursor, goal) = movement::up(
10056                    map,
10057                    selection.start,
10058                    selection.goal,
10059                    false,
10060                    text_layout_details,
10061                );
10062                selection.collapse_to(cursor, goal);
10063            });
10064        });
10065
10066        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10067        {
10068            cx.propagate();
10069        }
10070    }
10071
10072    pub fn move_up_by_lines(
10073        &mut self,
10074        action: &MoveUpByLines,
10075        window: &mut Window,
10076        cx: &mut Context<Self>,
10077    ) {
10078        if self.take_rename(true, window, cx).is_some() {
10079            return;
10080        }
10081
10082        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10083            cx.propagate();
10084            return;
10085        }
10086
10087        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10088
10089        let text_layout_details = &self.text_layout_details(window);
10090
10091        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10092            s.move_with(|map, selection| {
10093                if !selection.is_empty() {
10094                    selection.goal = SelectionGoal::None;
10095                }
10096                let (cursor, goal) = movement::up_by_rows(
10097                    map,
10098                    selection.start,
10099                    action.lines,
10100                    selection.goal,
10101                    false,
10102                    text_layout_details,
10103                );
10104                selection.collapse_to(cursor, goal);
10105            });
10106        })
10107    }
10108
10109    pub fn move_down_by_lines(
10110        &mut self,
10111        action: &MoveDownByLines,
10112        window: &mut Window,
10113        cx: &mut Context<Self>,
10114    ) {
10115        if self.take_rename(true, window, cx).is_some() {
10116            return;
10117        }
10118
10119        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10120            cx.propagate();
10121            return;
10122        }
10123
10124        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10125
10126        let text_layout_details = &self.text_layout_details(window);
10127
10128        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10129            s.move_with(|map, selection| {
10130                if !selection.is_empty() {
10131                    selection.goal = SelectionGoal::None;
10132                }
10133                let (cursor, goal) = movement::down_by_rows(
10134                    map,
10135                    selection.start,
10136                    action.lines,
10137                    selection.goal,
10138                    false,
10139                    text_layout_details,
10140                );
10141                selection.collapse_to(cursor, goal);
10142            });
10143        })
10144    }
10145
10146    pub fn select_down_by_lines(
10147        &mut self,
10148        action: &SelectDownByLines,
10149        window: &mut Window,
10150        cx: &mut Context<Self>,
10151    ) {
10152        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10153        let text_layout_details = &self.text_layout_details(window);
10154        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10155            s.move_heads_with(|map, head, goal| {
10156                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10157            })
10158        })
10159    }
10160
10161    pub fn select_up_by_lines(
10162        &mut self,
10163        action: &SelectUpByLines,
10164        window: &mut Window,
10165        cx: &mut Context<Self>,
10166    ) {
10167        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10168        let text_layout_details = &self.text_layout_details(window);
10169        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10170            s.move_heads_with(|map, head, goal| {
10171                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10172            })
10173        })
10174    }
10175
10176    pub fn select_page_up(
10177        &mut self,
10178        _: &SelectPageUp,
10179        window: &mut Window,
10180        cx: &mut Context<Self>,
10181    ) {
10182        let Some(row_count) = self.visible_row_count() else {
10183            return;
10184        };
10185
10186        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10187
10188        let text_layout_details = &self.text_layout_details(window);
10189
10190        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10191            s.move_heads_with(|map, head, goal| {
10192                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10193            })
10194        })
10195    }
10196
10197    pub fn move_page_up(
10198        &mut self,
10199        action: &MovePageUp,
10200        window: &mut Window,
10201        cx: &mut Context<Self>,
10202    ) {
10203        if self.take_rename(true, window, cx).is_some() {
10204            return;
10205        }
10206
10207        if self
10208            .context_menu
10209            .borrow_mut()
10210            .as_mut()
10211            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10212            .unwrap_or(false)
10213        {
10214            return;
10215        }
10216
10217        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10218            cx.propagate();
10219            return;
10220        }
10221
10222        let Some(row_count) = self.visible_row_count() else {
10223            return;
10224        };
10225
10226        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10227
10228        let autoscroll = if action.center_cursor {
10229            Autoscroll::center()
10230        } else {
10231            Autoscroll::fit()
10232        };
10233
10234        let text_layout_details = &self.text_layout_details(window);
10235
10236        self.change_selections(Some(autoscroll), window, cx, |s| {
10237            s.move_with(|map, selection| {
10238                if !selection.is_empty() {
10239                    selection.goal = SelectionGoal::None;
10240                }
10241                let (cursor, goal) = movement::up_by_rows(
10242                    map,
10243                    selection.end,
10244                    row_count,
10245                    selection.goal,
10246                    false,
10247                    text_layout_details,
10248                );
10249                selection.collapse_to(cursor, goal);
10250            });
10251        });
10252    }
10253
10254    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10255        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10256        let text_layout_details = &self.text_layout_details(window);
10257        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10258            s.move_heads_with(|map, head, goal| {
10259                movement::up(map, head, goal, false, text_layout_details)
10260            })
10261        })
10262    }
10263
10264    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10265        self.take_rename(true, window, cx);
10266
10267        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10268            cx.propagate();
10269            return;
10270        }
10271
10272        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10273
10274        let text_layout_details = &self.text_layout_details(window);
10275        let selection_count = self.selections.count();
10276        let first_selection = self.selections.first_anchor();
10277
10278        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10279            s.move_with(|map, selection| {
10280                if !selection.is_empty() {
10281                    selection.goal = SelectionGoal::None;
10282                }
10283                let (cursor, goal) = movement::down(
10284                    map,
10285                    selection.end,
10286                    selection.goal,
10287                    false,
10288                    text_layout_details,
10289                );
10290                selection.collapse_to(cursor, goal);
10291            });
10292        });
10293
10294        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10295        {
10296            cx.propagate();
10297        }
10298    }
10299
10300    pub fn select_page_down(
10301        &mut self,
10302        _: &SelectPageDown,
10303        window: &mut Window,
10304        cx: &mut Context<Self>,
10305    ) {
10306        let Some(row_count) = self.visible_row_count() else {
10307            return;
10308        };
10309
10310        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10311
10312        let text_layout_details = &self.text_layout_details(window);
10313
10314        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10315            s.move_heads_with(|map, head, goal| {
10316                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10317            })
10318        })
10319    }
10320
10321    pub fn move_page_down(
10322        &mut self,
10323        action: &MovePageDown,
10324        window: &mut Window,
10325        cx: &mut Context<Self>,
10326    ) {
10327        if self.take_rename(true, window, cx).is_some() {
10328            return;
10329        }
10330
10331        if self
10332            .context_menu
10333            .borrow_mut()
10334            .as_mut()
10335            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10336            .unwrap_or(false)
10337        {
10338            return;
10339        }
10340
10341        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10342            cx.propagate();
10343            return;
10344        }
10345
10346        let Some(row_count) = self.visible_row_count() else {
10347            return;
10348        };
10349
10350        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10351
10352        let autoscroll = if action.center_cursor {
10353            Autoscroll::center()
10354        } else {
10355            Autoscroll::fit()
10356        };
10357
10358        let text_layout_details = &self.text_layout_details(window);
10359        self.change_selections(Some(autoscroll), window, cx, |s| {
10360            s.move_with(|map, selection| {
10361                if !selection.is_empty() {
10362                    selection.goal = SelectionGoal::None;
10363                }
10364                let (cursor, goal) = movement::down_by_rows(
10365                    map,
10366                    selection.end,
10367                    row_count,
10368                    selection.goal,
10369                    false,
10370                    text_layout_details,
10371                );
10372                selection.collapse_to(cursor, goal);
10373            });
10374        });
10375    }
10376
10377    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10378        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10379        let text_layout_details = &self.text_layout_details(window);
10380        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10381            s.move_heads_with(|map, head, goal| {
10382                movement::down(map, head, goal, false, text_layout_details)
10383            })
10384        });
10385    }
10386
10387    pub fn context_menu_first(
10388        &mut self,
10389        _: &ContextMenuFirst,
10390        _window: &mut Window,
10391        cx: &mut Context<Self>,
10392    ) {
10393        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10394            context_menu.select_first(self.completion_provider.as_deref(), cx);
10395        }
10396    }
10397
10398    pub fn context_menu_prev(
10399        &mut self,
10400        _: &ContextMenuPrevious,
10401        _window: &mut Window,
10402        cx: &mut Context<Self>,
10403    ) {
10404        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10405            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10406        }
10407    }
10408
10409    pub fn context_menu_next(
10410        &mut self,
10411        _: &ContextMenuNext,
10412        _window: &mut Window,
10413        cx: &mut Context<Self>,
10414    ) {
10415        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10416            context_menu.select_next(self.completion_provider.as_deref(), cx);
10417        }
10418    }
10419
10420    pub fn context_menu_last(
10421        &mut self,
10422        _: &ContextMenuLast,
10423        _window: &mut Window,
10424        cx: &mut Context<Self>,
10425    ) {
10426        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10427            context_menu.select_last(self.completion_provider.as_deref(), cx);
10428        }
10429    }
10430
10431    pub fn move_to_previous_word_start(
10432        &mut self,
10433        _: &MoveToPreviousWordStart,
10434        window: &mut Window,
10435        cx: &mut Context<Self>,
10436    ) {
10437        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10438        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10439            s.move_cursors_with(|map, head, _| {
10440                (
10441                    movement::previous_word_start(map, head),
10442                    SelectionGoal::None,
10443                )
10444            });
10445        })
10446    }
10447
10448    pub fn move_to_previous_subword_start(
10449        &mut self,
10450        _: &MoveToPreviousSubwordStart,
10451        window: &mut Window,
10452        cx: &mut Context<Self>,
10453    ) {
10454        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10455        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10456            s.move_cursors_with(|map, head, _| {
10457                (
10458                    movement::previous_subword_start(map, head),
10459                    SelectionGoal::None,
10460                )
10461            });
10462        })
10463    }
10464
10465    pub fn select_to_previous_word_start(
10466        &mut self,
10467        _: &SelectToPreviousWordStart,
10468        window: &mut Window,
10469        cx: &mut Context<Self>,
10470    ) {
10471        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10472        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10473            s.move_heads_with(|map, head, _| {
10474                (
10475                    movement::previous_word_start(map, head),
10476                    SelectionGoal::None,
10477                )
10478            });
10479        })
10480    }
10481
10482    pub fn select_to_previous_subword_start(
10483        &mut self,
10484        _: &SelectToPreviousSubwordStart,
10485        window: &mut Window,
10486        cx: &mut Context<Self>,
10487    ) {
10488        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10489        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10490            s.move_heads_with(|map, head, _| {
10491                (
10492                    movement::previous_subword_start(map, head),
10493                    SelectionGoal::None,
10494                )
10495            });
10496        })
10497    }
10498
10499    pub fn delete_to_previous_word_start(
10500        &mut self,
10501        action: &DeleteToPreviousWordStart,
10502        window: &mut Window,
10503        cx: &mut Context<Self>,
10504    ) {
10505        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10506        self.transact(window, cx, |this, window, cx| {
10507            this.select_autoclose_pair(window, cx);
10508            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10509                s.move_with(|map, selection| {
10510                    if selection.is_empty() {
10511                        let cursor = if action.ignore_newlines {
10512                            movement::previous_word_start(map, selection.head())
10513                        } else {
10514                            movement::previous_word_start_or_newline(map, selection.head())
10515                        };
10516                        selection.set_head(cursor, SelectionGoal::None);
10517                    }
10518                });
10519            });
10520            this.insert("", window, cx);
10521        });
10522    }
10523
10524    pub fn delete_to_previous_subword_start(
10525        &mut self,
10526        _: &DeleteToPreviousSubwordStart,
10527        window: &mut Window,
10528        cx: &mut Context<Self>,
10529    ) {
10530        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10531        self.transact(window, cx, |this, window, cx| {
10532            this.select_autoclose_pair(window, cx);
10533            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10534                s.move_with(|map, selection| {
10535                    if selection.is_empty() {
10536                        let cursor = movement::previous_subword_start(map, selection.head());
10537                        selection.set_head(cursor, SelectionGoal::None);
10538                    }
10539                });
10540            });
10541            this.insert("", window, cx);
10542        });
10543    }
10544
10545    pub fn move_to_next_word_end(
10546        &mut self,
10547        _: &MoveToNextWordEnd,
10548        window: &mut Window,
10549        cx: &mut Context<Self>,
10550    ) {
10551        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10552        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10553            s.move_cursors_with(|map, head, _| {
10554                (movement::next_word_end(map, head), SelectionGoal::None)
10555            });
10556        })
10557    }
10558
10559    pub fn move_to_next_subword_end(
10560        &mut self,
10561        _: &MoveToNextSubwordEnd,
10562        window: &mut Window,
10563        cx: &mut Context<Self>,
10564    ) {
10565        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10566        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10567            s.move_cursors_with(|map, head, _| {
10568                (movement::next_subword_end(map, head), SelectionGoal::None)
10569            });
10570        })
10571    }
10572
10573    pub fn select_to_next_word_end(
10574        &mut self,
10575        _: &SelectToNextWordEnd,
10576        window: &mut Window,
10577        cx: &mut Context<Self>,
10578    ) {
10579        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10580        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10581            s.move_heads_with(|map, head, _| {
10582                (movement::next_word_end(map, head), SelectionGoal::None)
10583            });
10584        })
10585    }
10586
10587    pub fn select_to_next_subword_end(
10588        &mut self,
10589        _: &SelectToNextSubwordEnd,
10590        window: &mut Window,
10591        cx: &mut Context<Self>,
10592    ) {
10593        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10594        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10595            s.move_heads_with(|map, head, _| {
10596                (movement::next_subword_end(map, head), SelectionGoal::None)
10597            });
10598        })
10599    }
10600
10601    pub fn delete_to_next_word_end(
10602        &mut self,
10603        action: &DeleteToNextWordEnd,
10604        window: &mut Window,
10605        cx: &mut Context<Self>,
10606    ) {
10607        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10608        self.transact(window, cx, |this, window, cx| {
10609            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10610                s.move_with(|map, selection| {
10611                    if selection.is_empty() {
10612                        let cursor = if action.ignore_newlines {
10613                            movement::next_word_end(map, selection.head())
10614                        } else {
10615                            movement::next_word_end_or_newline(map, selection.head())
10616                        };
10617                        selection.set_head(cursor, SelectionGoal::None);
10618                    }
10619                });
10620            });
10621            this.insert("", window, cx);
10622        });
10623    }
10624
10625    pub fn delete_to_next_subword_end(
10626        &mut self,
10627        _: &DeleteToNextSubwordEnd,
10628        window: &mut Window,
10629        cx: &mut Context<Self>,
10630    ) {
10631        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10632        self.transact(window, cx, |this, window, cx| {
10633            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10634                s.move_with(|map, selection| {
10635                    if selection.is_empty() {
10636                        let cursor = movement::next_subword_end(map, selection.head());
10637                        selection.set_head(cursor, SelectionGoal::None);
10638                    }
10639                });
10640            });
10641            this.insert("", window, cx);
10642        });
10643    }
10644
10645    pub fn move_to_beginning_of_line(
10646        &mut self,
10647        action: &MoveToBeginningOfLine,
10648        window: &mut Window,
10649        cx: &mut Context<Self>,
10650    ) {
10651        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10652        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10653            s.move_cursors_with(|map, head, _| {
10654                (
10655                    movement::indented_line_beginning(
10656                        map,
10657                        head,
10658                        action.stop_at_soft_wraps,
10659                        action.stop_at_indent,
10660                    ),
10661                    SelectionGoal::None,
10662                )
10663            });
10664        })
10665    }
10666
10667    pub fn select_to_beginning_of_line(
10668        &mut self,
10669        action: &SelectToBeginningOfLine,
10670        window: &mut Window,
10671        cx: &mut Context<Self>,
10672    ) {
10673        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10674        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10675            s.move_heads_with(|map, head, _| {
10676                (
10677                    movement::indented_line_beginning(
10678                        map,
10679                        head,
10680                        action.stop_at_soft_wraps,
10681                        action.stop_at_indent,
10682                    ),
10683                    SelectionGoal::None,
10684                )
10685            });
10686        });
10687    }
10688
10689    pub fn delete_to_beginning_of_line(
10690        &mut self,
10691        action: &DeleteToBeginningOfLine,
10692        window: &mut Window,
10693        cx: &mut Context<Self>,
10694    ) {
10695        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10696        self.transact(window, cx, |this, window, cx| {
10697            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10698                s.move_with(|_, selection| {
10699                    selection.reversed = true;
10700                });
10701            });
10702
10703            this.select_to_beginning_of_line(
10704                &SelectToBeginningOfLine {
10705                    stop_at_soft_wraps: false,
10706                    stop_at_indent: action.stop_at_indent,
10707                },
10708                window,
10709                cx,
10710            );
10711            this.backspace(&Backspace, window, cx);
10712        });
10713    }
10714
10715    pub fn move_to_end_of_line(
10716        &mut self,
10717        action: &MoveToEndOfLine,
10718        window: &mut Window,
10719        cx: &mut Context<Self>,
10720    ) {
10721        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10722        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10723            s.move_cursors_with(|map, head, _| {
10724                (
10725                    movement::line_end(map, head, action.stop_at_soft_wraps),
10726                    SelectionGoal::None,
10727                )
10728            });
10729        })
10730    }
10731
10732    pub fn select_to_end_of_line(
10733        &mut self,
10734        action: &SelectToEndOfLine,
10735        window: &mut Window,
10736        cx: &mut Context<Self>,
10737    ) {
10738        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10739        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10740            s.move_heads_with(|map, head, _| {
10741                (
10742                    movement::line_end(map, head, action.stop_at_soft_wraps),
10743                    SelectionGoal::None,
10744                )
10745            });
10746        })
10747    }
10748
10749    pub fn delete_to_end_of_line(
10750        &mut self,
10751        _: &DeleteToEndOfLine,
10752        window: &mut Window,
10753        cx: &mut Context<Self>,
10754    ) {
10755        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10756        self.transact(window, cx, |this, window, cx| {
10757            this.select_to_end_of_line(
10758                &SelectToEndOfLine {
10759                    stop_at_soft_wraps: false,
10760                },
10761                window,
10762                cx,
10763            );
10764            this.delete(&Delete, window, cx);
10765        });
10766    }
10767
10768    pub fn cut_to_end_of_line(
10769        &mut self,
10770        _: &CutToEndOfLine,
10771        window: &mut Window,
10772        cx: &mut Context<Self>,
10773    ) {
10774        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10775        self.transact(window, cx, |this, window, cx| {
10776            this.select_to_end_of_line(
10777                &SelectToEndOfLine {
10778                    stop_at_soft_wraps: false,
10779                },
10780                window,
10781                cx,
10782            );
10783            this.cut(&Cut, window, cx);
10784        });
10785    }
10786
10787    pub fn move_to_start_of_paragraph(
10788        &mut self,
10789        _: &MoveToStartOfParagraph,
10790        window: &mut Window,
10791        cx: &mut Context<Self>,
10792    ) {
10793        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10794            cx.propagate();
10795            return;
10796        }
10797        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10798        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10799            s.move_with(|map, selection| {
10800                selection.collapse_to(
10801                    movement::start_of_paragraph(map, selection.head(), 1),
10802                    SelectionGoal::None,
10803                )
10804            });
10805        })
10806    }
10807
10808    pub fn move_to_end_of_paragraph(
10809        &mut self,
10810        _: &MoveToEndOfParagraph,
10811        window: &mut Window,
10812        cx: &mut Context<Self>,
10813    ) {
10814        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10815            cx.propagate();
10816            return;
10817        }
10818        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10819        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10820            s.move_with(|map, selection| {
10821                selection.collapse_to(
10822                    movement::end_of_paragraph(map, selection.head(), 1),
10823                    SelectionGoal::None,
10824                )
10825            });
10826        })
10827    }
10828
10829    pub fn select_to_start_of_paragraph(
10830        &mut self,
10831        _: &SelectToStartOfParagraph,
10832        window: &mut Window,
10833        cx: &mut Context<Self>,
10834    ) {
10835        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10836            cx.propagate();
10837            return;
10838        }
10839        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10840        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10841            s.move_heads_with(|map, head, _| {
10842                (
10843                    movement::start_of_paragraph(map, head, 1),
10844                    SelectionGoal::None,
10845                )
10846            });
10847        })
10848    }
10849
10850    pub fn select_to_end_of_paragraph(
10851        &mut self,
10852        _: &SelectToEndOfParagraph,
10853        window: &mut Window,
10854        cx: &mut Context<Self>,
10855    ) {
10856        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10857            cx.propagate();
10858            return;
10859        }
10860        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10861        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10862            s.move_heads_with(|map, head, _| {
10863                (
10864                    movement::end_of_paragraph(map, head, 1),
10865                    SelectionGoal::None,
10866                )
10867            });
10868        })
10869    }
10870
10871    pub fn move_to_start_of_excerpt(
10872        &mut self,
10873        _: &MoveToStartOfExcerpt,
10874        window: &mut Window,
10875        cx: &mut Context<Self>,
10876    ) {
10877        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10878            cx.propagate();
10879            return;
10880        }
10881        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10882        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10883            s.move_with(|map, selection| {
10884                selection.collapse_to(
10885                    movement::start_of_excerpt(
10886                        map,
10887                        selection.head(),
10888                        workspace::searchable::Direction::Prev,
10889                    ),
10890                    SelectionGoal::None,
10891                )
10892            });
10893        })
10894    }
10895
10896    pub fn move_to_start_of_next_excerpt(
10897        &mut self,
10898        _: &MoveToStartOfNextExcerpt,
10899        window: &mut Window,
10900        cx: &mut Context<Self>,
10901    ) {
10902        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10903            cx.propagate();
10904            return;
10905        }
10906
10907        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10908            s.move_with(|map, selection| {
10909                selection.collapse_to(
10910                    movement::start_of_excerpt(
10911                        map,
10912                        selection.head(),
10913                        workspace::searchable::Direction::Next,
10914                    ),
10915                    SelectionGoal::None,
10916                )
10917            });
10918        })
10919    }
10920
10921    pub fn move_to_end_of_excerpt(
10922        &mut self,
10923        _: &MoveToEndOfExcerpt,
10924        window: &mut Window,
10925        cx: &mut Context<Self>,
10926    ) {
10927        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10928            cx.propagate();
10929            return;
10930        }
10931        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10932        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10933            s.move_with(|map, selection| {
10934                selection.collapse_to(
10935                    movement::end_of_excerpt(
10936                        map,
10937                        selection.head(),
10938                        workspace::searchable::Direction::Next,
10939                    ),
10940                    SelectionGoal::None,
10941                )
10942            });
10943        })
10944    }
10945
10946    pub fn move_to_end_of_previous_excerpt(
10947        &mut self,
10948        _: &MoveToEndOfPreviousExcerpt,
10949        window: &mut Window,
10950        cx: &mut Context<Self>,
10951    ) {
10952        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10953            cx.propagate();
10954            return;
10955        }
10956        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10957        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10958            s.move_with(|map, selection| {
10959                selection.collapse_to(
10960                    movement::end_of_excerpt(
10961                        map,
10962                        selection.head(),
10963                        workspace::searchable::Direction::Prev,
10964                    ),
10965                    SelectionGoal::None,
10966                )
10967            });
10968        })
10969    }
10970
10971    pub fn select_to_start_of_excerpt(
10972        &mut self,
10973        _: &SelectToStartOfExcerpt,
10974        window: &mut Window,
10975        cx: &mut Context<Self>,
10976    ) {
10977        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10978            cx.propagate();
10979            return;
10980        }
10981        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10982        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10983            s.move_heads_with(|map, head, _| {
10984                (
10985                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10986                    SelectionGoal::None,
10987                )
10988            });
10989        })
10990    }
10991
10992    pub fn select_to_start_of_next_excerpt(
10993        &mut self,
10994        _: &SelectToStartOfNextExcerpt,
10995        window: &mut Window,
10996        cx: &mut Context<Self>,
10997    ) {
10998        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10999            cx.propagate();
11000            return;
11001        }
11002        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11003        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11004            s.move_heads_with(|map, head, _| {
11005                (
11006                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11007                    SelectionGoal::None,
11008                )
11009            });
11010        })
11011    }
11012
11013    pub fn select_to_end_of_excerpt(
11014        &mut self,
11015        _: &SelectToEndOfExcerpt,
11016        window: &mut Window,
11017        cx: &mut Context<Self>,
11018    ) {
11019        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11020            cx.propagate();
11021            return;
11022        }
11023        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11024        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11025            s.move_heads_with(|map, head, _| {
11026                (
11027                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11028                    SelectionGoal::None,
11029                )
11030            });
11031        })
11032    }
11033
11034    pub fn select_to_end_of_previous_excerpt(
11035        &mut self,
11036        _: &SelectToEndOfPreviousExcerpt,
11037        window: &mut Window,
11038        cx: &mut Context<Self>,
11039    ) {
11040        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11041            cx.propagate();
11042            return;
11043        }
11044        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11045        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11046            s.move_heads_with(|map, head, _| {
11047                (
11048                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11049                    SelectionGoal::None,
11050                )
11051            });
11052        })
11053    }
11054
11055    pub fn move_to_beginning(
11056        &mut self,
11057        _: &MoveToBeginning,
11058        window: &mut Window,
11059        cx: &mut Context<Self>,
11060    ) {
11061        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11062            cx.propagate();
11063            return;
11064        }
11065        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11066        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11067            s.select_ranges(vec![0..0]);
11068        });
11069    }
11070
11071    pub fn select_to_beginning(
11072        &mut self,
11073        _: &SelectToBeginning,
11074        window: &mut Window,
11075        cx: &mut Context<Self>,
11076    ) {
11077        let mut selection = self.selections.last::<Point>(cx);
11078        selection.set_head(Point::zero(), SelectionGoal::None);
11079        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11080        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11081            s.select(vec![selection]);
11082        });
11083    }
11084
11085    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11086        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11087            cx.propagate();
11088            return;
11089        }
11090        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11091        let cursor = self.buffer.read(cx).read(cx).len();
11092        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11093            s.select_ranges(vec![cursor..cursor])
11094        });
11095    }
11096
11097    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11098        self.nav_history = nav_history;
11099    }
11100
11101    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11102        self.nav_history.as_ref()
11103    }
11104
11105    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11106        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11107    }
11108
11109    fn push_to_nav_history(
11110        &mut self,
11111        cursor_anchor: Anchor,
11112        new_position: Option<Point>,
11113        is_deactivate: bool,
11114        cx: &mut Context<Self>,
11115    ) {
11116        if let Some(nav_history) = self.nav_history.as_mut() {
11117            let buffer = self.buffer.read(cx).read(cx);
11118            let cursor_position = cursor_anchor.to_point(&buffer);
11119            let scroll_state = self.scroll_manager.anchor();
11120            let scroll_top_row = scroll_state.top_row(&buffer);
11121            drop(buffer);
11122
11123            if let Some(new_position) = new_position {
11124                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11125                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11126                    return;
11127                }
11128            }
11129
11130            nav_history.push(
11131                Some(NavigationData {
11132                    cursor_anchor,
11133                    cursor_position,
11134                    scroll_anchor: scroll_state,
11135                    scroll_top_row,
11136                }),
11137                cx,
11138            );
11139            cx.emit(EditorEvent::PushedToNavHistory {
11140                anchor: cursor_anchor,
11141                is_deactivate,
11142            })
11143        }
11144    }
11145
11146    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11147        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11148        let buffer = self.buffer.read(cx).snapshot(cx);
11149        let mut selection = self.selections.first::<usize>(cx);
11150        selection.set_head(buffer.len(), SelectionGoal::None);
11151        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11152            s.select(vec![selection]);
11153        });
11154    }
11155
11156    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11157        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11158        let end = self.buffer.read(cx).read(cx).len();
11159        self.change_selections(None, window, cx, |s| {
11160            s.select_ranges(vec![0..end]);
11161        });
11162    }
11163
11164    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11165        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11166        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11167        let mut selections = self.selections.all::<Point>(cx);
11168        let max_point = display_map.buffer_snapshot.max_point();
11169        for selection in &mut selections {
11170            let rows = selection.spanned_rows(true, &display_map);
11171            selection.start = Point::new(rows.start.0, 0);
11172            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11173            selection.reversed = false;
11174        }
11175        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11176            s.select(selections);
11177        });
11178    }
11179
11180    pub fn split_selection_into_lines(
11181        &mut self,
11182        _: &SplitSelectionIntoLines,
11183        window: &mut Window,
11184        cx: &mut Context<Self>,
11185    ) {
11186        let selections = self
11187            .selections
11188            .all::<Point>(cx)
11189            .into_iter()
11190            .map(|selection| selection.start..selection.end)
11191            .collect::<Vec<_>>();
11192        self.unfold_ranges(&selections, true, true, cx);
11193
11194        let mut new_selection_ranges = Vec::new();
11195        {
11196            let buffer = self.buffer.read(cx).read(cx);
11197            for selection in selections {
11198                for row in selection.start.row..selection.end.row {
11199                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11200                    new_selection_ranges.push(cursor..cursor);
11201                }
11202
11203                let is_multiline_selection = selection.start.row != selection.end.row;
11204                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11205                // so this action feels more ergonomic when paired with other selection operations
11206                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11207                if !should_skip_last {
11208                    new_selection_ranges.push(selection.end..selection.end);
11209                }
11210            }
11211        }
11212        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11213            s.select_ranges(new_selection_ranges);
11214        });
11215    }
11216
11217    pub fn add_selection_above(
11218        &mut self,
11219        _: &AddSelectionAbove,
11220        window: &mut Window,
11221        cx: &mut Context<Self>,
11222    ) {
11223        self.add_selection(true, window, cx);
11224    }
11225
11226    pub fn add_selection_below(
11227        &mut self,
11228        _: &AddSelectionBelow,
11229        window: &mut Window,
11230        cx: &mut Context<Self>,
11231    ) {
11232        self.add_selection(false, window, cx);
11233    }
11234
11235    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11236        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11237
11238        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11239        let mut selections = self.selections.all::<Point>(cx);
11240        let text_layout_details = self.text_layout_details(window);
11241        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11242            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11243            let range = oldest_selection.display_range(&display_map).sorted();
11244
11245            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11246            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11247            let positions = start_x.min(end_x)..start_x.max(end_x);
11248
11249            selections.clear();
11250            let mut stack = Vec::new();
11251            for row in range.start.row().0..=range.end.row().0 {
11252                if let Some(selection) = self.selections.build_columnar_selection(
11253                    &display_map,
11254                    DisplayRow(row),
11255                    &positions,
11256                    oldest_selection.reversed,
11257                    &text_layout_details,
11258                ) {
11259                    stack.push(selection.id);
11260                    selections.push(selection);
11261                }
11262            }
11263
11264            if above {
11265                stack.reverse();
11266            }
11267
11268            AddSelectionsState { above, stack }
11269        });
11270
11271        let last_added_selection = *state.stack.last().unwrap();
11272        let mut new_selections = Vec::new();
11273        if above == state.above {
11274            let end_row = if above {
11275                DisplayRow(0)
11276            } else {
11277                display_map.max_point().row()
11278            };
11279
11280            'outer: for selection in selections {
11281                if selection.id == last_added_selection {
11282                    let range = selection.display_range(&display_map).sorted();
11283                    debug_assert_eq!(range.start.row(), range.end.row());
11284                    let mut row = range.start.row();
11285                    let positions =
11286                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11287                            px(start)..px(end)
11288                        } else {
11289                            let start_x =
11290                                display_map.x_for_display_point(range.start, &text_layout_details);
11291                            let end_x =
11292                                display_map.x_for_display_point(range.end, &text_layout_details);
11293                            start_x.min(end_x)..start_x.max(end_x)
11294                        };
11295
11296                    while row != end_row {
11297                        if above {
11298                            row.0 -= 1;
11299                        } else {
11300                            row.0 += 1;
11301                        }
11302
11303                        if let Some(new_selection) = self.selections.build_columnar_selection(
11304                            &display_map,
11305                            row,
11306                            &positions,
11307                            selection.reversed,
11308                            &text_layout_details,
11309                        ) {
11310                            state.stack.push(new_selection.id);
11311                            if above {
11312                                new_selections.push(new_selection);
11313                                new_selections.push(selection);
11314                            } else {
11315                                new_selections.push(selection);
11316                                new_selections.push(new_selection);
11317                            }
11318
11319                            continue 'outer;
11320                        }
11321                    }
11322                }
11323
11324                new_selections.push(selection);
11325            }
11326        } else {
11327            new_selections = selections;
11328            new_selections.retain(|s| s.id != last_added_selection);
11329            state.stack.pop();
11330        }
11331
11332        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11333            s.select(new_selections);
11334        });
11335        if state.stack.len() > 1 {
11336            self.add_selections_state = Some(state);
11337        }
11338    }
11339
11340    pub fn select_next_match_internal(
11341        &mut self,
11342        display_map: &DisplaySnapshot,
11343        replace_newest: bool,
11344        autoscroll: Option<Autoscroll>,
11345        window: &mut Window,
11346        cx: &mut Context<Self>,
11347    ) -> Result<()> {
11348        fn select_next_match_ranges(
11349            this: &mut Editor,
11350            range: Range<usize>,
11351            replace_newest: bool,
11352            auto_scroll: Option<Autoscroll>,
11353            window: &mut Window,
11354            cx: &mut Context<Editor>,
11355        ) {
11356            this.unfold_ranges(&[range.clone()], false, true, cx);
11357            this.change_selections(auto_scroll, window, cx, |s| {
11358                if replace_newest {
11359                    s.delete(s.newest_anchor().id);
11360                }
11361                s.insert_range(range.clone());
11362            });
11363        }
11364
11365        let buffer = &display_map.buffer_snapshot;
11366        let mut selections = self.selections.all::<usize>(cx);
11367        if let Some(mut select_next_state) = self.select_next_state.take() {
11368            let query = &select_next_state.query;
11369            if !select_next_state.done {
11370                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11371                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11372                let mut next_selected_range = None;
11373
11374                let bytes_after_last_selection =
11375                    buffer.bytes_in_range(last_selection.end..buffer.len());
11376                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11377                let query_matches = query
11378                    .stream_find_iter(bytes_after_last_selection)
11379                    .map(|result| (last_selection.end, result))
11380                    .chain(
11381                        query
11382                            .stream_find_iter(bytes_before_first_selection)
11383                            .map(|result| (0, result)),
11384                    );
11385
11386                for (start_offset, query_match) in query_matches {
11387                    let query_match = query_match.unwrap(); // can only fail due to I/O
11388                    let offset_range =
11389                        start_offset + query_match.start()..start_offset + query_match.end();
11390                    let display_range = offset_range.start.to_display_point(display_map)
11391                        ..offset_range.end.to_display_point(display_map);
11392
11393                    if !select_next_state.wordwise
11394                        || (!movement::is_inside_word(display_map, display_range.start)
11395                            && !movement::is_inside_word(display_map, display_range.end))
11396                    {
11397                        // TODO: This is n^2, because we might check all the selections
11398                        if !selections
11399                            .iter()
11400                            .any(|selection| selection.range().overlaps(&offset_range))
11401                        {
11402                            next_selected_range = Some(offset_range);
11403                            break;
11404                        }
11405                    }
11406                }
11407
11408                if let Some(next_selected_range) = next_selected_range {
11409                    select_next_match_ranges(
11410                        self,
11411                        next_selected_range,
11412                        replace_newest,
11413                        autoscroll,
11414                        window,
11415                        cx,
11416                    );
11417                } else {
11418                    select_next_state.done = true;
11419                }
11420            }
11421
11422            self.select_next_state = Some(select_next_state);
11423        } else {
11424            let mut only_carets = true;
11425            let mut same_text_selected = true;
11426            let mut selected_text = None;
11427
11428            let mut selections_iter = selections.iter().peekable();
11429            while let Some(selection) = selections_iter.next() {
11430                if selection.start != selection.end {
11431                    only_carets = false;
11432                }
11433
11434                if same_text_selected {
11435                    if selected_text.is_none() {
11436                        selected_text =
11437                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11438                    }
11439
11440                    if let Some(next_selection) = selections_iter.peek() {
11441                        if next_selection.range().len() == selection.range().len() {
11442                            let next_selected_text = buffer
11443                                .text_for_range(next_selection.range())
11444                                .collect::<String>();
11445                            if Some(next_selected_text) != selected_text {
11446                                same_text_selected = false;
11447                                selected_text = None;
11448                            }
11449                        } else {
11450                            same_text_selected = false;
11451                            selected_text = None;
11452                        }
11453                    }
11454                }
11455            }
11456
11457            if only_carets {
11458                for selection in &mut selections {
11459                    let word_range = movement::surrounding_word(
11460                        display_map,
11461                        selection.start.to_display_point(display_map),
11462                    );
11463                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11464                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11465                    selection.goal = SelectionGoal::None;
11466                    selection.reversed = false;
11467                    select_next_match_ranges(
11468                        self,
11469                        selection.start..selection.end,
11470                        replace_newest,
11471                        autoscroll,
11472                        window,
11473                        cx,
11474                    );
11475                }
11476
11477                if selections.len() == 1 {
11478                    let selection = selections
11479                        .last()
11480                        .expect("ensured that there's only one selection");
11481                    let query = buffer
11482                        .text_for_range(selection.start..selection.end)
11483                        .collect::<String>();
11484                    let is_empty = query.is_empty();
11485                    let select_state = SelectNextState {
11486                        query: AhoCorasick::new(&[query])?,
11487                        wordwise: true,
11488                        done: is_empty,
11489                    };
11490                    self.select_next_state = Some(select_state);
11491                } else {
11492                    self.select_next_state = None;
11493                }
11494            } else if let Some(selected_text) = selected_text {
11495                self.select_next_state = Some(SelectNextState {
11496                    query: AhoCorasick::new(&[selected_text])?,
11497                    wordwise: false,
11498                    done: false,
11499                });
11500                self.select_next_match_internal(
11501                    display_map,
11502                    replace_newest,
11503                    autoscroll,
11504                    window,
11505                    cx,
11506                )?;
11507            }
11508        }
11509        Ok(())
11510    }
11511
11512    pub fn select_all_matches(
11513        &mut self,
11514        _action: &SelectAllMatches,
11515        window: &mut Window,
11516        cx: &mut Context<Self>,
11517    ) -> Result<()> {
11518        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11519
11520        self.push_to_selection_history();
11521        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11522
11523        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11524        let Some(select_next_state) = self.select_next_state.as_mut() else {
11525            return Ok(());
11526        };
11527        if select_next_state.done {
11528            return Ok(());
11529        }
11530
11531        let mut new_selections = self.selections.all::<usize>(cx);
11532
11533        let buffer = &display_map.buffer_snapshot;
11534        let query_matches = select_next_state
11535            .query
11536            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11537
11538        for query_match in query_matches {
11539            let query_match = query_match.unwrap(); // can only fail due to I/O
11540            let offset_range = query_match.start()..query_match.end();
11541            let display_range = offset_range.start.to_display_point(&display_map)
11542                ..offset_range.end.to_display_point(&display_map);
11543
11544            if !select_next_state.wordwise
11545                || (!movement::is_inside_word(&display_map, display_range.start)
11546                    && !movement::is_inside_word(&display_map, display_range.end))
11547            {
11548                self.selections.change_with(cx, |selections| {
11549                    new_selections.push(Selection {
11550                        id: selections.new_selection_id(),
11551                        start: offset_range.start,
11552                        end: offset_range.end,
11553                        reversed: false,
11554                        goal: SelectionGoal::None,
11555                    });
11556                });
11557            }
11558        }
11559
11560        new_selections.sort_by_key(|selection| selection.start);
11561        let mut ix = 0;
11562        while ix + 1 < new_selections.len() {
11563            let current_selection = &new_selections[ix];
11564            let next_selection = &new_selections[ix + 1];
11565            if current_selection.range().overlaps(&next_selection.range()) {
11566                if current_selection.id < next_selection.id {
11567                    new_selections.remove(ix + 1);
11568                } else {
11569                    new_selections.remove(ix);
11570                }
11571            } else {
11572                ix += 1;
11573            }
11574        }
11575
11576        let reversed = self.selections.oldest::<usize>(cx).reversed;
11577
11578        for selection in new_selections.iter_mut() {
11579            selection.reversed = reversed;
11580        }
11581
11582        select_next_state.done = true;
11583        self.unfold_ranges(
11584            &new_selections
11585                .iter()
11586                .map(|selection| selection.range())
11587                .collect::<Vec<_>>(),
11588            false,
11589            false,
11590            cx,
11591        );
11592        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11593            selections.select(new_selections)
11594        });
11595
11596        Ok(())
11597    }
11598
11599    pub fn select_next(
11600        &mut self,
11601        action: &SelectNext,
11602        window: &mut Window,
11603        cx: &mut Context<Self>,
11604    ) -> Result<()> {
11605        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11606        self.push_to_selection_history();
11607        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11608        self.select_next_match_internal(
11609            &display_map,
11610            action.replace_newest,
11611            Some(Autoscroll::newest()),
11612            window,
11613            cx,
11614        )?;
11615        Ok(())
11616    }
11617
11618    pub fn select_previous(
11619        &mut self,
11620        action: &SelectPrevious,
11621        window: &mut Window,
11622        cx: &mut Context<Self>,
11623    ) -> Result<()> {
11624        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11625        self.push_to_selection_history();
11626        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11627        let buffer = &display_map.buffer_snapshot;
11628        let mut selections = self.selections.all::<usize>(cx);
11629        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11630            let query = &select_prev_state.query;
11631            if !select_prev_state.done {
11632                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11633                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11634                let mut next_selected_range = None;
11635                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11636                let bytes_before_last_selection =
11637                    buffer.reversed_bytes_in_range(0..last_selection.start);
11638                let bytes_after_first_selection =
11639                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11640                let query_matches = query
11641                    .stream_find_iter(bytes_before_last_selection)
11642                    .map(|result| (last_selection.start, result))
11643                    .chain(
11644                        query
11645                            .stream_find_iter(bytes_after_first_selection)
11646                            .map(|result| (buffer.len(), result)),
11647                    );
11648                for (end_offset, query_match) in query_matches {
11649                    let query_match = query_match.unwrap(); // can only fail due to I/O
11650                    let offset_range =
11651                        end_offset - query_match.end()..end_offset - query_match.start();
11652                    let display_range = offset_range.start.to_display_point(&display_map)
11653                        ..offset_range.end.to_display_point(&display_map);
11654
11655                    if !select_prev_state.wordwise
11656                        || (!movement::is_inside_word(&display_map, display_range.start)
11657                            && !movement::is_inside_word(&display_map, display_range.end))
11658                    {
11659                        next_selected_range = Some(offset_range);
11660                        break;
11661                    }
11662                }
11663
11664                if let Some(next_selected_range) = next_selected_range {
11665                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11666                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11667                        if action.replace_newest {
11668                            s.delete(s.newest_anchor().id);
11669                        }
11670                        s.insert_range(next_selected_range);
11671                    });
11672                } else {
11673                    select_prev_state.done = true;
11674                }
11675            }
11676
11677            self.select_prev_state = Some(select_prev_state);
11678        } else {
11679            let mut only_carets = true;
11680            let mut same_text_selected = true;
11681            let mut selected_text = None;
11682
11683            let mut selections_iter = selections.iter().peekable();
11684            while let Some(selection) = selections_iter.next() {
11685                if selection.start != selection.end {
11686                    only_carets = false;
11687                }
11688
11689                if same_text_selected {
11690                    if selected_text.is_none() {
11691                        selected_text =
11692                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11693                    }
11694
11695                    if let Some(next_selection) = selections_iter.peek() {
11696                        if next_selection.range().len() == selection.range().len() {
11697                            let next_selected_text = buffer
11698                                .text_for_range(next_selection.range())
11699                                .collect::<String>();
11700                            if Some(next_selected_text) != selected_text {
11701                                same_text_selected = false;
11702                                selected_text = None;
11703                            }
11704                        } else {
11705                            same_text_selected = false;
11706                            selected_text = None;
11707                        }
11708                    }
11709                }
11710            }
11711
11712            if only_carets {
11713                for selection in &mut selections {
11714                    let word_range = movement::surrounding_word(
11715                        &display_map,
11716                        selection.start.to_display_point(&display_map),
11717                    );
11718                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11719                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11720                    selection.goal = SelectionGoal::None;
11721                    selection.reversed = false;
11722                }
11723                if selections.len() == 1 {
11724                    let selection = selections
11725                        .last()
11726                        .expect("ensured that there's only one selection");
11727                    let query = buffer
11728                        .text_for_range(selection.start..selection.end)
11729                        .collect::<String>();
11730                    let is_empty = query.is_empty();
11731                    let select_state = SelectNextState {
11732                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11733                        wordwise: true,
11734                        done: is_empty,
11735                    };
11736                    self.select_prev_state = Some(select_state);
11737                } else {
11738                    self.select_prev_state = None;
11739                }
11740
11741                self.unfold_ranges(
11742                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11743                    false,
11744                    true,
11745                    cx,
11746                );
11747                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11748                    s.select(selections);
11749                });
11750            } else if let Some(selected_text) = selected_text {
11751                self.select_prev_state = Some(SelectNextState {
11752                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11753                    wordwise: false,
11754                    done: false,
11755                });
11756                self.select_previous(action, window, cx)?;
11757            }
11758        }
11759        Ok(())
11760    }
11761
11762    pub fn toggle_comments(
11763        &mut self,
11764        action: &ToggleComments,
11765        window: &mut Window,
11766        cx: &mut Context<Self>,
11767    ) {
11768        if self.read_only(cx) {
11769            return;
11770        }
11771        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11772        let text_layout_details = &self.text_layout_details(window);
11773        self.transact(window, cx, |this, window, cx| {
11774            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11775            let mut edits = Vec::new();
11776            let mut selection_edit_ranges = Vec::new();
11777            let mut last_toggled_row = None;
11778            let snapshot = this.buffer.read(cx).read(cx);
11779            let empty_str: Arc<str> = Arc::default();
11780            let mut suffixes_inserted = Vec::new();
11781            let ignore_indent = action.ignore_indent;
11782
11783            fn comment_prefix_range(
11784                snapshot: &MultiBufferSnapshot,
11785                row: MultiBufferRow,
11786                comment_prefix: &str,
11787                comment_prefix_whitespace: &str,
11788                ignore_indent: bool,
11789            ) -> Range<Point> {
11790                let indent_size = if ignore_indent {
11791                    0
11792                } else {
11793                    snapshot.indent_size_for_line(row).len
11794                };
11795
11796                let start = Point::new(row.0, indent_size);
11797
11798                let mut line_bytes = snapshot
11799                    .bytes_in_range(start..snapshot.max_point())
11800                    .flatten()
11801                    .copied();
11802
11803                // If this line currently begins with the line comment prefix, then record
11804                // the range containing the prefix.
11805                if line_bytes
11806                    .by_ref()
11807                    .take(comment_prefix.len())
11808                    .eq(comment_prefix.bytes())
11809                {
11810                    // Include any whitespace that matches the comment prefix.
11811                    let matching_whitespace_len = line_bytes
11812                        .zip(comment_prefix_whitespace.bytes())
11813                        .take_while(|(a, b)| a == b)
11814                        .count() as u32;
11815                    let end = Point::new(
11816                        start.row,
11817                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11818                    );
11819                    start..end
11820                } else {
11821                    start..start
11822                }
11823            }
11824
11825            fn comment_suffix_range(
11826                snapshot: &MultiBufferSnapshot,
11827                row: MultiBufferRow,
11828                comment_suffix: &str,
11829                comment_suffix_has_leading_space: bool,
11830            ) -> Range<Point> {
11831                let end = Point::new(row.0, snapshot.line_len(row));
11832                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11833
11834                let mut line_end_bytes = snapshot
11835                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11836                    .flatten()
11837                    .copied();
11838
11839                let leading_space_len = if suffix_start_column > 0
11840                    && line_end_bytes.next() == Some(b' ')
11841                    && comment_suffix_has_leading_space
11842                {
11843                    1
11844                } else {
11845                    0
11846                };
11847
11848                // If this line currently begins with the line comment prefix, then record
11849                // the range containing the prefix.
11850                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11851                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
11852                    start..end
11853                } else {
11854                    end..end
11855                }
11856            }
11857
11858            // TODO: Handle selections that cross excerpts
11859            for selection in &mut selections {
11860                let start_column = snapshot
11861                    .indent_size_for_line(MultiBufferRow(selection.start.row))
11862                    .len;
11863                let language = if let Some(language) =
11864                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11865                {
11866                    language
11867                } else {
11868                    continue;
11869                };
11870
11871                selection_edit_ranges.clear();
11872
11873                // If multiple selections contain a given row, avoid processing that
11874                // row more than once.
11875                let mut start_row = MultiBufferRow(selection.start.row);
11876                if last_toggled_row == Some(start_row) {
11877                    start_row = start_row.next_row();
11878                }
11879                let end_row =
11880                    if selection.end.row > selection.start.row && selection.end.column == 0 {
11881                        MultiBufferRow(selection.end.row - 1)
11882                    } else {
11883                        MultiBufferRow(selection.end.row)
11884                    };
11885                last_toggled_row = Some(end_row);
11886
11887                if start_row > end_row {
11888                    continue;
11889                }
11890
11891                // If the language has line comments, toggle those.
11892                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11893
11894                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11895                if ignore_indent {
11896                    full_comment_prefixes = full_comment_prefixes
11897                        .into_iter()
11898                        .map(|s| Arc::from(s.trim_end()))
11899                        .collect();
11900                }
11901
11902                if !full_comment_prefixes.is_empty() {
11903                    let first_prefix = full_comment_prefixes
11904                        .first()
11905                        .expect("prefixes is non-empty");
11906                    let prefix_trimmed_lengths = full_comment_prefixes
11907                        .iter()
11908                        .map(|p| p.trim_end_matches(' ').len())
11909                        .collect::<SmallVec<[usize; 4]>>();
11910
11911                    let mut all_selection_lines_are_comments = true;
11912
11913                    for row in start_row.0..=end_row.0 {
11914                        let row = MultiBufferRow(row);
11915                        if start_row < end_row && snapshot.is_line_blank(row) {
11916                            continue;
11917                        }
11918
11919                        let prefix_range = full_comment_prefixes
11920                            .iter()
11921                            .zip(prefix_trimmed_lengths.iter().copied())
11922                            .map(|(prefix, trimmed_prefix_len)| {
11923                                comment_prefix_range(
11924                                    snapshot.deref(),
11925                                    row,
11926                                    &prefix[..trimmed_prefix_len],
11927                                    &prefix[trimmed_prefix_len..],
11928                                    ignore_indent,
11929                                )
11930                            })
11931                            .max_by_key(|range| range.end.column - range.start.column)
11932                            .expect("prefixes is non-empty");
11933
11934                        if prefix_range.is_empty() {
11935                            all_selection_lines_are_comments = false;
11936                        }
11937
11938                        selection_edit_ranges.push(prefix_range);
11939                    }
11940
11941                    if all_selection_lines_are_comments {
11942                        edits.extend(
11943                            selection_edit_ranges
11944                                .iter()
11945                                .cloned()
11946                                .map(|range| (range, empty_str.clone())),
11947                        );
11948                    } else {
11949                        let min_column = selection_edit_ranges
11950                            .iter()
11951                            .map(|range| range.start.column)
11952                            .min()
11953                            .unwrap_or(0);
11954                        edits.extend(selection_edit_ranges.iter().map(|range| {
11955                            let position = Point::new(range.start.row, min_column);
11956                            (position..position, first_prefix.clone())
11957                        }));
11958                    }
11959                } else if let Some((full_comment_prefix, comment_suffix)) =
11960                    language.block_comment_delimiters()
11961                {
11962                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11963                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11964                    let prefix_range = comment_prefix_range(
11965                        snapshot.deref(),
11966                        start_row,
11967                        comment_prefix,
11968                        comment_prefix_whitespace,
11969                        ignore_indent,
11970                    );
11971                    let suffix_range = comment_suffix_range(
11972                        snapshot.deref(),
11973                        end_row,
11974                        comment_suffix.trim_start_matches(' '),
11975                        comment_suffix.starts_with(' '),
11976                    );
11977
11978                    if prefix_range.is_empty() || suffix_range.is_empty() {
11979                        edits.push((
11980                            prefix_range.start..prefix_range.start,
11981                            full_comment_prefix.clone(),
11982                        ));
11983                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11984                        suffixes_inserted.push((end_row, comment_suffix.len()));
11985                    } else {
11986                        edits.push((prefix_range, empty_str.clone()));
11987                        edits.push((suffix_range, empty_str.clone()));
11988                    }
11989                } else {
11990                    continue;
11991                }
11992            }
11993
11994            drop(snapshot);
11995            this.buffer.update(cx, |buffer, cx| {
11996                buffer.edit(edits, None, cx);
11997            });
11998
11999            // Adjust selections so that they end before any comment suffixes that
12000            // were inserted.
12001            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12002            let mut selections = this.selections.all::<Point>(cx);
12003            let snapshot = this.buffer.read(cx).read(cx);
12004            for selection in &mut selections {
12005                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12006                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12007                        Ordering::Less => {
12008                            suffixes_inserted.next();
12009                            continue;
12010                        }
12011                        Ordering::Greater => break,
12012                        Ordering::Equal => {
12013                            if selection.end.column == snapshot.line_len(row) {
12014                                if selection.is_empty() {
12015                                    selection.start.column -= suffix_len as u32;
12016                                }
12017                                selection.end.column -= suffix_len as u32;
12018                            }
12019                            break;
12020                        }
12021                    }
12022                }
12023            }
12024
12025            drop(snapshot);
12026            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12027                s.select(selections)
12028            });
12029
12030            let selections = this.selections.all::<Point>(cx);
12031            let selections_on_single_row = selections.windows(2).all(|selections| {
12032                selections[0].start.row == selections[1].start.row
12033                    && selections[0].end.row == selections[1].end.row
12034                    && selections[0].start.row == selections[0].end.row
12035            });
12036            let selections_selecting = selections
12037                .iter()
12038                .any(|selection| selection.start != selection.end);
12039            let advance_downwards = action.advance_downwards
12040                && selections_on_single_row
12041                && !selections_selecting
12042                && !matches!(this.mode, EditorMode::SingleLine { .. });
12043
12044            if advance_downwards {
12045                let snapshot = this.buffer.read(cx).snapshot(cx);
12046
12047                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12048                    s.move_cursors_with(|display_snapshot, display_point, _| {
12049                        let mut point = display_point.to_point(display_snapshot);
12050                        point.row += 1;
12051                        point = snapshot.clip_point(point, Bias::Left);
12052                        let display_point = point.to_display_point(display_snapshot);
12053                        let goal = SelectionGoal::HorizontalPosition(
12054                            display_snapshot
12055                                .x_for_display_point(display_point, text_layout_details)
12056                                .into(),
12057                        );
12058                        (display_point, goal)
12059                    })
12060                });
12061            }
12062        });
12063    }
12064
12065    pub fn select_enclosing_symbol(
12066        &mut self,
12067        _: &SelectEnclosingSymbol,
12068        window: &mut Window,
12069        cx: &mut Context<Self>,
12070    ) {
12071        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12072
12073        let buffer = self.buffer.read(cx).snapshot(cx);
12074        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12075
12076        fn update_selection(
12077            selection: &Selection<usize>,
12078            buffer_snap: &MultiBufferSnapshot,
12079        ) -> Option<Selection<usize>> {
12080            let cursor = selection.head();
12081            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12082            for symbol in symbols.iter().rev() {
12083                let start = symbol.range.start.to_offset(buffer_snap);
12084                let end = symbol.range.end.to_offset(buffer_snap);
12085                let new_range = start..end;
12086                if start < selection.start || end > selection.end {
12087                    return Some(Selection {
12088                        id: selection.id,
12089                        start: new_range.start,
12090                        end: new_range.end,
12091                        goal: SelectionGoal::None,
12092                        reversed: selection.reversed,
12093                    });
12094                }
12095            }
12096            None
12097        }
12098
12099        let mut selected_larger_symbol = false;
12100        let new_selections = old_selections
12101            .iter()
12102            .map(|selection| match update_selection(selection, &buffer) {
12103                Some(new_selection) => {
12104                    if new_selection.range() != selection.range() {
12105                        selected_larger_symbol = true;
12106                    }
12107                    new_selection
12108                }
12109                None => selection.clone(),
12110            })
12111            .collect::<Vec<_>>();
12112
12113        if selected_larger_symbol {
12114            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12115                s.select(new_selections);
12116            });
12117        }
12118    }
12119
12120    pub fn select_larger_syntax_node(
12121        &mut self,
12122        _: &SelectLargerSyntaxNode,
12123        window: &mut Window,
12124        cx: &mut Context<Self>,
12125    ) {
12126        let Some(visible_row_count) = self.visible_row_count() else {
12127            return;
12128        };
12129        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12130        if old_selections.is_empty() {
12131            return;
12132        }
12133
12134        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12135
12136        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12137        let buffer = self.buffer.read(cx).snapshot(cx);
12138
12139        let mut selected_larger_node = false;
12140        let mut new_selections = old_selections
12141            .iter()
12142            .map(|selection| {
12143                let old_range = selection.start..selection.end;
12144                let mut new_range = old_range.clone();
12145                let mut new_node = None;
12146                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12147                {
12148                    new_node = Some(node);
12149                    new_range = match containing_range {
12150                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12151                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12152                    };
12153                    if !display_map.intersects_fold(new_range.start)
12154                        && !display_map.intersects_fold(new_range.end)
12155                    {
12156                        break;
12157                    }
12158                }
12159
12160                if let Some(node) = new_node {
12161                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12162                    // nodes. Parent and grandparent are also logged because this operation will not
12163                    // visit nodes that have the same range as their parent.
12164                    log::info!("Node: {node:?}");
12165                    let parent = node.parent();
12166                    log::info!("Parent: {parent:?}");
12167                    let grandparent = parent.and_then(|x| x.parent());
12168                    log::info!("Grandparent: {grandparent:?}");
12169                }
12170
12171                selected_larger_node |= new_range != old_range;
12172                Selection {
12173                    id: selection.id,
12174                    start: new_range.start,
12175                    end: new_range.end,
12176                    goal: SelectionGoal::None,
12177                    reversed: selection.reversed,
12178                }
12179            })
12180            .collect::<Vec<_>>();
12181
12182        if !selected_larger_node {
12183            return; // don't put this call in the history
12184        }
12185
12186        // scroll based on transformation done to the last selection created by the user
12187        let (last_old, last_new) = old_selections
12188            .last()
12189            .zip(new_selections.last().cloned())
12190            .expect("old_selections isn't empty");
12191
12192        // revert selection
12193        let is_selection_reversed = {
12194            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12195            new_selections.last_mut().expect("checked above").reversed =
12196                should_newest_selection_be_reversed;
12197            should_newest_selection_be_reversed
12198        };
12199
12200        if selected_larger_node {
12201            self.select_syntax_node_history.disable_clearing = true;
12202            self.change_selections(None, window, cx, |s| {
12203                s.select(new_selections.clone());
12204            });
12205            self.select_syntax_node_history.disable_clearing = false;
12206        }
12207
12208        let start_row = last_new.start.to_display_point(&display_map).row().0;
12209        let end_row = last_new.end.to_display_point(&display_map).row().0;
12210        let selection_height = end_row - start_row + 1;
12211        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12212
12213        // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
12214        let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
12215            let middle_row = (end_row + start_row) / 2;
12216            let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12217            self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12218            SelectSyntaxNodeScrollBehavior::CenterSelection
12219        } else if is_selection_reversed {
12220            self.scroll_cursor_top(&Default::default(), window, cx);
12221            SelectSyntaxNodeScrollBehavior::CursorTop
12222        } else {
12223            self.scroll_cursor_bottom(&Default::default(), window, cx);
12224            SelectSyntaxNodeScrollBehavior::CursorBottom
12225        };
12226
12227        self.select_syntax_node_history.push((
12228            old_selections,
12229            scroll_behavior,
12230            is_selection_reversed,
12231        ));
12232    }
12233
12234    pub fn select_smaller_syntax_node(
12235        &mut self,
12236        _: &SelectSmallerSyntaxNode,
12237        window: &mut Window,
12238        cx: &mut Context<Self>,
12239    ) {
12240        let Some(visible_row_count) = self.visible_row_count() else {
12241            return;
12242        };
12243
12244        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12245
12246        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12247            self.select_syntax_node_history.pop()
12248        {
12249            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12250
12251            if let Some(selection) = selections.last_mut() {
12252                selection.reversed = is_selection_reversed;
12253            }
12254
12255            self.select_syntax_node_history.disable_clearing = true;
12256            self.change_selections(None, window, cx, |s| {
12257                s.select(selections.to_vec());
12258            });
12259            self.select_syntax_node_history.disable_clearing = false;
12260
12261            let newest = self.selections.newest::<usize>(cx);
12262            let start_row = newest.start.to_display_point(&display_map).row().0;
12263            let end_row = newest.end.to_display_point(&display_map).row().0;
12264
12265            match scroll_behavior {
12266                SelectSyntaxNodeScrollBehavior::CursorTop => {
12267                    self.scroll_cursor_top(&Default::default(), window, cx);
12268                }
12269                SelectSyntaxNodeScrollBehavior::CenterSelection => {
12270                    let middle_row = (end_row + start_row) / 2;
12271                    let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12272                    // centralize the selection, not the cursor
12273                    self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12274                }
12275                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12276                    self.scroll_cursor_bottom(&Default::default(), window, cx);
12277                }
12278            }
12279        }
12280    }
12281
12282    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12283        if !EditorSettings::get_global(cx).gutter.runnables {
12284            self.clear_tasks();
12285            return Task::ready(());
12286        }
12287        let project = self.project.as_ref().map(Entity::downgrade);
12288        cx.spawn_in(window, async move |this, cx| {
12289            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12290            let Some(project) = project.and_then(|p| p.upgrade()) else {
12291                return;
12292            };
12293            let Ok(display_snapshot) = this.update(cx, |this, cx| {
12294                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12295            }) else {
12296                return;
12297            };
12298
12299            let hide_runnables = project
12300                .update(cx, |project, cx| {
12301                    // Do not display any test indicators in non-dev server remote projects.
12302                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12303                })
12304                .unwrap_or(true);
12305            if hide_runnables {
12306                return;
12307            }
12308            let new_rows =
12309                cx.background_spawn({
12310                    let snapshot = display_snapshot.clone();
12311                    async move {
12312                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12313                    }
12314                })
12315                    .await;
12316
12317            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12318            this.update(cx, |this, _| {
12319                this.clear_tasks();
12320                for (key, value) in rows {
12321                    this.insert_tasks(key, value);
12322                }
12323            })
12324            .ok();
12325        })
12326    }
12327    fn fetch_runnable_ranges(
12328        snapshot: &DisplaySnapshot,
12329        range: Range<Anchor>,
12330    ) -> Vec<language::RunnableRange> {
12331        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12332    }
12333
12334    fn runnable_rows(
12335        project: Entity<Project>,
12336        snapshot: DisplaySnapshot,
12337        runnable_ranges: Vec<RunnableRange>,
12338        mut cx: AsyncWindowContext,
12339    ) -> Vec<((BufferId, u32), RunnableTasks)> {
12340        runnable_ranges
12341            .into_iter()
12342            .filter_map(|mut runnable| {
12343                let tasks = cx
12344                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12345                    .ok()?;
12346                if tasks.is_empty() {
12347                    return None;
12348                }
12349
12350                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12351
12352                let row = snapshot
12353                    .buffer_snapshot
12354                    .buffer_line_for_row(MultiBufferRow(point.row))?
12355                    .1
12356                    .start
12357                    .row;
12358
12359                let context_range =
12360                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12361                Some((
12362                    (runnable.buffer_id, row),
12363                    RunnableTasks {
12364                        templates: tasks,
12365                        offset: snapshot
12366                            .buffer_snapshot
12367                            .anchor_before(runnable.run_range.start),
12368                        context_range,
12369                        column: point.column,
12370                        extra_variables: runnable.extra_captures,
12371                    },
12372                ))
12373            })
12374            .collect()
12375    }
12376
12377    fn templates_with_tags(
12378        project: &Entity<Project>,
12379        runnable: &mut Runnable,
12380        cx: &mut App,
12381    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12382        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12383            let (worktree_id, file) = project
12384                .buffer_for_id(runnable.buffer, cx)
12385                .and_then(|buffer| buffer.read(cx).file())
12386                .map(|file| (file.worktree_id(cx), file.clone()))
12387                .unzip();
12388
12389            (
12390                project.task_store().read(cx).task_inventory().cloned(),
12391                worktree_id,
12392                file,
12393            )
12394        });
12395
12396        let tags = mem::take(&mut runnable.tags);
12397        let mut tags: Vec<_> = tags
12398            .into_iter()
12399            .flat_map(|tag| {
12400                let tag = tag.0.clone();
12401                inventory
12402                    .as_ref()
12403                    .into_iter()
12404                    .flat_map(|inventory| {
12405                        inventory.read(cx).list_tasks(
12406                            file.clone(),
12407                            Some(runnable.language.clone()),
12408                            worktree_id,
12409                            cx,
12410                        )
12411                    })
12412                    .filter(move |(_, template)| {
12413                        template.tags.iter().any(|source_tag| source_tag == &tag)
12414                    })
12415            })
12416            .sorted_by_key(|(kind, _)| kind.to_owned())
12417            .collect();
12418        if let Some((leading_tag_source, _)) = tags.first() {
12419            // Strongest source wins; if we have worktree tag binding, prefer that to
12420            // global and language bindings;
12421            // if we have a global binding, prefer that to language binding.
12422            let first_mismatch = tags
12423                .iter()
12424                .position(|(tag_source, _)| tag_source != leading_tag_source);
12425            if let Some(index) = first_mismatch {
12426                tags.truncate(index);
12427            }
12428        }
12429
12430        tags
12431    }
12432
12433    pub fn move_to_enclosing_bracket(
12434        &mut self,
12435        _: &MoveToEnclosingBracket,
12436        window: &mut Window,
12437        cx: &mut Context<Self>,
12438    ) {
12439        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12440        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12441            s.move_offsets_with(|snapshot, selection| {
12442                let Some(enclosing_bracket_ranges) =
12443                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12444                else {
12445                    return;
12446                };
12447
12448                let mut best_length = usize::MAX;
12449                let mut best_inside = false;
12450                let mut best_in_bracket_range = false;
12451                let mut best_destination = None;
12452                for (open, close) in enclosing_bracket_ranges {
12453                    let close = close.to_inclusive();
12454                    let length = close.end() - open.start;
12455                    let inside = selection.start >= open.end && selection.end <= *close.start();
12456                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12457                        || close.contains(&selection.head());
12458
12459                    // If best is next to a bracket and current isn't, skip
12460                    if !in_bracket_range && best_in_bracket_range {
12461                        continue;
12462                    }
12463
12464                    // Prefer smaller lengths unless best is inside and current isn't
12465                    if length > best_length && (best_inside || !inside) {
12466                        continue;
12467                    }
12468
12469                    best_length = length;
12470                    best_inside = inside;
12471                    best_in_bracket_range = in_bracket_range;
12472                    best_destination = Some(
12473                        if close.contains(&selection.start) && close.contains(&selection.end) {
12474                            if inside { open.end } else { open.start }
12475                        } else if inside {
12476                            *close.start()
12477                        } else {
12478                            *close.end()
12479                        },
12480                    );
12481                }
12482
12483                if let Some(destination) = best_destination {
12484                    selection.collapse_to(destination, SelectionGoal::None);
12485                }
12486            })
12487        });
12488    }
12489
12490    pub fn undo_selection(
12491        &mut self,
12492        _: &UndoSelection,
12493        window: &mut Window,
12494        cx: &mut Context<Self>,
12495    ) {
12496        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12497        self.end_selection(window, cx);
12498        self.selection_history.mode = SelectionHistoryMode::Undoing;
12499        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12500            self.change_selections(None, window, cx, |s| {
12501                s.select_anchors(entry.selections.to_vec())
12502            });
12503            self.select_next_state = entry.select_next_state;
12504            self.select_prev_state = entry.select_prev_state;
12505            self.add_selections_state = entry.add_selections_state;
12506            self.request_autoscroll(Autoscroll::newest(), cx);
12507        }
12508        self.selection_history.mode = SelectionHistoryMode::Normal;
12509    }
12510
12511    pub fn redo_selection(
12512        &mut self,
12513        _: &RedoSelection,
12514        window: &mut Window,
12515        cx: &mut Context<Self>,
12516    ) {
12517        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12518        self.end_selection(window, cx);
12519        self.selection_history.mode = SelectionHistoryMode::Redoing;
12520        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12521            self.change_selections(None, window, cx, |s| {
12522                s.select_anchors(entry.selections.to_vec())
12523            });
12524            self.select_next_state = entry.select_next_state;
12525            self.select_prev_state = entry.select_prev_state;
12526            self.add_selections_state = entry.add_selections_state;
12527            self.request_autoscroll(Autoscroll::newest(), cx);
12528        }
12529        self.selection_history.mode = SelectionHistoryMode::Normal;
12530    }
12531
12532    pub fn expand_excerpts(
12533        &mut self,
12534        action: &ExpandExcerpts,
12535        _: &mut Window,
12536        cx: &mut Context<Self>,
12537    ) {
12538        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12539    }
12540
12541    pub fn expand_excerpts_down(
12542        &mut self,
12543        action: &ExpandExcerptsDown,
12544        _: &mut Window,
12545        cx: &mut Context<Self>,
12546    ) {
12547        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12548    }
12549
12550    pub fn expand_excerpts_up(
12551        &mut self,
12552        action: &ExpandExcerptsUp,
12553        _: &mut Window,
12554        cx: &mut Context<Self>,
12555    ) {
12556        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12557    }
12558
12559    pub fn expand_excerpts_for_direction(
12560        &mut self,
12561        lines: u32,
12562        direction: ExpandExcerptDirection,
12563
12564        cx: &mut Context<Self>,
12565    ) {
12566        let selections = self.selections.disjoint_anchors();
12567
12568        let lines = if lines == 0 {
12569            EditorSettings::get_global(cx).expand_excerpt_lines
12570        } else {
12571            lines
12572        };
12573
12574        self.buffer.update(cx, |buffer, cx| {
12575            let snapshot = buffer.snapshot(cx);
12576            let mut excerpt_ids = selections
12577                .iter()
12578                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12579                .collect::<Vec<_>>();
12580            excerpt_ids.sort();
12581            excerpt_ids.dedup();
12582            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12583        })
12584    }
12585
12586    pub fn expand_excerpt(
12587        &mut self,
12588        excerpt: ExcerptId,
12589        direction: ExpandExcerptDirection,
12590        window: &mut Window,
12591        cx: &mut Context<Self>,
12592    ) {
12593        let current_scroll_position = self.scroll_position(cx);
12594        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12595        self.buffer.update(cx, |buffer, cx| {
12596            buffer.expand_excerpts([excerpt], lines, direction, cx)
12597        });
12598        if direction == ExpandExcerptDirection::Down {
12599            let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12600            self.set_scroll_position(new_scroll_position, window, cx);
12601        }
12602    }
12603
12604    pub fn go_to_singleton_buffer_point(
12605        &mut self,
12606        point: Point,
12607        window: &mut Window,
12608        cx: &mut Context<Self>,
12609    ) {
12610        self.go_to_singleton_buffer_range(point..point, window, cx);
12611    }
12612
12613    pub fn go_to_singleton_buffer_range(
12614        &mut self,
12615        range: Range<Point>,
12616        window: &mut Window,
12617        cx: &mut Context<Self>,
12618    ) {
12619        let multibuffer = self.buffer().read(cx);
12620        let Some(buffer) = multibuffer.as_singleton() else {
12621            return;
12622        };
12623        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12624            return;
12625        };
12626        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12627            return;
12628        };
12629        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12630            s.select_anchor_ranges([start..end])
12631        });
12632    }
12633
12634    fn go_to_diagnostic(
12635        &mut self,
12636        _: &GoToDiagnostic,
12637        window: &mut Window,
12638        cx: &mut Context<Self>,
12639    ) {
12640        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12641        self.go_to_diagnostic_impl(Direction::Next, window, cx)
12642    }
12643
12644    fn go_to_prev_diagnostic(
12645        &mut self,
12646        _: &GoToPreviousDiagnostic,
12647        window: &mut Window,
12648        cx: &mut Context<Self>,
12649    ) {
12650        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12651        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12652    }
12653
12654    pub fn go_to_diagnostic_impl(
12655        &mut self,
12656        direction: Direction,
12657        window: &mut Window,
12658        cx: &mut Context<Self>,
12659    ) {
12660        let buffer = self.buffer.read(cx).snapshot(cx);
12661        let selection = self.selections.newest::<usize>(cx);
12662
12663        // If there is an active Diagnostic Popover jump to its diagnostic instead.
12664        if direction == Direction::Next {
12665            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12666                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12667                    return;
12668                };
12669                self.activate_diagnostics(
12670                    buffer_id,
12671                    popover.local_diagnostic.diagnostic.group_id,
12672                    window,
12673                    cx,
12674                );
12675                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12676                    let primary_range_start = active_diagnostics.primary_range.start;
12677                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12678                        let mut new_selection = s.newest_anchor().clone();
12679                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12680                        s.select_anchors(vec![new_selection.clone()]);
12681                    });
12682                    self.refresh_inline_completion(false, true, window, cx);
12683                }
12684                return;
12685            }
12686        }
12687
12688        let active_group_id = self
12689            .active_diagnostics
12690            .as_ref()
12691            .map(|active_group| active_group.group_id);
12692        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12693            active_diagnostics
12694                .primary_range
12695                .to_offset(&buffer)
12696                .to_inclusive()
12697        });
12698        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12699            if active_primary_range.contains(&selection.head()) {
12700                *active_primary_range.start()
12701            } else {
12702                selection.head()
12703            }
12704        } else {
12705            selection.head()
12706        };
12707
12708        let snapshot = self.snapshot(window, cx);
12709        let primary_diagnostics_before = buffer
12710            .diagnostics_in_range::<usize>(0..search_start)
12711            .filter(|entry| entry.diagnostic.is_primary)
12712            .filter(|entry| entry.range.start != entry.range.end)
12713            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12714            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12715            .collect::<Vec<_>>();
12716        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12717            primary_diagnostics_before
12718                .iter()
12719                .position(|entry| entry.diagnostic.group_id == active_group_id)
12720        });
12721
12722        let primary_diagnostics_after = buffer
12723            .diagnostics_in_range::<usize>(search_start..buffer.len())
12724            .filter(|entry| entry.diagnostic.is_primary)
12725            .filter(|entry| entry.range.start != entry.range.end)
12726            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12727            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12728            .collect::<Vec<_>>();
12729        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12730            primary_diagnostics_after
12731                .iter()
12732                .enumerate()
12733                .rev()
12734                .find_map(|(i, entry)| {
12735                    if entry.diagnostic.group_id == active_group_id {
12736                        Some(i)
12737                    } else {
12738                        None
12739                    }
12740                })
12741        });
12742
12743        let next_primary_diagnostic = match direction {
12744            Direction::Prev => primary_diagnostics_before
12745                .iter()
12746                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12747                .rev()
12748                .next(),
12749            Direction::Next => primary_diagnostics_after
12750                .iter()
12751                .skip(
12752                    last_same_group_diagnostic_after
12753                        .map(|index| index + 1)
12754                        .unwrap_or(0),
12755                )
12756                .next(),
12757        };
12758
12759        // Cycle around to the start of the buffer, potentially moving back to the start of
12760        // the currently active diagnostic.
12761        let cycle_around = || match direction {
12762            Direction::Prev => primary_diagnostics_after
12763                .iter()
12764                .rev()
12765                .chain(primary_diagnostics_before.iter().rev())
12766                .next(),
12767            Direction::Next => primary_diagnostics_before
12768                .iter()
12769                .chain(primary_diagnostics_after.iter())
12770                .next(),
12771        };
12772
12773        if let Some((primary_range, group_id)) = next_primary_diagnostic
12774            .or_else(cycle_around)
12775            .map(|entry| (&entry.range, entry.diagnostic.group_id))
12776        {
12777            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12778                return;
12779            };
12780            self.activate_diagnostics(buffer_id, group_id, window, cx);
12781            if self.active_diagnostics.is_some() {
12782                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12783                    s.select(vec![Selection {
12784                        id: selection.id,
12785                        start: primary_range.start,
12786                        end: primary_range.start,
12787                        reversed: false,
12788                        goal: SelectionGoal::None,
12789                    }]);
12790                });
12791                self.refresh_inline_completion(false, true, window, cx);
12792            }
12793        }
12794    }
12795
12796    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12797        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12798        let snapshot = self.snapshot(window, cx);
12799        let selection = self.selections.newest::<Point>(cx);
12800        self.go_to_hunk_before_or_after_position(
12801            &snapshot,
12802            selection.head(),
12803            Direction::Next,
12804            window,
12805            cx,
12806        );
12807    }
12808
12809    pub fn go_to_hunk_before_or_after_position(
12810        &mut self,
12811        snapshot: &EditorSnapshot,
12812        position: Point,
12813        direction: Direction,
12814        window: &mut Window,
12815        cx: &mut Context<Editor>,
12816    ) {
12817        let row = if direction == Direction::Next {
12818            self.hunk_after_position(snapshot, position)
12819                .map(|hunk| hunk.row_range.start)
12820        } else {
12821            self.hunk_before_position(snapshot, position)
12822        };
12823
12824        if let Some(row) = row {
12825            let destination = Point::new(row.0, 0);
12826            let autoscroll = Autoscroll::center();
12827
12828            self.unfold_ranges(&[destination..destination], false, false, cx);
12829            self.change_selections(Some(autoscroll), window, cx, |s| {
12830                s.select_ranges([destination..destination]);
12831            });
12832        }
12833    }
12834
12835    fn hunk_after_position(
12836        &mut self,
12837        snapshot: &EditorSnapshot,
12838        position: Point,
12839    ) -> Option<MultiBufferDiffHunk> {
12840        snapshot
12841            .buffer_snapshot
12842            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12843            .find(|hunk| hunk.row_range.start.0 > position.row)
12844            .or_else(|| {
12845                snapshot
12846                    .buffer_snapshot
12847                    .diff_hunks_in_range(Point::zero()..position)
12848                    .find(|hunk| hunk.row_range.end.0 < position.row)
12849            })
12850    }
12851
12852    fn go_to_prev_hunk(
12853        &mut self,
12854        _: &GoToPreviousHunk,
12855        window: &mut Window,
12856        cx: &mut Context<Self>,
12857    ) {
12858        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12859        let snapshot = self.snapshot(window, cx);
12860        let selection = self.selections.newest::<Point>(cx);
12861        self.go_to_hunk_before_or_after_position(
12862            &snapshot,
12863            selection.head(),
12864            Direction::Prev,
12865            window,
12866            cx,
12867        );
12868    }
12869
12870    fn hunk_before_position(
12871        &mut self,
12872        snapshot: &EditorSnapshot,
12873        position: Point,
12874    ) -> Option<MultiBufferRow> {
12875        snapshot
12876            .buffer_snapshot
12877            .diff_hunk_before(position)
12878            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12879    }
12880
12881    fn go_to_line<T: 'static>(
12882        &mut self,
12883        position: Anchor,
12884        highlight_color: Option<Hsla>,
12885        window: &mut Window,
12886        cx: &mut Context<Self>,
12887    ) {
12888        let snapshot = self.snapshot(window, cx).display_snapshot;
12889        let position = position.to_point(&snapshot.buffer_snapshot);
12890        let start = snapshot
12891            .buffer_snapshot
12892            .clip_point(Point::new(position.row, 0), Bias::Left);
12893        let end = start + Point::new(1, 0);
12894        let start = snapshot.buffer_snapshot.anchor_before(start);
12895        let end = snapshot.buffer_snapshot.anchor_before(end);
12896
12897        self.highlight_rows::<T>(
12898            start..end,
12899            highlight_color
12900                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12901            false,
12902            cx,
12903        );
12904        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
12905    }
12906
12907    pub fn go_to_definition(
12908        &mut self,
12909        _: &GoToDefinition,
12910        window: &mut Window,
12911        cx: &mut Context<Self>,
12912    ) -> Task<Result<Navigated>> {
12913        let definition =
12914            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12915        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
12916        cx.spawn_in(window, async move |editor, cx| {
12917            if definition.await? == Navigated::Yes {
12918                return Ok(Navigated::Yes);
12919            }
12920            match fallback_strategy {
12921                GoToDefinitionFallback::None => Ok(Navigated::No),
12922                GoToDefinitionFallback::FindAllReferences => {
12923                    match editor.update_in(cx, |editor, window, cx| {
12924                        editor.find_all_references(&FindAllReferences, window, cx)
12925                    })? {
12926                        Some(references) => references.await,
12927                        None => Ok(Navigated::No),
12928                    }
12929                }
12930            }
12931        })
12932    }
12933
12934    pub fn go_to_declaration(
12935        &mut self,
12936        _: &GoToDeclaration,
12937        window: &mut Window,
12938        cx: &mut Context<Self>,
12939    ) -> Task<Result<Navigated>> {
12940        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12941    }
12942
12943    pub fn go_to_declaration_split(
12944        &mut self,
12945        _: &GoToDeclaration,
12946        window: &mut Window,
12947        cx: &mut Context<Self>,
12948    ) -> Task<Result<Navigated>> {
12949        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12950    }
12951
12952    pub fn go_to_implementation(
12953        &mut self,
12954        _: &GoToImplementation,
12955        window: &mut Window,
12956        cx: &mut Context<Self>,
12957    ) -> Task<Result<Navigated>> {
12958        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12959    }
12960
12961    pub fn go_to_implementation_split(
12962        &mut self,
12963        _: &GoToImplementationSplit,
12964        window: &mut Window,
12965        cx: &mut Context<Self>,
12966    ) -> Task<Result<Navigated>> {
12967        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12968    }
12969
12970    pub fn go_to_type_definition(
12971        &mut self,
12972        _: &GoToTypeDefinition,
12973        window: &mut Window,
12974        cx: &mut Context<Self>,
12975    ) -> Task<Result<Navigated>> {
12976        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12977    }
12978
12979    pub fn go_to_definition_split(
12980        &mut self,
12981        _: &GoToDefinitionSplit,
12982        window: &mut Window,
12983        cx: &mut Context<Self>,
12984    ) -> Task<Result<Navigated>> {
12985        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12986    }
12987
12988    pub fn go_to_type_definition_split(
12989        &mut self,
12990        _: &GoToTypeDefinitionSplit,
12991        window: &mut Window,
12992        cx: &mut Context<Self>,
12993    ) -> Task<Result<Navigated>> {
12994        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12995    }
12996
12997    fn go_to_definition_of_kind(
12998        &mut self,
12999        kind: GotoDefinitionKind,
13000        split: bool,
13001        window: &mut Window,
13002        cx: &mut Context<Self>,
13003    ) -> Task<Result<Navigated>> {
13004        let Some(provider) = self.semantics_provider.clone() else {
13005            return Task::ready(Ok(Navigated::No));
13006        };
13007        let head = self.selections.newest::<usize>(cx).head();
13008        let buffer = self.buffer.read(cx);
13009        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13010            text_anchor
13011        } else {
13012            return Task::ready(Ok(Navigated::No));
13013        };
13014
13015        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13016            return Task::ready(Ok(Navigated::No));
13017        };
13018
13019        cx.spawn_in(window, async move |editor, cx| {
13020            let definitions = definitions.await?;
13021            let navigated = editor
13022                .update_in(cx, |editor, window, cx| {
13023                    editor.navigate_to_hover_links(
13024                        Some(kind),
13025                        definitions
13026                            .into_iter()
13027                            .filter(|location| {
13028                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13029                            })
13030                            .map(HoverLink::Text)
13031                            .collect::<Vec<_>>(),
13032                        split,
13033                        window,
13034                        cx,
13035                    )
13036                })?
13037                .await?;
13038            anyhow::Ok(navigated)
13039        })
13040    }
13041
13042    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13043        let selection = self.selections.newest_anchor();
13044        let head = selection.head();
13045        let tail = selection.tail();
13046
13047        let Some((buffer, start_position)) =
13048            self.buffer.read(cx).text_anchor_for_position(head, cx)
13049        else {
13050            return;
13051        };
13052
13053        let end_position = if head != tail {
13054            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13055                return;
13056            };
13057            Some(pos)
13058        } else {
13059            None
13060        };
13061
13062        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13063            let url = if let Some(end_pos) = end_position {
13064                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13065            } else {
13066                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13067            };
13068
13069            if let Some(url) = url {
13070                editor.update(cx, |_, cx| {
13071                    cx.open_url(&url);
13072                })
13073            } else {
13074                Ok(())
13075            }
13076        });
13077
13078        url_finder.detach();
13079    }
13080
13081    pub fn open_selected_filename(
13082        &mut self,
13083        _: &OpenSelectedFilename,
13084        window: &mut Window,
13085        cx: &mut Context<Self>,
13086    ) {
13087        let Some(workspace) = self.workspace() else {
13088            return;
13089        };
13090
13091        let position = self.selections.newest_anchor().head();
13092
13093        let Some((buffer, buffer_position)) =
13094            self.buffer.read(cx).text_anchor_for_position(position, cx)
13095        else {
13096            return;
13097        };
13098
13099        let project = self.project.clone();
13100
13101        cx.spawn_in(window, async move |_, cx| {
13102            let result = find_file(&buffer, project, buffer_position, cx).await;
13103
13104            if let Some((_, path)) = result {
13105                workspace
13106                    .update_in(cx, |workspace, window, cx| {
13107                        workspace.open_resolved_path(path, window, cx)
13108                    })?
13109                    .await?;
13110            }
13111            anyhow::Ok(())
13112        })
13113        .detach();
13114    }
13115
13116    pub(crate) fn navigate_to_hover_links(
13117        &mut self,
13118        kind: Option<GotoDefinitionKind>,
13119        mut definitions: Vec<HoverLink>,
13120        split: bool,
13121        window: &mut Window,
13122        cx: &mut Context<Editor>,
13123    ) -> Task<Result<Navigated>> {
13124        // If there is one definition, just open it directly
13125        if definitions.len() == 1 {
13126            let definition = definitions.pop().unwrap();
13127
13128            enum TargetTaskResult {
13129                Location(Option<Location>),
13130                AlreadyNavigated,
13131            }
13132
13133            let target_task = match definition {
13134                HoverLink::Text(link) => {
13135                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13136                }
13137                HoverLink::InlayHint(lsp_location, server_id) => {
13138                    let computation =
13139                        self.compute_target_location(lsp_location, server_id, window, cx);
13140                    cx.background_spawn(async move {
13141                        let location = computation.await?;
13142                        Ok(TargetTaskResult::Location(location))
13143                    })
13144                }
13145                HoverLink::Url(url) => {
13146                    cx.open_url(&url);
13147                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13148                }
13149                HoverLink::File(path) => {
13150                    if let Some(workspace) = self.workspace() {
13151                        cx.spawn_in(window, async move |_, cx| {
13152                            workspace
13153                                .update_in(cx, |workspace, window, cx| {
13154                                    workspace.open_resolved_path(path, window, cx)
13155                                })?
13156                                .await
13157                                .map(|_| TargetTaskResult::AlreadyNavigated)
13158                        })
13159                    } else {
13160                        Task::ready(Ok(TargetTaskResult::Location(None)))
13161                    }
13162                }
13163            };
13164            cx.spawn_in(window, async move |editor, cx| {
13165                let target = match target_task.await.context("target resolution task")? {
13166                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13167                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13168                    TargetTaskResult::Location(Some(target)) => target,
13169                };
13170
13171                editor.update_in(cx, |editor, window, cx| {
13172                    let Some(workspace) = editor.workspace() else {
13173                        return Navigated::No;
13174                    };
13175                    let pane = workspace.read(cx).active_pane().clone();
13176
13177                    let range = target.range.to_point(target.buffer.read(cx));
13178                    let range = editor.range_for_match(&range);
13179                    let range = collapse_multiline_range(range);
13180
13181                    if !split
13182                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13183                    {
13184                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13185                    } else {
13186                        window.defer(cx, move |window, cx| {
13187                            let target_editor: Entity<Self> =
13188                                workspace.update(cx, |workspace, cx| {
13189                                    let pane = if split {
13190                                        workspace.adjacent_pane(window, cx)
13191                                    } else {
13192                                        workspace.active_pane().clone()
13193                                    };
13194
13195                                    workspace.open_project_item(
13196                                        pane,
13197                                        target.buffer.clone(),
13198                                        true,
13199                                        true,
13200                                        window,
13201                                        cx,
13202                                    )
13203                                });
13204                            target_editor.update(cx, |target_editor, cx| {
13205                                // When selecting a definition in a different buffer, disable the nav history
13206                                // to avoid creating a history entry at the previous cursor location.
13207                                pane.update(cx, |pane, _| pane.disable_history());
13208                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13209                                pane.update(cx, |pane, _| pane.enable_history());
13210                            });
13211                        });
13212                    }
13213                    Navigated::Yes
13214                })
13215            })
13216        } else if !definitions.is_empty() {
13217            cx.spawn_in(window, async move |editor, cx| {
13218                let (title, location_tasks, workspace) = editor
13219                    .update_in(cx, |editor, window, cx| {
13220                        let tab_kind = match kind {
13221                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13222                            _ => "Definitions",
13223                        };
13224                        let title = definitions
13225                            .iter()
13226                            .find_map(|definition| match definition {
13227                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13228                                    let buffer = origin.buffer.read(cx);
13229                                    format!(
13230                                        "{} for {}",
13231                                        tab_kind,
13232                                        buffer
13233                                            .text_for_range(origin.range.clone())
13234                                            .collect::<String>()
13235                                    )
13236                                }),
13237                                HoverLink::InlayHint(_, _) => None,
13238                                HoverLink::Url(_) => None,
13239                                HoverLink::File(_) => None,
13240                            })
13241                            .unwrap_or(tab_kind.to_string());
13242                        let location_tasks = definitions
13243                            .into_iter()
13244                            .map(|definition| match definition {
13245                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13246                                HoverLink::InlayHint(lsp_location, server_id) => editor
13247                                    .compute_target_location(lsp_location, server_id, window, cx),
13248                                HoverLink::Url(_) => Task::ready(Ok(None)),
13249                                HoverLink::File(_) => Task::ready(Ok(None)),
13250                            })
13251                            .collect::<Vec<_>>();
13252                        (title, location_tasks, editor.workspace().clone())
13253                    })
13254                    .context("location tasks preparation")?;
13255
13256                let locations = future::join_all(location_tasks)
13257                    .await
13258                    .into_iter()
13259                    .filter_map(|location| location.transpose())
13260                    .collect::<Result<_>>()
13261                    .context("location tasks")?;
13262
13263                let Some(workspace) = workspace else {
13264                    return Ok(Navigated::No);
13265                };
13266                let opened = workspace
13267                    .update_in(cx, |workspace, window, cx| {
13268                        Self::open_locations_in_multibuffer(
13269                            workspace,
13270                            locations,
13271                            title,
13272                            split,
13273                            MultibufferSelectionMode::First,
13274                            window,
13275                            cx,
13276                        )
13277                    })
13278                    .ok();
13279
13280                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13281            })
13282        } else {
13283            Task::ready(Ok(Navigated::No))
13284        }
13285    }
13286
13287    fn compute_target_location(
13288        &self,
13289        lsp_location: lsp::Location,
13290        server_id: LanguageServerId,
13291        window: &mut Window,
13292        cx: &mut Context<Self>,
13293    ) -> Task<anyhow::Result<Option<Location>>> {
13294        let Some(project) = self.project.clone() else {
13295            return Task::ready(Ok(None));
13296        };
13297
13298        cx.spawn_in(window, async move |editor, cx| {
13299            let location_task = editor.update(cx, |_, cx| {
13300                project.update(cx, |project, cx| {
13301                    let language_server_name = project
13302                        .language_server_statuses(cx)
13303                        .find(|(id, _)| server_id == *id)
13304                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13305                    language_server_name.map(|language_server_name| {
13306                        project.open_local_buffer_via_lsp(
13307                            lsp_location.uri.clone(),
13308                            server_id,
13309                            language_server_name,
13310                            cx,
13311                        )
13312                    })
13313                })
13314            })?;
13315            let location = match location_task {
13316                Some(task) => Some({
13317                    let target_buffer_handle = task.await.context("open local buffer")?;
13318                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13319                        let target_start = target_buffer
13320                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13321                        let target_end = target_buffer
13322                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13323                        target_buffer.anchor_after(target_start)
13324                            ..target_buffer.anchor_before(target_end)
13325                    })?;
13326                    Location {
13327                        buffer: target_buffer_handle,
13328                        range,
13329                    }
13330                }),
13331                None => None,
13332            };
13333            Ok(location)
13334        })
13335    }
13336
13337    pub fn find_all_references(
13338        &mut self,
13339        _: &FindAllReferences,
13340        window: &mut Window,
13341        cx: &mut Context<Self>,
13342    ) -> Option<Task<Result<Navigated>>> {
13343        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13344
13345        let selection = self.selections.newest::<usize>(cx);
13346        let multi_buffer = self.buffer.read(cx);
13347        let head = selection.head();
13348
13349        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13350        let head_anchor = multi_buffer_snapshot.anchor_at(
13351            head,
13352            if head < selection.tail() {
13353                Bias::Right
13354            } else {
13355                Bias::Left
13356            },
13357        );
13358
13359        match self
13360            .find_all_references_task_sources
13361            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13362        {
13363            Ok(_) => {
13364                log::info!(
13365                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13366                );
13367                return None;
13368            }
13369            Err(i) => {
13370                self.find_all_references_task_sources.insert(i, head_anchor);
13371            }
13372        }
13373
13374        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13375        let workspace = self.workspace()?;
13376        let project = workspace.read(cx).project().clone();
13377        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13378        Some(cx.spawn_in(window, async move |editor, cx| {
13379            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13380                if let Ok(i) = editor
13381                    .find_all_references_task_sources
13382                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13383                {
13384                    editor.find_all_references_task_sources.remove(i);
13385                }
13386            });
13387
13388            let locations = references.await?;
13389            if locations.is_empty() {
13390                return anyhow::Ok(Navigated::No);
13391            }
13392
13393            workspace.update_in(cx, |workspace, window, cx| {
13394                let title = locations
13395                    .first()
13396                    .as_ref()
13397                    .map(|location| {
13398                        let buffer = location.buffer.read(cx);
13399                        format!(
13400                            "References to `{}`",
13401                            buffer
13402                                .text_for_range(location.range.clone())
13403                                .collect::<String>()
13404                        )
13405                    })
13406                    .unwrap();
13407                Self::open_locations_in_multibuffer(
13408                    workspace,
13409                    locations,
13410                    title,
13411                    false,
13412                    MultibufferSelectionMode::First,
13413                    window,
13414                    cx,
13415                );
13416                Navigated::Yes
13417            })
13418        }))
13419    }
13420
13421    /// Opens a multibuffer with the given project locations in it
13422    pub fn open_locations_in_multibuffer(
13423        workspace: &mut Workspace,
13424        mut locations: Vec<Location>,
13425        title: String,
13426        split: bool,
13427        multibuffer_selection_mode: MultibufferSelectionMode,
13428        window: &mut Window,
13429        cx: &mut Context<Workspace>,
13430    ) {
13431        // If there are multiple definitions, open them in a multibuffer
13432        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13433        let mut locations = locations.into_iter().peekable();
13434        let mut ranges = Vec::new();
13435        let capability = workspace.project().read(cx).capability();
13436
13437        let excerpt_buffer = cx.new(|cx| {
13438            let mut multibuffer = MultiBuffer::new(capability);
13439            while let Some(location) = locations.next() {
13440                let buffer = location.buffer.read(cx);
13441                let mut ranges_for_buffer = Vec::new();
13442                let range = location.range.to_offset(buffer);
13443                ranges_for_buffer.push(range.clone());
13444
13445                while let Some(next_location) = locations.peek() {
13446                    if next_location.buffer == location.buffer {
13447                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
13448                        locations.next();
13449                    } else {
13450                        break;
13451                    }
13452                }
13453
13454                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13455                ranges.extend(multibuffer.push_excerpts_with_context_lines(
13456                    location.buffer.clone(),
13457                    ranges_for_buffer,
13458                    DEFAULT_MULTIBUFFER_CONTEXT,
13459                    cx,
13460                ))
13461            }
13462
13463            multibuffer.with_title(title)
13464        });
13465
13466        let editor = cx.new(|cx| {
13467            Editor::for_multibuffer(
13468                excerpt_buffer,
13469                Some(workspace.project().clone()),
13470                window,
13471                cx,
13472            )
13473        });
13474        editor.update(cx, |editor, cx| {
13475            match multibuffer_selection_mode {
13476                MultibufferSelectionMode::First => {
13477                    if let Some(first_range) = ranges.first() {
13478                        editor.change_selections(None, window, cx, |selections| {
13479                            selections.clear_disjoint();
13480                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13481                        });
13482                    }
13483                    editor.highlight_background::<Self>(
13484                        &ranges,
13485                        |theme| theme.editor_highlighted_line_background,
13486                        cx,
13487                    );
13488                }
13489                MultibufferSelectionMode::All => {
13490                    editor.change_selections(None, window, cx, |selections| {
13491                        selections.clear_disjoint();
13492                        selections.select_anchor_ranges(ranges);
13493                    });
13494                }
13495            }
13496            editor.register_buffers_with_language_servers(cx);
13497        });
13498
13499        let item = Box::new(editor);
13500        let item_id = item.item_id();
13501
13502        if split {
13503            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13504        } else {
13505            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13506                let (preview_item_id, preview_item_idx) =
13507                    workspace.active_pane().update(cx, |pane, _| {
13508                        (pane.preview_item_id(), pane.preview_item_idx())
13509                    });
13510
13511                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13512
13513                if let Some(preview_item_id) = preview_item_id {
13514                    workspace.active_pane().update(cx, |pane, cx| {
13515                        pane.remove_item(preview_item_id, false, false, window, cx);
13516                    });
13517                }
13518            } else {
13519                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13520            }
13521        }
13522        workspace.active_pane().update(cx, |pane, cx| {
13523            pane.set_preview_item_id(Some(item_id), cx);
13524        });
13525    }
13526
13527    pub fn rename(
13528        &mut self,
13529        _: &Rename,
13530        window: &mut Window,
13531        cx: &mut Context<Self>,
13532    ) -> Option<Task<Result<()>>> {
13533        use language::ToOffset as _;
13534
13535        let provider = self.semantics_provider.clone()?;
13536        let selection = self.selections.newest_anchor().clone();
13537        let (cursor_buffer, cursor_buffer_position) = self
13538            .buffer
13539            .read(cx)
13540            .text_anchor_for_position(selection.head(), cx)?;
13541        let (tail_buffer, cursor_buffer_position_end) = self
13542            .buffer
13543            .read(cx)
13544            .text_anchor_for_position(selection.tail(), cx)?;
13545        if tail_buffer != cursor_buffer {
13546            return None;
13547        }
13548
13549        let snapshot = cursor_buffer.read(cx).snapshot();
13550        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13551        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13552        let prepare_rename = provider
13553            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13554            .unwrap_or_else(|| Task::ready(Ok(None)));
13555        drop(snapshot);
13556
13557        Some(cx.spawn_in(window, async move |this, cx| {
13558            let rename_range = if let Some(range) = prepare_rename.await? {
13559                Some(range)
13560            } else {
13561                this.update(cx, |this, cx| {
13562                    let buffer = this.buffer.read(cx).snapshot(cx);
13563                    let mut buffer_highlights = this
13564                        .document_highlights_for_position(selection.head(), &buffer)
13565                        .filter(|highlight| {
13566                            highlight.start.excerpt_id == selection.head().excerpt_id
13567                                && highlight.end.excerpt_id == selection.head().excerpt_id
13568                        });
13569                    buffer_highlights
13570                        .next()
13571                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13572                })?
13573            };
13574            if let Some(rename_range) = rename_range {
13575                this.update_in(cx, |this, window, cx| {
13576                    let snapshot = cursor_buffer.read(cx).snapshot();
13577                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13578                    let cursor_offset_in_rename_range =
13579                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13580                    let cursor_offset_in_rename_range_end =
13581                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13582
13583                    this.take_rename(false, window, cx);
13584                    let buffer = this.buffer.read(cx).read(cx);
13585                    let cursor_offset = selection.head().to_offset(&buffer);
13586                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13587                    let rename_end = rename_start + rename_buffer_range.len();
13588                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13589                    let mut old_highlight_id = None;
13590                    let old_name: Arc<str> = buffer
13591                        .chunks(rename_start..rename_end, true)
13592                        .map(|chunk| {
13593                            if old_highlight_id.is_none() {
13594                                old_highlight_id = chunk.syntax_highlight_id;
13595                            }
13596                            chunk.text
13597                        })
13598                        .collect::<String>()
13599                        .into();
13600
13601                    drop(buffer);
13602
13603                    // Position the selection in the rename editor so that it matches the current selection.
13604                    this.show_local_selections = false;
13605                    let rename_editor = cx.new(|cx| {
13606                        let mut editor = Editor::single_line(window, cx);
13607                        editor.buffer.update(cx, |buffer, cx| {
13608                            buffer.edit([(0..0, old_name.clone())], None, cx)
13609                        });
13610                        let rename_selection_range = match cursor_offset_in_rename_range
13611                            .cmp(&cursor_offset_in_rename_range_end)
13612                        {
13613                            Ordering::Equal => {
13614                                editor.select_all(&SelectAll, window, cx);
13615                                return editor;
13616                            }
13617                            Ordering::Less => {
13618                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13619                            }
13620                            Ordering::Greater => {
13621                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13622                            }
13623                        };
13624                        if rename_selection_range.end > old_name.len() {
13625                            editor.select_all(&SelectAll, window, cx);
13626                        } else {
13627                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13628                                s.select_ranges([rename_selection_range]);
13629                            });
13630                        }
13631                        editor
13632                    });
13633                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13634                        if e == &EditorEvent::Focused {
13635                            cx.emit(EditorEvent::FocusedIn)
13636                        }
13637                    })
13638                    .detach();
13639
13640                    let write_highlights =
13641                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13642                    let read_highlights =
13643                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
13644                    let ranges = write_highlights
13645                        .iter()
13646                        .flat_map(|(_, ranges)| ranges.iter())
13647                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13648                        .cloned()
13649                        .collect();
13650
13651                    this.highlight_text::<Rename>(
13652                        ranges,
13653                        HighlightStyle {
13654                            fade_out: Some(0.6),
13655                            ..Default::default()
13656                        },
13657                        cx,
13658                    );
13659                    let rename_focus_handle = rename_editor.focus_handle(cx);
13660                    window.focus(&rename_focus_handle);
13661                    let block_id = this.insert_blocks(
13662                        [BlockProperties {
13663                            style: BlockStyle::Flex,
13664                            placement: BlockPlacement::Below(range.start),
13665                            height: 1,
13666                            render: Arc::new({
13667                                let rename_editor = rename_editor.clone();
13668                                move |cx: &mut BlockContext| {
13669                                    let mut text_style = cx.editor_style.text.clone();
13670                                    if let Some(highlight_style) = old_highlight_id
13671                                        .and_then(|h| h.style(&cx.editor_style.syntax))
13672                                    {
13673                                        text_style = text_style.highlight(highlight_style);
13674                                    }
13675                                    div()
13676                                        .block_mouse_down()
13677                                        .pl(cx.anchor_x)
13678                                        .child(EditorElement::new(
13679                                            &rename_editor,
13680                                            EditorStyle {
13681                                                background: cx.theme().system().transparent,
13682                                                local_player: cx.editor_style.local_player,
13683                                                text: text_style,
13684                                                scrollbar_width: cx.editor_style.scrollbar_width,
13685                                                syntax: cx.editor_style.syntax.clone(),
13686                                                status: cx.editor_style.status.clone(),
13687                                                inlay_hints_style: HighlightStyle {
13688                                                    font_weight: Some(FontWeight::BOLD),
13689                                                    ..make_inlay_hints_style(cx.app)
13690                                                },
13691                                                inline_completion_styles: make_suggestion_styles(
13692                                                    cx.app,
13693                                                ),
13694                                                ..EditorStyle::default()
13695                                            },
13696                                        ))
13697                                        .into_any_element()
13698                                }
13699                            }),
13700                            priority: 0,
13701                        }],
13702                        Some(Autoscroll::fit()),
13703                        cx,
13704                    )[0];
13705                    this.pending_rename = Some(RenameState {
13706                        range,
13707                        old_name,
13708                        editor: rename_editor,
13709                        block_id,
13710                    });
13711                })?;
13712            }
13713
13714            Ok(())
13715        }))
13716    }
13717
13718    pub fn confirm_rename(
13719        &mut self,
13720        _: &ConfirmRename,
13721        window: &mut Window,
13722        cx: &mut Context<Self>,
13723    ) -> Option<Task<Result<()>>> {
13724        let rename = self.take_rename(false, window, cx)?;
13725        let workspace = self.workspace()?.downgrade();
13726        let (buffer, start) = self
13727            .buffer
13728            .read(cx)
13729            .text_anchor_for_position(rename.range.start, cx)?;
13730        let (end_buffer, _) = self
13731            .buffer
13732            .read(cx)
13733            .text_anchor_for_position(rename.range.end, cx)?;
13734        if buffer != end_buffer {
13735            return None;
13736        }
13737
13738        let old_name = rename.old_name;
13739        let new_name = rename.editor.read(cx).text(cx);
13740
13741        let rename = self.semantics_provider.as_ref()?.perform_rename(
13742            &buffer,
13743            start,
13744            new_name.clone(),
13745            cx,
13746        )?;
13747
13748        Some(cx.spawn_in(window, async move |editor, cx| {
13749            let project_transaction = rename.await?;
13750            Self::open_project_transaction(
13751                &editor,
13752                workspace,
13753                project_transaction,
13754                format!("Rename: {}{}", old_name, new_name),
13755                cx,
13756            )
13757            .await?;
13758
13759            editor.update(cx, |editor, cx| {
13760                editor.refresh_document_highlights(cx);
13761            })?;
13762            Ok(())
13763        }))
13764    }
13765
13766    fn take_rename(
13767        &mut self,
13768        moving_cursor: bool,
13769        window: &mut Window,
13770        cx: &mut Context<Self>,
13771    ) -> Option<RenameState> {
13772        let rename = self.pending_rename.take()?;
13773        if rename.editor.focus_handle(cx).is_focused(window) {
13774            window.focus(&self.focus_handle);
13775        }
13776
13777        self.remove_blocks(
13778            [rename.block_id].into_iter().collect(),
13779            Some(Autoscroll::fit()),
13780            cx,
13781        );
13782        self.clear_highlights::<Rename>(cx);
13783        self.show_local_selections = true;
13784
13785        if moving_cursor {
13786            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13787                editor.selections.newest::<usize>(cx).head()
13788            });
13789
13790            // Update the selection to match the position of the selection inside
13791            // the rename editor.
13792            let snapshot = self.buffer.read(cx).read(cx);
13793            let rename_range = rename.range.to_offset(&snapshot);
13794            let cursor_in_editor = snapshot
13795                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13796                .min(rename_range.end);
13797            drop(snapshot);
13798
13799            self.change_selections(None, window, cx, |s| {
13800                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13801            });
13802        } else {
13803            self.refresh_document_highlights(cx);
13804        }
13805
13806        Some(rename)
13807    }
13808
13809    pub fn pending_rename(&self) -> Option<&RenameState> {
13810        self.pending_rename.as_ref()
13811    }
13812
13813    fn format(
13814        &mut self,
13815        _: &Format,
13816        window: &mut Window,
13817        cx: &mut Context<Self>,
13818    ) -> Option<Task<Result<()>>> {
13819        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13820
13821        let project = match &self.project {
13822            Some(project) => project.clone(),
13823            None => return None,
13824        };
13825
13826        Some(self.perform_format(
13827            project,
13828            FormatTrigger::Manual,
13829            FormatTarget::Buffers,
13830            window,
13831            cx,
13832        ))
13833    }
13834
13835    fn format_selections(
13836        &mut self,
13837        _: &FormatSelections,
13838        window: &mut Window,
13839        cx: &mut Context<Self>,
13840    ) -> Option<Task<Result<()>>> {
13841        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13842
13843        let project = match &self.project {
13844            Some(project) => project.clone(),
13845            None => return None,
13846        };
13847
13848        let ranges = self
13849            .selections
13850            .all_adjusted(cx)
13851            .into_iter()
13852            .map(|selection| selection.range())
13853            .collect_vec();
13854
13855        Some(self.perform_format(
13856            project,
13857            FormatTrigger::Manual,
13858            FormatTarget::Ranges(ranges),
13859            window,
13860            cx,
13861        ))
13862    }
13863
13864    fn perform_format(
13865        &mut self,
13866        project: Entity<Project>,
13867        trigger: FormatTrigger,
13868        target: FormatTarget,
13869        window: &mut Window,
13870        cx: &mut Context<Self>,
13871    ) -> Task<Result<()>> {
13872        let buffer = self.buffer.clone();
13873        let (buffers, target) = match target {
13874            FormatTarget::Buffers => {
13875                let mut buffers = buffer.read(cx).all_buffers();
13876                if trigger == FormatTrigger::Save {
13877                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
13878                }
13879                (buffers, LspFormatTarget::Buffers)
13880            }
13881            FormatTarget::Ranges(selection_ranges) => {
13882                let multi_buffer = buffer.read(cx);
13883                let snapshot = multi_buffer.read(cx);
13884                let mut buffers = HashSet::default();
13885                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13886                    BTreeMap::new();
13887                for selection_range in selection_ranges {
13888                    for (buffer, buffer_range, _) in
13889                        snapshot.range_to_buffer_ranges(selection_range)
13890                    {
13891                        let buffer_id = buffer.remote_id();
13892                        let start = buffer.anchor_before(buffer_range.start);
13893                        let end = buffer.anchor_after(buffer_range.end);
13894                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13895                        buffer_id_to_ranges
13896                            .entry(buffer_id)
13897                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13898                            .or_insert_with(|| vec![start..end]);
13899                    }
13900                }
13901                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13902            }
13903        };
13904
13905        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13906        let format = project.update(cx, |project, cx| {
13907            project.format(buffers, target, true, trigger, cx)
13908        });
13909
13910        cx.spawn_in(window, async move |_, cx| {
13911            let transaction = futures::select_biased! {
13912                transaction = format.log_err().fuse() => transaction,
13913                () = timeout => {
13914                    log::warn!("timed out waiting for formatting");
13915                    None
13916                }
13917            };
13918
13919            buffer
13920                .update(cx, |buffer, cx| {
13921                    if let Some(transaction) = transaction {
13922                        if !buffer.is_singleton() {
13923                            buffer.push_transaction(&transaction.0, cx);
13924                        }
13925                    }
13926                    cx.notify();
13927                })
13928                .ok();
13929
13930            Ok(())
13931        })
13932    }
13933
13934    fn organize_imports(
13935        &mut self,
13936        _: &OrganizeImports,
13937        window: &mut Window,
13938        cx: &mut Context<Self>,
13939    ) -> Option<Task<Result<()>>> {
13940        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13941        let project = match &self.project {
13942            Some(project) => project.clone(),
13943            None => return None,
13944        };
13945        Some(self.perform_code_action_kind(
13946            project,
13947            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13948            window,
13949            cx,
13950        ))
13951    }
13952
13953    fn perform_code_action_kind(
13954        &mut self,
13955        project: Entity<Project>,
13956        kind: CodeActionKind,
13957        window: &mut Window,
13958        cx: &mut Context<Self>,
13959    ) -> Task<Result<()>> {
13960        let buffer = self.buffer.clone();
13961        let buffers = buffer.read(cx).all_buffers();
13962        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13963        let apply_action = project.update(cx, |project, cx| {
13964            project.apply_code_action_kind(buffers, kind, true, cx)
13965        });
13966        cx.spawn_in(window, async move |_, cx| {
13967            let transaction = futures::select_biased! {
13968                () = timeout => {
13969                    log::warn!("timed out waiting for executing code action");
13970                    None
13971                }
13972                transaction = apply_action.log_err().fuse() => transaction,
13973            };
13974            buffer
13975                .update(cx, |buffer, cx| {
13976                    // check if we need this
13977                    if let Some(transaction) = transaction {
13978                        if !buffer.is_singleton() {
13979                            buffer.push_transaction(&transaction.0, cx);
13980                        }
13981                    }
13982                    cx.notify();
13983                })
13984                .ok();
13985            Ok(())
13986        })
13987    }
13988
13989    fn restart_language_server(
13990        &mut self,
13991        _: &RestartLanguageServer,
13992        _: &mut Window,
13993        cx: &mut Context<Self>,
13994    ) {
13995        if let Some(project) = self.project.clone() {
13996            self.buffer.update(cx, |multi_buffer, cx| {
13997                project.update(cx, |project, cx| {
13998                    project.restart_language_servers_for_buffers(
13999                        multi_buffer.all_buffers().into_iter().collect(),
14000                        cx,
14001                    );
14002                });
14003            })
14004        }
14005    }
14006
14007    fn cancel_language_server_work(
14008        workspace: &mut Workspace,
14009        _: &actions::CancelLanguageServerWork,
14010        _: &mut Window,
14011        cx: &mut Context<Workspace>,
14012    ) {
14013        let project = workspace.project();
14014        let buffers = workspace
14015            .active_item(cx)
14016            .and_then(|item| item.act_as::<Editor>(cx))
14017            .map_or(HashSet::default(), |editor| {
14018                editor.read(cx).buffer.read(cx).all_buffers()
14019            });
14020        project.update(cx, |project, cx| {
14021            project.cancel_language_server_work_for_buffers(buffers, cx);
14022        });
14023    }
14024
14025    fn show_character_palette(
14026        &mut self,
14027        _: &ShowCharacterPalette,
14028        window: &mut Window,
14029        _: &mut Context<Self>,
14030    ) {
14031        window.show_character_palette();
14032    }
14033
14034    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14035        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14036            let buffer = self.buffer.read(cx).snapshot(cx);
14037            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14038            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14039            let is_valid = buffer
14040                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14041                .any(|entry| {
14042                    entry.diagnostic.is_primary
14043                        && !entry.range.is_empty()
14044                        && entry.range.start == primary_range_start
14045                        && entry.diagnostic.message == active_diagnostics.primary_message
14046                });
14047
14048            if is_valid != active_diagnostics.is_valid {
14049                active_diagnostics.is_valid = is_valid;
14050                if is_valid {
14051                    let mut new_styles = HashMap::default();
14052                    for (block_id, diagnostic) in &active_diagnostics.blocks {
14053                        new_styles.insert(
14054                            *block_id,
14055                            diagnostic_block_renderer(diagnostic.clone(), None, true),
14056                        );
14057                    }
14058                    self.display_map.update(cx, |display_map, _cx| {
14059                        display_map.replace_blocks(new_styles);
14060                    });
14061                } else {
14062                    self.dismiss_diagnostics(cx);
14063                }
14064            }
14065        }
14066    }
14067
14068    fn activate_diagnostics(
14069        &mut self,
14070        buffer_id: BufferId,
14071        group_id: usize,
14072        window: &mut Window,
14073        cx: &mut Context<Self>,
14074    ) {
14075        self.dismiss_diagnostics(cx);
14076        let snapshot = self.snapshot(window, cx);
14077        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14078            let buffer = self.buffer.read(cx).snapshot(cx);
14079
14080            let mut primary_range = None;
14081            let mut primary_message = None;
14082            let diagnostic_group = buffer
14083                .diagnostic_group(buffer_id, group_id)
14084                .filter_map(|entry| {
14085                    let start = entry.range.start;
14086                    let end = entry.range.end;
14087                    if snapshot.is_line_folded(MultiBufferRow(start.row))
14088                        && (start.row == end.row
14089                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
14090                    {
14091                        return None;
14092                    }
14093                    if entry.diagnostic.is_primary {
14094                        primary_range = Some(entry.range.clone());
14095                        primary_message = Some(entry.diagnostic.message.clone());
14096                    }
14097                    Some(entry)
14098                })
14099                .collect::<Vec<_>>();
14100            let primary_range = primary_range?;
14101            let primary_message = primary_message?;
14102
14103            let blocks = display_map
14104                .insert_blocks(
14105                    diagnostic_group.iter().map(|entry| {
14106                        let diagnostic = entry.diagnostic.clone();
14107                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14108                        BlockProperties {
14109                            style: BlockStyle::Fixed,
14110                            placement: BlockPlacement::Below(
14111                                buffer.anchor_after(entry.range.start),
14112                            ),
14113                            height: message_height,
14114                            render: diagnostic_block_renderer(diagnostic, None, true),
14115                            priority: 0,
14116                        }
14117                    }),
14118                    cx,
14119                )
14120                .into_iter()
14121                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14122                .collect();
14123
14124            Some(ActiveDiagnosticGroup {
14125                primary_range: buffer.anchor_before(primary_range.start)
14126                    ..buffer.anchor_after(primary_range.end),
14127                primary_message,
14128                group_id,
14129                blocks,
14130                is_valid: true,
14131            })
14132        });
14133    }
14134
14135    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14136        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14137            self.display_map.update(cx, |display_map, cx| {
14138                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14139            });
14140            cx.notify();
14141        }
14142    }
14143
14144    /// Disable inline diagnostics rendering for this editor.
14145    pub fn disable_inline_diagnostics(&mut self) {
14146        self.inline_diagnostics_enabled = false;
14147        self.inline_diagnostics_update = Task::ready(());
14148        self.inline_diagnostics.clear();
14149    }
14150
14151    pub fn inline_diagnostics_enabled(&self) -> bool {
14152        self.inline_diagnostics_enabled
14153    }
14154
14155    pub fn show_inline_diagnostics(&self) -> bool {
14156        self.show_inline_diagnostics
14157    }
14158
14159    pub fn toggle_inline_diagnostics(
14160        &mut self,
14161        _: &ToggleInlineDiagnostics,
14162        window: &mut Window,
14163        cx: &mut Context<Editor>,
14164    ) {
14165        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14166        self.refresh_inline_diagnostics(false, window, cx);
14167    }
14168
14169    fn refresh_inline_diagnostics(
14170        &mut self,
14171        debounce: bool,
14172        window: &mut Window,
14173        cx: &mut Context<Self>,
14174    ) {
14175        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14176            self.inline_diagnostics_update = Task::ready(());
14177            self.inline_diagnostics.clear();
14178            return;
14179        }
14180
14181        let debounce_ms = ProjectSettings::get_global(cx)
14182            .diagnostics
14183            .inline
14184            .update_debounce_ms;
14185        let debounce = if debounce && debounce_ms > 0 {
14186            Some(Duration::from_millis(debounce_ms))
14187        } else {
14188            None
14189        };
14190        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14191            if let Some(debounce) = debounce {
14192                cx.background_executor().timer(debounce).await;
14193            }
14194            let Some(snapshot) = editor
14195                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14196                .ok()
14197            else {
14198                return;
14199            };
14200
14201            let new_inline_diagnostics = cx
14202                .background_spawn(async move {
14203                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14204                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14205                        let message = diagnostic_entry
14206                            .diagnostic
14207                            .message
14208                            .split_once('\n')
14209                            .map(|(line, _)| line)
14210                            .map(SharedString::new)
14211                            .unwrap_or_else(|| {
14212                                SharedString::from(diagnostic_entry.diagnostic.message)
14213                            });
14214                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14215                        let (Ok(i) | Err(i)) = inline_diagnostics
14216                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14217                        inline_diagnostics.insert(
14218                            i,
14219                            (
14220                                start_anchor,
14221                                InlineDiagnostic {
14222                                    message,
14223                                    group_id: diagnostic_entry.diagnostic.group_id,
14224                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14225                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14226                                    severity: diagnostic_entry.diagnostic.severity,
14227                                },
14228                            ),
14229                        );
14230                    }
14231                    inline_diagnostics
14232                })
14233                .await;
14234
14235            editor
14236                .update(cx, |editor, cx| {
14237                    editor.inline_diagnostics = new_inline_diagnostics;
14238                    cx.notify();
14239                })
14240                .ok();
14241        });
14242    }
14243
14244    pub fn set_selections_from_remote(
14245        &mut self,
14246        selections: Vec<Selection<Anchor>>,
14247        pending_selection: Option<Selection<Anchor>>,
14248        window: &mut Window,
14249        cx: &mut Context<Self>,
14250    ) {
14251        let old_cursor_position = self.selections.newest_anchor().head();
14252        self.selections.change_with(cx, |s| {
14253            s.select_anchors(selections);
14254            if let Some(pending_selection) = pending_selection {
14255                s.set_pending(pending_selection, SelectMode::Character);
14256            } else {
14257                s.clear_pending();
14258            }
14259        });
14260        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14261    }
14262
14263    fn push_to_selection_history(&mut self) {
14264        self.selection_history.push(SelectionHistoryEntry {
14265            selections: self.selections.disjoint_anchors(),
14266            select_next_state: self.select_next_state.clone(),
14267            select_prev_state: self.select_prev_state.clone(),
14268            add_selections_state: self.add_selections_state.clone(),
14269        });
14270    }
14271
14272    pub fn transact(
14273        &mut self,
14274        window: &mut Window,
14275        cx: &mut Context<Self>,
14276        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14277    ) -> Option<TransactionId> {
14278        self.start_transaction_at(Instant::now(), window, cx);
14279        update(self, window, cx);
14280        self.end_transaction_at(Instant::now(), cx)
14281    }
14282
14283    pub fn start_transaction_at(
14284        &mut self,
14285        now: Instant,
14286        window: &mut Window,
14287        cx: &mut Context<Self>,
14288    ) {
14289        self.end_selection(window, cx);
14290        if let Some(tx_id) = self
14291            .buffer
14292            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14293        {
14294            self.selection_history
14295                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14296            cx.emit(EditorEvent::TransactionBegun {
14297                transaction_id: tx_id,
14298            })
14299        }
14300    }
14301
14302    pub fn end_transaction_at(
14303        &mut self,
14304        now: Instant,
14305        cx: &mut Context<Self>,
14306    ) -> Option<TransactionId> {
14307        if let Some(transaction_id) = self
14308            .buffer
14309            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14310        {
14311            if let Some((_, end_selections)) =
14312                self.selection_history.transaction_mut(transaction_id)
14313            {
14314                *end_selections = Some(self.selections.disjoint_anchors());
14315            } else {
14316                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14317            }
14318
14319            cx.emit(EditorEvent::Edited { transaction_id });
14320            Some(transaction_id)
14321        } else {
14322            None
14323        }
14324    }
14325
14326    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14327        if self.selection_mark_mode {
14328            self.change_selections(None, window, cx, |s| {
14329                s.move_with(|_, sel| {
14330                    sel.collapse_to(sel.head(), SelectionGoal::None);
14331                });
14332            })
14333        }
14334        self.selection_mark_mode = true;
14335        cx.notify();
14336    }
14337
14338    pub fn swap_selection_ends(
14339        &mut self,
14340        _: &actions::SwapSelectionEnds,
14341        window: &mut Window,
14342        cx: &mut Context<Self>,
14343    ) {
14344        self.change_selections(None, window, cx, |s| {
14345            s.move_with(|_, sel| {
14346                if sel.start != sel.end {
14347                    sel.reversed = !sel.reversed
14348                }
14349            });
14350        });
14351        self.request_autoscroll(Autoscroll::newest(), cx);
14352        cx.notify();
14353    }
14354
14355    pub fn toggle_fold(
14356        &mut self,
14357        _: &actions::ToggleFold,
14358        window: &mut Window,
14359        cx: &mut Context<Self>,
14360    ) {
14361        if self.is_singleton(cx) {
14362            let selection = self.selections.newest::<Point>(cx);
14363
14364            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14365            let range = if selection.is_empty() {
14366                let point = selection.head().to_display_point(&display_map);
14367                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14368                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14369                    .to_point(&display_map);
14370                start..end
14371            } else {
14372                selection.range()
14373            };
14374            if display_map.folds_in_range(range).next().is_some() {
14375                self.unfold_lines(&Default::default(), window, cx)
14376            } else {
14377                self.fold(&Default::default(), window, cx)
14378            }
14379        } else {
14380            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14381            let buffer_ids: HashSet<_> = self
14382                .selections
14383                .disjoint_anchor_ranges()
14384                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14385                .collect();
14386
14387            let should_unfold = buffer_ids
14388                .iter()
14389                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14390
14391            for buffer_id in buffer_ids {
14392                if should_unfold {
14393                    self.unfold_buffer(buffer_id, cx);
14394                } else {
14395                    self.fold_buffer(buffer_id, cx);
14396                }
14397            }
14398        }
14399    }
14400
14401    pub fn toggle_fold_recursive(
14402        &mut self,
14403        _: &actions::ToggleFoldRecursive,
14404        window: &mut Window,
14405        cx: &mut Context<Self>,
14406    ) {
14407        let selection = self.selections.newest::<Point>(cx);
14408
14409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14410        let range = if selection.is_empty() {
14411            let point = selection.head().to_display_point(&display_map);
14412            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14413            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14414                .to_point(&display_map);
14415            start..end
14416        } else {
14417            selection.range()
14418        };
14419        if display_map.folds_in_range(range).next().is_some() {
14420            self.unfold_recursive(&Default::default(), window, cx)
14421        } else {
14422            self.fold_recursive(&Default::default(), window, cx)
14423        }
14424    }
14425
14426    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14427        if self.is_singleton(cx) {
14428            let mut to_fold = Vec::new();
14429            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14430            let selections = self.selections.all_adjusted(cx);
14431
14432            for selection in selections {
14433                let range = selection.range().sorted();
14434                let buffer_start_row = range.start.row;
14435
14436                if range.start.row != range.end.row {
14437                    let mut found = false;
14438                    let mut row = range.start.row;
14439                    while row <= range.end.row {
14440                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14441                        {
14442                            found = true;
14443                            row = crease.range().end.row + 1;
14444                            to_fold.push(crease);
14445                        } else {
14446                            row += 1
14447                        }
14448                    }
14449                    if found {
14450                        continue;
14451                    }
14452                }
14453
14454                for row in (0..=range.start.row).rev() {
14455                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14456                        if crease.range().end.row >= buffer_start_row {
14457                            to_fold.push(crease);
14458                            if row <= range.start.row {
14459                                break;
14460                            }
14461                        }
14462                    }
14463                }
14464            }
14465
14466            self.fold_creases(to_fold, true, window, cx);
14467        } else {
14468            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14469            let buffer_ids = self
14470                .selections
14471                .disjoint_anchor_ranges()
14472                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14473                .collect::<HashSet<_>>();
14474            for buffer_id in buffer_ids {
14475                self.fold_buffer(buffer_id, cx);
14476            }
14477        }
14478    }
14479
14480    fn fold_at_level(
14481        &mut self,
14482        fold_at: &FoldAtLevel,
14483        window: &mut Window,
14484        cx: &mut Context<Self>,
14485    ) {
14486        if !self.buffer.read(cx).is_singleton() {
14487            return;
14488        }
14489
14490        let fold_at_level = fold_at.0;
14491        let snapshot = self.buffer.read(cx).snapshot(cx);
14492        let mut to_fold = Vec::new();
14493        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14494
14495        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14496            while start_row < end_row {
14497                match self
14498                    .snapshot(window, cx)
14499                    .crease_for_buffer_row(MultiBufferRow(start_row))
14500                {
14501                    Some(crease) => {
14502                        let nested_start_row = crease.range().start.row + 1;
14503                        let nested_end_row = crease.range().end.row;
14504
14505                        if current_level < fold_at_level {
14506                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14507                        } else if current_level == fold_at_level {
14508                            to_fold.push(crease);
14509                        }
14510
14511                        start_row = nested_end_row + 1;
14512                    }
14513                    None => start_row += 1,
14514                }
14515            }
14516        }
14517
14518        self.fold_creases(to_fold, true, window, cx);
14519    }
14520
14521    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14522        if self.buffer.read(cx).is_singleton() {
14523            let mut fold_ranges = Vec::new();
14524            let snapshot = self.buffer.read(cx).snapshot(cx);
14525
14526            for row in 0..snapshot.max_row().0 {
14527                if let Some(foldable_range) = self
14528                    .snapshot(window, cx)
14529                    .crease_for_buffer_row(MultiBufferRow(row))
14530                {
14531                    fold_ranges.push(foldable_range);
14532                }
14533            }
14534
14535            self.fold_creases(fold_ranges, true, window, cx);
14536        } else {
14537            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14538                editor
14539                    .update_in(cx, |editor, _, cx| {
14540                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14541                            editor.fold_buffer(buffer_id, cx);
14542                        }
14543                    })
14544                    .ok();
14545            });
14546        }
14547    }
14548
14549    pub fn fold_function_bodies(
14550        &mut self,
14551        _: &actions::FoldFunctionBodies,
14552        window: &mut Window,
14553        cx: &mut Context<Self>,
14554    ) {
14555        let snapshot = self.buffer.read(cx).snapshot(cx);
14556
14557        let ranges = snapshot
14558            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14559            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14560            .collect::<Vec<_>>();
14561
14562        let creases = ranges
14563            .into_iter()
14564            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14565            .collect();
14566
14567        self.fold_creases(creases, true, window, cx);
14568    }
14569
14570    pub fn fold_recursive(
14571        &mut self,
14572        _: &actions::FoldRecursive,
14573        window: &mut Window,
14574        cx: &mut Context<Self>,
14575    ) {
14576        let mut to_fold = Vec::new();
14577        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14578        let selections = self.selections.all_adjusted(cx);
14579
14580        for selection in selections {
14581            let range = selection.range().sorted();
14582            let buffer_start_row = range.start.row;
14583
14584            if range.start.row != range.end.row {
14585                let mut found = false;
14586                for row in range.start.row..=range.end.row {
14587                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14588                        found = true;
14589                        to_fold.push(crease);
14590                    }
14591                }
14592                if found {
14593                    continue;
14594                }
14595            }
14596
14597            for row in (0..=range.start.row).rev() {
14598                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14599                    if crease.range().end.row >= buffer_start_row {
14600                        to_fold.push(crease);
14601                    } else {
14602                        break;
14603                    }
14604                }
14605            }
14606        }
14607
14608        self.fold_creases(to_fold, true, window, cx);
14609    }
14610
14611    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14612        let buffer_row = fold_at.buffer_row;
14613        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14614
14615        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14616            let autoscroll = self
14617                .selections
14618                .all::<Point>(cx)
14619                .iter()
14620                .any(|selection| crease.range().overlaps(&selection.range()));
14621
14622            self.fold_creases(vec![crease], autoscroll, window, cx);
14623        }
14624    }
14625
14626    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14627        if self.is_singleton(cx) {
14628            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14629            let buffer = &display_map.buffer_snapshot;
14630            let selections = self.selections.all::<Point>(cx);
14631            let ranges = selections
14632                .iter()
14633                .map(|s| {
14634                    let range = s.display_range(&display_map).sorted();
14635                    let mut start = range.start.to_point(&display_map);
14636                    let mut end = range.end.to_point(&display_map);
14637                    start.column = 0;
14638                    end.column = buffer.line_len(MultiBufferRow(end.row));
14639                    start..end
14640                })
14641                .collect::<Vec<_>>();
14642
14643            self.unfold_ranges(&ranges, true, true, cx);
14644        } else {
14645            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14646            let buffer_ids = self
14647                .selections
14648                .disjoint_anchor_ranges()
14649                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14650                .collect::<HashSet<_>>();
14651            for buffer_id in buffer_ids {
14652                self.unfold_buffer(buffer_id, cx);
14653            }
14654        }
14655    }
14656
14657    pub fn unfold_recursive(
14658        &mut self,
14659        _: &UnfoldRecursive,
14660        _window: &mut Window,
14661        cx: &mut Context<Self>,
14662    ) {
14663        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14664        let selections = self.selections.all::<Point>(cx);
14665        let ranges = selections
14666            .iter()
14667            .map(|s| {
14668                let mut range = s.display_range(&display_map).sorted();
14669                *range.start.column_mut() = 0;
14670                *range.end.column_mut() = display_map.line_len(range.end.row());
14671                let start = range.start.to_point(&display_map);
14672                let end = range.end.to_point(&display_map);
14673                start..end
14674            })
14675            .collect::<Vec<_>>();
14676
14677        self.unfold_ranges(&ranges, true, true, cx);
14678    }
14679
14680    pub fn unfold_at(
14681        &mut self,
14682        unfold_at: &UnfoldAt,
14683        _window: &mut Window,
14684        cx: &mut Context<Self>,
14685    ) {
14686        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14687
14688        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14689            ..Point::new(
14690                unfold_at.buffer_row.0,
14691                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14692            );
14693
14694        let autoscroll = self
14695            .selections
14696            .all::<Point>(cx)
14697            .iter()
14698            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14699
14700        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14701    }
14702
14703    pub fn unfold_all(
14704        &mut self,
14705        _: &actions::UnfoldAll,
14706        _window: &mut Window,
14707        cx: &mut Context<Self>,
14708    ) {
14709        if self.buffer.read(cx).is_singleton() {
14710            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14711            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14712        } else {
14713            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14714                editor
14715                    .update(cx, |editor, cx| {
14716                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14717                            editor.unfold_buffer(buffer_id, cx);
14718                        }
14719                    })
14720                    .ok();
14721            });
14722        }
14723    }
14724
14725    pub fn fold_selected_ranges(
14726        &mut self,
14727        _: &FoldSelectedRanges,
14728        window: &mut Window,
14729        cx: &mut Context<Self>,
14730    ) {
14731        let selections = self.selections.all_adjusted(cx);
14732        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14733        let ranges = selections
14734            .into_iter()
14735            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14736            .collect::<Vec<_>>();
14737        self.fold_creases(ranges, true, window, cx);
14738    }
14739
14740    pub fn fold_ranges<T: ToOffset + Clone>(
14741        &mut self,
14742        ranges: Vec<Range<T>>,
14743        auto_scroll: bool,
14744        window: &mut Window,
14745        cx: &mut Context<Self>,
14746    ) {
14747        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14748        let ranges = ranges
14749            .into_iter()
14750            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14751            .collect::<Vec<_>>();
14752        self.fold_creases(ranges, auto_scroll, window, cx);
14753    }
14754
14755    pub fn fold_creases<T: ToOffset + Clone>(
14756        &mut self,
14757        creases: Vec<Crease<T>>,
14758        auto_scroll: bool,
14759        window: &mut Window,
14760        cx: &mut Context<Self>,
14761    ) {
14762        if creases.is_empty() {
14763            return;
14764        }
14765
14766        let mut buffers_affected = HashSet::default();
14767        let multi_buffer = self.buffer().read(cx);
14768        for crease in &creases {
14769            if let Some((_, buffer, _)) =
14770                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14771            {
14772                buffers_affected.insert(buffer.read(cx).remote_id());
14773            };
14774        }
14775
14776        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14777
14778        if auto_scroll {
14779            self.request_autoscroll(Autoscroll::fit(), cx);
14780        }
14781
14782        cx.notify();
14783
14784        if let Some(active_diagnostics) = self.active_diagnostics.take() {
14785            // Clear diagnostics block when folding a range that contains it.
14786            let snapshot = self.snapshot(window, cx);
14787            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14788                drop(snapshot);
14789                self.active_diagnostics = Some(active_diagnostics);
14790                self.dismiss_diagnostics(cx);
14791            } else {
14792                self.active_diagnostics = Some(active_diagnostics);
14793            }
14794        }
14795
14796        self.scrollbar_marker_state.dirty = true;
14797        self.folds_did_change(cx);
14798    }
14799
14800    /// Removes any folds whose ranges intersect any of the given ranges.
14801    pub fn unfold_ranges<T: ToOffset + Clone>(
14802        &mut self,
14803        ranges: &[Range<T>],
14804        inclusive: bool,
14805        auto_scroll: bool,
14806        cx: &mut Context<Self>,
14807    ) {
14808        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14809            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14810        });
14811        self.folds_did_change(cx);
14812    }
14813
14814    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14815        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14816            return;
14817        }
14818        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14819        self.display_map.update(cx, |display_map, cx| {
14820            display_map.fold_buffers([buffer_id], cx)
14821        });
14822        cx.emit(EditorEvent::BufferFoldToggled {
14823            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14824            folded: true,
14825        });
14826        cx.notify();
14827    }
14828
14829    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14830        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14831            return;
14832        }
14833        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14834        self.display_map.update(cx, |display_map, cx| {
14835            display_map.unfold_buffers([buffer_id], cx);
14836        });
14837        cx.emit(EditorEvent::BufferFoldToggled {
14838            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14839            folded: false,
14840        });
14841        cx.notify();
14842    }
14843
14844    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14845        self.display_map.read(cx).is_buffer_folded(buffer)
14846    }
14847
14848    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14849        self.display_map.read(cx).folded_buffers()
14850    }
14851
14852    /// Removes any folds with the given ranges.
14853    pub fn remove_folds_with_type<T: ToOffset + Clone>(
14854        &mut self,
14855        ranges: &[Range<T>],
14856        type_id: TypeId,
14857        auto_scroll: bool,
14858        cx: &mut Context<Self>,
14859    ) {
14860        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14861            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14862        });
14863        self.folds_did_change(cx);
14864    }
14865
14866    fn remove_folds_with<T: ToOffset + Clone>(
14867        &mut self,
14868        ranges: &[Range<T>],
14869        auto_scroll: bool,
14870        cx: &mut Context<Self>,
14871        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14872    ) {
14873        if ranges.is_empty() {
14874            return;
14875        }
14876
14877        let mut buffers_affected = HashSet::default();
14878        let multi_buffer = self.buffer().read(cx);
14879        for range in ranges {
14880            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14881                buffers_affected.insert(buffer.read(cx).remote_id());
14882            };
14883        }
14884
14885        self.display_map.update(cx, update);
14886
14887        if auto_scroll {
14888            self.request_autoscroll(Autoscroll::fit(), cx);
14889        }
14890
14891        cx.notify();
14892        self.scrollbar_marker_state.dirty = true;
14893        self.active_indent_guides_state.dirty = true;
14894    }
14895
14896    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14897        self.display_map.read(cx).fold_placeholder.clone()
14898    }
14899
14900    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14901        self.buffer.update(cx, |buffer, cx| {
14902            buffer.set_all_diff_hunks_expanded(cx);
14903        });
14904    }
14905
14906    pub fn expand_all_diff_hunks(
14907        &mut self,
14908        _: &ExpandAllDiffHunks,
14909        _window: &mut Window,
14910        cx: &mut Context<Self>,
14911    ) {
14912        self.buffer.update(cx, |buffer, cx| {
14913            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14914        });
14915    }
14916
14917    pub fn toggle_selected_diff_hunks(
14918        &mut self,
14919        _: &ToggleSelectedDiffHunks,
14920        _window: &mut Window,
14921        cx: &mut Context<Self>,
14922    ) {
14923        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14924        self.toggle_diff_hunks_in_ranges(ranges, cx);
14925    }
14926
14927    pub fn diff_hunks_in_ranges<'a>(
14928        &'a self,
14929        ranges: &'a [Range<Anchor>],
14930        buffer: &'a MultiBufferSnapshot,
14931    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14932        ranges.iter().flat_map(move |range| {
14933            let end_excerpt_id = range.end.excerpt_id;
14934            let range = range.to_point(buffer);
14935            let mut peek_end = range.end;
14936            if range.end.row < buffer.max_row().0 {
14937                peek_end = Point::new(range.end.row + 1, 0);
14938            }
14939            buffer
14940                .diff_hunks_in_range(range.start..peek_end)
14941                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14942        })
14943    }
14944
14945    pub fn has_stageable_diff_hunks_in_ranges(
14946        &self,
14947        ranges: &[Range<Anchor>],
14948        snapshot: &MultiBufferSnapshot,
14949    ) -> bool {
14950        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14951        hunks.any(|hunk| hunk.status().has_secondary_hunk())
14952    }
14953
14954    pub fn toggle_staged_selected_diff_hunks(
14955        &mut self,
14956        _: &::git::ToggleStaged,
14957        _: &mut Window,
14958        cx: &mut Context<Self>,
14959    ) {
14960        let snapshot = self.buffer.read(cx).snapshot(cx);
14961        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14962        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14963        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14964    }
14965
14966    pub fn set_render_diff_hunk_controls(
14967        &mut self,
14968        render_diff_hunk_controls: RenderDiffHunkControlsFn,
14969        cx: &mut Context<Self>,
14970    ) {
14971        self.render_diff_hunk_controls = render_diff_hunk_controls;
14972        cx.notify();
14973    }
14974
14975    pub fn stage_and_next(
14976        &mut self,
14977        _: &::git::StageAndNext,
14978        window: &mut Window,
14979        cx: &mut Context<Self>,
14980    ) {
14981        self.do_stage_or_unstage_and_next(true, window, cx);
14982    }
14983
14984    pub fn unstage_and_next(
14985        &mut self,
14986        _: &::git::UnstageAndNext,
14987        window: &mut Window,
14988        cx: &mut Context<Self>,
14989    ) {
14990        self.do_stage_or_unstage_and_next(false, window, cx);
14991    }
14992
14993    pub fn stage_or_unstage_diff_hunks(
14994        &mut self,
14995        stage: bool,
14996        ranges: Vec<Range<Anchor>>,
14997        cx: &mut Context<Self>,
14998    ) {
14999        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15000        cx.spawn(async move |this, cx| {
15001            task.await?;
15002            this.update(cx, |this, cx| {
15003                let snapshot = this.buffer.read(cx).snapshot(cx);
15004                let chunk_by = this
15005                    .diff_hunks_in_ranges(&ranges, &snapshot)
15006                    .chunk_by(|hunk| hunk.buffer_id);
15007                for (buffer_id, hunks) in &chunk_by {
15008                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15009                }
15010            })
15011        })
15012        .detach_and_log_err(cx);
15013    }
15014
15015    fn save_buffers_for_ranges_if_needed(
15016        &mut self,
15017        ranges: &[Range<Anchor>],
15018        cx: &mut Context<Editor>,
15019    ) -> Task<Result<()>> {
15020        let multibuffer = self.buffer.read(cx);
15021        let snapshot = multibuffer.read(cx);
15022        let buffer_ids: HashSet<_> = ranges
15023            .iter()
15024            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15025            .collect();
15026        drop(snapshot);
15027
15028        let mut buffers = HashSet::default();
15029        for buffer_id in buffer_ids {
15030            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15031                let buffer = buffer_entity.read(cx);
15032                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15033                {
15034                    buffers.insert(buffer_entity);
15035                }
15036            }
15037        }
15038
15039        if let Some(project) = &self.project {
15040            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15041        } else {
15042            Task::ready(Ok(()))
15043        }
15044    }
15045
15046    fn do_stage_or_unstage_and_next(
15047        &mut self,
15048        stage: bool,
15049        window: &mut Window,
15050        cx: &mut Context<Self>,
15051    ) {
15052        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15053
15054        if ranges.iter().any(|range| range.start != range.end) {
15055            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15056            return;
15057        }
15058
15059        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15060        let snapshot = self.snapshot(window, cx);
15061        let position = self.selections.newest::<Point>(cx).head();
15062        let mut row = snapshot
15063            .buffer_snapshot
15064            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15065            .find(|hunk| hunk.row_range.start.0 > position.row)
15066            .map(|hunk| hunk.row_range.start);
15067
15068        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15069        // Outside of the project diff editor, wrap around to the beginning.
15070        if !all_diff_hunks_expanded {
15071            row = row.or_else(|| {
15072                snapshot
15073                    .buffer_snapshot
15074                    .diff_hunks_in_range(Point::zero()..position)
15075                    .find(|hunk| hunk.row_range.end.0 < position.row)
15076                    .map(|hunk| hunk.row_range.start)
15077            });
15078        }
15079
15080        if let Some(row) = row {
15081            let destination = Point::new(row.0, 0);
15082            let autoscroll = Autoscroll::center();
15083
15084            self.unfold_ranges(&[destination..destination], false, false, cx);
15085            self.change_selections(Some(autoscroll), window, cx, |s| {
15086                s.select_ranges([destination..destination]);
15087            });
15088        }
15089    }
15090
15091    fn do_stage_or_unstage(
15092        &self,
15093        stage: bool,
15094        buffer_id: BufferId,
15095        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15096        cx: &mut App,
15097    ) -> Option<()> {
15098        let project = self.project.as_ref()?;
15099        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15100        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15101        let buffer_snapshot = buffer.read(cx).snapshot();
15102        let file_exists = buffer_snapshot
15103            .file()
15104            .is_some_and(|file| file.disk_state().exists());
15105        diff.update(cx, |diff, cx| {
15106            diff.stage_or_unstage_hunks(
15107                stage,
15108                &hunks
15109                    .map(|hunk| buffer_diff::DiffHunk {
15110                        buffer_range: hunk.buffer_range,
15111                        diff_base_byte_range: hunk.diff_base_byte_range,
15112                        secondary_status: hunk.secondary_status,
15113                        range: Point::zero()..Point::zero(), // unused
15114                    })
15115                    .collect::<Vec<_>>(),
15116                &buffer_snapshot,
15117                file_exists,
15118                cx,
15119            )
15120        });
15121        None
15122    }
15123
15124    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15125        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15126        self.buffer
15127            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15128    }
15129
15130    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15131        self.buffer.update(cx, |buffer, cx| {
15132            let ranges = vec![Anchor::min()..Anchor::max()];
15133            if !buffer.all_diff_hunks_expanded()
15134                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15135            {
15136                buffer.collapse_diff_hunks(ranges, cx);
15137                true
15138            } else {
15139                false
15140            }
15141        })
15142    }
15143
15144    fn toggle_diff_hunks_in_ranges(
15145        &mut self,
15146        ranges: Vec<Range<Anchor>>,
15147        cx: &mut Context<Editor>,
15148    ) {
15149        self.buffer.update(cx, |buffer, cx| {
15150            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15151            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15152        })
15153    }
15154
15155    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15156        self.buffer.update(cx, |buffer, cx| {
15157            let snapshot = buffer.snapshot(cx);
15158            let excerpt_id = range.end.excerpt_id;
15159            let point_range = range.to_point(&snapshot);
15160            let expand = !buffer.single_hunk_is_expanded(range, cx);
15161            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15162        })
15163    }
15164
15165    pub(crate) fn apply_all_diff_hunks(
15166        &mut self,
15167        _: &ApplyAllDiffHunks,
15168        window: &mut Window,
15169        cx: &mut Context<Self>,
15170    ) {
15171        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15172
15173        let buffers = self.buffer.read(cx).all_buffers();
15174        for branch_buffer in buffers {
15175            branch_buffer.update(cx, |branch_buffer, cx| {
15176                branch_buffer.merge_into_base(Vec::new(), cx);
15177            });
15178        }
15179
15180        if let Some(project) = self.project.clone() {
15181            self.save(true, project, window, cx).detach_and_log_err(cx);
15182        }
15183    }
15184
15185    pub(crate) fn apply_selected_diff_hunks(
15186        &mut self,
15187        _: &ApplyDiffHunk,
15188        window: &mut Window,
15189        cx: &mut Context<Self>,
15190    ) {
15191        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15192        let snapshot = self.snapshot(window, cx);
15193        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15194        let mut ranges_by_buffer = HashMap::default();
15195        self.transact(window, cx, |editor, _window, cx| {
15196            for hunk in hunks {
15197                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15198                    ranges_by_buffer
15199                        .entry(buffer.clone())
15200                        .or_insert_with(Vec::new)
15201                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15202                }
15203            }
15204
15205            for (buffer, ranges) in ranges_by_buffer {
15206                buffer.update(cx, |buffer, cx| {
15207                    buffer.merge_into_base(ranges, cx);
15208                });
15209            }
15210        });
15211
15212        if let Some(project) = self.project.clone() {
15213            self.save(true, project, window, cx).detach_and_log_err(cx);
15214        }
15215    }
15216
15217    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15218        if hovered != self.gutter_hovered {
15219            self.gutter_hovered = hovered;
15220            cx.notify();
15221        }
15222    }
15223
15224    pub fn insert_blocks(
15225        &mut self,
15226        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15227        autoscroll: Option<Autoscroll>,
15228        cx: &mut Context<Self>,
15229    ) -> Vec<CustomBlockId> {
15230        let blocks = self
15231            .display_map
15232            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15233        if let Some(autoscroll) = autoscroll {
15234            self.request_autoscroll(autoscroll, cx);
15235        }
15236        cx.notify();
15237        blocks
15238    }
15239
15240    pub fn resize_blocks(
15241        &mut self,
15242        heights: HashMap<CustomBlockId, u32>,
15243        autoscroll: Option<Autoscroll>,
15244        cx: &mut Context<Self>,
15245    ) {
15246        self.display_map
15247            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15248        if let Some(autoscroll) = autoscroll {
15249            self.request_autoscroll(autoscroll, cx);
15250        }
15251        cx.notify();
15252    }
15253
15254    pub fn replace_blocks(
15255        &mut self,
15256        renderers: HashMap<CustomBlockId, RenderBlock>,
15257        autoscroll: Option<Autoscroll>,
15258        cx: &mut Context<Self>,
15259    ) {
15260        self.display_map
15261            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15262        if let Some(autoscroll) = autoscroll {
15263            self.request_autoscroll(autoscroll, cx);
15264        }
15265        cx.notify();
15266    }
15267
15268    pub fn remove_blocks(
15269        &mut self,
15270        block_ids: HashSet<CustomBlockId>,
15271        autoscroll: Option<Autoscroll>,
15272        cx: &mut Context<Self>,
15273    ) {
15274        self.display_map.update(cx, |display_map, cx| {
15275            display_map.remove_blocks(block_ids, cx)
15276        });
15277        if let Some(autoscroll) = autoscroll {
15278            self.request_autoscroll(autoscroll, cx);
15279        }
15280        cx.notify();
15281    }
15282
15283    pub fn row_for_block(
15284        &self,
15285        block_id: CustomBlockId,
15286        cx: &mut Context<Self>,
15287    ) -> Option<DisplayRow> {
15288        self.display_map
15289            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15290    }
15291
15292    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15293        self.focused_block = Some(focused_block);
15294    }
15295
15296    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15297        self.focused_block.take()
15298    }
15299
15300    pub fn insert_creases(
15301        &mut self,
15302        creases: impl IntoIterator<Item = Crease<Anchor>>,
15303        cx: &mut Context<Self>,
15304    ) -> Vec<CreaseId> {
15305        self.display_map
15306            .update(cx, |map, cx| map.insert_creases(creases, cx))
15307    }
15308
15309    pub fn remove_creases(
15310        &mut self,
15311        ids: impl IntoIterator<Item = CreaseId>,
15312        cx: &mut Context<Self>,
15313    ) {
15314        self.display_map
15315            .update(cx, |map, cx| map.remove_creases(ids, cx));
15316    }
15317
15318    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15319        self.display_map
15320            .update(cx, |map, cx| map.snapshot(cx))
15321            .longest_row()
15322    }
15323
15324    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15325        self.display_map
15326            .update(cx, |map, cx| map.snapshot(cx))
15327            .max_point()
15328    }
15329
15330    pub fn text(&self, cx: &App) -> String {
15331        self.buffer.read(cx).read(cx).text()
15332    }
15333
15334    pub fn is_empty(&self, cx: &App) -> bool {
15335        self.buffer.read(cx).read(cx).is_empty()
15336    }
15337
15338    pub fn text_option(&self, cx: &App) -> Option<String> {
15339        let text = self.text(cx);
15340        let text = text.trim();
15341
15342        if text.is_empty() {
15343            return None;
15344        }
15345
15346        Some(text.to_string())
15347    }
15348
15349    pub fn set_text(
15350        &mut self,
15351        text: impl Into<Arc<str>>,
15352        window: &mut Window,
15353        cx: &mut Context<Self>,
15354    ) {
15355        self.transact(window, cx, |this, _, cx| {
15356            this.buffer
15357                .read(cx)
15358                .as_singleton()
15359                .expect("you can only call set_text on editors for singleton buffers")
15360                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15361        });
15362    }
15363
15364    pub fn display_text(&self, cx: &mut App) -> String {
15365        self.display_map
15366            .update(cx, |map, cx| map.snapshot(cx))
15367            .text()
15368    }
15369
15370    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15371        let mut wrap_guides = smallvec::smallvec![];
15372
15373        if self.show_wrap_guides == Some(false) {
15374            return wrap_guides;
15375        }
15376
15377        let settings = self.buffer.read(cx).language_settings(cx);
15378        if settings.show_wrap_guides {
15379            match self.soft_wrap_mode(cx) {
15380                SoftWrap::Column(soft_wrap) => {
15381                    wrap_guides.push((soft_wrap as usize, true));
15382                }
15383                SoftWrap::Bounded(soft_wrap) => {
15384                    wrap_guides.push((soft_wrap as usize, true));
15385                }
15386                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15387            }
15388            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15389        }
15390
15391        wrap_guides
15392    }
15393
15394    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15395        let settings = self.buffer.read(cx).language_settings(cx);
15396        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15397        match mode {
15398            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15399                SoftWrap::None
15400            }
15401            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15402            language_settings::SoftWrap::PreferredLineLength => {
15403                SoftWrap::Column(settings.preferred_line_length)
15404            }
15405            language_settings::SoftWrap::Bounded => {
15406                SoftWrap::Bounded(settings.preferred_line_length)
15407            }
15408        }
15409    }
15410
15411    pub fn set_soft_wrap_mode(
15412        &mut self,
15413        mode: language_settings::SoftWrap,
15414
15415        cx: &mut Context<Self>,
15416    ) {
15417        self.soft_wrap_mode_override = Some(mode);
15418        cx.notify();
15419    }
15420
15421    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15422        self.hard_wrap = hard_wrap;
15423        cx.notify();
15424    }
15425
15426    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15427        self.text_style_refinement = Some(style);
15428    }
15429
15430    /// called by the Element so we know what style we were most recently rendered with.
15431    pub(crate) fn set_style(
15432        &mut self,
15433        style: EditorStyle,
15434        window: &mut Window,
15435        cx: &mut Context<Self>,
15436    ) {
15437        let rem_size = window.rem_size();
15438        self.display_map.update(cx, |map, cx| {
15439            map.set_font(
15440                style.text.font(),
15441                style.text.font_size.to_pixels(rem_size),
15442                cx,
15443            )
15444        });
15445        self.style = Some(style);
15446    }
15447
15448    pub fn style(&self) -> Option<&EditorStyle> {
15449        self.style.as_ref()
15450    }
15451
15452    // Called by the element. This method is not designed to be called outside of the editor
15453    // element's layout code because it does not notify when rewrapping is computed synchronously.
15454    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15455        self.display_map
15456            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15457    }
15458
15459    pub fn set_soft_wrap(&mut self) {
15460        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15461    }
15462
15463    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15464        if self.soft_wrap_mode_override.is_some() {
15465            self.soft_wrap_mode_override.take();
15466        } else {
15467            let soft_wrap = match self.soft_wrap_mode(cx) {
15468                SoftWrap::GitDiff => return,
15469                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15470                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15471                    language_settings::SoftWrap::None
15472                }
15473            };
15474            self.soft_wrap_mode_override = Some(soft_wrap);
15475        }
15476        cx.notify();
15477    }
15478
15479    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15480        let Some(workspace) = self.workspace() else {
15481            return;
15482        };
15483        let fs = workspace.read(cx).app_state().fs.clone();
15484        let current_show = TabBarSettings::get_global(cx).show;
15485        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15486            setting.show = Some(!current_show);
15487        });
15488    }
15489
15490    pub fn toggle_indent_guides(
15491        &mut self,
15492        _: &ToggleIndentGuides,
15493        _: &mut Window,
15494        cx: &mut Context<Self>,
15495    ) {
15496        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15497            self.buffer
15498                .read(cx)
15499                .language_settings(cx)
15500                .indent_guides
15501                .enabled
15502        });
15503        self.show_indent_guides = Some(!currently_enabled);
15504        cx.notify();
15505    }
15506
15507    fn should_show_indent_guides(&self) -> Option<bool> {
15508        self.show_indent_guides
15509    }
15510
15511    pub fn toggle_line_numbers(
15512        &mut self,
15513        _: &ToggleLineNumbers,
15514        _: &mut Window,
15515        cx: &mut Context<Self>,
15516    ) {
15517        let mut editor_settings = EditorSettings::get_global(cx).clone();
15518        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15519        EditorSettings::override_global(editor_settings, cx);
15520    }
15521
15522    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15523        if let Some(show_line_numbers) = self.show_line_numbers {
15524            return show_line_numbers;
15525        }
15526        EditorSettings::get_global(cx).gutter.line_numbers
15527    }
15528
15529    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15530        self.use_relative_line_numbers
15531            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15532    }
15533
15534    pub fn toggle_relative_line_numbers(
15535        &mut self,
15536        _: &ToggleRelativeLineNumbers,
15537        _: &mut Window,
15538        cx: &mut Context<Self>,
15539    ) {
15540        let is_relative = self.should_use_relative_line_numbers(cx);
15541        self.set_relative_line_number(Some(!is_relative), cx)
15542    }
15543
15544    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15545        self.use_relative_line_numbers = is_relative;
15546        cx.notify();
15547    }
15548
15549    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15550        self.show_gutter = show_gutter;
15551        cx.notify();
15552    }
15553
15554    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15555        self.show_scrollbars = show_scrollbars;
15556        cx.notify();
15557    }
15558
15559    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15560        self.show_line_numbers = Some(show_line_numbers);
15561        cx.notify();
15562    }
15563
15564    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15565        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15566        cx.notify();
15567    }
15568
15569    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15570        self.show_code_actions = Some(show_code_actions);
15571        cx.notify();
15572    }
15573
15574    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15575        self.show_runnables = Some(show_runnables);
15576        cx.notify();
15577    }
15578
15579    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15580        self.show_breakpoints = Some(show_breakpoints);
15581        cx.notify();
15582    }
15583
15584    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15585        if self.display_map.read(cx).masked != masked {
15586            self.display_map.update(cx, |map, _| map.masked = masked);
15587        }
15588        cx.notify()
15589    }
15590
15591    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15592        self.show_wrap_guides = Some(show_wrap_guides);
15593        cx.notify();
15594    }
15595
15596    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15597        self.show_indent_guides = Some(show_indent_guides);
15598        cx.notify();
15599    }
15600
15601    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15602        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15603            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15604                if let Some(dir) = file.abs_path(cx).parent() {
15605                    return Some(dir.to_owned());
15606                }
15607            }
15608
15609            if let Some(project_path) = buffer.read(cx).project_path(cx) {
15610                return Some(project_path.path.to_path_buf());
15611            }
15612        }
15613
15614        None
15615    }
15616
15617    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15618        self.active_excerpt(cx)?
15619            .1
15620            .read(cx)
15621            .file()
15622            .and_then(|f| f.as_local())
15623    }
15624
15625    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15626        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15627            let buffer = buffer.read(cx);
15628            if let Some(project_path) = buffer.project_path(cx) {
15629                let project = self.project.as_ref()?.read(cx);
15630                project.absolute_path(&project_path, cx)
15631            } else {
15632                buffer
15633                    .file()
15634                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15635            }
15636        })
15637    }
15638
15639    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15640        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15641            let project_path = buffer.read(cx).project_path(cx)?;
15642            let project = self.project.as_ref()?.read(cx);
15643            let entry = project.entry_for_path(&project_path, cx)?;
15644            let path = entry.path.to_path_buf();
15645            Some(path)
15646        })
15647    }
15648
15649    pub fn reveal_in_finder(
15650        &mut self,
15651        _: &RevealInFileManager,
15652        _window: &mut Window,
15653        cx: &mut Context<Self>,
15654    ) {
15655        if let Some(target) = self.target_file(cx) {
15656            cx.reveal_path(&target.abs_path(cx));
15657        }
15658    }
15659
15660    pub fn copy_path(
15661        &mut self,
15662        _: &zed_actions::workspace::CopyPath,
15663        _window: &mut Window,
15664        cx: &mut Context<Self>,
15665    ) {
15666        if let Some(path) = self.target_file_abs_path(cx) {
15667            if let Some(path) = path.to_str() {
15668                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15669            }
15670        }
15671    }
15672
15673    pub fn copy_relative_path(
15674        &mut self,
15675        _: &zed_actions::workspace::CopyRelativePath,
15676        _window: &mut Window,
15677        cx: &mut Context<Self>,
15678    ) {
15679        if let Some(path) = self.target_file_path(cx) {
15680            if let Some(path) = path.to_str() {
15681                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15682            }
15683        }
15684    }
15685
15686    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15687        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15688            buffer.read(cx).project_path(cx)
15689        } else {
15690            None
15691        }
15692    }
15693
15694    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15695        let _ = maybe!({
15696            let breakpoint_store = self.breakpoint_store.as_ref()?;
15697
15698            let Some((_, _, active_position)) =
15699                breakpoint_store.read(cx).active_position().cloned()
15700            else {
15701                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15702                return None;
15703            };
15704
15705            let snapshot = self
15706                .project
15707                .as_ref()?
15708                .read(cx)
15709                .buffer_for_id(active_position.buffer_id?, cx)?
15710                .read(cx)
15711                .snapshot();
15712
15713            for (id, ExcerptRange { context, .. }) in self
15714                .buffer
15715                .read(cx)
15716                .excerpts_for_buffer(active_position.buffer_id?, cx)
15717            {
15718                if context.start.cmp(&active_position, &snapshot).is_ge()
15719                    || context.end.cmp(&active_position, &snapshot).is_lt()
15720                {
15721                    continue;
15722                }
15723                let snapshot = self.buffer.read(cx).snapshot(cx);
15724                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15725
15726                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15727                self.go_to_line::<DebugCurrentRowHighlight>(
15728                    multibuffer_anchor,
15729                    Some(cx.theme().colors().editor_debugger_active_line_background),
15730                    window,
15731                    cx,
15732                );
15733
15734                cx.notify();
15735            }
15736
15737            Some(())
15738        });
15739    }
15740
15741    pub fn copy_file_name_without_extension(
15742        &mut self,
15743        _: &CopyFileNameWithoutExtension,
15744        _: &mut Window,
15745        cx: &mut Context<Self>,
15746    ) {
15747        if let Some(file) = self.target_file(cx) {
15748            if let Some(file_stem) = file.path().file_stem() {
15749                if let Some(name) = file_stem.to_str() {
15750                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15751                }
15752            }
15753        }
15754    }
15755
15756    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15757        if let Some(file) = self.target_file(cx) {
15758            if let Some(file_name) = file.path().file_name() {
15759                if let Some(name) = file_name.to_str() {
15760                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15761                }
15762            }
15763        }
15764    }
15765
15766    pub fn toggle_git_blame(
15767        &mut self,
15768        _: &::git::Blame,
15769        window: &mut Window,
15770        cx: &mut Context<Self>,
15771    ) {
15772        self.show_git_blame_gutter = !self.show_git_blame_gutter;
15773
15774        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15775            self.start_git_blame(true, window, cx);
15776        }
15777
15778        cx.notify();
15779    }
15780
15781    pub fn toggle_git_blame_inline(
15782        &mut self,
15783        _: &ToggleGitBlameInline,
15784        window: &mut Window,
15785        cx: &mut Context<Self>,
15786    ) {
15787        self.toggle_git_blame_inline_internal(true, window, cx);
15788        cx.notify();
15789    }
15790
15791    pub fn git_blame_inline_enabled(&self) -> bool {
15792        self.git_blame_inline_enabled
15793    }
15794
15795    pub fn toggle_selection_menu(
15796        &mut self,
15797        _: &ToggleSelectionMenu,
15798        _: &mut Window,
15799        cx: &mut Context<Self>,
15800    ) {
15801        self.show_selection_menu = self
15802            .show_selection_menu
15803            .map(|show_selections_menu| !show_selections_menu)
15804            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15805
15806        cx.notify();
15807    }
15808
15809    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15810        self.show_selection_menu
15811            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15812    }
15813
15814    fn start_git_blame(
15815        &mut self,
15816        user_triggered: bool,
15817        window: &mut Window,
15818        cx: &mut Context<Self>,
15819    ) {
15820        if let Some(project) = self.project.as_ref() {
15821            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15822                return;
15823            };
15824
15825            if buffer.read(cx).file().is_none() {
15826                return;
15827            }
15828
15829            let focused = self.focus_handle(cx).contains_focused(window, cx);
15830
15831            let project = project.clone();
15832            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15833            self.blame_subscription =
15834                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15835            self.blame = Some(blame);
15836        }
15837    }
15838
15839    fn toggle_git_blame_inline_internal(
15840        &mut self,
15841        user_triggered: bool,
15842        window: &mut Window,
15843        cx: &mut Context<Self>,
15844    ) {
15845        if self.git_blame_inline_enabled {
15846            self.git_blame_inline_enabled = false;
15847            self.show_git_blame_inline = false;
15848            self.show_git_blame_inline_delay_task.take();
15849        } else {
15850            self.git_blame_inline_enabled = true;
15851            self.start_git_blame_inline(user_triggered, window, cx);
15852        }
15853
15854        cx.notify();
15855    }
15856
15857    fn start_git_blame_inline(
15858        &mut self,
15859        user_triggered: bool,
15860        window: &mut Window,
15861        cx: &mut Context<Self>,
15862    ) {
15863        self.start_git_blame(user_triggered, window, cx);
15864
15865        if ProjectSettings::get_global(cx)
15866            .git
15867            .inline_blame_delay()
15868            .is_some()
15869        {
15870            self.start_inline_blame_timer(window, cx);
15871        } else {
15872            self.show_git_blame_inline = true
15873        }
15874    }
15875
15876    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15877        self.blame.as_ref()
15878    }
15879
15880    pub fn show_git_blame_gutter(&self) -> bool {
15881        self.show_git_blame_gutter
15882    }
15883
15884    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15885        self.show_git_blame_gutter && self.has_blame_entries(cx)
15886    }
15887
15888    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15889        self.show_git_blame_inline
15890            && (self.focus_handle.is_focused(window)
15891                || self
15892                    .git_blame_inline_tooltip
15893                    .as_ref()
15894                    .and_then(|t| t.upgrade())
15895                    .is_some())
15896            && !self.newest_selection_head_on_empty_line(cx)
15897            && self.has_blame_entries(cx)
15898    }
15899
15900    fn has_blame_entries(&self, cx: &App) -> bool {
15901        self.blame()
15902            .map_or(false, |blame| blame.read(cx).has_generated_entries())
15903    }
15904
15905    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15906        let cursor_anchor = self.selections.newest_anchor().head();
15907
15908        let snapshot = self.buffer.read(cx).snapshot(cx);
15909        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15910
15911        snapshot.line_len(buffer_row) == 0
15912    }
15913
15914    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15915        let buffer_and_selection = maybe!({
15916            let selection = self.selections.newest::<Point>(cx);
15917            let selection_range = selection.range();
15918
15919            let multi_buffer = self.buffer().read(cx);
15920            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15921            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15922
15923            let (buffer, range, _) = if selection.reversed {
15924                buffer_ranges.first()
15925            } else {
15926                buffer_ranges.last()
15927            }?;
15928
15929            let selection = text::ToPoint::to_point(&range.start, &buffer).row
15930                ..text::ToPoint::to_point(&range.end, &buffer).row;
15931            Some((
15932                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15933                selection,
15934            ))
15935        });
15936
15937        let Some((buffer, selection)) = buffer_and_selection else {
15938            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15939        };
15940
15941        let Some(project) = self.project.as_ref() else {
15942            return Task::ready(Err(anyhow!("editor does not have project")));
15943        };
15944
15945        project.update(cx, |project, cx| {
15946            project.get_permalink_to_line(&buffer, selection, cx)
15947        })
15948    }
15949
15950    pub fn copy_permalink_to_line(
15951        &mut self,
15952        _: &CopyPermalinkToLine,
15953        window: &mut Window,
15954        cx: &mut Context<Self>,
15955    ) {
15956        let permalink_task = self.get_permalink_to_line(cx);
15957        let workspace = self.workspace();
15958
15959        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15960            Ok(permalink) => {
15961                cx.update(|_, cx| {
15962                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15963                })
15964                .ok();
15965            }
15966            Err(err) => {
15967                let message = format!("Failed to copy permalink: {err}");
15968
15969                Err::<(), anyhow::Error>(err).log_err();
15970
15971                if let Some(workspace) = workspace {
15972                    workspace
15973                        .update_in(cx, |workspace, _, cx| {
15974                            struct CopyPermalinkToLine;
15975
15976                            workspace.show_toast(
15977                                Toast::new(
15978                                    NotificationId::unique::<CopyPermalinkToLine>(),
15979                                    message,
15980                                ),
15981                                cx,
15982                            )
15983                        })
15984                        .ok();
15985                }
15986            }
15987        })
15988        .detach();
15989    }
15990
15991    pub fn copy_file_location(
15992        &mut self,
15993        _: &CopyFileLocation,
15994        _: &mut Window,
15995        cx: &mut Context<Self>,
15996    ) {
15997        let selection = self.selections.newest::<Point>(cx).start.row + 1;
15998        if let Some(file) = self.target_file(cx) {
15999            if let Some(path) = file.path().to_str() {
16000                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16001            }
16002        }
16003    }
16004
16005    pub fn open_permalink_to_line(
16006        &mut self,
16007        _: &OpenPermalinkToLine,
16008        window: &mut Window,
16009        cx: &mut Context<Self>,
16010    ) {
16011        let permalink_task = self.get_permalink_to_line(cx);
16012        let workspace = self.workspace();
16013
16014        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16015            Ok(permalink) => {
16016                cx.update(|_, cx| {
16017                    cx.open_url(permalink.as_ref());
16018                })
16019                .ok();
16020            }
16021            Err(err) => {
16022                let message = format!("Failed to open permalink: {err}");
16023
16024                Err::<(), anyhow::Error>(err).log_err();
16025
16026                if let Some(workspace) = workspace {
16027                    workspace
16028                        .update(cx, |workspace, cx| {
16029                            struct OpenPermalinkToLine;
16030
16031                            workspace.show_toast(
16032                                Toast::new(
16033                                    NotificationId::unique::<OpenPermalinkToLine>(),
16034                                    message,
16035                                ),
16036                                cx,
16037                            )
16038                        })
16039                        .ok();
16040                }
16041            }
16042        })
16043        .detach();
16044    }
16045
16046    pub fn insert_uuid_v4(
16047        &mut self,
16048        _: &InsertUuidV4,
16049        window: &mut Window,
16050        cx: &mut Context<Self>,
16051    ) {
16052        self.insert_uuid(UuidVersion::V4, window, cx);
16053    }
16054
16055    pub fn insert_uuid_v7(
16056        &mut self,
16057        _: &InsertUuidV7,
16058        window: &mut Window,
16059        cx: &mut Context<Self>,
16060    ) {
16061        self.insert_uuid(UuidVersion::V7, window, cx);
16062    }
16063
16064    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16065        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16066        self.transact(window, cx, |this, window, cx| {
16067            let edits = this
16068                .selections
16069                .all::<Point>(cx)
16070                .into_iter()
16071                .map(|selection| {
16072                    let uuid = match version {
16073                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16074                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16075                    };
16076
16077                    (selection.range(), uuid.to_string())
16078                });
16079            this.edit(edits, cx);
16080            this.refresh_inline_completion(true, false, window, cx);
16081        });
16082    }
16083
16084    pub fn open_selections_in_multibuffer(
16085        &mut self,
16086        _: &OpenSelectionsInMultibuffer,
16087        window: &mut Window,
16088        cx: &mut Context<Self>,
16089    ) {
16090        let multibuffer = self.buffer.read(cx);
16091
16092        let Some(buffer) = multibuffer.as_singleton() else {
16093            return;
16094        };
16095
16096        let Some(workspace) = self.workspace() else {
16097            return;
16098        };
16099
16100        let locations = self
16101            .selections
16102            .disjoint_anchors()
16103            .iter()
16104            .map(|range| Location {
16105                buffer: buffer.clone(),
16106                range: range.start.text_anchor..range.end.text_anchor,
16107            })
16108            .collect::<Vec<_>>();
16109
16110        let title = multibuffer.title(cx).to_string();
16111
16112        cx.spawn_in(window, async move |_, cx| {
16113            workspace.update_in(cx, |workspace, window, cx| {
16114                Self::open_locations_in_multibuffer(
16115                    workspace,
16116                    locations,
16117                    format!("Selections for '{title}'"),
16118                    false,
16119                    MultibufferSelectionMode::All,
16120                    window,
16121                    cx,
16122                );
16123            })
16124        })
16125        .detach();
16126    }
16127
16128    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16129    /// last highlight added will be used.
16130    ///
16131    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16132    pub fn highlight_rows<T: 'static>(
16133        &mut self,
16134        range: Range<Anchor>,
16135        color: Hsla,
16136        should_autoscroll: bool,
16137        cx: &mut Context<Self>,
16138    ) {
16139        let snapshot = self.buffer().read(cx).snapshot(cx);
16140        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16141        let ix = row_highlights.binary_search_by(|highlight| {
16142            Ordering::Equal
16143                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16144                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16145        });
16146
16147        if let Err(mut ix) = ix {
16148            let index = post_inc(&mut self.highlight_order);
16149
16150            // If this range intersects with the preceding highlight, then merge it with
16151            // the preceding highlight. Otherwise insert a new highlight.
16152            let mut merged = false;
16153            if ix > 0 {
16154                let prev_highlight = &mut row_highlights[ix - 1];
16155                if prev_highlight
16156                    .range
16157                    .end
16158                    .cmp(&range.start, &snapshot)
16159                    .is_ge()
16160                {
16161                    ix -= 1;
16162                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16163                        prev_highlight.range.end = range.end;
16164                    }
16165                    merged = true;
16166                    prev_highlight.index = index;
16167                    prev_highlight.color = color;
16168                    prev_highlight.should_autoscroll = should_autoscroll;
16169                }
16170            }
16171
16172            if !merged {
16173                row_highlights.insert(
16174                    ix,
16175                    RowHighlight {
16176                        range: range.clone(),
16177                        index,
16178                        color,
16179                        should_autoscroll,
16180                    },
16181                );
16182            }
16183
16184            // If any of the following highlights intersect with this one, merge them.
16185            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16186                let highlight = &row_highlights[ix];
16187                if next_highlight
16188                    .range
16189                    .start
16190                    .cmp(&highlight.range.end, &snapshot)
16191                    .is_le()
16192                {
16193                    if next_highlight
16194                        .range
16195                        .end
16196                        .cmp(&highlight.range.end, &snapshot)
16197                        .is_gt()
16198                    {
16199                        row_highlights[ix].range.end = next_highlight.range.end;
16200                    }
16201                    row_highlights.remove(ix + 1);
16202                } else {
16203                    break;
16204                }
16205            }
16206        }
16207    }
16208
16209    /// Remove any highlighted row ranges of the given type that intersect the
16210    /// given ranges.
16211    pub fn remove_highlighted_rows<T: 'static>(
16212        &mut self,
16213        ranges_to_remove: Vec<Range<Anchor>>,
16214        cx: &mut Context<Self>,
16215    ) {
16216        let snapshot = self.buffer().read(cx).snapshot(cx);
16217        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16218        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16219        row_highlights.retain(|highlight| {
16220            while let Some(range_to_remove) = ranges_to_remove.peek() {
16221                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16222                    Ordering::Less | Ordering::Equal => {
16223                        ranges_to_remove.next();
16224                    }
16225                    Ordering::Greater => {
16226                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16227                            Ordering::Less | Ordering::Equal => {
16228                                return false;
16229                            }
16230                            Ordering::Greater => break,
16231                        }
16232                    }
16233                }
16234            }
16235
16236            true
16237        })
16238    }
16239
16240    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16241    pub fn clear_row_highlights<T: 'static>(&mut self) {
16242        self.highlighted_rows.remove(&TypeId::of::<T>());
16243    }
16244
16245    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16246    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16247        self.highlighted_rows
16248            .get(&TypeId::of::<T>())
16249            .map_or(&[] as &[_], |vec| vec.as_slice())
16250            .iter()
16251            .map(|highlight| (highlight.range.clone(), highlight.color))
16252    }
16253
16254    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16255    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16256    /// Allows to ignore certain kinds of highlights.
16257    pub fn highlighted_display_rows(
16258        &self,
16259        window: &mut Window,
16260        cx: &mut App,
16261    ) -> BTreeMap<DisplayRow, LineHighlight> {
16262        let snapshot = self.snapshot(window, cx);
16263        let mut used_highlight_orders = HashMap::default();
16264        self.highlighted_rows
16265            .iter()
16266            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16267            .fold(
16268                BTreeMap::<DisplayRow, LineHighlight>::new(),
16269                |mut unique_rows, highlight| {
16270                    let start = highlight.range.start.to_display_point(&snapshot);
16271                    let end = highlight.range.end.to_display_point(&snapshot);
16272                    let start_row = start.row().0;
16273                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16274                        && end.column() == 0
16275                    {
16276                        end.row().0.saturating_sub(1)
16277                    } else {
16278                        end.row().0
16279                    };
16280                    for row in start_row..=end_row {
16281                        let used_index =
16282                            used_highlight_orders.entry(row).or_insert(highlight.index);
16283                        if highlight.index >= *used_index {
16284                            *used_index = highlight.index;
16285                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16286                        }
16287                    }
16288                    unique_rows
16289                },
16290            )
16291    }
16292
16293    pub fn highlighted_display_row_for_autoscroll(
16294        &self,
16295        snapshot: &DisplaySnapshot,
16296    ) -> Option<DisplayRow> {
16297        self.highlighted_rows
16298            .values()
16299            .flat_map(|highlighted_rows| highlighted_rows.iter())
16300            .filter_map(|highlight| {
16301                if highlight.should_autoscroll {
16302                    Some(highlight.range.start.to_display_point(snapshot).row())
16303                } else {
16304                    None
16305                }
16306            })
16307            .min()
16308    }
16309
16310    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16311        self.highlight_background::<SearchWithinRange>(
16312            ranges,
16313            |colors| colors.editor_document_highlight_read_background,
16314            cx,
16315        )
16316    }
16317
16318    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16319        self.breadcrumb_header = Some(new_header);
16320    }
16321
16322    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16323        self.clear_background_highlights::<SearchWithinRange>(cx);
16324    }
16325
16326    pub fn highlight_background<T: 'static>(
16327        &mut self,
16328        ranges: &[Range<Anchor>],
16329        color_fetcher: fn(&ThemeColors) -> Hsla,
16330        cx: &mut Context<Self>,
16331    ) {
16332        self.background_highlights
16333            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16334        self.scrollbar_marker_state.dirty = true;
16335        cx.notify();
16336    }
16337
16338    pub fn clear_background_highlights<T: 'static>(
16339        &mut self,
16340        cx: &mut Context<Self>,
16341    ) -> Option<BackgroundHighlight> {
16342        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16343        if !text_highlights.1.is_empty() {
16344            self.scrollbar_marker_state.dirty = true;
16345            cx.notify();
16346        }
16347        Some(text_highlights)
16348    }
16349
16350    pub fn highlight_gutter<T: 'static>(
16351        &mut self,
16352        ranges: &[Range<Anchor>],
16353        color_fetcher: fn(&App) -> Hsla,
16354        cx: &mut Context<Self>,
16355    ) {
16356        self.gutter_highlights
16357            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16358        cx.notify();
16359    }
16360
16361    pub fn clear_gutter_highlights<T: 'static>(
16362        &mut self,
16363        cx: &mut Context<Self>,
16364    ) -> Option<GutterHighlight> {
16365        cx.notify();
16366        self.gutter_highlights.remove(&TypeId::of::<T>())
16367    }
16368
16369    #[cfg(feature = "test-support")]
16370    pub fn all_text_background_highlights(
16371        &self,
16372        window: &mut Window,
16373        cx: &mut Context<Self>,
16374    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16375        let snapshot = self.snapshot(window, cx);
16376        let buffer = &snapshot.buffer_snapshot;
16377        let start = buffer.anchor_before(0);
16378        let end = buffer.anchor_after(buffer.len());
16379        let theme = cx.theme().colors();
16380        self.background_highlights_in_range(start..end, &snapshot, theme)
16381    }
16382
16383    #[cfg(feature = "test-support")]
16384    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16385        let snapshot = self.buffer().read(cx).snapshot(cx);
16386
16387        let highlights = self
16388            .background_highlights
16389            .get(&TypeId::of::<items::BufferSearchHighlights>());
16390
16391        if let Some((_color, ranges)) = highlights {
16392            ranges
16393                .iter()
16394                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16395                .collect_vec()
16396        } else {
16397            vec![]
16398        }
16399    }
16400
16401    fn document_highlights_for_position<'a>(
16402        &'a self,
16403        position: Anchor,
16404        buffer: &'a MultiBufferSnapshot,
16405    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16406        let read_highlights = self
16407            .background_highlights
16408            .get(&TypeId::of::<DocumentHighlightRead>())
16409            .map(|h| &h.1);
16410        let write_highlights = self
16411            .background_highlights
16412            .get(&TypeId::of::<DocumentHighlightWrite>())
16413            .map(|h| &h.1);
16414        let left_position = position.bias_left(buffer);
16415        let right_position = position.bias_right(buffer);
16416        read_highlights
16417            .into_iter()
16418            .chain(write_highlights)
16419            .flat_map(move |ranges| {
16420                let start_ix = match ranges.binary_search_by(|probe| {
16421                    let cmp = probe.end.cmp(&left_position, buffer);
16422                    if cmp.is_ge() {
16423                        Ordering::Greater
16424                    } else {
16425                        Ordering::Less
16426                    }
16427                }) {
16428                    Ok(i) | Err(i) => i,
16429                };
16430
16431                ranges[start_ix..]
16432                    .iter()
16433                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16434            })
16435    }
16436
16437    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16438        self.background_highlights
16439            .get(&TypeId::of::<T>())
16440            .map_or(false, |(_, highlights)| !highlights.is_empty())
16441    }
16442
16443    pub fn background_highlights_in_range(
16444        &self,
16445        search_range: Range<Anchor>,
16446        display_snapshot: &DisplaySnapshot,
16447        theme: &ThemeColors,
16448    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16449        let mut results = Vec::new();
16450        for (color_fetcher, ranges) in self.background_highlights.values() {
16451            let color = color_fetcher(theme);
16452            let start_ix = match ranges.binary_search_by(|probe| {
16453                let cmp = probe
16454                    .end
16455                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16456                if cmp.is_gt() {
16457                    Ordering::Greater
16458                } else {
16459                    Ordering::Less
16460                }
16461            }) {
16462                Ok(i) | Err(i) => i,
16463            };
16464            for range in &ranges[start_ix..] {
16465                if range
16466                    .start
16467                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16468                    .is_ge()
16469                {
16470                    break;
16471                }
16472
16473                let start = range.start.to_display_point(display_snapshot);
16474                let end = range.end.to_display_point(display_snapshot);
16475                results.push((start..end, color))
16476            }
16477        }
16478        results
16479    }
16480
16481    pub fn background_highlight_row_ranges<T: 'static>(
16482        &self,
16483        search_range: Range<Anchor>,
16484        display_snapshot: &DisplaySnapshot,
16485        count: usize,
16486    ) -> Vec<RangeInclusive<DisplayPoint>> {
16487        let mut results = Vec::new();
16488        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16489            return vec![];
16490        };
16491
16492        let start_ix = match ranges.binary_search_by(|probe| {
16493            let cmp = probe
16494                .end
16495                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16496            if cmp.is_gt() {
16497                Ordering::Greater
16498            } else {
16499                Ordering::Less
16500            }
16501        }) {
16502            Ok(i) | Err(i) => i,
16503        };
16504        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16505            if let (Some(start_display), Some(end_display)) = (start, end) {
16506                results.push(
16507                    start_display.to_display_point(display_snapshot)
16508                        ..=end_display.to_display_point(display_snapshot),
16509                );
16510            }
16511        };
16512        let mut start_row: Option<Point> = None;
16513        let mut end_row: Option<Point> = None;
16514        if ranges.len() > count {
16515            return Vec::new();
16516        }
16517        for range in &ranges[start_ix..] {
16518            if range
16519                .start
16520                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16521                .is_ge()
16522            {
16523                break;
16524            }
16525            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16526            if let Some(current_row) = &end_row {
16527                if end.row == current_row.row {
16528                    continue;
16529                }
16530            }
16531            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16532            if start_row.is_none() {
16533                assert_eq!(end_row, None);
16534                start_row = Some(start);
16535                end_row = Some(end);
16536                continue;
16537            }
16538            if let Some(current_end) = end_row.as_mut() {
16539                if start.row > current_end.row + 1 {
16540                    push_region(start_row, end_row);
16541                    start_row = Some(start);
16542                    end_row = Some(end);
16543                } else {
16544                    // Merge two hunks.
16545                    *current_end = end;
16546                }
16547            } else {
16548                unreachable!();
16549            }
16550        }
16551        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16552        push_region(start_row, end_row);
16553        results
16554    }
16555
16556    pub fn gutter_highlights_in_range(
16557        &self,
16558        search_range: Range<Anchor>,
16559        display_snapshot: &DisplaySnapshot,
16560        cx: &App,
16561    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16562        let mut results = Vec::new();
16563        for (color_fetcher, ranges) in self.gutter_highlights.values() {
16564            let color = color_fetcher(cx);
16565            let start_ix = match ranges.binary_search_by(|probe| {
16566                let cmp = probe
16567                    .end
16568                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16569                if cmp.is_gt() {
16570                    Ordering::Greater
16571                } else {
16572                    Ordering::Less
16573                }
16574            }) {
16575                Ok(i) | Err(i) => i,
16576            };
16577            for range in &ranges[start_ix..] {
16578                if range
16579                    .start
16580                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16581                    .is_ge()
16582                {
16583                    break;
16584                }
16585
16586                let start = range.start.to_display_point(display_snapshot);
16587                let end = range.end.to_display_point(display_snapshot);
16588                results.push((start..end, color))
16589            }
16590        }
16591        results
16592    }
16593
16594    /// Get the text ranges corresponding to the redaction query
16595    pub fn redacted_ranges(
16596        &self,
16597        search_range: Range<Anchor>,
16598        display_snapshot: &DisplaySnapshot,
16599        cx: &App,
16600    ) -> Vec<Range<DisplayPoint>> {
16601        display_snapshot
16602            .buffer_snapshot
16603            .redacted_ranges(search_range, |file| {
16604                if let Some(file) = file {
16605                    file.is_private()
16606                        && EditorSettings::get(
16607                            Some(SettingsLocation {
16608                                worktree_id: file.worktree_id(cx),
16609                                path: file.path().as_ref(),
16610                            }),
16611                            cx,
16612                        )
16613                        .redact_private_values
16614                } else {
16615                    false
16616                }
16617            })
16618            .map(|range| {
16619                range.start.to_display_point(display_snapshot)
16620                    ..range.end.to_display_point(display_snapshot)
16621            })
16622            .collect()
16623    }
16624
16625    pub fn highlight_text<T: 'static>(
16626        &mut self,
16627        ranges: Vec<Range<Anchor>>,
16628        style: HighlightStyle,
16629        cx: &mut Context<Self>,
16630    ) {
16631        self.display_map.update(cx, |map, _| {
16632            map.highlight_text(TypeId::of::<T>(), ranges, style)
16633        });
16634        cx.notify();
16635    }
16636
16637    pub(crate) fn highlight_inlays<T: 'static>(
16638        &mut self,
16639        highlights: Vec<InlayHighlight>,
16640        style: HighlightStyle,
16641        cx: &mut Context<Self>,
16642    ) {
16643        self.display_map.update(cx, |map, _| {
16644            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16645        });
16646        cx.notify();
16647    }
16648
16649    pub fn text_highlights<'a, T: 'static>(
16650        &'a self,
16651        cx: &'a App,
16652    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16653        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16654    }
16655
16656    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16657        let cleared = self
16658            .display_map
16659            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16660        if cleared {
16661            cx.notify();
16662        }
16663    }
16664
16665    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16666        (self.read_only(cx) || self.blink_manager.read(cx).visible())
16667            && self.focus_handle.is_focused(window)
16668    }
16669
16670    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16671        self.show_cursor_when_unfocused = is_enabled;
16672        cx.notify();
16673    }
16674
16675    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16676        cx.notify();
16677    }
16678
16679    fn on_buffer_event(
16680        &mut self,
16681        multibuffer: &Entity<MultiBuffer>,
16682        event: &multi_buffer::Event,
16683        window: &mut Window,
16684        cx: &mut Context<Self>,
16685    ) {
16686        match event {
16687            multi_buffer::Event::Edited {
16688                singleton_buffer_edited,
16689                edited_buffer: buffer_edited,
16690            } => {
16691                self.scrollbar_marker_state.dirty = true;
16692                self.active_indent_guides_state.dirty = true;
16693                self.refresh_active_diagnostics(cx);
16694                self.refresh_code_actions(window, cx);
16695                if self.has_active_inline_completion() {
16696                    self.update_visible_inline_completion(window, cx);
16697                }
16698                if let Some(buffer) = buffer_edited {
16699                    let buffer_id = buffer.read(cx).remote_id();
16700                    if !self.registered_buffers.contains_key(&buffer_id) {
16701                        if let Some(project) = self.project.as_ref() {
16702                            project.update(cx, |project, cx| {
16703                                self.registered_buffers.insert(
16704                                    buffer_id,
16705                                    project.register_buffer_with_language_servers(&buffer, cx),
16706                                );
16707                            })
16708                        }
16709                    }
16710                }
16711                cx.emit(EditorEvent::BufferEdited);
16712                cx.emit(SearchEvent::MatchesInvalidated);
16713                if *singleton_buffer_edited {
16714                    if let Some(project) = &self.project {
16715                        #[allow(clippy::mutable_key_type)]
16716                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16717                            multibuffer
16718                                .all_buffers()
16719                                .into_iter()
16720                                .filter_map(|buffer| {
16721                                    buffer.update(cx, |buffer, cx| {
16722                                        let language = buffer.language()?;
16723                                        let should_discard = project.update(cx, |project, cx| {
16724                                            project.is_local()
16725                                                && !project.has_language_servers_for(buffer, cx)
16726                                        });
16727                                        should_discard.not().then_some(language.clone())
16728                                    })
16729                                })
16730                                .collect::<HashSet<_>>()
16731                        });
16732                        if !languages_affected.is_empty() {
16733                            self.refresh_inlay_hints(
16734                                InlayHintRefreshReason::BufferEdited(languages_affected),
16735                                cx,
16736                            );
16737                        }
16738                    }
16739                }
16740
16741                let Some(project) = &self.project else { return };
16742                let (telemetry, is_via_ssh) = {
16743                    let project = project.read(cx);
16744                    let telemetry = project.client().telemetry().clone();
16745                    let is_via_ssh = project.is_via_ssh();
16746                    (telemetry, is_via_ssh)
16747                };
16748                refresh_linked_ranges(self, window, cx);
16749                telemetry.log_edit_event("editor", is_via_ssh);
16750            }
16751            multi_buffer::Event::ExcerptsAdded {
16752                buffer,
16753                predecessor,
16754                excerpts,
16755            } => {
16756                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16757                let buffer_id = buffer.read(cx).remote_id();
16758                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16759                    if let Some(project) = &self.project {
16760                        get_uncommitted_diff_for_buffer(
16761                            project,
16762                            [buffer.clone()],
16763                            self.buffer.clone(),
16764                            cx,
16765                        )
16766                        .detach();
16767                    }
16768                }
16769                cx.emit(EditorEvent::ExcerptsAdded {
16770                    buffer: buffer.clone(),
16771                    predecessor: *predecessor,
16772                    excerpts: excerpts.clone(),
16773                });
16774                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16775            }
16776            multi_buffer::Event::ExcerptsRemoved { ids } => {
16777                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16778                let buffer = self.buffer.read(cx);
16779                self.registered_buffers
16780                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16781                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16782                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16783            }
16784            multi_buffer::Event::ExcerptsEdited {
16785                excerpt_ids,
16786                buffer_ids,
16787            } => {
16788                self.display_map.update(cx, |map, cx| {
16789                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
16790                });
16791                cx.emit(EditorEvent::ExcerptsEdited {
16792                    ids: excerpt_ids.clone(),
16793                })
16794            }
16795            multi_buffer::Event::ExcerptsExpanded { ids } => {
16796                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16797                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16798            }
16799            multi_buffer::Event::Reparsed(buffer_id) => {
16800                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16801                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16802
16803                cx.emit(EditorEvent::Reparsed(*buffer_id));
16804            }
16805            multi_buffer::Event::DiffHunksToggled => {
16806                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16807            }
16808            multi_buffer::Event::LanguageChanged(buffer_id) => {
16809                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16810                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16811                cx.emit(EditorEvent::Reparsed(*buffer_id));
16812                cx.notify();
16813            }
16814            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16815            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16816            multi_buffer::Event::FileHandleChanged
16817            | multi_buffer::Event::Reloaded
16818            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16819            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16820            multi_buffer::Event::DiagnosticsUpdated => {
16821                self.refresh_active_diagnostics(cx);
16822                self.refresh_inline_diagnostics(true, window, cx);
16823                self.scrollbar_marker_state.dirty = true;
16824                cx.notify();
16825            }
16826            _ => {}
16827        };
16828    }
16829
16830    fn on_display_map_changed(
16831        &mut self,
16832        _: Entity<DisplayMap>,
16833        _: &mut Window,
16834        cx: &mut Context<Self>,
16835    ) {
16836        cx.notify();
16837    }
16838
16839    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16840        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16841        self.update_edit_prediction_settings(cx);
16842        self.refresh_inline_completion(true, false, window, cx);
16843        self.refresh_inlay_hints(
16844            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16845                self.selections.newest_anchor().head(),
16846                &self.buffer.read(cx).snapshot(cx),
16847                cx,
16848            )),
16849            cx,
16850        );
16851
16852        let old_cursor_shape = self.cursor_shape;
16853
16854        {
16855            let editor_settings = EditorSettings::get_global(cx);
16856            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16857            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16858            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16859            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
16860        }
16861
16862        if old_cursor_shape != self.cursor_shape {
16863            cx.emit(EditorEvent::CursorShapeChanged);
16864        }
16865
16866        let project_settings = ProjectSettings::get_global(cx);
16867        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16868
16869        if self.mode == EditorMode::Full {
16870            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16871            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16872            if self.show_inline_diagnostics != show_inline_diagnostics {
16873                self.show_inline_diagnostics = show_inline_diagnostics;
16874                self.refresh_inline_diagnostics(false, window, cx);
16875            }
16876
16877            if self.git_blame_inline_enabled != inline_blame_enabled {
16878                self.toggle_git_blame_inline_internal(false, window, cx);
16879            }
16880        }
16881
16882        cx.notify();
16883    }
16884
16885    pub fn set_searchable(&mut self, searchable: bool) {
16886        self.searchable = searchable;
16887    }
16888
16889    pub fn searchable(&self) -> bool {
16890        self.searchable
16891    }
16892
16893    fn open_proposed_changes_editor(
16894        &mut self,
16895        _: &OpenProposedChangesEditor,
16896        window: &mut Window,
16897        cx: &mut Context<Self>,
16898    ) {
16899        let Some(workspace) = self.workspace() else {
16900            cx.propagate();
16901            return;
16902        };
16903
16904        let selections = self.selections.all::<usize>(cx);
16905        let multi_buffer = self.buffer.read(cx);
16906        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16907        let mut new_selections_by_buffer = HashMap::default();
16908        for selection in selections {
16909            for (buffer, range, _) in
16910                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16911            {
16912                let mut range = range.to_point(buffer);
16913                range.start.column = 0;
16914                range.end.column = buffer.line_len(range.end.row);
16915                new_selections_by_buffer
16916                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16917                    .or_insert(Vec::new())
16918                    .push(range)
16919            }
16920        }
16921
16922        let proposed_changes_buffers = new_selections_by_buffer
16923            .into_iter()
16924            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16925            .collect::<Vec<_>>();
16926        let proposed_changes_editor = cx.new(|cx| {
16927            ProposedChangesEditor::new(
16928                "Proposed changes",
16929                proposed_changes_buffers,
16930                self.project.clone(),
16931                window,
16932                cx,
16933            )
16934        });
16935
16936        window.defer(cx, move |window, cx| {
16937            workspace.update(cx, |workspace, cx| {
16938                workspace.active_pane().update(cx, |pane, cx| {
16939                    pane.add_item(
16940                        Box::new(proposed_changes_editor),
16941                        true,
16942                        true,
16943                        None,
16944                        window,
16945                        cx,
16946                    );
16947                });
16948            });
16949        });
16950    }
16951
16952    pub fn open_excerpts_in_split(
16953        &mut self,
16954        _: &OpenExcerptsSplit,
16955        window: &mut Window,
16956        cx: &mut Context<Self>,
16957    ) {
16958        self.open_excerpts_common(None, true, window, cx)
16959    }
16960
16961    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16962        self.open_excerpts_common(None, false, window, cx)
16963    }
16964
16965    fn open_excerpts_common(
16966        &mut self,
16967        jump_data: Option<JumpData>,
16968        split: bool,
16969        window: &mut Window,
16970        cx: &mut Context<Self>,
16971    ) {
16972        let Some(workspace) = self.workspace() else {
16973            cx.propagate();
16974            return;
16975        };
16976
16977        if self.buffer.read(cx).is_singleton() {
16978            cx.propagate();
16979            return;
16980        }
16981
16982        let mut new_selections_by_buffer = HashMap::default();
16983        match &jump_data {
16984            Some(JumpData::MultiBufferPoint {
16985                excerpt_id,
16986                position,
16987                anchor,
16988                line_offset_from_top,
16989            }) => {
16990                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16991                if let Some(buffer) = multi_buffer_snapshot
16992                    .buffer_id_for_excerpt(*excerpt_id)
16993                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16994                {
16995                    let buffer_snapshot = buffer.read(cx).snapshot();
16996                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16997                        language::ToPoint::to_point(anchor, &buffer_snapshot)
16998                    } else {
16999                        buffer_snapshot.clip_point(*position, Bias::Left)
17000                    };
17001                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17002                    new_selections_by_buffer.insert(
17003                        buffer,
17004                        (
17005                            vec![jump_to_offset..jump_to_offset],
17006                            Some(*line_offset_from_top),
17007                        ),
17008                    );
17009                }
17010            }
17011            Some(JumpData::MultiBufferRow {
17012                row,
17013                line_offset_from_top,
17014            }) => {
17015                let point = MultiBufferPoint::new(row.0, 0);
17016                if let Some((buffer, buffer_point, _)) =
17017                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17018                {
17019                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17020                    new_selections_by_buffer
17021                        .entry(buffer)
17022                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17023                        .0
17024                        .push(buffer_offset..buffer_offset)
17025                }
17026            }
17027            None => {
17028                let selections = self.selections.all::<usize>(cx);
17029                let multi_buffer = self.buffer.read(cx);
17030                for selection in selections {
17031                    for (snapshot, range, _, anchor) in multi_buffer
17032                        .snapshot(cx)
17033                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17034                    {
17035                        if let Some(anchor) = anchor {
17036                            // selection is in a deleted hunk
17037                            let Some(buffer_id) = anchor.buffer_id else {
17038                                continue;
17039                            };
17040                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17041                                continue;
17042                            };
17043                            let offset = text::ToOffset::to_offset(
17044                                &anchor.text_anchor,
17045                                &buffer_handle.read(cx).snapshot(),
17046                            );
17047                            let range = offset..offset;
17048                            new_selections_by_buffer
17049                                .entry(buffer_handle)
17050                                .or_insert((Vec::new(), None))
17051                                .0
17052                                .push(range)
17053                        } else {
17054                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17055                            else {
17056                                continue;
17057                            };
17058                            new_selections_by_buffer
17059                                .entry(buffer_handle)
17060                                .or_insert((Vec::new(), None))
17061                                .0
17062                                .push(range)
17063                        }
17064                    }
17065                }
17066            }
17067        }
17068
17069        if new_selections_by_buffer.is_empty() {
17070            return;
17071        }
17072
17073        // We defer the pane interaction because we ourselves are a workspace item
17074        // and activating a new item causes the pane to call a method on us reentrantly,
17075        // which panics if we're on the stack.
17076        window.defer(cx, move |window, cx| {
17077            workspace.update(cx, |workspace, cx| {
17078                let pane = if split {
17079                    workspace.adjacent_pane(window, cx)
17080                } else {
17081                    workspace.active_pane().clone()
17082                };
17083
17084                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17085                    let editor = buffer
17086                        .read(cx)
17087                        .file()
17088                        .is_none()
17089                        .then(|| {
17090                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17091                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17092                            // Instead, we try to activate the existing editor in the pane first.
17093                            let (editor, pane_item_index) =
17094                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17095                                    let editor = item.downcast::<Editor>()?;
17096                                    let singleton_buffer =
17097                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17098                                    if singleton_buffer == buffer {
17099                                        Some((editor, i))
17100                                    } else {
17101                                        None
17102                                    }
17103                                })?;
17104                            pane.update(cx, |pane, cx| {
17105                                pane.activate_item(pane_item_index, true, true, window, cx)
17106                            });
17107                            Some(editor)
17108                        })
17109                        .flatten()
17110                        .unwrap_or_else(|| {
17111                            workspace.open_project_item::<Self>(
17112                                pane.clone(),
17113                                buffer,
17114                                true,
17115                                true,
17116                                window,
17117                                cx,
17118                            )
17119                        });
17120
17121                    editor.update(cx, |editor, cx| {
17122                        let autoscroll = match scroll_offset {
17123                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17124                            None => Autoscroll::newest(),
17125                        };
17126                        let nav_history = editor.nav_history.take();
17127                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17128                            s.select_ranges(ranges);
17129                        });
17130                        editor.nav_history = nav_history;
17131                    });
17132                }
17133            })
17134        });
17135    }
17136
17137    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17138        let snapshot = self.buffer.read(cx).read(cx);
17139        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17140        Some(
17141            ranges
17142                .iter()
17143                .map(move |range| {
17144                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17145                })
17146                .collect(),
17147        )
17148    }
17149
17150    fn selection_replacement_ranges(
17151        &self,
17152        range: Range<OffsetUtf16>,
17153        cx: &mut App,
17154    ) -> Vec<Range<OffsetUtf16>> {
17155        let selections = self.selections.all::<OffsetUtf16>(cx);
17156        let newest_selection = selections
17157            .iter()
17158            .max_by_key(|selection| selection.id)
17159            .unwrap();
17160        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17161        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17162        let snapshot = self.buffer.read(cx).read(cx);
17163        selections
17164            .into_iter()
17165            .map(|mut selection| {
17166                selection.start.0 =
17167                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17168                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17169                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17170                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17171            })
17172            .collect()
17173    }
17174
17175    fn report_editor_event(
17176        &self,
17177        event_type: &'static str,
17178        file_extension: Option<String>,
17179        cx: &App,
17180    ) {
17181        if cfg!(any(test, feature = "test-support")) {
17182            return;
17183        }
17184
17185        let Some(project) = &self.project else { return };
17186
17187        // If None, we are in a file without an extension
17188        let file = self
17189            .buffer
17190            .read(cx)
17191            .as_singleton()
17192            .and_then(|b| b.read(cx).file());
17193        let file_extension = file_extension.or(file
17194            .as_ref()
17195            .and_then(|file| Path::new(file.file_name(cx)).extension())
17196            .and_then(|e| e.to_str())
17197            .map(|a| a.to_string()));
17198
17199        let vim_mode = cx
17200            .global::<SettingsStore>()
17201            .raw_user_settings()
17202            .get("vim_mode")
17203            == Some(&serde_json::Value::Bool(true));
17204
17205        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17206        let copilot_enabled = edit_predictions_provider
17207            == language::language_settings::EditPredictionProvider::Copilot;
17208        let copilot_enabled_for_language = self
17209            .buffer
17210            .read(cx)
17211            .language_settings(cx)
17212            .show_edit_predictions;
17213
17214        let project = project.read(cx);
17215        telemetry::event!(
17216            event_type,
17217            file_extension,
17218            vim_mode,
17219            copilot_enabled,
17220            copilot_enabled_for_language,
17221            edit_predictions_provider,
17222            is_via_ssh = project.is_via_ssh(),
17223        );
17224    }
17225
17226    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17227    /// with each line being an array of {text, highlight} objects.
17228    fn copy_highlight_json(
17229        &mut self,
17230        _: &CopyHighlightJson,
17231        window: &mut Window,
17232        cx: &mut Context<Self>,
17233    ) {
17234        #[derive(Serialize)]
17235        struct Chunk<'a> {
17236            text: String,
17237            highlight: Option<&'a str>,
17238        }
17239
17240        let snapshot = self.buffer.read(cx).snapshot(cx);
17241        let range = self
17242            .selected_text_range(false, window, cx)
17243            .and_then(|selection| {
17244                if selection.range.is_empty() {
17245                    None
17246                } else {
17247                    Some(selection.range)
17248                }
17249            })
17250            .unwrap_or_else(|| 0..snapshot.len());
17251
17252        let chunks = snapshot.chunks(range, true);
17253        let mut lines = Vec::new();
17254        let mut line: VecDeque<Chunk> = VecDeque::new();
17255
17256        let Some(style) = self.style.as_ref() else {
17257            return;
17258        };
17259
17260        for chunk in chunks {
17261            let highlight = chunk
17262                .syntax_highlight_id
17263                .and_then(|id| id.name(&style.syntax));
17264            let mut chunk_lines = chunk.text.split('\n').peekable();
17265            while let Some(text) = chunk_lines.next() {
17266                let mut merged_with_last_token = false;
17267                if let Some(last_token) = line.back_mut() {
17268                    if last_token.highlight == highlight {
17269                        last_token.text.push_str(text);
17270                        merged_with_last_token = true;
17271                    }
17272                }
17273
17274                if !merged_with_last_token {
17275                    line.push_back(Chunk {
17276                        text: text.into(),
17277                        highlight,
17278                    });
17279                }
17280
17281                if chunk_lines.peek().is_some() {
17282                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17283                        line.pop_front();
17284                    }
17285                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17286                        line.pop_back();
17287                    }
17288
17289                    lines.push(mem::take(&mut line));
17290                }
17291            }
17292        }
17293
17294        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17295            return;
17296        };
17297        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17298    }
17299
17300    pub fn open_context_menu(
17301        &mut self,
17302        _: &OpenContextMenu,
17303        window: &mut Window,
17304        cx: &mut Context<Self>,
17305    ) {
17306        self.request_autoscroll(Autoscroll::newest(), cx);
17307        let position = self.selections.newest_display(cx).start;
17308        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17309    }
17310
17311    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17312        &self.inlay_hint_cache
17313    }
17314
17315    pub fn replay_insert_event(
17316        &mut self,
17317        text: &str,
17318        relative_utf16_range: Option<Range<isize>>,
17319        window: &mut Window,
17320        cx: &mut Context<Self>,
17321    ) {
17322        if !self.input_enabled {
17323            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17324            return;
17325        }
17326        if let Some(relative_utf16_range) = relative_utf16_range {
17327            let selections = self.selections.all::<OffsetUtf16>(cx);
17328            self.change_selections(None, window, cx, |s| {
17329                let new_ranges = selections.into_iter().map(|range| {
17330                    let start = OffsetUtf16(
17331                        range
17332                            .head()
17333                            .0
17334                            .saturating_add_signed(relative_utf16_range.start),
17335                    );
17336                    let end = OffsetUtf16(
17337                        range
17338                            .head()
17339                            .0
17340                            .saturating_add_signed(relative_utf16_range.end),
17341                    );
17342                    start..end
17343                });
17344                s.select_ranges(new_ranges);
17345            });
17346        }
17347
17348        self.handle_input(text, window, cx);
17349    }
17350
17351    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17352        let Some(provider) = self.semantics_provider.as_ref() else {
17353            return false;
17354        };
17355
17356        let mut supports = false;
17357        self.buffer().update(cx, |this, cx| {
17358            this.for_each_buffer(|buffer| {
17359                supports |= provider.supports_inlay_hints(buffer, cx);
17360            });
17361        });
17362
17363        supports
17364    }
17365
17366    pub fn is_focused(&self, window: &Window) -> bool {
17367        self.focus_handle.is_focused(window)
17368    }
17369
17370    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17371        cx.emit(EditorEvent::Focused);
17372
17373        if let Some(descendant) = self
17374            .last_focused_descendant
17375            .take()
17376            .and_then(|descendant| descendant.upgrade())
17377        {
17378            window.focus(&descendant);
17379        } else {
17380            if let Some(blame) = self.blame.as_ref() {
17381                blame.update(cx, GitBlame::focus)
17382            }
17383
17384            self.blink_manager.update(cx, BlinkManager::enable);
17385            self.show_cursor_names(window, cx);
17386            self.buffer.update(cx, |buffer, cx| {
17387                buffer.finalize_last_transaction(cx);
17388                if self.leader_peer_id.is_none() {
17389                    buffer.set_active_selections(
17390                        &self.selections.disjoint_anchors(),
17391                        self.selections.line_mode,
17392                        self.cursor_shape,
17393                        cx,
17394                    );
17395                }
17396            });
17397        }
17398    }
17399
17400    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17401        cx.emit(EditorEvent::FocusedIn)
17402    }
17403
17404    fn handle_focus_out(
17405        &mut self,
17406        event: FocusOutEvent,
17407        _window: &mut Window,
17408        cx: &mut Context<Self>,
17409    ) {
17410        if event.blurred != self.focus_handle {
17411            self.last_focused_descendant = Some(event.blurred);
17412        }
17413        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17414    }
17415
17416    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17417        self.blink_manager.update(cx, BlinkManager::disable);
17418        self.buffer
17419            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17420
17421        if let Some(blame) = self.blame.as_ref() {
17422            blame.update(cx, GitBlame::blur)
17423        }
17424        if !self.hover_state.focused(window, cx) {
17425            hide_hover(self, cx);
17426        }
17427        if !self
17428            .context_menu
17429            .borrow()
17430            .as_ref()
17431            .is_some_and(|context_menu| context_menu.focused(window, cx))
17432        {
17433            self.hide_context_menu(window, cx);
17434        }
17435        self.discard_inline_completion(false, cx);
17436        cx.emit(EditorEvent::Blurred);
17437        cx.notify();
17438    }
17439
17440    pub fn register_action<A: Action>(
17441        &mut self,
17442        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17443    ) -> Subscription {
17444        let id = self.next_editor_action_id.post_inc();
17445        let listener = Arc::new(listener);
17446        self.editor_actions.borrow_mut().insert(
17447            id,
17448            Box::new(move |window, _| {
17449                let listener = listener.clone();
17450                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17451                    let action = action.downcast_ref().unwrap();
17452                    if phase == DispatchPhase::Bubble {
17453                        listener(action, window, cx)
17454                    }
17455                })
17456            }),
17457        );
17458
17459        let editor_actions = self.editor_actions.clone();
17460        Subscription::new(move || {
17461            editor_actions.borrow_mut().remove(&id);
17462        })
17463    }
17464
17465    pub fn file_header_size(&self) -> u32 {
17466        FILE_HEADER_HEIGHT
17467    }
17468
17469    pub fn restore(
17470        &mut self,
17471        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17472        window: &mut Window,
17473        cx: &mut Context<Self>,
17474    ) {
17475        let workspace = self.workspace();
17476        let project = self.project.as_ref();
17477        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17478            let mut tasks = Vec::new();
17479            for (buffer_id, changes) in revert_changes {
17480                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17481                    buffer.update(cx, |buffer, cx| {
17482                        buffer.edit(
17483                            changes
17484                                .into_iter()
17485                                .map(|(range, text)| (range, text.to_string())),
17486                            None,
17487                            cx,
17488                        );
17489                    });
17490
17491                    if let Some(project) =
17492                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17493                    {
17494                        project.update(cx, |project, cx| {
17495                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17496                        })
17497                    }
17498                }
17499            }
17500            tasks
17501        });
17502        cx.spawn_in(window, async move |_, cx| {
17503            for (buffer, task) in save_tasks {
17504                let result = task.await;
17505                if result.is_err() {
17506                    let Some(path) = buffer
17507                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17508                        .ok()
17509                    else {
17510                        continue;
17511                    };
17512                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17513                        let Some(task) = cx
17514                            .update_window_entity(&workspace, |workspace, window, cx| {
17515                                workspace
17516                                    .open_path_preview(path, None, false, false, false, window, cx)
17517                            })
17518                            .ok()
17519                        else {
17520                            continue;
17521                        };
17522                        task.await.log_err();
17523                    }
17524                }
17525            }
17526        })
17527        .detach();
17528        self.change_selections(None, window, cx, |selections| selections.refresh());
17529    }
17530
17531    pub fn to_pixel_point(
17532        &self,
17533        source: multi_buffer::Anchor,
17534        editor_snapshot: &EditorSnapshot,
17535        window: &mut Window,
17536    ) -> Option<gpui::Point<Pixels>> {
17537        let source_point = source.to_display_point(editor_snapshot);
17538        self.display_to_pixel_point(source_point, editor_snapshot, window)
17539    }
17540
17541    pub fn display_to_pixel_point(
17542        &self,
17543        source: DisplayPoint,
17544        editor_snapshot: &EditorSnapshot,
17545        window: &mut Window,
17546    ) -> Option<gpui::Point<Pixels>> {
17547        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17548        let text_layout_details = self.text_layout_details(window);
17549        let scroll_top = text_layout_details
17550            .scroll_anchor
17551            .scroll_position(editor_snapshot)
17552            .y;
17553
17554        if source.row().as_f32() < scroll_top.floor() {
17555            return None;
17556        }
17557        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17558        let source_y = line_height * (source.row().as_f32() - scroll_top);
17559        Some(gpui::Point::new(source_x, source_y))
17560    }
17561
17562    pub fn has_visible_completions_menu(&self) -> bool {
17563        !self.edit_prediction_preview_is_active()
17564            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17565                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17566            })
17567    }
17568
17569    pub fn register_addon<T: Addon>(&mut self, instance: T) {
17570        self.addons
17571            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17572    }
17573
17574    pub fn unregister_addon<T: Addon>(&mut self) {
17575        self.addons.remove(&std::any::TypeId::of::<T>());
17576    }
17577
17578    pub fn addon<T: Addon>(&self) -> Option<&T> {
17579        let type_id = std::any::TypeId::of::<T>();
17580        self.addons
17581            .get(&type_id)
17582            .and_then(|item| item.to_any().downcast_ref::<T>())
17583    }
17584
17585    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17586        let text_layout_details = self.text_layout_details(window);
17587        let style = &text_layout_details.editor_style;
17588        let font_id = window.text_system().resolve_font(&style.text.font());
17589        let font_size = style.text.font_size.to_pixels(window.rem_size());
17590        let line_height = style.text.line_height_in_pixels(window.rem_size());
17591        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17592
17593        gpui::Size::new(em_width, line_height)
17594    }
17595
17596    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17597        self.load_diff_task.clone()
17598    }
17599
17600    fn read_metadata_from_db(
17601        &mut self,
17602        item_id: u64,
17603        workspace_id: WorkspaceId,
17604        window: &mut Window,
17605        cx: &mut Context<Editor>,
17606    ) {
17607        if self.is_singleton(cx)
17608            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17609        {
17610            let buffer_snapshot = OnceCell::new();
17611
17612            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17613                if !folds.is_empty() {
17614                    let snapshot =
17615                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17616                    self.fold_ranges(
17617                        folds
17618                            .into_iter()
17619                            .map(|(start, end)| {
17620                                snapshot.clip_offset(start, Bias::Left)
17621                                    ..snapshot.clip_offset(end, Bias::Right)
17622                            })
17623                            .collect(),
17624                        false,
17625                        window,
17626                        cx,
17627                    );
17628                }
17629            }
17630
17631            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17632                if !selections.is_empty() {
17633                    let snapshot =
17634                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17635                    self.change_selections(None, window, cx, |s| {
17636                        s.select_ranges(selections.into_iter().map(|(start, end)| {
17637                            snapshot.clip_offset(start, Bias::Left)
17638                                ..snapshot.clip_offset(end, Bias::Right)
17639                        }));
17640                    });
17641                }
17642            };
17643        }
17644
17645        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17646    }
17647}
17648
17649fn insert_extra_newline_brackets(
17650    buffer: &MultiBufferSnapshot,
17651    range: Range<usize>,
17652    language: &language::LanguageScope,
17653) -> bool {
17654    let leading_whitespace_len = buffer
17655        .reversed_chars_at(range.start)
17656        .take_while(|c| c.is_whitespace() && *c != '\n')
17657        .map(|c| c.len_utf8())
17658        .sum::<usize>();
17659    let trailing_whitespace_len = buffer
17660        .chars_at(range.end)
17661        .take_while(|c| c.is_whitespace() && *c != '\n')
17662        .map(|c| c.len_utf8())
17663        .sum::<usize>();
17664    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17665
17666    language.brackets().any(|(pair, enabled)| {
17667        let pair_start = pair.start.trim_end();
17668        let pair_end = pair.end.trim_start();
17669
17670        enabled
17671            && pair.newline
17672            && buffer.contains_str_at(range.end, pair_end)
17673            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17674    })
17675}
17676
17677fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17678    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17679        [(buffer, range, _)] => (*buffer, range.clone()),
17680        _ => return false,
17681    };
17682    let pair = {
17683        let mut result: Option<BracketMatch> = None;
17684
17685        for pair in buffer
17686            .all_bracket_ranges(range.clone())
17687            .filter(move |pair| {
17688                pair.open_range.start <= range.start && pair.close_range.end >= range.end
17689            })
17690        {
17691            let len = pair.close_range.end - pair.open_range.start;
17692
17693            if let Some(existing) = &result {
17694                let existing_len = existing.close_range.end - existing.open_range.start;
17695                if len > existing_len {
17696                    continue;
17697                }
17698            }
17699
17700            result = Some(pair);
17701        }
17702
17703        result
17704    };
17705    let Some(pair) = pair else {
17706        return false;
17707    };
17708    pair.newline_only
17709        && buffer
17710            .chars_for_range(pair.open_range.end..range.start)
17711            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17712            .all(|c| c.is_whitespace() && c != '\n')
17713}
17714
17715fn get_uncommitted_diff_for_buffer(
17716    project: &Entity<Project>,
17717    buffers: impl IntoIterator<Item = Entity<Buffer>>,
17718    buffer: Entity<MultiBuffer>,
17719    cx: &mut App,
17720) -> Task<()> {
17721    let mut tasks = Vec::new();
17722    project.update(cx, |project, cx| {
17723        for buffer in buffers {
17724            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17725        }
17726    });
17727    cx.spawn(async move |cx| {
17728        let diffs = future::join_all(tasks).await;
17729        buffer
17730            .update(cx, |buffer, cx| {
17731                for diff in diffs.into_iter().flatten() {
17732                    buffer.add_diff(diff, cx);
17733                }
17734            })
17735            .ok();
17736    })
17737}
17738
17739fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17740    let tab_size = tab_size.get() as usize;
17741    let mut width = offset;
17742
17743    for ch in text.chars() {
17744        width += if ch == '\t' {
17745            tab_size - (width % tab_size)
17746        } else {
17747            1
17748        };
17749    }
17750
17751    width - offset
17752}
17753
17754#[cfg(test)]
17755mod tests {
17756    use super::*;
17757
17758    #[test]
17759    fn test_string_size_with_expanded_tabs() {
17760        let nz = |val| NonZeroU32::new(val).unwrap();
17761        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17762        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17763        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17764        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17765        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17766        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17767        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17768        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17769    }
17770}
17771
17772/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17773struct WordBreakingTokenizer<'a> {
17774    input: &'a str,
17775}
17776
17777impl<'a> WordBreakingTokenizer<'a> {
17778    fn new(input: &'a str) -> Self {
17779        Self { input }
17780    }
17781}
17782
17783fn is_char_ideographic(ch: char) -> bool {
17784    use unicode_script::Script::*;
17785    use unicode_script::UnicodeScript;
17786    matches!(ch.script(), Han | Tangut | Yi)
17787}
17788
17789fn is_grapheme_ideographic(text: &str) -> bool {
17790    text.chars().any(is_char_ideographic)
17791}
17792
17793fn is_grapheme_whitespace(text: &str) -> bool {
17794    text.chars().any(|x| x.is_whitespace())
17795}
17796
17797fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17798    text.chars().next().map_or(false, |ch| {
17799        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17800    })
17801}
17802
17803#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17804enum WordBreakToken<'a> {
17805    Word { token: &'a str, grapheme_len: usize },
17806    InlineWhitespace { token: &'a str, grapheme_len: usize },
17807    Newline,
17808}
17809
17810impl<'a> Iterator for WordBreakingTokenizer<'a> {
17811    /// Yields a span, the count of graphemes in the token, and whether it was
17812    /// whitespace. Note that it also breaks at word boundaries.
17813    type Item = WordBreakToken<'a>;
17814
17815    fn next(&mut self) -> Option<Self::Item> {
17816        use unicode_segmentation::UnicodeSegmentation;
17817        if self.input.is_empty() {
17818            return None;
17819        }
17820
17821        let mut iter = self.input.graphemes(true).peekable();
17822        let mut offset = 0;
17823        let mut grapheme_len = 0;
17824        if let Some(first_grapheme) = iter.next() {
17825            let is_newline = first_grapheme == "\n";
17826            let is_whitespace = is_grapheme_whitespace(first_grapheme);
17827            offset += first_grapheme.len();
17828            grapheme_len += 1;
17829            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17830                if let Some(grapheme) = iter.peek().copied() {
17831                    if should_stay_with_preceding_ideograph(grapheme) {
17832                        offset += grapheme.len();
17833                        grapheme_len += 1;
17834                    }
17835                }
17836            } else {
17837                let mut words = self.input[offset..].split_word_bound_indices().peekable();
17838                let mut next_word_bound = words.peek().copied();
17839                if next_word_bound.map_or(false, |(i, _)| i == 0) {
17840                    next_word_bound = words.next();
17841                }
17842                while let Some(grapheme) = iter.peek().copied() {
17843                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
17844                        break;
17845                    };
17846                    if is_grapheme_whitespace(grapheme) != is_whitespace
17847                        || (grapheme == "\n") != is_newline
17848                    {
17849                        break;
17850                    };
17851                    offset += grapheme.len();
17852                    grapheme_len += 1;
17853                    iter.next();
17854                }
17855            }
17856            let token = &self.input[..offset];
17857            self.input = &self.input[offset..];
17858            if token == "\n" {
17859                Some(WordBreakToken::Newline)
17860            } else if is_whitespace {
17861                Some(WordBreakToken::InlineWhitespace {
17862                    token,
17863                    grapheme_len,
17864                })
17865            } else {
17866                Some(WordBreakToken::Word {
17867                    token,
17868                    grapheme_len,
17869                })
17870            }
17871        } else {
17872            None
17873        }
17874    }
17875}
17876
17877#[test]
17878fn test_word_breaking_tokenizer() {
17879    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17880        ("", &[]),
17881        ("  ", &[whitespace("  ", 2)]),
17882        ("Ʒ", &[word("Ʒ", 1)]),
17883        ("Ǽ", &[word("Ǽ", 1)]),
17884        ("", &[word("", 1)]),
17885        ("⋑⋑", &[word("⋑⋑", 2)]),
17886        (
17887            "原理,进而",
17888            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
17889        ),
17890        (
17891            "hello world",
17892            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17893        ),
17894        (
17895            "hello, world",
17896            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17897        ),
17898        (
17899            "  hello world",
17900            &[
17901                whitespace("  ", 2),
17902                word("hello", 5),
17903                whitespace(" ", 1),
17904                word("world", 5),
17905            ],
17906        ),
17907        (
17908            "这是什么 \n 钢笔",
17909            &[
17910                word("", 1),
17911                word("", 1),
17912                word("", 1),
17913                word("", 1),
17914                whitespace(" ", 1),
17915                newline(),
17916                whitespace(" ", 1),
17917                word("", 1),
17918                word("", 1),
17919            ],
17920        ),
17921        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
17922    ];
17923
17924    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17925        WordBreakToken::Word {
17926            token,
17927            grapheme_len,
17928        }
17929    }
17930
17931    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17932        WordBreakToken::InlineWhitespace {
17933            token,
17934            grapheme_len,
17935        }
17936    }
17937
17938    fn newline() -> WordBreakToken<'static> {
17939        WordBreakToken::Newline
17940    }
17941
17942    for (input, result) in tests {
17943        assert_eq!(
17944            WordBreakingTokenizer::new(input)
17945                .collect::<Vec<_>>()
17946                .as_slice(),
17947            *result,
17948        );
17949    }
17950}
17951
17952fn wrap_with_prefix(
17953    line_prefix: String,
17954    unwrapped_text: String,
17955    wrap_column: usize,
17956    tab_size: NonZeroU32,
17957    preserve_existing_whitespace: bool,
17958) -> String {
17959    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17960    let mut wrapped_text = String::new();
17961    let mut current_line = line_prefix.clone();
17962
17963    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17964    let mut current_line_len = line_prefix_len;
17965    let mut in_whitespace = false;
17966    for token in tokenizer {
17967        let have_preceding_whitespace = in_whitespace;
17968        match token {
17969            WordBreakToken::Word {
17970                token,
17971                grapheme_len,
17972            } => {
17973                in_whitespace = false;
17974                if current_line_len + grapheme_len > wrap_column
17975                    && current_line_len != line_prefix_len
17976                {
17977                    wrapped_text.push_str(current_line.trim_end());
17978                    wrapped_text.push('\n');
17979                    current_line.truncate(line_prefix.len());
17980                    current_line_len = line_prefix_len;
17981                }
17982                current_line.push_str(token);
17983                current_line_len += grapheme_len;
17984            }
17985            WordBreakToken::InlineWhitespace {
17986                mut token,
17987                mut grapheme_len,
17988            } => {
17989                in_whitespace = true;
17990                if have_preceding_whitespace && !preserve_existing_whitespace {
17991                    continue;
17992                }
17993                if !preserve_existing_whitespace {
17994                    token = " ";
17995                    grapheme_len = 1;
17996                }
17997                if current_line_len + grapheme_len > wrap_column {
17998                    wrapped_text.push_str(current_line.trim_end());
17999                    wrapped_text.push('\n');
18000                    current_line.truncate(line_prefix.len());
18001                    current_line_len = line_prefix_len;
18002                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18003                    current_line.push_str(token);
18004                    current_line_len += grapheme_len;
18005                }
18006            }
18007            WordBreakToken::Newline => {
18008                in_whitespace = true;
18009                if preserve_existing_whitespace {
18010                    wrapped_text.push_str(current_line.trim_end());
18011                    wrapped_text.push('\n');
18012                    current_line.truncate(line_prefix.len());
18013                    current_line_len = line_prefix_len;
18014                } else if have_preceding_whitespace {
18015                    continue;
18016                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18017                {
18018                    wrapped_text.push_str(current_line.trim_end());
18019                    wrapped_text.push('\n');
18020                    current_line.truncate(line_prefix.len());
18021                    current_line_len = line_prefix_len;
18022                } else if current_line_len != line_prefix_len {
18023                    current_line.push(' ');
18024                    current_line_len += 1;
18025                }
18026            }
18027        }
18028    }
18029
18030    if !current_line.is_empty() {
18031        wrapped_text.push_str(&current_line);
18032    }
18033    wrapped_text
18034}
18035
18036#[test]
18037fn test_wrap_with_prefix() {
18038    assert_eq!(
18039        wrap_with_prefix(
18040            "# ".to_string(),
18041            "abcdefg".to_string(),
18042            4,
18043            NonZeroU32::new(4).unwrap(),
18044            false,
18045        ),
18046        "# abcdefg"
18047    );
18048    assert_eq!(
18049        wrap_with_prefix(
18050            "".to_string(),
18051            "\thello world".to_string(),
18052            8,
18053            NonZeroU32::new(4).unwrap(),
18054            false,
18055        ),
18056        "hello\nworld"
18057    );
18058    assert_eq!(
18059        wrap_with_prefix(
18060            "// ".to_string(),
18061            "xx \nyy zz aa bb cc".to_string(),
18062            12,
18063            NonZeroU32::new(4).unwrap(),
18064            false,
18065        ),
18066        "// xx yy zz\n// aa bb cc"
18067    );
18068    assert_eq!(
18069        wrap_with_prefix(
18070            String::new(),
18071            "这是什么 \n 钢笔".to_string(),
18072            3,
18073            NonZeroU32::new(4).unwrap(),
18074            false,
18075        ),
18076        "这是什\n么 钢\n"
18077    );
18078}
18079
18080pub trait CollaborationHub {
18081    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18082    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18083    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18084}
18085
18086impl CollaborationHub for Entity<Project> {
18087    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18088        self.read(cx).collaborators()
18089    }
18090
18091    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18092        self.read(cx).user_store().read(cx).participant_indices()
18093    }
18094
18095    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18096        let this = self.read(cx);
18097        let user_ids = this.collaborators().values().map(|c| c.user_id);
18098        this.user_store().read_with(cx, |user_store, cx| {
18099            user_store.participant_names(user_ids, cx)
18100        })
18101    }
18102}
18103
18104pub trait SemanticsProvider {
18105    fn hover(
18106        &self,
18107        buffer: &Entity<Buffer>,
18108        position: text::Anchor,
18109        cx: &mut App,
18110    ) -> Option<Task<Vec<project::Hover>>>;
18111
18112    fn inlay_hints(
18113        &self,
18114        buffer_handle: Entity<Buffer>,
18115        range: Range<text::Anchor>,
18116        cx: &mut App,
18117    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18118
18119    fn resolve_inlay_hint(
18120        &self,
18121        hint: InlayHint,
18122        buffer_handle: Entity<Buffer>,
18123        server_id: LanguageServerId,
18124        cx: &mut App,
18125    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18126
18127    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18128
18129    fn document_highlights(
18130        &self,
18131        buffer: &Entity<Buffer>,
18132        position: text::Anchor,
18133        cx: &mut App,
18134    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18135
18136    fn definitions(
18137        &self,
18138        buffer: &Entity<Buffer>,
18139        position: text::Anchor,
18140        kind: GotoDefinitionKind,
18141        cx: &mut App,
18142    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18143
18144    fn range_for_rename(
18145        &self,
18146        buffer: &Entity<Buffer>,
18147        position: text::Anchor,
18148        cx: &mut App,
18149    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18150
18151    fn perform_rename(
18152        &self,
18153        buffer: &Entity<Buffer>,
18154        position: text::Anchor,
18155        new_name: String,
18156        cx: &mut App,
18157    ) -> Option<Task<Result<ProjectTransaction>>>;
18158}
18159
18160pub trait CompletionProvider {
18161    fn completions(
18162        &self,
18163        excerpt_id: ExcerptId,
18164        buffer: &Entity<Buffer>,
18165        buffer_position: text::Anchor,
18166        trigger: CompletionContext,
18167        window: &mut Window,
18168        cx: &mut Context<Editor>,
18169    ) -> Task<Result<Option<Vec<Completion>>>>;
18170
18171    fn resolve_completions(
18172        &self,
18173        buffer: Entity<Buffer>,
18174        completion_indices: Vec<usize>,
18175        completions: Rc<RefCell<Box<[Completion]>>>,
18176        cx: &mut Context<Editor>,
18177    ) -> Task<Result<bool>>;
18178
18179    fn apply_additional_edits_for_completion(
18180        &self,
18181        _buffer: Entity<Buffer>,
18182        _completions: Rc<RefCell<Box<[Completion]>>>,
18183        _completion_index: usize,
18184        _push_to_history: bool,
18185        _cx: &mut Context<Editor>,
18186    ) -> Task<Result<Option<language::Transaction>>> {
18187        Task::ready(Ok(None))
18188    }
18189
18190    fn is_completion_trigger(
18191        &self,
18192        buffer: &Entity<Buffer>,
18193        position: language::Anchor,
18194        text: &str,
18195        trigger_in_words: bool,
18196        cx: &mut Context<Editor>,
18197    ) -> bool;
18198
18199    fn sort_completions(&self) -> bool {
18200        true
18201    }
18202
18203    fn filter_completions(&self) -> bool {
18204        true
18205    }
18206}
18207
18208pub trait CodeActionProvider {
18209    fn id(&self) -> Arc<str>;
18210
18211    fn code_actions(
18212        &self,
18213        buffer: &Entity<Buffer>,
18214        range: Range<text::Anchor>,
18215        window: &mut Window,
18216        cx: &mut App,
18217    ) -> Task<Result<Vec<CodeAction>>>;
18218
18219    fn apply_code_action(
18220        &self,
18221        buffer_handle: Entity<Buffer>,
18222        action: CodeAction,
18223        excerpt_id: ExcerptId,
18224        push_to_history: bool,
18225        window: &mut Window,
18226        cx: &mut App,
18227    ) -> Task<Result<ProjectTransaction>>;
18228}
18229
18230impl CodeActionProvider for Entity<Project> {
18231    fn id(&self) -> Arc<str> {
18232        "project".into()
18233    }
18234
18235    fn code_actions(
18236        &self,
18237        buffer: &Entity<Buffer>,
18238        range: Range<text::Anchor>,
18239        _window: &mut Window,
18240        cx: &mut App,
18241    ) -> Task<Result<Vec<CodeAction>>> {
18242        self.update(cx, |project, cx| {
18243            let code_lens = project.code_lens(buffer, range.clone(), cx);
18244            let code_actions = project.code_actions(buffer, range, None, cx);
18245            cx.background_spawn(async move {
18246                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18247                Ok(code_lens
18248                    .context("code lens fetch")?
18249                    .into_iter()
18250                    .chain(code_actions.context("code action fetch")?)
18251                    .collect())
18252            })
18253        })
18254    }
18255
18256    fn apply_code_action(
18257        &self,
18258        buffer_handle: Entity<Buffer>,
18259        action: CodeAction,
18260        _excerpt_id: ExcerptId,
18261        push_to_history: bool,
18262        _window: &mut Window,
18263        cx: &mut App,
18264    ) -> Task<Result<ProjectTransaction>> {
18265        self.update(cx, |project, cx| {
18266            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18267        })
18268    }
18269}
18270
18271fn snippet_completions(
18272    project: &Project,
18273    buffer: &Entity<Buffer>,
18274    buffer_position: text::Anchor,
18275    cx: &mut App,
18276) -> Task<Result<Vec<Completion>>> {
18277    let language = buffer.read(cx).language_at(buffer_position);
18278    let language_name = language.as_ref().map(|language| language.lsp_id());
18279    let snippet_store = project.snippets().read(cx);
18280    let snippets = snippet_store.snippets_for(language_name, cx);
18281
18282    if snippets.is_empty() {
18283        return Task::ready(Ok(vec![]));
18284    }
18285    let snapshot = buffer.read(cx).text_snapshot();
18286    let chars: String = snapshot
18287        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18288        .collect();
18289
18290    let scope = language.map(|language| language.default_scope());
18291    let executor = cx.background_executor().clone();
18292
18293    cx.background_spawn(async move {
18294        let classifier = CharClassifier::new(scope).for_completion(true);
18295        let mut last_word = chars
18296            .chars()
18297            .take_while(|c| classifier.is_word(*c))
18298            .collect::<String>();
18299        last_word = last_word.chars().rev().collect();
18300
18301        if last_word.is_empty() {
18302            return Ok(vec![]);
18303        }
18304
18305        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18306        let to_lsp = |point: &text::Anchor| {
18307            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18308            point_to_lsp(end)
18309        };
18310        let lsp_end = to_lsp(&buffer_position);
18311
18312        let candidates = snippets
18313            .iter()
18314            .enumerate()
18315            .flat_map(|(ix, snippet)| {
18316                snippet
18317                    .prefix
18318                    .iter()
18319                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18320            })
18321            .collect::<Vec<StringMatchCandidate>>();
18322
18323        let mut matches = fuzzy::match_strings(
18324            &candidates,
18325            &last_word,
18326            last_word.chars().any(|c| c.is_uppercase()),
18327            100,
18328            &Default::default(),
18329            executor,
18330        )
18331        .await;
18332
18333        // Remove all candidates where the query's start does not match the start of any word in the candidate
18334        if let Some(query_start) = last_word.chars().next() {
18335            matches.retain(|string_match| {
18336                split_words(&string_match.string).any(|word| {
18337                    // Check that the first codepoint of the word as lowercase matches the first
18338                    // codepoint of the query as lowercase
18339                    word.chars()
18340                        .flat_map(|codepoint| codepoint.to_lowercase())
18341                        .zip(query_start.to_lowercase())
18342                        .all(|(word_cp, query_cp)| word_cp == query_cp)
18343                })
18344            });
18345        }
18346
18347        let matched_strings = matches
18348            .into_iter()
18349            .map(|m| m.string)
18350            .collect::<HashSet<_>>();
18351
18352        let result: Vec<Completion> = snippets
18353            .into_iter()
18354            .filter_map(|snippet| {
18355                let matching_prefix = snippet
18356                    .prefix
18357                    .iter()
18358                    .find(|prefix| matched_strings.contains(*prefix))?;
18359                let start = as_offset - last_word.len();
18360                let start = snapshot.anchor_before(start);
18361                let range = start..buffer_position;
18362                let lsp_start = to_lsp(&start);
18363                let lsp_range = lsp::Range {
18364                    start: lsp_start,
18365                    end: lsp_end,
18366                };
18367                Some(Completion {
18368                    old_range: range,
18369                    new_text: snippet.body.clone(),
18370                    source: CompletionSource::Lsp {
18371                        server_id: LanguageServerId(usize::MAX),
18372                        resolved: true,
18373                        lsp_completion: Box::new(lsp::CompletionItem {
18374                            label: snippet.prefix.first().unwrap().clone(),
18375                            kind: Some(CompletionItemKind::SNIPPET),
18376                            label_details: snippet.description.as_ref().map(|description| {
18377                                lsp::CompletionItemLabelDetails {
18378                                    detail: Some(description.clone()),
18379                                    description: None,
18380                                }
18381                            }),
18382                            insert_text_format: Some(InsertTextFormat::SNIPPET),
18383                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18384                                lsp::InsertReplaceEdit {
18385                                    new_text: snippet.body.clone(),
18386                                    insert: lsp_range,
18387                                    replace: lsp_range,
18388                                },
18389                            )),
18390                            filter_text: Some(snippet.body.clone()),
18391                            sort_text: Some(char::MAX.to_string()),
18392                            ..lsp::CompletionItem::default()
18393                        }),
18394                        lsp_defaults: None,
18395                    },
18396                    label: CodeLabel {
18397                        text: matching_prefix.clone(),
18398                        runs: Vec::new(),
18399                        filter_range: 0..matching_prefix.len(),
18400                    },
18401                    icon_path: None,
18402                    documentation: snippet
18403                        .description
18404                        .clone()
18405                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
18406                    confirm: None,
18407                })
18408            })
18409            .collect();
18410
18411        Ok(result)
18412    })
18413}
18414
18415impl CompletionProvider for Entity<Project> {
18416    fn completions(
18417        &self,
18418        _excerpt_id: ExcerptId,
18419        buffer: &Entity<Buffer>,
18420        buffer_position: text::Anchor,
18421        options: CompletionContext,
18422        _window: &mut Window,
18423        cx: &mut Context<Editor>,
18424    ) -> Task<Result<Option<Vec<Completion>>>> {
18425        self.update(cx, |project, cx| {
18426            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18427            let project_completions = project.completions(buffer, buffer_position, options, cx);
18428            cx.background_spawn(async move {
18429                let snippets_completions = snippets.await?;
18430                match project_completions.await? {
18431                    Some(mut completions) => {
18432                        completions.extend(snippets_completions);
18433                        Ok(Some(completions))
18434                    }
18435                    None => {
18436                        if snippets_completions.is_empty() {
18437                            Ok(None)
18438                        } else {
18439                            Ok(Some(snippets_completions))
18440                        }
18441                    }
18442                }
18443            })
18444        })
18445    }
18446
18447    fn resolve_completions(
18448        &self,
18449        buffer: Entity<Buffer>,
18450        completion_indices: Vec<usize>,
18451        completions: Rc<RefCell<Box<[Completion]>>>,
18452        cx: &mut Context<Editor>,
18453    ) -> Task<Result<bool>> {
18454        self.update(cx, |project, cx| {
18455            project.lsp_store().update(cx, |lsp_store, cx| {
18456                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18457            })
18458        })
18459    }
18460
18461    fn apply_additional_edits_for_completion(
18462        &self,
18463        buffer: Entity<Buffer>,
18464        completions: Rc<RefCell<Box<[Completion]>>>,
18465        completion_index: usize,
18466        push_to_history: bool,
18467        cx: &mut Context<Editor>,
18468    ) -> Task<Result<Option<language::Transaction>>> {
18469        self.update(cx, |project, cx| {
18470            project.lsp_store().update(cx, |lsp_store, cx| {
18471                lsp_store.apply_additional_edits_for_completion(
18472                    buffer,
18473                    completions,
18474                    completion_index,
18475                    push_to_history,
18476                    cx,
18477                )
18478            })
18479        })
18480    }
18481
18482    fn is_completion_trigger(
18483        &self,
18484        buffer: &Entity<Buffer>,
18485        position: language::Anchor,
18486        text: &str,
18487        trigger_in_words: bool,
18488        cx: &mut Context<Editor>,
18489    ) -> bool {
18490        let mut chars = text.chars();
18491        let char = if let Some(char) = chars.next() {
18492            char
18493        } else {
18494            return false;
18495        };
18496        if chars.next().is_some() {
18497            return false;
18498        }
18499
18500        let buffer = buffer.read(cx);
18501        let snapshot = buffer.snapshot();
18502        if !snapshot.settings_at(position, cx).show_completions_on_input {
18503            return false;
18504        }
18505        let classifier = snapshot.char_classifier_at(position).for_completion(true);
18506        if trigger_in_words && classifier.is_word(char) {
18507            return true;
18508        }
18509
18510        buffer.completion_triggers().contains(text)
18511    }
18512}
18513
18514impl SemanticsProvider for Entity<Project> {
18515    fn hover(
18516        &self,
18517        buffer: &Entity<Buffer>,
18518        position: text::Anchor,
18519        cx: &mut App,
18520    ) -> Option<Task<Vec<project::Hover>>> {
18521        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18522    }
18523
18524    fn document_highlights(
18525        &self,
18526        buffer: &Entity<Buffer>,
18527        position: text::Anchor,
18528        cx: &mut App,
18529    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18530        Some(self.update(cx, |project, cx| {
18531            project.document_highlights(buffer, position, cx)
18532        }))
18533    }
18534
18535    fn definitions(
18536        &self,
18537        buffer: &Entity<Buffer>,
18538        position: text::Anchor,
18539        kind: GotoDefinitionKind,
18540        cx: &mut App,
18541    ) -> Option<Task<Result<Vec<LocationLink>>>> {
18542        Some(self.update(cx, |project, cx| match kind {
18543            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18544            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18545            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18546            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18547        }))
18548    }
18549
18550    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18551        // TODO: make this work for remote projects
18552        self.update(cx, |this, cx| {
18553            buffer.update(cx, |buffer, cx| {
18554                this.any_language_server_supports_inlay_hints(buffer, cx)
18555            })
18556        })
18557    }
18558
18559    fn inlay_hints(
18560        &self,
18561        buffer_handle: Entity<Buffer>,
18562        range: Range<text::Anchor>,
18563        cx: &mut App,
18564    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18565        Some(self.update(cx, |project, cx| {
18566            project.inlay_hints(buffer_handle, range, cx)
18567        }))
18568    }
18569
18570    fn resolve_inlay_hint(
18571        &self,
18572        hint: InlayHint,
18573        buffer_handle: Entity<Buffer>,
18574        server_id: LanguageServerId,
18575        cx: &mut App,
18576    ) -> Option<Task<anyhow::Result<InlayHint>>> {
18577        Some(self.update(cx, |project, cx| {
18578            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18579        }))
18580    }
18581
18582    fn range_for_rename(
18583        &self,
18584        buffer: &Entity<Buffer>,
18585        position: text::Anchor,
18586        cx: &mut App,
18587    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18588        Some(self.update(cx, |project, cx| {
18589            let buffer = buffer.clone();
18590            let task = project.prepare_rename(buffer.clone(), position, cx);
18591            cx.spawn(async move |_, cx| {
18592                Ok(match task.await? {
18593                    PrepareRenameResponse::Success(range) => Some(range),
18594                    PrepareRenameResponse::InvalidPosition => None,
18595                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18596                        // Fallback on using TreeSitter info to determine identifier range
18597                        buffer.update(cx, |buffer, _| {
18598                            let snapshot = buffer.snapshot();
18599                            let (range, kind) = snapshot.surrounding_word(position);
18600                            if kind != Some(CharKind::Word) {
18601                                return None;
18602                            }
18603                            Some(
18604                                snapshot.anchor_before(range.start)
18605                                    ..snapshot.anchor_after(range.end),
18606                            )
18607                        })?
18608                    }
18609                })
18610            })
18611        }))
18612    }
18613
18614    fn perform_rename(
18615        &self,
18616        buffer: &Entity<Buffer>,
18617        position: text::Anchor,
18618        new_name: String,
18619        cx: &mut App,
18620    ) -> Option<Task<Result<ProjectTransaction>>> {
18621        Some(self.update(cx, |project, cx| {
18622            project.perform_rename(buffer.clone(), position, new_name, cx)
18623        }))
18624    }
18625}
18626
18627fn inlay_hint_settings(
18628    location: Anchor,
18629    snapshot: &MultiBufferSnapshot,
18630    cx: &mut Context<Editor>,
18631) -> InlayHintSettings {
18632    let file = snapshot.file_at(location);
18633    let language = snapshot.language_at(location).map(|l| l.name());
18634    language_settings(language, file, cx).inlay_hints
18635}
18636
18637fn consume_contiguous_rows(
18638    contiguous_row_selections: &mut Vec<Selection<Point>>,
18639    selection: &Selection<Point>,
18640    display_map: &DisplaySnapshot,
18641    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18642) -> (MultiBufferRow, MultiBufferRow) {
18643    contiguous_row_selections.push(selection.clone());
18644    let start_row = MultiBufferRow(selection.start.row);
18645    let mut end_row = ending_row(selection, display_map);
18646
18647    while let Some(next_selection) = selections.peek() {
18648        if next_selection.start.row <= end_row.0 {
18649            end_row = ending_row(next_selection, display_map);
18650            contiguous_row_selections.push(selections.next().unwrap().clone());
18651        } else {
18652            break;
18653        }
18654    }
18655    (start_row, end_row)
18656}
18657
18658fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18659    if next_selection.end.column > 0 || next_selection.is_empty() {
18660        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18661    } else {
18662        MultiBufferRow(next_selection.end.row)
18663    }
18664}
18665
18666impl EditorSnapshot {
18667    pub fn remote_selections_in_range<'a>(
18668        &'a self,
18669        range: &'a Range<Anchor>,
18670        collaboration_hub: &dyn CollaborationHub,
18671        cx: &'a App,
18672    ) -> impl 'a + Iterator<Item = RemoteSelection> {
18673        let participant_names = collaboration_hub.user_names(cx);
18674        let participant_indices = collaboration_hub.user_participant_indices(cx);
18675        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18676        let collaborators_by_replica_id = collaborators_by_peer_id
18677            .iter()
18678            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18679            .collect::<HashMap<_, _>>();
18680        self.buffer_snapshot
18681            .selections_in_range(range, false)
18682            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18683                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18684                let participant_index = participant_indices.get(&collaborator.user_id).copied();
18685                let user_name = participant_names.get(&collaborator.user_id).cloned();
18686                Some(RemoteSelection {
18687                    replica_id,
18688                    selection,
18689                    cursor_shape,
18690                    line_mode,
18691                    participant_index,
18692                    peer_id: collaborator.peer_id,
18693                    user_name,
18694                })
18695            })
18696    }
18697
18698    pub fn hunks_for_ranges(
18699        &self,
18700        ranges: impl IntoIterator<Item = Range<Point>>,
18701    ) -> Vec<MultiBufferDiffHunk> {
18702        let mut hunks = Vec::new();
18703        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18704            HashMap::default();
18705        for query_range in ranges {
18706            let query_rows =
18707                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18708            for hunk in self.buffer_snapshot.diff_hunks_in_range(
18709                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18710            ) {
18711                // Include deleted hunks that are adjacent to the query range, because
18712                // otherwise they would be missed.
18713                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18714                if hunk.status().is_deleted() {
18715                    intersects_range |= hunk.row_range.start == query_rows.end;
18716                    intersects_range |= hunk.row_range.end == query_rows.start;
18717                }
18718                if intersects_range {
18719                    if !processed_buffer_rows
18720                        .entry(hunk.buffer_id)
18721                        .or_default()
18722                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18723                    {
18724                        continue;
18725                    }
18726                    hunks.push(hunk);
18727                }
18728            }
18729        }
18730
18731        hunks
18732    }
18733
18734    fn display_diff_hunks_for_rows<'a>(
18735        &'a self,
18736        display_rows: Range<DisplayRow>,
18737        folded_buffers: &'a HashSet<BufferId>,
18738    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18739        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18740        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18741
18742        self.buffer_snapshot
18743            .diff_hunks_in_range(buffer_start..buffer_end)
18744            .filter_map(|hunk| {
18745                if folded_buffers.contains(&hunk.buffer_id) {
18746                    return None;
18747                }
18748
18749                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18750                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18751
18752                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18753                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18754
18755                let display_hunk = if hunk_display_start.column() != 0 {
18756                    DisplayDiffHunk::Folded {
18757                        display_row: hunk_display_start.row(),
18758                    }
18759                } else {
18760                    let mut end_row = hunk_display_end.row();
18761                    if hunk_display_end.column() > 0 {
18762                        end_row.0 += 1;
18763                    }
18764                    let is_created_file = hunk.is_created_file();
18765                    DisplayDiffHunk::Unfolded {
18766                        status: hunk.status(),
18767                        diff_base_byte_range: hunk.diff_base_byte_range,
18768                        display_row_range: hunk_display_start.row()..end_row,
18769                        multi_buffer_range: Anchor::range_in_buffer(
18770                            hunk.excerpt_id,
18771                            hunk.buffer_id,
18772                            hunk.buffer_range,
18773                        ),
18774                        is_created_file,
18775                    }
18776                };
18777
18778                Some(display_hunk)
18779            })
18780    }
18781
18782    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18783        self.display_snapshot.buffer_snapshot.language_at(position)
18784    }
18785
18786    pub fn is_focused(&self) -> bool {
18787        self.is_focused
18788    }
18789
18790    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18791        self.placeholder_text.as_ref()
18792    }
18793
18794    pub fn scroll_position(&self) -> gpui::Point<f32> {
18795        self.scroll_anchor.scroll_position(&self.display_snapshot)
18796    }
18797
18798    fn gutter_dimensions(
18799        &self,
18800        font_id: FontId,
18801        font_size: Pixels,
18802        max_line_number_width: Pixels,
18803        cx: &App,
18804    ) -> Option<GutterDimensions> {
18805        if !self.show_gutter {
18806            return None;
18807        }
18808
18809        let descent = cx.text_system().descent(font_id, font_size);
18810        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18811        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18812
18813        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18814            matches!(
18815                ProjectSettings::get_global(cx).git.git_gutter,
18816                Some(GitGutterSetting::TrackedFiles)
18817            )
18818        });
18819        let gutter_settings = EditorSettings::get_global(cx).gutter;
18820        let show_line_numbers = self
18821            .show_line_numbers
18822            .unwrap_or(gutter_settings.line_numbers);
18823        let line_gutter_width = if show_line_numbers {
18824            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18825            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18826            max_line_number_width.max(min_width_for_number_on_gutter)
18827        } else {
18828            0.0.into()
18829        };
18830
18831        let show_code_actions = self
18832            .show_code_actions
18833            .unwrap_or(gutter_settings.code_actions);
18834
18835        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18836        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18837
18838        let git_blame_entries_width =
18839            self.git_blame_gutter_max_author_length
18840                .map(|max_author_length| {
18841                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18842
18843                    /// The number of characters to dedicate to gaps and margins.
18844                    const SPACING_WIDTH: usize = 4;
18845
18846                    let max_char_count = max_author_length
18847                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18848                        + ::git::SHORT_SHA_LENGTH
18849                        + MAX_RELATIVE_TIMESTAMP.len()
18850                        + SPACING_WIDTH;
18851
18852                    em_advance * max_char_count
18853                });
18854
18855        let is_singleton = self.buffer_snapshot.is_singleton();
18856
18857        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18858        left_padding += if !is_singleton {
18859            em_width * 4.0
18860        } else if show_code_actions || show_runnables || show_breakpoints {
18861            em_width * 3.0
18862        } else if show_git_gutter && show_line_numbers {
18863            em_width * 2.0
18864        } else if show_git_gutter || show_line_numbers {
18865            em_width
18866        } else {
18867            px(0.)
18868        };
18869
18870        let shows_folds = is_singleton && gutter_settings.folds;
18871
18872        let right_padding = if shows_folds && show_line_numbers {
18873            em_width * 4.0
18874        } else if shows_folds || (!is_singleton && show_line_numbers) {
18875            em_width * 3.0
18876        } else if show_line_numbers {
18877            em_width
18878        } else {
18879            px(0.)
18880        };
18881
18882        Some(GutterDimensions {
18883            left_padding,
18884            right_padding,
18885            width: line_gutter_width + left_padding + right_padding,
18886            margin: -descent,
18887            git_blame_entries_width,
18888        })
18889    }
18890
18891    pub fn render_crease_toggle(
18892        &self,
18893        buffer_row: MultiBufferRow,
18894        row_contains_cursor: bool,
18895        editor: Entity<Editor>,
18896        window: &mut Window,
18897        cx: &mut App,
18898    ) -> Option<AnyElement> {
18899        let folded = self.is_line_folded(buffer_row);
18900        let mut is_foldable = false;
18901
18902        if let Some(crease) = self
18903            .crease_snapshot
18904            .query_row(buffer_row, &self.buffer_snapshot)
18905        {
18906            is_foldable = true;
18907            match crease {
18908                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18909                    if let Some(render_toggle) = render_toggle {
18910                        let toggle_callback =
18911                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18912                                if folded {
18913                                    editor.update(cx, |editor, cx| {
18914                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18915                                    });
18916                                } else {
18917                                    editor.update(cx, |editor, cx| {
18918                                        editor.unfold_at(
18919                                            &crate::UnfoldAt { buffer_row },
18920                                            window,
18921                                            cx,
18922                                        )
18923                                    });
18924                                }
18925                            });
18926                        return Some((render_toggle)(
18927                            buffer_row,
18928                            folded,
18929                            toggle_callback,
18930                            window,
18931                            cx,
18932                        ));
18933                    }
18934                }
18935            }
18936        }
18937
18938        is_foldable |= self.starts_indent(buffer_row);
18939
18940        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18941            Some(
18942                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18943                    .toggle_state(folded)
18944                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18945                        if folded {
18946                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18947                        } else {
18948                            this.fold_at(&FoldAt { buffer_row }, window, cx);
18949                        }
18950                    }))
18951                    .into_any_element(),
18952            )
18953        } else {
18954            None
18955        }
18956    }
18957
18958    pub fn render_crease_trailer(
18959        &self,
18960        buffer_row: MultiBufferRow,
18961        window: &mut Window,
18962        cx: &mut App,
18963    ) -> Option<AnyElement> {
18964        let folded = self.is_line_folded(buffer_row);
18965        if let Crease::Inline { render_trailer, .. } = self
18966            .crease_snapshot
18967            .query_row(buffer_row, &self.buffer_snapshot)?
18968        {
18969            let render_trailer = render_trailer.as_ref()?;
18970            Some(render_trailer(buffer_row, folded, window, cx))
18971        } else {
18972            None
18973        }
18974    }
18975}
18976
18977impl Deref for EditorSnapshot {
18978    type Target = DisplaySnapshot;
18979
18980    fn deref(&self) -> &Self::Target {
18981        &self.display_snapshot
18982    }
18983}
18984
18985#[derive(Clone, Debug, PartialEq, Eq)]
18986pub enum EditorEvent {
18987    InputIgnored {
18988        text: Arc<str>,
18989    },
18990    InputHandled {
18991        utf16_range_to_replace: Option<Range<isize>>,
18992        text: Arc<str>,
18993    },
18994    ExcerptsAdded {
18995        buffer: Entity<Buffer>,
18996        predecessor: ExcerptId,
18997        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18998    },
18999    ExcerptsRemoved {
19000        ids: Vec<ExcerptId>,
19001    },
19002    BufferFoldToggled {
19003        ids: Vec<ExcerptId>,
19004        folded: bool,
19005    },
19006    ExcerptsEdited {
19007        ids: Vec<ExcerptId>,
19008    },
19009    ExcerptsExpanded {
19010        ids: Vec<ExcerptId>,
19011    },
19012    BufferEdited,
19013    Edited {
19014        transaction_id: clock::Lamport,
19015    },
19016    Reparsed(BufferId),
19017    Focused,
19018    FocusedIn,
19019    Blurred,
19020    DirtyChanged,
19021    Saved,
19022    TitleChanged,
19023    DiffBaseChanged,
19024    SelectionsChanged {
19025        local: bool,
19026    },
19027    ScrollPositionChanged {
19028        local: bool,
19029        autoscroll: bool,
19030    },
19031    Closed,
19032    TransactionUndone {
19033        transaction_id: clock::Lamport,
19034    },
19035    TransactionBegun {
19036        transaction_id: clock::Lamport,
19037    },
19038    Reloaded,
19039    CursorShapeChanged,
19040    PushedToNavHistory {
19041        anchor: Anchor,
19042        is_deactivate: bool,
19043    },
19044}
19045
19046impl EventEmitter<EditorEvent> for Editor {}
19047
19048impl Focusable for Editor {
19049    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19050        self.focus_handle.clone()
19051    }
19052}
19053
19054impl Render for Editor {
19055    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19056        let settings = ThemeSettings::get_global(cx);
19057
19058        let mut text_style = match self.mode {
19059            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19060                color: cx.theme().colors().editor_foreground,
19061                font_family: settings.ui_font.family.clone(),
19062                font_features: settings.ui_font.features.clone(),
19063                font_fallbacks: settings.ui_font.fallbacks.clone(),
19064                font_size: rems(0.875).into(),
19065                font_weight: settings.ui_font.weight,
19066                line_height: relative(settings.buffer_line_height.value()),
19067                ..Default::default()
19068            },
19069            EditorMode::Full => TextStyle {
19070                color: cx.theme().colors().editor_foreground,
19071                font_family: settings.buffer_font.family.clone(),
19072                font_features: settings.buffer_font.features.clone(),
19073                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19074                font_size: settings.buffer_font_size(cx).into(),
19075                font_weight: settings.buffer_font.weight,
19076                line_height: relative(settings.buffer_line_height.value()),
19077                ..Default::default()
19078            },
19079        };
19080        if let Some(text_style_refinement) = &self.text_style_refinement {
19081            text_style.refine(text_style_refinement)
19082        }
19083
19084        let background = match self.mode {
19085            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19086            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19087            EditorMode::Full => cx.theme().colors().editor_background,
19088        };
19089
19090        EditorElement::new(
19091            &cx.entity(),
19092            EditorStyle {
19093                background,
19094                local_player: cx.theme().players().local(),
19095                text: text_style,
19096                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19097                syntax: cx.theme().syntax().clone(),
19098                status: cx.theme().status().clone(),
19099                inlay_hints_style: make_inlay_hints_style(cx),
19100                inline_completion_styles: make_suggestion_styles(cx),
19101                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19102            },
19103        )
19104    }
19105}
19106
19107impl EntityInputHandler for Editor {
19108    fn text_for_range(
19109        &mut self,
19110        range_utf16: Range<usize>,
19111        adjusted_range: &mut Option<Range<usize>>,
19112        _: &mut Window,
19113        cx: &mut Context<Self>,
19114    ) -> Option<String> {
19115        let snapshot = self.buffer.read(cx).read(cx);
19116        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19117        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19118        if (start.0..end.0) != range_utf16 {
19119            adjusted_range.replace(start.0..end.0);
19120        }
19121        Some(snapshot.text_for_range(start..end).collect())
19122    }
19123
19124    fn selected_text_range(
19125        &mut self,
19126        ignore_disabled_input: bool,
19127        _: &mut Window,
19128        cx: &mut Context<Self>,
19129    ) -> Option<UTF16Selection> {
19130        // Prevent the IME menu from appearing when holding down an alphabetic key
19131        // while input is disabled.
19132        if !ignore_disabled_input && !self.input_enabled {
19133            return None;
19134        }
19135
19136        let selection = self.selections.newest::<OffsetUtf16>(cx);
19137        let range = selection.range();
19138
19139        Some(UTF16Selection {
19140            range: range.start.0..range.end.0,
19141            reversed: selection.reversed,
19142        })
19143    }
19144
19145    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19146        let snapshot = self.buffer.read(cx).read(cx);
19147        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19148        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19149    }
19150
19151    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19152        self.clear_highlights::<InputComposition>(cx);
19153        self.ime_transaction.take();
19154    }
19155
19156    fn replace_text_in_range(
19157        &mut self,
19158        range_utf16: Option<Range<usize>>,
19159        text: &str,
19160        window: &mut Window,
19161        cx: &mut Context<Self>,
19162    ) {
19163        if !self.input_enabled {
19164            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19165            return;
19166        }
19167
19168        self.transact(window, cx, |this, window, cx| {
19169            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19170                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19171                Some(this.selection_replacement_ranges(range_utf16, cx))
19172            } else {
19173                this.marked_text_ranges(cx)
19174            };
19175
19176            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19177                let newest_selection_id = this.selections.newest_anchor().id;
19178                this.selections
19179                    .all::<OffsetUtf16>(cx)
19180                    .iter()
19181                    .zip(ranges_to_replace.iter())
19182                    .find_map(|(selection, range)| {
19183                        if selection.id == newest_selection_id {
19184                            Some(
19185                                (range.start.0 as isize - selection.head().0 as isize)
19186                                    ..(range.end.0 as isize - selection.head().0 as isize),
19187                            )
19188                        } else {
19189                            None
19190                        }
19191                    })
19192            });
19193
19194            cx.emit(EditorEvent::InputHandled {
19195                utf16_range_to_replace: range_to_replace,
19196                text: text.into(),
19197            });
19198
19199            if let Some(new_selected_ranges) = new_selected_ranges {
19200                this.change_selections(None, window, cx, |selections| {
19201                    selections.select_ranges(new_selected_ranges)
19202                });
19203                this.backspace(&Default::default(), window, cx);
19204            }
19205
19206            this.handle_input(text, window, cx);
19207        });
19208
19209        if let Some(transaction) = self.ime_transaction {
19210            self.buffer.update(cx, |buffer, cx| {
19211                buffer.group_until_transaction(transaction, cx);
19212            });
19213        }
19214
19215        self.unmark_text(window, cx);
19216    }
19217
19218    fn replace_and_mark_text_in_range(
19219        &mut self,
19220        range_utf16: Option<Range<usize>>,
19221        text: &str,
19222        new_selected_range_utf16: Option<Range<usize>>,
19223        window: &mut Window,
19224        cx: &mut Context<Self>,
19225    ) {
19226        if !self.input_enabled {
19227            return;
19228        }
19229
19230        let transaction = self.transact(window, cx, |this, window, cx| {
19231            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19232                let snapshot = this.buffer.read(cx).read(cx);
19233                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19234                    for marked_range in &mut marked_ranges {
19235                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19236                        marked_range.start.0 += relative_range_utf16.start;
19237                        marked_range.start =
19238                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19239                        marked_range.end =
19240                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19241                    }
19242                }
19243                Some(marked_ranges)
19244            } else if let Some(range_utf16) = range_utf16 {
19245                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19246                Some(this.selection_replacement_ranges(range_utf16, cx))
19247            } else {
19248                None
19249            };
19250
19251            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19252                let newest_selection_id = this.selections.newest_anchor().id;
19253                this.selections
19254                    .all::<OffsetUtf16>(cx)
19255                    .iter()
19256                    .zip(ranges_to_replace.iter())
19257                    .find_map(|(selection, range)| {
19258                        if selection.id == newest_selection_id {
19259                            Some(
19260                                (range.start.0 as isize - selection.head().0 as isize)
19261                                    ..(range.end.0 as isize - selection.head().0 as isize),
19262                            )
19263                        } else {
19264                            None
19265                        }
19266                    })
19267            });
19268
19269            cx.emit(EditorEvent::InputHandled {
19270                utf16_range_to_replace: range_to_replace,
19271                text: text.into(),
19272            });
19273
19274            if let Some(ranges) = ranges_to_replace {
19275                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19276            }
19277
19278            let marked_ranges = {
19279                let snapshot = this.buffer.read(cx).read(cx);
19280                this.selections
19281                    .disjoint_anchors()
19282                    .iter()
19283                    .map(|selection| {
19284                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19285                    })
19286                    .collect::<Vec<_>>()
19287            };
19288
19289            if text.is_empty() {
19290                this.unmark_text(window, cx);
19291            } else {
19292                this.highlight_text::<InputComposition>(
19293                    marked_ranges.clone(),
19294                    HighlightStyle {
19295                        underline: Some(UnderlineStyle {
19296                            thickness: px(1.),
19297                            color: None,
19298                            wavy: false,
19299                        }),
19300                        ..Default::default()
19301                    },
19302                    cx,
19303                );
19304            }
19305
19306            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19307            let use_autoclose = this.use_autoclose;
19308            let use_auto_surround = this.use_auto_surround;
19309            this.set_use_autoclose(false);
19310            this.set_use_auto_surround(false);
19311            this.handle_input(text, window, cx);
19312            this.set_use_autoclose(use_autoclose);
19313            this.set_use_auto_surround(use_auto_surround);
19314
19315            if let Some(new_selected_range) = new_selected_range_utf16 {
19316                let snapshot = this.buffer.read(cx).read(cx);
19317                let new_selected_ranges = marked_ranges
19318                    .into_iter()
19319                    .map(|marked_range| {
19320                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19321                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19322                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19323                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19324                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19325                    })
19326                    .collect::<Vec<_>>();
19327
19328                drop(snapshot);
19329                this.change_selections(None, window, cx, |selections| {
19330                    selections.select_ranges(new_selected_ranges)
19331                });
19332            }
19333        });
19334
19335        self.ime_transaction = self.ime_transaction.or(transaction);
19336        if let Some(transaction) = self.ime_transaction {
19337            self.buffer.update(cx, |buffer, cx| {
19338                buffer.group_until_transaction(transaction, cx);
19339            });
19340        }
19341
19342        if self.text_highlights::<InputComposition>(cx).is_none() {
19343            self.ime_transaction.take();
19344        }
19345    }
19346
19347    fn bounds_for_range(
19348        &mut self,
19349        range_utf16: Range<usize>,
19350        element_bounds: gpui::Bounds<Pixels>,
19351        window: &mut Window,
19352        cx: &mut Context<Self>,
19353    ) -> Option<gpui::Bounds<Pixels>> {
19354        let text_layout_details = self.text_layout_details(window);
19355        let gpui::Size {
19356            width: em_width,
19357            height: line_height,
19358        } = self.character_size(window);
19359
19360        let snapshot = self.snapshot(window, cx);
19361        let scroll_position = snapshot.scroll_position();
19362        let scroll_left = scroll_position.x * em_width;
19363
19364        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19365        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19366            + self.gutter_dimensions.width
19367            + self.gutter_dimensions.margin;
19368        let y = line_height * (start.row().as_f32() - scroll_position.y);
19369
19370        Some(Bounds {
19371            origin: element_bounds.origin + point(x, y),
19372            size: size(em_width, line_height),
19373        })
19374    }
19375
19376    fn character_index_for_point(
19377        &mut self,
19378        point: gpui::Point<Pixels>,
19379        _window: &mut Window,
19380        _cx: &mut Context<Self>,
19381    ) -> Option<usize> {
19382        let position_map = self.last_position_map.as_ref()?;
19383        if !position_map.text_hitbox.contains(&point) {
19384            return None;
19385        }
19386        let display_point = position_map.point_for_position(point).previous_valid;
19387        let anchor = position_map
19388            .snapshot
19389            .display_point_to_anchor(display_point, Bias::Left);
19390        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19391        Some(utf16_offset.0)
19392    }
19393}
19394
19395trait SelectionExt {
19396    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19397    fn spanned_rows(
19398        &self,
19399        include_end_if_at_line_start: bool,
19400        map: &DisplaySnapshot,
19401    ) -> Range<MultiBufferRow>;
19402}
19403
19404impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19405    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19406        let start = self
19407            .start
19408            .to_point(&map.buffer_snapshot)
19409            .to_display_point(map);
19410        let end = self
19411            .end
19412            .to_point(&map.buffer_snapshot)
19413            .to_display_point(map);
19414        if self.reversed {
19415            end..start
19416        } else {
19417            start..end
19418        }
19419    }
19420
19421    fn spanned_rows(
19422        &self,
19423        include_end_if_at_line_start: bool,
19424        map: &DisplaySnapshot,
19425    ) -> Range<MultiBufferRow> {
19426        let start = self.start.to_point(&map.buffer_snapshot);
19427        let mut end = self.end.to_point(&map.buffer_snapshot);
19428        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19429            end.row -= 1;
19430        }
19431
19432        let buffer_start = map.prev_line_boundary(start).0;
19433        let buffer_end = map.next_line_boundary(end).0;
19434        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19435    }
19436}
19437
19438impl<T: InvalidationRegion> InvalidationStack<T> {
19439    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19440    where
19441        S: Clone + ToOffset,
19442    {
19443        while let Some(region) = self.last() {
19444            let all_selections_inside_invalidation_ranges =
19445                if selections.len() == region.ranges().len() {
19446                    selections
19447                        .iter()
19448                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19449                        .all(|(selection, invalidation_range)| {
19450                            let head = selection.head().to_offset(buffer);
19451                            invalidation_range.start <= head && invalidation_range.end >= head
19452                        })
19453                } else {
19454                    false
19455                };
19456
19457            if all_selections_inside_invalidation_ranges {
19458                break;
19459            } else {
19460                self.pop();
19461            }
19462        }
19463    }
19464}
19465
19466impl<T> Default for InvalidationStack<T> {
19467    fn default() -> Self {
19468        Self(Default::default())
19469    }
19470}
19471
19472impl<T> Deref for InvalidationStack<T> {
19473    type Target = Vec<T>;
19474
19475    fn deref(&self) -> &Self::Target {
19476        &self.0
19477    }
19478}
19479
19480impl<T> DerefMut for InvalidationStack<T> {
19481    fn deref_mut(&mut self) -> &mut Self::Target {
19482        &mut self.0
19483    }
19484}
19485
19486impl InvalidationRegion for SnippetState {
19487    fn ranges(&self) -> &[Range<Anchor>] {
19488        &self.ranges[self.active_index]
19489    }
19490}
19491
19492pub fn diagnostic_block_renderer(
19493    diagnostic: Diagnostic,
19494    max_message_rows: Option<u8>,
19495    allow_closing: bool,
19496) -> RenderBlock {
19497    let (text_without_backticks, code_ranges) =
19498        highlight_diagnostic_message(&diagnostic, max_message_rows);
19499
19500    Arc::new(move |cx: &mut BlockContext| {
19501        let group_id: SharedString = cx.block_id.to_string().into();
19502
19503        let mut text_style = cx.window.text_style().clone();
19504        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19505        let theme_settings = ThemeSettings::get_global(cx);
19506        text_style.font_family = theme_settings.buffer_font.family.clone();
19507        text_style.font_style = theme_settings.buffer_font.style;
19508        text_style.font_features = theme_settings.buffer_font.features.clone();
19509        text_style.font_weight = theme_settings.buffer_font.weight;
19510
19511        let multi_line_diagnostic = diagnostic.message.contains('\n');
19512
19513        let buttons = |diagnostic: &Diagnostic| {
19514            if multi_line_diagnostic {
19515                v_flex()
19516            } else {
19517                h_flex()
19518            }
19519            .when(allow_closing, |div| {
19520                div.children(diagnostic.is_primary.then(|| {
19521                    IconButton::new("close-block", IconName::XCircle)
19522                        .icon_color(Color::Muted)
19523                        .size(ButtonSize::Compact)
19524                        .style(ButtonStyle::Transparent)
19525                        .visible_on_hover(group_id.clone())
19526                        .on_click(move |_click, window, cx| {
19527                            window.dispatch_action(Box::new(Cancel), cx)
19528                        })
19529                        .tooltip(|window, cx| {
19530                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19531                        })
19532                }))
19533            })
19534            .child(
19535                IconButton::new("copy-block", IconName::Copy)
19536                    .icon_color(Color::Muted)
19537                    .size(ButtonSize::Compact)
19538                    .style(ButtonStyle::Transparent)
19539                    .visible_on_hover(group_id.clone())
19540                    .on_click({
19541                        let message = diagnostic.message.clone();
19542                        move |_click, _, cx| {
19543                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19544                        }
19545                    })
19546                    .tooltip(Tooltip::text("Copy diagnostic message")),
19547            )
19548        };
19549
19550        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19551            AvailableSpace::min_size(),
19552            cx.window,
19553            cx.app,
19554        );
19555
19556        h_flex()
19557            .id(cx.block_id)
19558            .group(group_id.clone())
19559            .relative()
19560            .size_full()
19561            .block_mouse_down()
19562            .pl(cx.gutter_dimensions.width)
19563            .w(cx.max_width - cx.gutter_dimensions.full_width())
19564            .child(
19565                div()
19566                    .flex()
19567                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19568                    .flex_shrink(),
19569            )
19570            .child(buttons(&diagnostic))
19571            .child(div().flex().flex_shrink_0().child(
19572                StyledText::new(text_without_backticks.clone()).with_default_highlights(
19573                    &text_style,
19574                    code_ranges.iter().map(|range| {
19575                        (
19576                            range.clone(),
19577                            HighlightStyle {
19578                                font_weight: Some(FontWeight::BOLD),
19579                                ..Default::default()
19580                            },
19581                        )
19582                    }),
19583                ),
19584            ))
19585            .into_any_element()
19586    })
19587}
19588
19589fn inline_completion_edit_text(
19590    current_snapshot: &BufferSnapshot,
19591    edits: &[(Range<Anchor>, String)],
19592    edit_preview: &EditPreview,
19593    include_deletions: bool,
19594    cx: &App,
19595) -> HighlightedText {
19596    let edits = edits
19597        .iter()
19598        .map(|(anchor, text)| {
19599            (
19600                anchor.start.text_anchor..anchor.end.text_anchor,
19601                text.clone(),
19602            )
19603        })
19604        .collect::<Vec<_>>();
19605
19606    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19607}
19608
19609pub fn highlight_diagnostic_message(
19610    diagnostic: &Diagnostic,
19611    mut max_message_rows: Option<u8>,
19612) -> (SharedString, Vec<Range<usize>>) {
19613    let mut text_without_backticks = String::new();
19614    let mut code_ranges = Vec::new();
19615
19616    if let Some(source) = &diagnostic.source {
19617        text_without_backticks.push_str(source);
19618        code_ranges.push(0..source.len());
19619        text_without_backticks.push_str(": ");
19620    }
19621
19622    let mut prev_offset = 0;
19623    let mut in_code_block = false;
19624    let has_row_limit = max_message_rows.is_some();
19625    let mut newline_indices = diagnostic
19626        .message
19627        .match_indices('\n')
19628        .filter(|_| has_row_limit)
19629        .map(|(ix, _)| ix)
19630        .fuse()
19631        .peekable();
19632
19633    for (quote_ix, _) in diagnostic
19634        .message
19635        .match_indices('`')
19636        .chain([(diagnostic.message.len(), "")])
19637    {
19638        let mut first_newline_ix = None;
19639        let mut last_newline_ix = None;
19640        while let Some(newline_ix) = newline_indices.peek() {
19641            if *newline_ix < quote_ix {
19642                if first_newline_ix.is_none() {
19643                    first_newline_ix = Some(*newline_ix);
19644                }
19645                last_newline_ix = Some(*newline_ix);
19646
19647                if let Some(rows_left) = &mut max_message_rows {
19648                    if *rows_left == 0 {
19649                        break;
19650                    } else {
19651                        *rows_left -= 1;
19652                    }
19653                }
19654                let _ = newline_indices.next();
19655            } else {
19656                break;
19657            }
19658        }
19659        let prev_len = text_without_backticks.len();
19660        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19661        text_without_backticks.push_str(new_text);
19662        if in_code_block {
19663            code_ranges.push(prev_len..text_without_backticks.len());
19664        }
19665        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19666        in_code_block = !in_code_block;
19667        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19668            text_without_backticks.push_str("...");
19669            break;
19670        }
19671    }
19672
19673    (text_without_backticks.into(), code_ranges)
19674}
19675
19676fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19677    match severity {
19678        DiagnosticSeverity::ERROR => colors.error,
19679        DiagnosticSeverity::WARNING => colors.warning,
19680        DiagnosticSeverity::INFORMATION => colors.info,
19681        DiagnosticSeverity::HINT => colors.info,
19682        _ => colors.ignored,
19683    }
19684}
19685
19686pub fn styled_runs_for_code_label<'a>(
19687    label: &'a CodeLabel,
19688    syntax_theme: &'a theme::SyntaxTheme,
19689) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19690    let fade_out = HighlightStyle {
19691        fade_out: Some(0.35),
19692        ..Default::default()
19693    };
19694
19695    let mut prev_end = label.filter_range.end;
19696    label
19697        .runs
19698        .iter()
19699        .enumerate()
19700        .flat_map(move |(ix, (range, highlight_id))| {
19701            let style = if let Some(style) = highlight_id.style(syntax_theme) {
19702                style
19703            } else {
19704                return Default::default();
19705            };
19706            let mut muted_style = style;
19707            muted_style.highlight(fade_out);
19708
19709            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19710            if range.start >= label.filter_range.end {
19711                if range.start > prev_end {
19712                    runs.push((prev_end..range.start, fade_out));
19713                }
19714                runs.push((range.clone(), muted_style));
19715            } else if range.end <= label.filter_range.end {
19716                runs.push((range.clone(), style));
19717            } else {
19718                runs.push((range.start..label.filter_range.end, style));
19719                runs.push((label.filter_range.end..range.end, muted_style));
19720            }
19721            prev_end = cmp::max(prev_end, range.end);
19722
19723            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19724                runs.push((prev_end..label.text.len(), fade_out));
19725            }
19726
19727            runs
19728        })
19729}
19730
19731pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19732    let mut prev_index = 0;
19733    let mut prev_codepoint: Option<char> = None;
19734    text.char_indices()
19735        .chain([(text.len(), '\0')])
19736        .filter_map(move |(index, codepoint)| {
19737            let prev_codepoint = prev_codepoint.replace(codepoint)?;
19738            let is_boundary = index == text.len()
19739                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19740                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19741            if is_boundary {
19742                let chunk = &text[prev_index..index];
19743                prev_index = index;
19744                Some(chunk)
19745            } else {
19746                None
19747            }
19748        })
19749}
19750
19751pub trait RangeToAnchorExt: Sized {
19752    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19753
19754    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19755        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19756        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19757    }
19758}
19759
19760impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19761    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19762        let start_offset = self.start.to_offset(snapshot);
19763        let end_offset = self.end.to_offset(snapshot);
19764        if start_offset == end_offset {
19765            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19766        } else {
19767            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19768        }
19769    }
19770}
19771
19772pub trait RowExt {
19773    fn as_f32(&self) -> f32;
19774
19775    fn next_row(&self) -> Self;
19776
19777    fn previous_row(&self) -> Self;
19778
19779    fn minus(&self, other: Self) -> u32;
19780}
19781
19782impl RowExt for DisplayRow {
19783    fn as_f32(&self) -> f32 {
19784        self.0 as f32
19785    }
19786
19787    fn next_row(&self) -> Self {
19788        Self(self.0 + 1)
19789    }
19790
19791    fn previous_row(&self) -> Self {
19792        Self(self.0.saturating_sub(1))
19793    }
19794
19795    fn minus(&self, other: Self) -> u32 {
19796        self.0 - other.0
19797    }
19798}
19799
19800impl RowExt for MultiBufferRow {
19801    fn as_f32(&self) -> f32 {
19802        self.0 as f32
19803    }
19804
19805    fn next_row(&self) -> Self {
19806        Self(self.0 + 1)
19807    }
19808
19809    fn previous_row(&self) -> Self {
19810        Self(self.0.saturating_sub(1))
19811    }
19812
19813    fn minus(&self, other: Self) -> u32 {
19814        self.0 - other.0
19815    }
19816}
19817
19818trait RowRangeExt {
19819    type Row;
19820
19821    fn len(&self) -> usize;
19822
19823    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19824}
19825
19826impl RowRangeExt for Range<MultiBufferRow> {
19827    type Row = MultiBufferRow;
19828
19829    fn len(&self) -> usize {
19830        (self.end.0 - self.start.0) as usize
19831    }
19832
19833    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19834        (self.start.0..self.end.0).map(MultiBufferRow)
19835    }
19836}
19837
19838impl RowRangeExt for Range<DisplayRow> {
19839    type Row = DisplayRow;
19840
19841    fn len(&self) -> usize {
19842        (self.end.0 - self.start.0) as usize
19843    }
19844
19845    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19846        (self.start.0..self.end.0).map(DisplayRow)
19847    }
19848}
19849
19850/// If select range has more than one line, we
19851/// just point the cursor to range.start.
19852fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19853    if range.start.row == range.end.row {
19854        range
19855    } else {
19856        range.start..range.start
19857    }
19858}
19859pub struct KillRing(ClipboardItem);
19860impl Global for KillRing {}
19861
19862const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19863
19864struct BreakpointPromptEditor {
19865    pub(crate) prompt: Entity<Editor>,
19866    editor: WeakEntity<Editor>,
19867    breakpoint_anchor: Anchor,
19868    breakpoint: Breakpoint,
19869    block_ids: HashSet<CustomBlockId>,
19870    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19871    _subscriptions: Vec<Subscription>,
19872}
19873
19874impl BreakpointPromptEditor {
19875    const MAX_LINES: u8 = 4;
19876
19877    fn new(
19878        editor: WeakEntity<Editor>,
19879        breakpoint_anchor: Anchor,
19880        breakpoint: Breakpoint,
19881        window: &mut Window,
19882        cx: &mut Context<Self>,
19883    ) -> Self {
19884        let buffer = cx.new(|cx| {
19885            Buffer::local(
19886                breakpoint
19887                    .message
19888                    .as_ref()
19889                    .map(|msg| msg.to_string())
19890                    .unwrap_or_default(),
19891                cx,
19892            )
19893        });
19894        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19895
19896        let prompt = cx.new(|cx| {
19897            let mut prompt = Editor::new(
19898                EditorMode::AutoHeight {
19899                    max_lines: Self::MAX_LINES as usize,
19900                },
19901                buffer,
19902                None,
19903                window,
19904                cx,
19905            );
19906            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19907            prompt.set_show_cursor_when_unfocused(false, cx);
19908            prompt.set_placeholder_text(
19909                "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19910                cx,
19911            );
19912
19913            prompt
19914        });
19915
19916        Self {
19917            prompt,
19918            editor,
19919            breakpoint_anchor,
19920            breakpoint,
19921            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19922            block_ids: Default::default(),
19923            _subscriptions: vec![],
19924        }
19925    }
19926
19927    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19928        self.block_ids.extend(block_ids)
19929    }
19930
19931    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19932        if let Some(editor) = self.editor.upgrade() {
19933            let log_message = self
19934                .prompt
19935                .read(cx)
19936                .buffer
19937                .read(cx)
19938                .as_singleton()
19939                .expect("A multi buffer in breakpoint prompt isn't possible")
19940                .read(cx)
19941                .as_rope()
19942                .to_string();
19943
19944            editor.update(cx, |editor, cx| {
19945                editor.edit_breakpoint_at_anchor(
19946                    self.breakpoint_anchor,
19947                    self.breakpoint.clone(),
19948                    BreakpointEditAction::EditLogMessage(log_message.into()),
19949                    cx,
19950                );
19951
19952                editor.remove_blocks(self.block_ids.clone(), None, cx);
19953                cx.focus_self(window);
19954            });
19955        }
19956    }
19957
19958    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19959        self.editor
19960            .update(cx, |editor, cx| {
19961                editor.remove_blocks(self.block_ids.clone(), None, cx);
19962                window.focus(&editor.focus_handle);
19963            })
19964            .log_err();
19965    }
19966
19967    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19968        let settings = ThemeSettings::get_global(cx);
19969        let text_style = TextStyle {
19970            color: if self.prompt.read(cx).read_only(cx) {
19971                cx.theme().colors().text_disabled
19972            } else {
19973                cx.theme().colors().text
19974            },
19975            font_family: settings.buffer_font.family.clone(),
19976            font_fallbacks: settings.buffer_font.fallbacks.clone(),
19977            font_size: settings.buffer_font_size(cx).into(),
19978            font_weight: settings.buffer_font.weight,
19979            line_height: relative(settings.buffer_line_height.value()),
19980            ..Default::default()
19981        };
19982        EditorElement::new(
19983            &self.prompt,
19984            EditorStyle {
19985                background: cx.theme().colors().editor_background,
19986                local_player: cx.theme().players().local(),
19987                text: text_style,
19988                ..Default::default()
19989            },
19990        )
19991    }
19992}
19993
19994impl Render for BreakpointPromptEditor {
19995    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19996        let gutter_dimensions = *self.gutter_dimensions.lock();
19997        h_flex()
19998            .key_context("Editor")
19999            .bg(cx.theme().colors().editor_background)
20000            .border_y_1()
20001            .border_color(cx.theme().status().info_border)
20002            .size_full()
20003            .py(window.line_height() / 2.5)
20004            .on_action(cx.listener(Self::confirm))
20005            .on_action(cx.listener(Self::cancel))
20006            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20007            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20008    }
20009}
20010
20011impl Focusable for BreakpointPromptEditor {
20012    fn focus_handle(&self, cx: &App) -> FocusHandle {
20013        self.prompt.focus_handle(cx)
20014    }
20015}
20016
20017fn all_edits_insertions_or_deletions(
20018    edits: &Vec<(Range<Anchor>, String)>,
20019    snapshot: &MultiBufferSnapshot,
20020) -> bool {
20021    let mut all_insertions = true;
20022    let mut all_deletions = true;
20023
20024    for (range, new_text) in edits.iter() {
20025        let range_is_empty = range.to_offset(&snapshot).is_empty();
20026        let text_is_empty = new_text.is_empty();
20027
20028        if range_is_empty != text_is_empty {
20029            if range_is_empty {
20030                all_deletions = false;
20031            } else {
20032                all_insertions = false;
20033            }
20034        } else {
20035            return false;
20036        }
20037
20038        if !all_insertions && !all_deletions {
20039            return false;
20040        }
20041    }
20042    all_insertions || all_deletions
20043}
20044
20045struct MissingEditPredictionKeybindingTooltip;
20046
20047impl Render for MissingEditPredictionKeybindingTooltip {
20048    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20049        ui::tooltip_container(window, cx, |container, _, cx| {
20050            container
20051                .flex_shrink_0()
20052                .max_w_80()
20053                .min_h(rems_from_px(124.))
20054                .justify_between()
20055                .child(
20056                    v_flex()
20057                        .flex_1()
20058                        .text_ui_sm(cx)
20059                        .child(Label::new("Conflict with Accept Keybinding"))
20060                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20061                )
20062                .child(
20063                    h_flex()
20064                        .pb_1()
20065                        .gap_1()
20066                        .items_end()
20067                        .w_full()
20068                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20069                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20070                        }))
20071                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20072                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20073                        })),
20074                )
20075        })
20076    }
20077}
20078
20079#[derive(Debug, Clone, Copy, PartialEq)]
20080pub struct LineHighlight {
20081    pub background: Background,
20082    pub border: Option<gpui::Hsla>,
20083}
20084
20085impl From<Hsla> for LineHighlight {
20086    fn from(hsla: Hsla) -> Self {
20087        Self {
20088            background: hsla.into(),
20089            border: None,
20090        }
20091    }
20092}
20093
20094impl From<Background> for LineHighlight {
20095    fn from(background: Background) -> Self {
20096        Self {
20097            background,
20098            border: None,
20099        }
20100    }
20101}
20102
20103fn render_diff_hunk_controls(
20104    row: u32,
20105    status: &DiffHunkStatus,
20106    hunk_range: Range<Anchor>,
20107    is_created_file: bool,
20108    line_height: Pixels,
20109    editor: &Entity<Editor>,
20110    _window: &mut Window,
20111    cx: &mut App,
20112) -> AnyElement {
20113    h_flex()
20114        .h(line_height)
20115        .mr_1()
20116        .gap_1()
20117        .px_0p5()
20118        .pb_1()
20119        .border_x_1()
20120        .border_b_1()
20121        .border_color(cx.theme().colors().border_variant)
20122        .rounded_b_lg()
20123        .bg(cx.theme().colors().editor_background)
20124        .gap_1()
20125        .occlude()
20126        .shadow_md()
20127        .child(if status.has_secondary_hunk() {
20128            Button::new(("stage", row as u64), "Stage")
20129                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20130                .tooltip({
20131                    let focus_handle = editor.focus_handle(cx);
20132                    move |window, cx| {
20133                        Tooltip::for_action_in(
20134                            "Stage Hunk",
20135                            &::git::ToggleStaged,
20136                            &focus_handle,
20137                            window,
20138                            cx,
20139                        )
20140                    }
20141                })
20142                .on_click({
20143                    let editor = editor.clone();
20144                    move |_event, _window, cx| {
20145                        editor.update(cx, |editor, cx| {
20146                            editor.stage_or_unstage_diff_hunks(
20147                                true,
20148                                vec![hunk_range.start..hunk_range.start],
20149                                cx,
20150                            );
20151                        });
20152                    }
20153                })
20154        } else {
20155            Button::new(("unstage", row as u64), "Unstage")
20156                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20157                .tooltip({
20158                    let focus_handle = editor.focus_handle(cx);
20159                    move |window, cx| {
20160                        Tooltip::for_action_in(
20161                            "Unstage Hunk",
20162                            &::git::ToggleStaged,
20163                            &focus_handle,
20164                            window,
20165                            cx,
20166                        )
20167                    }
20168                })
20169                .on_click({
20170                    let editor = editor.clone();
20171                    move |_event, _window, cx| {
20172                        editor.update(cx, |editor, cx| {
20173                            editor.stage_or_unstage_diff_hunks(
20174                                false,
20175                                vec![hunk_range.start..hunk_range.start],
20176                                cx,
20177                            );
20178                        });
20179                    }
20180                })
20181        })
20182        .child(
20183            Button::new("restore", "Restore")
20184                .tooltip({
20185                    let focus_handle = editor.focus_handle(cx);
20186                    move |window, cx| {
20187                        Tooltip::for_action_in(
20188                            "Restore Hunk",
20189                            &::git::Restore,
20190                            &focus_handle,
20191                            window,
20192                            cx,
20193                        )
20194                    }
20195                })
20196                .on_click({
20197                    let editor = editor.clone();
20198                    move |_event, window, cx| {
20199                        editor.update(cx, |editor, cx| {
20200                            let snapshot = editor.snapshot(window, cx);
20201                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20202                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20203                        });
20204                    }
20205                })
20206                .disabled(is_created_file),
20207        )
20208        .when(
20209            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20210            |el| {
20211                el.child(
20212                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20213                        .shape(IconButtonShape::Square)
20214                        .icon_size(IconSize::Small)
20215                        // .disabled(!has_multiple_hunks)
20216                        .tooltip({
20217                            let focus_handle = editor.focus_handle(cx);
20218                            move |window, cx| {
20219                                Tooltip::for_action_in(
20220                                    "Next Hunk",
20221                                    &GoToHunk,
20222                                    &focus_handle,
20223                                    window,
20224                                    cx,
20225                                )
20226                            }
20227                        })
20228                        .on_click({
20229                            let editor = editor.clone();
20230                            move |_event, window, cx| {
20231                                editor.update(cx, |editor, cx| {
20232                                    let snapshot = editor.snapshot(window, cx);
20233                                    let position =
20234                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20235                                    editor.go_to_hunk_before_or_after_position(
20236                                        &snapshot,
20237                                        position,
20238                                        Direction::Next,
20239                                        window,
20240                                        cx,
20241                                    );
20242                                    editor.expand_selected_diff_hunks(cx);
20243                                });
20244                            }
20245                        }),
20246                )
20247                .child(
20248                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20249                        .shape(IconButtonShape::Square)
20250                        .icon_size(IconSize::Small)
20251                        // .disabled(!has_multiple_hunks)
20252                        .tooltip({
20253                            let focus_handle = editor.focus_handle(cx);
20254                            move |window, cx| {
20255                                Tooltip::for_action_in(
20256                                    "Previous Hunk",
20257                                    &GoToPreviousHunk,
20258                                    &focus_handle,
20259                                    window,
20260                                    cx,
20261                                )
20262                            }
20263                        })
20264                        .on_click({
20265                            let editor = editor.clone();
20266                            move |_event, window, cx| {
20267                                editor.update(cx, |editor, cx| {
20268                                    let snapshot = editor.snapshot(window, cx);
20269                                    let point =
20270                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20271                                    editor.go_to_hunk_before_or_after_position(
20272                                        &snapshot,
20273                                        point,
20274                                        Direction::Prev,
20275                                        window,
20276                                        cx,
20277                                    );
20278                                    editor.expand_selected_diff_hunks(cx);
20279                                });
20280                            }
20281                        }),
20282                )
20283            },
20284        )
20285        .into_any_element()
20286}