editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::{status::FileStatus, Restore};
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
   89    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  106    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  107    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  124    InsertTextFormat, LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  208pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  209
  210pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  211pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  212
  213const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  214    alt: true,
  215    shift: true,
  216    control: false,
  217    platform: false,
  218    function: false,
  219};
  220
  221#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  222pub enum InlayId {
  223    InlineCompletion(usize),
  224    Hint(usize),
  225}
  226
  227impl InlayId {
  228    fn id(&self) -> usize {
  229        match self {
  230            Self::InlineCompletion(id) => *id,
  231            Self::Hint(id) => *id,
  232        }
  233    }
  234}
  235
  236enum DocumentHighlightRead {}
  237enum DocumentHighlightWrite {}
  238enum InputComposition {}
  239enum SelectedTextHighlight {}
  240
  241#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  242pub enum Navigated {
  243    Yes,
  244    No,
  245}
  246
  247impl Navigated {
  248    pub fn from_bool(yes: bool) -> Navigated {
  249        if yes {
  250            Navigated::Yes
  251        } else {
  252            Navigated::No
  253        }
  254    }
  255}
  256
  257#[derive(Debug, Clone, PartialEq, Eq)]
  258enum DisplayDiffHunk {
  259    Folded {
  260        display_row: DisplayRow,
  261    },
  262    Unfolded {
  263        diff_base_byte_range: Range<usize>,
  264        display_row_range: Range<DisplayRow>,
  265        multi_buffer_range: Range<Anchor>,
  266        status: DiffHunkStatus,
  267    },
  268}
  269
  270pub fn init_settings(cx: &mut App) {
  271    EditorSettings::register(cx);
  272}
  273
  274pub fn init(cx: &mut App) {
  275    init_settings(cx);
  276
  277    workspace::register_project_item::<Editor>(cx);
  278    workspace::FollowableViewRegistry::register::<Editor>(cx);
  279    workspace::register_serializable_item::<Editor>(cx);
  280
  281    cx.observe_new(
  282        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  283            workspace.register_action(Editor::new_file);
  284            workspace.register_action(Editor::new_file_vertical);
  285            workspace.register_action(Editor::new_file_horizontal);
  286            workspace.register_action(Editor::cancel_language_server_work);
  287        },
  288    )
  289    .detach();
  290
  291    cx.on_action(move |_: &workspace::NewFile, cx| {
  292        let app_state = workspace::AppState::global(cx);
  293        if let Some(app_state) = app_state.upgrade() {
  294            workspace::open_new(
  295                Default::default(),
  296                app_state,
  297                cx,
  298                |workspace, window, cx| {
  299                    Editor::new_file(workspace, &Default::default(), window, cx)
  300                },
  301            )
  302            .detach();
  303        }
  304    });
  305    cx.on_action(move |_: &workspace::NewWindow, cx| {
  306        let app_state = workspace::AppState::global(cx);
  307        if let Some(app_state) = app_state.upgrade() {
  308            workspace::open_new(
  309                Default::default(),
  310                app_state,
  311                cx,
  312                |workspace, window, cx| {
  313                    cx.activate(true);
  314                    Editor::new_file(workspace, &Default::default(), window, cx)
  315                },
  316            )
  317            .detach();
  318        }
  319    });
  320}
  321
  322pub struct SearchWithinRange;
  323
  324trait InvalidationRegion {
  325    fn ranges(&self) -> &[Range<Anchor>];
  326}
  327
  328#[derive(Clone, Debug, PartialEq)]
  329pub enum SelectPhase {
  330    Begin {
  331        position: DisplayPoint,
  332        add: bool,
  333        click_count: usize,
  334    },
  335    BeginColumnar {
  336        position: DisplayPoint,
  337        reset: bool,
  338        goal_column: u32,
  339    },
  340    Extend {
  341        position: DisplayPoint,
  342        click_count: usize,
  343    },
  344    Update {
  345        position: DisplayPoint,
  346        goal_column: u32,
  347        scroll_delta: gpui::Point<f32>,
  348    },
  349    End,
  350}
  351
  352#[derive(Clone, Debug)]
  353pub enum SelectMode {
  354    Character,
  355    Word(Range<Anchor>),
  356    Line(Range<Anchor>),
  357    All,
  358}
  359
  360#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  361pub enum EditorMode {
  362    SingleLine { auto_width: bool },
  363    AutoHeight { max_lines: usize },
  364    Full,
  365}
  366
  367#[derive(Copy, Clone, Debug)]
  368pub enum SoftWrap {
  369    /// Prefer not to wrap at all.
  370    ///
  371    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  372    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  373    GitDiff,
  374    /// Prefer a single line generally, unless an overly long line is encountered.
  375    None,
  376    /// Soft wrap lines that exceed the editor width.
  377    EditorWidth,
  378    /// Soft wrap lines at the preferred line length.
  379    Column(u32),
  380    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  381    Bounded(u32),
  382}
  383
  384#[derive(Clone)]
  385pub struct EditorStyle {
  386    pub background: Hsla,
  387    pub local_player: PlayerColor,
  388    pub text: TextStyle,
  389    pub scrollbar_width: Pixels,
  390    pub syntax: Arc<SyntaxTheme>,
  391    pub status: StatusColors,
  392    pub inlay_hints_style: HighlightStyle,
  393    pub inline_completion_styles: InlineCompletionStyles,
  394    pub unnecessary_code_fade: f32,
  395}
  396
  397impl Default for EditorStyle {
  398    fn default() -> Self {
  399        Self {
  400            background: Hsla::default(),
  401            local_player: PlayerColor::default(),
  402            text: TextStyle::default(),
  403            scrollbar_width: Pixels::default(),
  404            syntax: Default::default(),
  405            // HACK: Status colors don't have a real default.
  406            // We should look into removing the status colors from the editor
  407            // style and retrieve them directly from the theme.
  408            status: StatusColors::dark(),
  409            inlay_hints_style: HighlightStyle::default(),
  410            inline_completion_styles: InlineCompletionStyles {
  411                insertion: HighlightStyle::default(),
  412                whitespace: HighlightStyle::default(),
  413            },
  414            unnecessary_code_fade: Default::default(),
  415        }
  416    }
  417}
  418
  419pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  420    let show_background = language_settings::language_settings(None, None, cx)
  421        .inlay_hints
  422        .show_background;
  423
  424    HighlightStyle {
  425        color: Some(cx.theme().status().hint),
  426        background_color: show_background.then(|| cx.theme().status().hint_background),
  427        ..HighlightStyle::default()
  428    }
  429}
  430
  431pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  432    InlineCompletionStyles {
  433        insertion: HighlightStyle {
  434            color: Some(cx.theme().status().predictive),
  435            ..HighlightStyle::default()
  436        },
  437        whitespace: HighlightStyle {
  438            background_color: Some(cx.theme().status().created_background),
  439            ..HighlightStyle::default()
  440        },
  441    }
  442}
  443
  444type CompletionId = usize;
  445
  446pub(crate) enum EditDisplayMode {
  447    TabAccept,
  448    DiffPopover,
  449    Inline,
  450}
  451
  452enum InlineCompletion {
  453    Edit {
  454        edits: Vec<(Range<Anchor>, String)>,
  455        edit_preview: Option<EditPreview>,
  456        display_mode: EditDisplayMode,
  457        snapshot: BufferSnapshot,
  458    },
  459    Move {
  460        target: Anchor,
  461        snapshot: BufferSnapshot,
  462    },
  463}
  464
  465struct InlineCompletionState {
  466    inlay_ids: Vec<InlayId>,
  467    completion: InlineCompletion,
  468    completion_id: Option<SharedString>,
  469    invalidation_range: Range<Anchor>,
  470}
  471
  472enum EditPredictionSettings {
  473    Disabled,
  474    Enabled {
  475        show_in_menu: bool,
  476        preview_requires_modifier: bool,
  477    },
  478}
  479
  480enum InlineCompletionHighlight {}
  481
  482#[derive(Debug, Clone)]
  483struct InlineDiagnostic {
  484    message: SharedString,
  485    group_id: usize,
  486    is_primary: bool,
  487    start: Point,
  488    severity: DiagnosticSeverity,
  489}
  490
  491pub enum MenuInlineCompletionsPolicy {
  492    Never,
  493    ByProvider,
  494}
  495
  496pub enum EditPredictionPreview {
  497    /// Modifier is not pressed
  498    Inactive { released_too_fast: bool },
  499    /// Modifier pressed
  500    Active {
  501        since: Instant,
  502        previous_scroll_position: Option<ScrollAnchor>,
  503    },
  504}
  505
  506impl EditPredictionPreview {
  507    pub fn released_too_fast(&self) -> bool {
  508        match self {
  509            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  510            EditPredictionPreview::Active { .. } => false,
  511        }
  512    }
  513
  514    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  515        if let EditPredictionPreview::Active {
  516            previous_scroll_position,
  517            ..
  518        } = self
  519        {
  520            *previous_scroll_position = scroll_position;
  521        }
  522    }
  523}
  524
  525#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  526struct EditorActionId(usize);
  527
  528impl EditorActionId {
  529    pub fn post_inc(&mut self) -> Self {
  530        let answer = self.0;
  531
  532        *self = Self(answer + 1);
  533
  534        Self(answer)
  535    }
  536}
  537
  538// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  539// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  540
  541type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  542type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  543
  544#[derive(Default)]
  545struct ScrollbarMarkerState {
  546    scrollbar_size: Size<Pixels>,
  547    dirty: bool,
  548    markers: Arc<[PaintQuad]>,
  549    pending_refresh: Option<Task<Result<()>>>,
  550}
  551
  552impl ScrollbarMarkerState {
  553    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  554        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  555    }
  556}
  557
  558#[derive(Clone, Debug)]
  559struct RunnableTasks {
  560    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  561    offset: multi_buffer::Anchor,
  562    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  563    column: u32,
  564    // Values of all named captures, including those starting with '_'
  565    extra_variables: HashMap<String, String>,
  566    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  567    context_range: Range<BufferOffset>,
  568}
  569
  570impl RunnableTasks {
  571    fn resolve<'a>(
  572        &'a self,
  573        cx: &'a task::TaskContext,
  574    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  575        self.templates.iter().filter_map(|(kind, template)| {
  576            template
  577                .resolve_task(&kind.to_id_base(), cx)
  578                .map(|task| (kind.clone(), task))
  579        })
  580    }
  581}
  582
  583#[derive(Clone)]
  584struct ResolvedTasks {
  585    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  586    position: Anchor,
  587}
  588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  589struct BufferOffset(usize);
  590
  591// Addons allow storing per-editor state in other crates (e.g. Vim)
  592pub trait Addon: 'static {
  593    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  594
  595    fn render_buffer_header_controls(
  596        &self,
  597        _: &ExcerptInfo,
  598        _: &Window,
  599        _: &App,
  600    ) -> Option<AnyElement> {
  601        None
  602    }
  603
  604    fn to_any(&self) -> &dyn std::any::Any;
  605}
  606
  607#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  608pub enum IsVimMode {
  609    Yes,
  610    No,
  611}
  612
  613/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  614///
  615/// See the [module level documentation](self) for more information.
  616pub struct Editor {
  617    focus_handle: FocusHandle,
  618    last_focused_descendant: Option<WeakFocusHandle>,
  619    /// The text buffer being edited
  620    buffer: Entity<MultiBuffer>,
  621    /// Map of how text in the buffer should be displayed.
  622    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  623    pub display_map: Entity<DisplayMap>,
  624    pub selections: SelectionsCollection,
  625    pub scroll_manager: ScrollManager,
  626    /// When inline assist editors are linked, they all render cursors because
  627    /// typing enters text into each of them, even the ones that aren't focused.
  628    pub(crate) show_cursor_when_unfocused: bool,
  629    columnar_selection_tail: Option<Anchor>,
  630    add_selections_state: Option<AddSelectionsState>,
  631    select_next_state: Option<SelectNextState>,
  632    select_prev_state: Option<SelectNextState>,
  633    selection_history: SelectionHistory,
  634    autoclose_regions: Vec<AutocloseRegion>,
  635    snippet_stack: InvalidationStack<SnippetState>,
  636    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  637    ime_transaction: Option<TransactionId>,
  638    active_diagnostics: Option<ActiveDiagnosticGroup>,
  639    show_inline_diagnostics: bool,
  640    inline_diagnostics_update: Task<()>,
  641    inline_diagnostics_enabled: bool,
  642    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  643    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  644
  645    // TODO: make this a access method
  646    pub project: Option<Entity<Project>>,
  647    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  648    completion_provider: Option<Box<dyn CompletionProvider>>,
  649    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  650    blink_manager: Entity<BlinkManager>,
  651    show_cursor_names: bool,
  652    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  653    pub show_local_selections: bool,
  654    mode: EditorMode,
  655    show_breadcrumbs: bool,
  656    show_gutter: bool,
  657    show_scrollbars: bool,
  658    show_line_numbers: Option<bool>,
  659    use_relative_line_numbers: Option<bool>,
  660    show_git_diff_gutter: Option<bool>,
  661    show_code_actions: Option<bool>,
  662    show_runnables: Option<bool>,
  663    show_wrap_guides: Option<bool>,
  664    show_indent_guides: Option<bool>,
  665    placeholder_text: Option<Arc<str>>,
  666    highlight_order: usize,
  667    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  668    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  669    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  670    scrollbar_marker_state: ScrollbarMarkerState,
  671    active_indent_guides_state: ActiveIndentGuidesState,
  672    nav_history: Option<ItemNavHistory>,
  673    context_menu: RefCell<Option<CodeContextMenu>>,
  674    mouse_context_menu: Option<MouseContextMenu>,
  675    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  676    signature_help_state: SignatureHelpState,
  677    auto_signature_help: Option<bool>,
  678    find_all_references_task_sources: Vec<Anchor>,
  679    next_completion_id: CompletionId,
  680    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  681    code_actions_task: Option<Task<Result<()>>>,
  682    selection_highlight_task: Option<Task<()>>,
  683    document_highlights_task: Option<Task<()>>,
  684    linked_editing_range_task: Option<Task<Option<()>>>,
  685    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  686    pending_rename: Option<RenameState>,
  687    searchable: bool,
  688    cursor_shape: CursorShape,
  689    current_line_highlight: Option<CurrentLineHighlight>,
  690    collapse_matches: bool,
  691    autoindent_mode: Option<AutoindentMode>,
  692    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  693    input_enabled: bool,
  694    use_modal_editing: bool,
  695    read_only: bool,
  696    leader_peer_id: Option<PeerId>,
  697    remote_id: Option<ViewId>,
  698    hover_state: HoverState,
  699    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  700    gutter_hovered: bool,
  701    hovered_link_state: Option<HoveredLinkState>,
  702    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  703    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  704    active_inline_completion: Option<InlineCompletionState>,
  705    /// Used to prevent flickering as the user types while the menu is open
  706    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  707    edit_prediction_settings: EditPredictionSettings,
  708    inline_completions_hidden_for_vim_mode: bool,
  709    show_inline_completions_override: Option<bool>,
  710    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  711    edit_prediction_preview: EditPredictionPreview,
  712    edit_prediction_indent_conflict: bool,
  713    edit_prediction_requires_modifier_in_indent_conflict: bool,
  714    inlay_hint_cache: InlayHintCache,
  715    next_inlay_id: usize,
  716    _subscriptions: Vec<Subscription>,
  717    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  718    gutter_dimensions: GutterDimensions,
  719    style: Option<EditorStyle>,
  720    text_style_refinement: Option<TextStyleRefinement>,
  721    next_editor_action_id: EditorActionId,
  722    editor_actions:
  723        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  724    use_autoclose: bool,
  725    use_auto_surround: bool,
  726    auto_replace_emoji_shortcode: bool,
  727    show_git_blame_gutter: bool,
  728    show_git_blame_inline: bool,
  729    show_git_blame_inline_delay_task: Option<Task<()>>,
  730    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  731    git_blame_inline_enabled: bool,
  732    serialize_dirty_buffers: bool,
  733    show_selection_menu: Option<bool>,
  734    blame: Option<Entity<GitBlame>>,
  735    blame_subscription: Option<Subscription>,
  736    custom_context_menu: Option<
  737        Box<
  738            dyn 'static
  739                + Fn(
  740                    &mut Self,
  741                    DisplayPoint,
  742                    &mut Window,
  743                    &mut Context<Self>,
  744                ) -> Option<Entity<ui::ContextMenu>>,
  745        >,
  746    >,
  747    last_bounds: Option<Bounds<Pixels>>,
  748    last_position_map: Option<Rc<PositionMap>>,
  749    expect_bounds_change: Option<Bounds<Pixels>>,
  750    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  751    tasks_update_task: Option<Task<()>>,
  752    in_project_search: bool,
  753    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  754    breadcrumb_header: Option<String>,
  755    focused_block: Option<FocusedBlock>,
  756    next_scroll_position: NextScrollCursorCenterTopBottom,
  757    addons: HashMap<TypeId, Box<dyn Addon>>,
  758    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  759    load_diff_task: Option<Shared<Task<()>>>,
  760    selection_mark_mode: bool,
  761    toggle_fold_multiple_buffers: Task<()>,
  762    _scroll_cursor_center_top_bottom_task: Task<()>,
  763    serialize_selections: Task<()>,
  764}
  765
  766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  767enum NextScrollCursorCenterTopBottom {
  768    #[default]
  769    Center,
  770    Top,
  771    Bottom,
  772}
  773
  774impl NextScrollCursorCenterTopBottom {
  775    fn next(&self) -> Self {
  776        match self {
  777            Self::Center => Self::Top,
  778            Self::Top => Self::Bottom,
  779            Self::Bottom => Self::Center,
  780        }
  781    }
  782}
  783
  784#[derive(Clone)]
  785pub struct EditorSnapshot {
  786    pub mode: EditorMode,
  787    show_gutter: bool,
  788    show_line_numbers: Option<bool>,
  789    show_git_diff_gutter: Option<bool>,
  790    show_code_actions: Option<bool>,
  791    show_runnables: Option<bool>,
  792    git_blame_gutter_max_author_length: Option<usize>,
  793    pub display_snapshot: DisplaySnapshot,
  794    pub placeholder_text: Option<Arc<str>>,
  795    is_focused: bool,
  796    scroll_anchor: ScrollAnchor,
  797    ongoing_scroll: OngoingScroll,
  798    current_line_highlight: CurrentLineHighlight,
  799    gutter_hovered: bool,
  800}
  801
  802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  803
  804#[derive(Default, Debug, Clone, Copy)]
  805pub struct GutterDimensions {
  806    pub left_padding: Pixels,
  807    pub right_padding: Pixels,
  808    pub width: Pixels,
  809    pub margin: Pixels,
  810    pub git_blame_entries_width: Option<Pixels>,
  811}
  812
  813impl GutterDimensions {
  814    /// The full width of the space taken up by the gutter.
  815    pub fn full_width(&self) -> Pixels {
  816        self.margin + self.width
  817    }
  818
  819    /// The width of the space reserved for the fold indicators,
  820    /// use alongside 'justify_end' and `gutter_width` to
  821    /// right align content with the line numbers
  822    pub fn fold_area_width(&self) -> Pixels {
  823        self.margin + self.right_padding
  824    }
  825}
  826
  827#[derive(Debug)]
  828pub struct RemoteSelection {
  829    pub replica_id: ReplicaId,
  830    pub selection: Selection<Anchor>,
  831    pub cursor_shape: CursorShape,
  832    pub peer_id: PeerId,
  833    pub line_mode: bool,
  834    pub participant_index: Option<ParticipantIndex>,
  835    pub user_name: Option<SharedString>,
  836}
  837
  838#[derive(Clone, Debug)]
  839struct SelectionHistoryEntry {
  840    selections: Arc<[Selection<Anchor>]>,
  841    select_next_state: Option<SelectNextState>,
  842    select_prev_state: Option<SelectNextState>,
  843    add_selections_state: Option<AddSelectionsState>,
  844}
  845
  846enum SelectionHistoryMode {
  847    Normal,
  848    Undoing,
  849    Redoing,
  850}
  851
  852#[derive(Clone, PartialEq, Eq, Hash)]
  853struct HoveredCursor {
  854    replica_id: u16,
  855    selection_id: usize,
  856}
  857
  858impl Default for SelectionHistoryMode {
  859    fn default() -> Self {
  860        Self::Normal
  861    }
  862}
  863
  864#[derive(Default)]
  865struct SelectionHistory {
  866    #[allow(clippy::type_complexity)]
  867    selections_by_transaction:
  868        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  869    mode: SelectionHistoryMode,
  870    undo_stack: VecDeque<SelectionHistoryEntry>,
  871    redo_stack: VecDeque<SelectionHistoryEntry>,
  872}
  873
  874impl SelectionHistory {
  875    fn insert_transaction(
  876        &mut self,
  877        transaction_id: TransactionId,
  878        selections: Arc<[Selection<Anchor>]>,
  879    ) {
  880        self.selections_by_transaction
  881            .insert(transaction_id, (selections, None));
  882    }
  883
  884    #[allow(clippy::type_complexity)]
  885    fn transaction(
  886        &self,
  887        transaction_id: TransactionId,
  888    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  889        self.selections_by_transaction.get(&transaction_id)
  890    }
  891
  892    #[allow(clippy::type_complexity)]
  893    fn transaction_mut(
  894        &mut self,
  895        transaction_id: TransactionId,
  896    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  897        self.selections_by_transaction.get_mut(&transaction_id)
  898    }
  899
  900    fn push(&mut self, entry: SelectionHistoryEntry) {
  901        if !entry.selections.is_empty() {
  902            match self.mode {
  903                SelectionHistoryMode::Normal => {
  904                    self.push_undo(entry);
  905                    self.redo_stack.clear();
  906                }
  907                SelectionHistoryMode::Undoing => self.push_redo(entry),
  908                SelectionHistoryMode::Redoing => self.push_undo(entry),
  909            }
  910        }
  911    }
  912
  913    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  914        if self
  915            .undo_stack
  916            .back()
  917            .map_or(true, |e| e.selections != entry.selections)
  918        {
  919            self.undo_stack.push_back(entry);
  920            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  921                self.undo_stack.pop_front();
  922            }
  923        }
  924    }
  925
  926    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  927        if self
  928            .redo_stack
  929            .back()
  930            .map_or(true, |e| e.selections != entry.selections)
  931        {
  932            self.redo_stack.push_back(entry);
  933            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  934                self.redo_stack.pop_front();
  935            }
  936        }
  937    }
  938}
  939
  940struct RowHighlight {
  941    index: usize,
  942    range: Range<Anchor>,
  943    color: Hsla,
  944    should_autoscroll: bool,
  945}
  946
  947#[derive(Clone, Debug)]
  948struct AddSelectionsState {
  949    above: bool,
  950    stack: Vec<usize>,
  951}
  952
  953#[derive(Clone)]
  954struct SelectNextState {
  955    query: AhoCorasick,
  956    wordwise: bool,
  957    done: bool,
  958}
  959
  960impl std::fmt::Debug for SelectNextState {
  961    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  962        f.debug_struct(std::any::type_name::<Self>())
  963            .field("wordwise", &self.wordwise)
  964            .field("done", &self.done)
  965            .finish()
  966    }
  967}
  968
  969#[derive(Debug)]
  970struct AutocloseRegion {
  971    selection_id: usize,
  972    range: Range<Anchor>,
  973    pair: BracketPair,
  974}
  975
  976#[derive(Debug)]
  977struct SnippetState {
  978    ranges: Vec<Vec<Range<Anchor>>>,
  979    active_index: usize,
  980    choices: Vec<Option<Vec<String>>>,
  981}
  982
  983#[doc(hidden)]
  984pub struct RenameState {
  985    pub range: Range<Anchor>,
  986    pub old_name: Arc<str>,
  987    pub editor: Entity<Editor>,
  988    block_id: CustomBlockId,
  989}
  990
  991struct InvalidationStack<T>(Vec<T>);
  992
  993struct RegisteredInlineCompletionProvider {
  994    provider: Arc<dyn InlineCompletionProviderHandle>,
  995    _subscription: Subscription,
  996}
  997
  998#[derive(Debug, PartialEq, Eq)]
  999struct ActiveDiagnosticGroup {
 1000    primary_range: Range<Anchor>,
 1001    primary_message: String,
 1002    group_id: usize,
 1003    blocks: HashMap<CustomBlockId, Diagnostic>,
 1004    is_valid: bool,
 1005}
 1006
 1007#[derive(Serialize, Deserialize, Clone, Debug)]
 1008pub struct ClipboardSelection {
 1009    /// The number of bytes in this selection.
 1010    pub len: usize,
 1011    /// Whether this was a full-line selection.
 1012    pub is_entire_line: bool,
 1013    /// The column where this selection originally started.
 1014    pub start_column: u32,
 1015}
 1016
 1017#[derive(Debug)]
 1018pub(crate) struct NavigationData {
 1019    cursor_anchor: Anchor,
 1020    cursor_position: Point,
 1021    scroll_anchor: ScrollAnchor,
 1022    scroll_top_row: u32,
 1023}
 1024
 1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1026pub enum GotoDefinitionKind {
 1027    Symbol,
 1028    Declaration,
 1029    Type,
 1030    Implementation,
 1031}
 1032
 1033#[derive(Debug, Clone)]
 1034enum InlayHintRefreshReason {
 1035    ModifiersChanged(bool),
 1036    Toggle(bool),
 1037    SettingsChange(InlayHintSettings),
 1038    NewLinesShown,
 1039    BufferEdited(HashSet<Arc<Language>>),
 1040    RefreshRequested,
 1041    ExcerptsRemoved(Vec<ExcerptId>),
 1042}
 1043
 1044impl InlayHintRefreshReason {
 1045    fn description(&self) -> &'static str {
 1046        match self {
 1047            Self::ModifiersChanged(_) => "modifiers changed",
 1048            Self::Toggle(_) => "toggle",
 1049            Self::SettingsChange(_) => "settings change",
 1050            Self::NewLinesShown => "new lines shown",
 1051            Self::BufferEdited(_) => "buffer edited",
 1052            Self::RefreshRequested => "refresh requested",
 1053            Self::ExcerptsRemoved(_) => "excerpts removed",
 1054        }
 1055    }
 1056}
 1057
 1058pub enum FormatTarget {
 1059    Buffers,
 1060    Ranges(Vec<Range<MultiBufferPoint>>),
 1061}
 1062
 1063pub(crate) struct FocusedBlock {
 1064    id: BlockId,
 1065    focus_handle: WeakFocusHandle,
 1066}
 1067
 1068#[derive(Clone)]
 1069enum JumpData {
 1070    MultiBufferRow {
 1071        row: MultiBufferRow,
 1072        line_offset_from_top: u32,
 1073    },
 1074    MultiBufferPoint {
 1075        excerpt_id: ExcerptId,
 1076        position: Point,
 1077        anchor: text::Anchor,
 1078        line_offset_from_top: u32,
 1079    },
 1080}
 1081
 1082pub enum MultibufferSelectionMode {
 1083    First,
 1084    All,
 1085}
 1086
 1087impl Editor {
 1088    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1089        let buffer = cx.new(|cx| Buffer::local("", cx));
 1090        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1091        Self::new(
 1092            EditorMode::SingleLine { auto_width: false },
 1093            buffer,
 1094            None,
 1095            false,
 1096            window,
 1097            cx,
 1098        )
 1099    }
 1100
 1101    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1102        let buffer = cx.new(|cx| Buffer::local("", cx));
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1105    }
 1106
 1107    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1108        let buffer = cx.new(|cx| Buffer::local("", cx));
 1109        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1110        Self::new(
 1111            EditorMode::SingleLine { auto_width: true },
 1112            buffer,
 1113            None,
 1114            false,
 1115            window,
 1116            cx,
 1117        )
 1118    }
 1119
 1120    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1121        let buffer = cx.new(|cx| Buffer::local("", cx));
 1122        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1123        Self::new(
 1124            EditorMode::AutoHeight { max_lines },
 1125            buffer,
 1126            None,
 1127            false,
 1128            window,
 1129            cx,
 1130        )
 1131    }
 1132
 1133    pub fn for_buffer(
 1134        buffer: Entity<Buffer>,
 1135        project: Option<Entity<Project>>,
 1136        window: &mut Window,
 1137        cx: &mut Context<Self>,
 1138    ) -> Self {
 1139        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1140        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1141    }
 1142
 1143    pub fn for_multibuffer(
 1144        buffer: Entity<MultiBuffer>,
 1145        project: Option<Entity<Project>>,
 1146        show_excerpt_controls: bool,
 1147        window: &mut Window,
 1148        cx: &mut Context<Self>,
 1149    ) -> Self {
 1150        Self::new(
 1151            EditorMode::Full,
 1152            buffer,
 1153            project,
 1154            show_excerpt_controls,
 1155            window,
 1156            cx,
 1157        )
 1158    }
 1159
 1160    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1161        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1162        let mut clone = Self::new(
 1163            self.mode,
 1164            self.buffer.clone(),
 1165            self.project.clone(),
 1166            show_excerpt_controls,
 1167            window,
 1168            cx,
 1169        );
 1170        self.display_map.update(cx, |display_map, cx| {
 1171            let snapshot = display_map.snapshot(cx);
 1172            clone.display_map.update(cx, |display_map, cx| {
 1173                display_map.set_state(&snapshot, cx);
 1174            });
 1175        });
 1176        clone.selections.clone_state(&self.selections);
 1177        clone.scroll_manager.clone_state(&self.scroll_manager);
 1178        clone.searchable = self.searchable;
 1179        clone
 1180    }
 1181
 1182    pub fn new(
 1183        mode: EditorMode,
 1184        buffer: Entity<MultiBuffer>,
 1185        project: Option<Entity<Project>>,
 1186        show_excerpt_controls: bool,
 1187        window: &mut Window,
 1188        cx: &mut Context<Self>,
 1189    ) -> Self {
 1190        let style = window.text_style();
 1191        let font_size = style.font_size.to_pixels(window.rem_size());
 1192        let editor = cx.entity().downgrade();
 1193        let fold_placeholder = FoldPlaceholder {
 1194            constrain_width: true,
 1195            render: Arc::new(move |fold_id, fold_range, cx| {
 1196                let editor = editor.clone();
 1197                div()
 1198                    .id(fold_id)
 1199                    .bg(cx.theme().colors().ghost_element_background)
 1200                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1201                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1202                    .rounded_sm()
 1203                    .size_full()
 1204                    .cursor_pointer()
 1205                    .child("")
 1206                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1207                    .on_click(move |_, _window, cx| {
 1208                        editor
 1209                            .update(cx, |editor, cx| {
 1210                                editor.unfold_ranges(
 1211                                    &[fold_range.start..fold_range.end],
 1212                                    true,
 1213                                    false,
 1214                                    cx,
 1215                                );
 1216                                cx.stop_propagation();
 1217                            })
 1218                            .ok();
 1219                    })
 1220                    .into_any()
 1221            }),
 1222            merge_adjacent: true,
 1223            ..Default::default()
 1224        };
 1225        let display_map = cx.new(|cx| {
 1226            DisplayMap::new(
 1227                buffer.clone(),
 1228                style.font(),
 1229                font_size,
 1230                None,
 1231                show_excerpt_controls,
 1232                FILE_HEADER_HEIGHT,
 1233                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1234                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1235                fold_placeholder,
 1236                cx,
 1237            )
 1238        });
 1239
 1240        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1241
 1242        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1243
 1244        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1245            .then(|| language_settings::SoftWrap::None);
 1246
 1247        let mut project_subscriptions = Vec::new();
 1248        if mode == EditorMode::Full {
 1249            if let Some(project) = project.as_ref() {
 1250                if buffer.read(cx).is_singleton() {
 1251                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1252                        cx.emit(EditorEvent::TitleChanged);
 1253                    }));
 1254                }
 1255                project_subscriptions.push(cx.subscribe_in(
 1256                    project,
 1257                    window,
 1258                    |editor, _, event, window, cx| {
 1259                        if let project::Event::RefreshInlayHints = event {
 1260                            editor
 1261                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1262                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1263                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1264                                let focus_handle = editor.focus_handle(cx);
 1265                                if focus_handle.is_focused(window) {
 1266                                    let snapshot = buffer.read(cx).snapshot();
 1267                                    for (range, snippet) in snippet_edits {
 1268                                        let editor_range =
 1269                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1270                                        editor
 1271                                            .insert_snippet(
 1272                                                &[editor_range],
 1273                                                snippet.clone(),
 1274                                                window,
 1275                                                cx,
 1276                                            )
 1277                                            .ok();
 1278                                    }
 1279                                }
 1280                            }
 1281                        }
 1282                    },
 1283                ));
 1284                if let Some(task_inventory) = project
 1285                    .read(cx)
 1286                    .task_store()
 1287                    .read(cx)
 1288                    .task_inventory()
 1289                    .cloned()
 1290                {
 1291                    project_subscriptions.push(cx.observe_in(
 1292                        &task_inventory,
 1293                        window,
 1294                        |editor, _, window, cx| {
 1295                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1296                        },
 1297                    ));
 1298                }
 1299            }
 1300        }
 1301
 1302        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1303
 1304        let inlay_hint_settings =
 1305            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1306        let focus_handle = cx.focus_handle();
 1307        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1308            .detach();
 1309        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1310            .detach();
 1311        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1312            .detach();
 1313        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1314            .detach();
 1315
 1316        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1317            Some(false)
 1318        } else {
 1319            None
 1320        };
 1321
 1322        let mut code_action_providers = Vec::new();
 1323        let mut load_uncommitted_diff = None;
 1324        if let Some(project) = project.clone() {
 1325            load_uncommitted_diff = Some(
 1326                get_uncommitted_diff_for_buffer(
 1327                    &project,
 1328                    buffer.read(cx).all_buffers(),
 1329                    buffer.clone(),
 1330                    cx,
 1331                )
 1332                .shared(),
 1333            );
 1334            code_action_providers.push(Rc::new(project) as Rc<_>);
 1335        }
 1336
 1337        let mut this = Self {
 1338            focus_handle,
 1339            show_cursor_when_unfocused: false,
 1340            last_focused_descendant: None,
 1341            buffer: buffer.clone(),
 1342            display_map: display_map.clone(),
 1343            selections,
 1344            scroll_manager: ScrollManager::new(cx),
 1345            columnar_selection_tail: None,
 1346            add_selections_state: None,
 1347            select_next_state: None,
 1348            select_prev_state: None,
 1349            selection_history: Default::default(),
 1350            autoclose_regions: Default::default(),
 1351            snippet_stack: Default::default(),
 1352            select_larger_syntax_node_stack: Vec::new(),
 1353            ime_transaction: Default::default(),
 1354            active_diagnostics: None,
 1355            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1356            inline_diagnostics_update: Task::ready(()),
 1357            inline_diagnostics: Vec::new(),
 1358            soft_wrap_mode_override,
 1359            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1360            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1361            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1362            project,
 1363            blink_manager: blink_manager.clone(),
 1364            show_local_selections: true,
 1365            show_scrollbars: true,
 1366            mode,
 1367            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1368            show_gutter: mode == EditorMode::Full,
 1369            show_line_numbers: None,
 1370            use_relative_line_numbers: None,
 1371            show_git_diff_gutter: None,
 1372            show_code_actions: None,
 1373            show_runnables: None,
 1374            show_wrap_guides: None,
 1375            show_indent_guides,
 1376            placeholder_text: None,
 1377            highlight_order: 0,
 1378            highlighted_rows: HashMap::default(),
 1379            background_highlights: Default::default(),
 1380            gutter_highlights: TreeMap::default(),
 1381            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1382            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1383            nav_history: None,
 1384            context_menu: RefCell::new(None),
 1385            mouse_context_menu: None,
 1386            completion_tasks: Default::default(),
 1387            signature_help_state: SignatureHelpState::default(),
 1388            auto_signature_help: None,
 1389            find_all_references_task_sources: Vec::new(),
 1390            next_completion_id: 0,
 1391            next_inlay_id: 0,
 1392            code_action_providers,
 1393            available_code_actions: Default::default(),
 1394            code_actions_task: Default::default(),
 1395            selection_highlight_task: Default::default(),
 1396            document_highlights_task: Default::default(),
 1397            linked_editing_range_task: Default::default(),
 1398            pending_rename: Default::default(),
 1399            searchable: true,
 1400            cursor_shape: EditorSettings::get_global(cx)
 1401                .cursor_shape
 1402                .unwrap_or_default(),
 1403            current_line_highlight: None,
 1404            autoindent_mode: Some(AutoindentMode::EachLine),
 1405            collapse_matches: false,
 1406            workspace: None,
 1407            input_enabled: true,
 1408            use_modal_editing: mode == EditorMode::Full,
 1409            read_only: false,
 1410            use_autoclose: true,
 1411            use_auto_surround: true,
 1412            auto_replace_emoji_shortcode: false,
 1413            leader_peer_id: None,
 1414            remote_id: None,
 1415            hover_state: Default::default(),
 1416            pending_mouse_down: None,
 1417            hovered_link_state: Default::default(),
 1418            edit_prediction_provider: None,
 1419            active_inline_completion: None,
 1420            stale_inline_completion_in_menu: None,
 1421            edit_prediction_preview: EditPredictionPreview::Inactive {
 1422                released_too_fast: false,
 1423            },
 1424            inline_diagnostics_enabled: mode == EditorMode::Full,
 1425            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1426
 1427            gutter_hovered: false,
 1428            pixel_position_of_newest_cursor: None,
 1429            last_bounds: None,
 1430            last_position_map: None,
 1431            expect_bounds_change: None,
 1432            gutter_dimensions: GutterDimensions::default(),
 1433            style: None,
 1434            show_cursor_names: false,
 1435            hovered_cursors: Default::default(),
 1436            next_editor_action_id: EditorActionId::default(),
 1437            editor_actions: Rc::default(),
 1438            inline_completions_hidden_for_vim_mode: false,
 1439            show_inline_completions_override: None,
 1440            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1441            edit_prediction_settings: EditPredictionSettings::Disabled,
 1442            edit_prediction_indent_conflict: false,
 1443            edit_prediction_requires_modifier_in_indent_conflict: true,
 1444            custom_context_menu: None,
 1445            show_git_blame_gutter: false,
 1446            show_git_blame_inline: false,
 1447            show_selection_menu: None,
 1448            show_git_blame_inline_delay_task: None,
 1449            git_blame_inline_tooltip: None,
 1450            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1451            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1452                .session
 1453                .restore_unsaved_buffers,
 1454            blame: None,
 1455            blame_subscription: None,
 1456            tasks: Default::default(),
 1457            _subscriptions: vec![
 1458                cx.observe(&buffer, Self::on_buffer_changed),
 1459                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1460                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1461                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1462                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1463                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1464                cx.observe_window_activation(window, |editor, window, cx| {
 1465                    let active = window.is_window_active();
 1466                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1467                        if active {
 1468                            blink_manager.enable(cx);
 1469                        } else {
 1470                            blink_manager.disable(cx);
 1471                        }
 1472                    });
 1473                }),
 1474            ],
 1475            tasks_update_task: None,
 1476            linked_edit_ranges: Default::default(),
 1477            in_project_search: false,
 1478            previous_search_ranges: None,
 1479            breadcrumb_header: None,
 1480            focused_block: None,
 1481            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1482            addons: HashMap::default(),
 1483            registered_buffers: HashMap::default(),
 1484            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1485            selection_mark_mode: false,
 1486            toggle_fold_multiple_buffers: Task::ready(()),
 1487            serialize_selections: Task::ready(()),
 1488            text_style_refinement: None,
 1489            load_diff_task: load_uncommitted_diff,
 1490        };
 1491        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1492        this._subscriptions.extend(project_subscriptions);
 1493
 1494        this.end_selection(window, cx);
 1495        this.scroll_manager.show_scrollbar(window, cx);
 1496
 1497        if mode == EditorMode::Full {
 1498            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1499            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1500
 1501            if this.git_blame_inline_enabled {
 1502                this.git_blame_inline_enabled = true;
 1503                this.start_git_blame_inline(false, window, cx);
 1504            }
 1505
 1506            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1507                if let Some(project) = this.project.as_ref() {
 1508                    let handle = project.update(cx, |project, cx| {
 1509                        project.register_buffer_with_language_servers(&buffer, cx)
 1510                    });
 1511                    this.registered_buffers
 1512                        .insert(buffer.read(cx).remote_id(), handle);
 1513                }
 1514            }
 1515        }
 1516
 1517        this.report_editor_event("Editor Opened", None, cx);
 1518        this
 1519    }
 1520
 1521    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1522        self.mouse_context_menu
 1523            .as_ref()
 1524            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1525    }
 1526
 1527    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1528        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1529    }
 1530
 1531    fn key_context_internal(
 1532        &self,
 1533        has_active_edit_prediction: bool,
 1534        window: &Window,
 1535        cx: &App,
 1536    ) -> KeyContext {
 1537        let mut key_context = KeyContext::new_with_defaults();
 1538        key_context.add("Editor");
 1539        let mode = match self.mode {
 1540            EditorMode::SingleLine { .. } => "single_line",
 1541            EditorMode::AutoHeight { .. } => "auto_height",
 1542            EditorMode::Full => "full",
 1543        };
 1544
 1545        if EditorSettings::jupyter_enabled(cx) {
 1546            key_context.add("jupyter");
 1547        }
 1548
 1549        key_context.set("mode", mode);
 1550        if self.pending_rename.is_some() {
 1551            key_context.add("renaming");
 1552        }
 1553
 1554        match self.context_menu.borrow().as_ref() {
 1555            Some(CodeContextMenu::Completions(_)) => {
 1556                key_context.add("menu");
 1557                key_context.add("showing_completions");
 1558            }
 1559            Some(CodeContextMenu::CodeActions(_)) => {
 1560                key_context.add("menu");
 1561                key_context.add("showing_code_actions")
 1562            }
 1563            None => {}
 1564        }
 1565
 1566        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1567        if !self.focus_handle(cx).contains_focused(window, cx)
 1568            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1569        {
 1570            for addon in self.addons.values() {
 1571                addon.extend_key_context(&mut key_context, cx)
 1572            }
 1573        }
 1574
 1575        if let Some(extension) = self
 1576            .buffer
 1577            .read(cx)
 1578            .as_singleton()
 1579            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1580        {
 1581            key_context.set("extension", extension.to_string());
 1582        }
 1583
 1584        if has_active_edit_prediction {
 1585            if self.edit_prediction_in_conflict() {
 1586                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1587            } else {
 1588                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1589                key_context.add("copilot_suggestion");
 1590            }
 1591        }
 1592
 1593        if self.selection_mark_mode {
 1594            key_context.add("selection_mode");
 1595        }
 1596
 1597        key_context
 1598    }
 1599
 1600    pub fn edit_prediction_in_conflict(&self) -> bool {
 1601        if !self.show_edit_predictions_in_menu() {
 1602            return false;
 1603        }
 1604
 1605        let showing_completions = self
 1606            .context_menu
 1607            .borrow()
 1608            .as_ref()
 1609            .map_or(false, |context| {
 1610                matches!(context, CodeContextMenu::Completions(_))
 1611            });
 1612
 1613        showing_completions
 1614            || self.edit_prediction_requires_modifier()
 1615            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1616            // bindings to insert tab characters.
 1617            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1618    }
 1619
 1620    pub fn accept_edit_prediction_keybind(
 1621        &self,
 1622        window: &Window,
 1623        cx: &App,
 1624    ) -> AcceptEditPredictionBinding {
 1625        let key_context = self.key_context_internal(true, window, cx);
 1626        let in_conflict = self.edit_prediction_in_conflict();
 1627
 1628        AcceptEditPredictionBinding(
 1629            window
 1630                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1631                .into_iter()
 1632                .filter(|binding| {
 1633                    !in_conflict
 1634                        || binding
 1635                            .keystrokes()
 1636                            .first()
 1637                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1638                })
 1639                .rev()
 1640                .min_by_key(|binding| {
 1641                    binding
 1642                        .keystrokes()
 1643                        .first()
 1644                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1645                }),
 1646        )
 1647    }
 1648
 1649    pub fn new_file(
 1650        workspace: &mut Workspace,
 1651        _: &workspace::NewFile,
 1652        window: &mut Window,
 1653        cx: &mut Context<Workspace>,
 1654    ) {
 1655        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1656            "Failed to create buffer",
 1657            window,
 1658            cx,
 1659            |e, _, _| match e.error_code() {
 1660                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1661                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1662                e.error_tag("required").unwrap_or("the latest version")
 1663            )),
 1664                _ => None,
 1665            },
 1666        );
 1667    }
 1668
 1669    pub fn new_in_workspace(
 1670        workspace: &mut Workspace,
 1671        window: &mut Window,
 1672        cx: &mut Context<Workspace>,
 1673    ) -> Task<Result<Entity<Editor>>> {
 1674        let project = workspace.project().clone();
 1675        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1676
 1677        cx.spawn_in(window, |workspace, mut cx| async move {
 1678            let buffer = create.await?;
 1679            workspace.update_in(&mut cx, |workspace, window, cx| {
 1680                let editor =
 1681                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1682                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1683                editor
 1684            })
 1685        })
 1686    }
 1687
 1688    fn new_file_vertical(
 1689        workspace: &mut Workspace,
 1690        _: &workspace::NewFileSplitVertical,
 1691        window: &mut Window,
 1692        cx: &mut Context<Workspace>,
 1693    ) {
 1694        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1695    }
 1696
 1697    fn new_file_horizontal(
 1698        workspace: &mut Workspace,
 1699        _: &workspace::NewFileSplitHorizontal,
 1700        window: &mut Window,
 1701        cx: &mut Context<Workspace>,
 1702    ) {
 1703        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1704    }
 1705
 1706    fn new_file_in_direction(
 1707        workspace: &mut Workspace,
 1708        direction: SplitDirection,
 1709        window: &mut Window,
 1710        cx: &mut Context<Workspace>,
 1711    ) {
 1712        let project = workspace.project().clone();
 1713        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1714
 1715        cx.spawn_in(window, |workspace, mut cx| async move {
 1716            let buffer = create.await?;
 1717            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1718                workspace.split_item(
 1719                    direction,
 1720                    Box::new(
 1721                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1722                    ),
 1723                    window,
 1724                    cx,
 1725                )
 1726            })?;
 1727            anyhow::Ok(())
 1728        })
 1729        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1730            match e.error_code() {
 1731                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1732                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1733                e.error_tag("required").unwrap_or("the latest version")
 1734            )),
 1735                _ => None,
 1736            }
 1737        });
 1738    }
 1739
 1740    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1741        self.leader_peer_id
 1742    }
 1743
 1744    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1745        &self.buffer
 1746    }
 1747
 1748    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1749        self.workspace.as_ref()?.0.upgrade()
 1750    }
 1751
 1752    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1753        self.buffer().read(cx).title(cx)
 1754    }
 1755
 1756    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1757        let git_blame_gutter_max_author_length = self
 1758            .render_git_blame_gutter(cx)
 1759            .then(|| {
 1760                if let Some(blame) = self.blame.as_ref() {
 1761                    let max_author_length =
 1762                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1763                    Some(max_author_length)
 1764                } else {
 1765                    None
 1766                }
 1767            })
 1768            .flatten();
 1769
 1770        EditorSnapshot {
 1771            mode: self.mode,
 1772            show_gutter: self.show_gutter,
 1773            show_line_numbers: self.show_line_numbers,
 1774            show_git_diff_gutter: self.show_git_diff_gutter,
 1775            show_code_actions: self.show_code_actions,
 1776            show_runnables: self.show_runnables,
 1777            git_blame_gutter_max_author_length,
 1778            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1779            scroll_anchor: self.scroll_manager.anchor(),
 1780            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1781            placeholder_text: self.placeholder_text.clone(),
 1782            is_focused: self.focus_handle.is_focused(window),
 1783            current_line_highlight: self
 1784                .current_line_highlight
 1785                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1786            gutter_hovered: self.gutter_hovered,
 1787        }
 1788    }
 1789
 1790    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1791        self.buffer.read(cx).language_at(point, cx)
 1792    }
 1793
 1794    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1795        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1796    }
 1797
 1798    pub fn active_excerpt(
 1799        &self,
 1800        cx: &App,
 1801    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1802        self.buffer
 1803            .read(cx)
 1804            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1805    }
 1806
 1807    pub fn mode(&self) -> EditorMode {
 1808        self.mode
 1809    }
 1810
 1811    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1812        self.collaboration_hub.as_deref()
 1813    }
 1814
 1815    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1816        self.collaboration_hub = Some(hub);
 1817    }
 1818
 1819    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1820        self.in_project_search = in_project_search;
 1821    }
 1822
 1823    pub fn set_custom_context_menu(
 1824        &mut self,
 1825        f: impl 'static
 1826            + Fn(
 1827                &mut Self,
 1828                DisplayPoint,
 1829                &mut Window,
 1830                &mut Context<Self>,
 1831            ) -> Option<Entity<ui::ContextMenu>>,
 1832    ) {
 1833        self.custom_context_menu = Some(Box::new(f))
 1834    }
 1835
 1836    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1837        self.completion_provider = provider;
 1838    }
 1839
 1840    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1841        self.semantics_provider.clone()
 1842    }
 1843
 1844    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1845        self.semantics_provider = provider;
 1846    }
 1847
 1848    pub fn set_edit_prediction_provider<T>(
 1849        &mut self,
 1850        provider: Option<Entity<T>>,
 1851        window: &mut Window,
 1852        cx: &mut Context<Self>,
 1853    ) where
 1854        T: EditPredictionProvider,
 1855    {
 1856        self.edit_prediction_provider =
 1857            provider.map(|provider| RegisteredInlineCompletionProvider {
 1858                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1859                    if this.focus_handle.is_focused(window) {
 1860                        this.update_visible_inline_completion(window, cx);
 1861                    }
 1862                }),
 1863                provider: Arc::new(provider),
 1864            });
 1865        self.update_edit_prediction_settings(cx);
 1866        self.refresh_inline_completion(false, false, window, cx);
 1867    }
 1868
 1869    pub fn placeholder_text(&self) -> Option<&str> {
 1870        self.placeholder_text.as_deref()
 1871    }
 1872
 1873    pub fn set_placeholder_text(
 1874        &mut self,
 1875        placeholder_text: impl Into<Arc<str>>,
 1876        cx: &mut Context<Self>,
 1877    ) {
 1878        let placeholder_text = Some(placeholder_text.into());
 1879        if self.placeholder_text != placeholder_text {
 1880            self.placeholder_text = placeholder_text;
 1881            cx.notify();
 1882        }
 1883    }
 1884
 1885    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1886        self.cursor_shape = cursor_shape;
 1887
 1888        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1889        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1890
 1891        cx.notify();
 1892    }
 1893
 1894    pub fn set_current_line_highlight(
 1895        &mut self,
 1896        current_line_highlight: Option<CurrentLineHighlight>,
 1897    ) {
 1898        self.current_line_highlight = current_line_highlight;
 1899    }
 1900
 1901    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1902        self.collapse_matches = collapse_matches;
 1903    }
 1904
 1905    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1906        let buffers = self.buffer.read(cx).all_buffers();
 1907        let Some(project) = self.project.as_ref() else {
 1908            return;
 1909        };
 1910        project.update(cx, |project, cx| {
 1911            for buffer in buffers {
 1912                self.registered_buffers
 1913                    .entry(buffer.read(cx).remote_id())
 1914                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1915            }
 1916        })
 1917    }
 1918
 1919    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1920        if self.collapse_matches {
 1921            return range.start..range.start;
 1922        }
 1923        range.clone()
 1924    }
 1925
 1926    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1927        if self.display_map.read(cx).clip_at_line_ends != clip {
 1928            self.display_map
 1929                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1930        }
 1931    }
 1932
 1933    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1934        self.input_enabled = input_enabled;
 1935    }
 1936
 1937    pub fn set_inline_completions_hidden_for_vim_mode(
 1938        &mut self,
 1939        hidden: bool,
 1940        window: &mut Window,
 1941        cx: &mut Context<Self>,
 1942    ) {
 1943        if hidden != self.inline_completions_hidden_for_vim_mode {
 1944            self.inline_completions_hidden_for_vim_mode = hidden;
 1945            if hidden {
 1946                self.update_visible_inline_completion(window, cx);
 1947            } else {
 1948                self.refresh_inline_completion(true, false, window, cx);
 1949            }
 1950        }
 1951    }
 1952
 1953    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1954        self.menu_inline_completions_policy = value;
 1955    }
 1956
 1957    pub fn set_autoindent(&mut self, autoindent: bool) {
 1958        if autoindent {
 1959            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1960        } else {
 1961            self.autoindent_mode = None;
 1962        }
 1963    }
 1964
 1965    pub fn read_only(&self, cx: &App) -> bool {
 1966        self.read_only || self.buffer.read(cx).read_only()
 1967    }
 1968
 1969    pub fn set_read_only(&mut self, read_only: bool) {
 1970        self.read_only = read_only;
 1971    }
 1972
 1973    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1974        self.use_autoclose = autoclose;
 1975    }
 1976
 1977    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1978        self.use_auto_surround = auto_surround;
 1979    }
 1980
 1981    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1982        self.auto_replace_emoji_shortcode = auto_replace;
 1983    }
 1984
 1985    pub fn toggle_edit_predictions(
 1986        &mut self,
 1987        _: &ToggleEditPrediction,
 1988        window: &mut Window,
 1989        cx: &mut Context<Self>,
 1990    ) {
 1991        if self.show_inline_completions_override.is_some() {
 1992            self.set_show_edit_predictions(None, window, cx);
 1993        } else {
 1994            let show_edit_predictions = !self.edit_predictions_enabled();
 1995            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1996        }
 1997    }
 1998
 1999    pub fn set_show_edit_predictions(
 2000        &mut self,
 2001        show_edit_predictions: Option<bool>,
 2002        window: &mut Window,
 2003        cx: &mut Context<Self>,
 2004    ) {
 2005        self.show_inline_completions_override = show_edit_predictions;
 2006        self.update_edit_prediction_settings(cx);
 2007
 2008        if let Some(false) = show_edit_predictions {
 2009            self.discard_inline_completion(false, cx);
 2010        } else {
 2011            self.refresh_inline_completion(false, true, window, cx);
 2012        }
 2013    }
 2014
 2015    fn inline_completions_disabled_in_scope(
 2016        &self,
 2017        buffer: &Entity<Buffer>,
 2018        buffer_position: language::Anchor,
 2019        cx: &App,
 2020    ) -> bool {
 2021        let snapshot = buffer.read(cx).snapshot();
 2022        let settings = snapshot.settings_at(buffer_position, cx);
 2023
 2024        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2025            return false;
 2026        };
 2027
 2028        scope.override_name().map_or(false, |scope_name| {
 2029            settings
 2030                .edit_predictions_disabled_in
 2031                .iter()
 2032                .any(|s| s == scope_name)
 2033        })
 2034    }
 2035
 2036    pub fn set_use_modal_editing(&mut self, to: bool) {
 2037        self.use_modal_editing = to;
 2038    }
 2039
 2040    pub fn use_modal_editing(&self) -> bool {
 2041        self.use_modal_editing
 2042    }
 2043
 2044    fn selections_did_change(
 2045        &mut self,
 2046        local: bool,
 2047        old_cursor_position: &Anchor,
 2048        show_completions: bool,
 2049        window: &mut Window,
 2050        cx: &mut Context<Self>,
 2051    ) {
 2052        window.invalidate_character_coordinates();
 2053
 2054        // Copy selections to primary selection buffer
 2055        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2056        if local {
 2057            let selections = self.selections.all::<usize>(cx);
 2058            let buffer_handle = self.buffer.read(cx).read(cx);
 2059
 2060            let mut text = String::new();
 2061            for (index, selection) in selections.iter().enumerate() {
 2062                let text_for_selection = buffer_handle
 2063                    .text_for_range(selection.start..selection.end)
 2064                    .collect::<String>();
 2065
 2066                text.push_str(&text_for_selection);
 2067                if index != selections.len() - 1 {
 2068                    text.push('\n');
 2069                }
 2070            }
 2071
 2072            if !text.is_empty() {
 2073                cx.write_to_primary(ClipboardItem::new_string(text));
 2074            }
 2075        }
 2076
 2077        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2078            self.buffer.update(cx, |buffer, cx| {
 2079                buffer.set_active_selections(
 2080                    &self.selections.disjoint_anchors(),
 2081                    self.selections.line_mode,
 2082                    self.cursor_shape,
 2083                    cx,
 2084                )
 2085            });
 2086        }
 2087        let display_map = self
 2088            .display_map
 2089            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2090        let buffer = &display_map.buffer_snapshot;
 2091        self.add_selections_state = None;
 2092        self.select_next_state = None;
 2093        self.select_prev_state = None;
 2094        self.select_larger_syntax_node_stack.clear();
 2095        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2096        self.snippet_stack
 2097            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2098        self.take_rename(false, window, cx);
 2099
 2100        let new_cursor_position = self.selections.newest_anchor().head();
 2101
 2102        self.push_to_nav_history(
 2103            *old_cursor_position,
 2104            Some(new_cursor_position.to_point(buffer)),
 2105            cx,
 2106        );
 2107
 2108        if local {
 2109            let new_cursor_position = self.selections.newest_anchor().head();
 2110            let mut context_menu = self.context_menu.borrow_mut();
 2111            let completion_menu = match context_menu.as_ref() {
 2112                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2113                _ => {
 2114                    *context_menu = None;
 2115                    None
 2116                }
 2117            };
 2118            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2119                if !self.registered_buffers.contains_key(&buffer_id) {
 2120                    if let Some(project) = self.project.as_ref() {
 2121                        project.update(cx, |project, cx| {
 2122                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2123                                return;
 2124                            };
 2125                            self.registered_buffers.insert(
 2126                                buffer_id,
 2127                                project.register_buffer_with_language_servers(&buffer, cx),
 2128                            );
 2129                        })
 2130                    }
 2131                }
 2132            }
 2133
 2134            if let Some(completion_menu) = completion_menu {
 2135                let cursor_position = new_cursor_position.to_offset(buffer);
 2136                let (word_range, kind) =
 2137                    buffer.surrounding_word(completion_menu.initial_position, true);
 2138                if kind == Some(CharKind::Word)
 2139                    && word_range.to_inclusive().contains(&cursor_position)
 2140                {
 2141                    let mut completion_menu = completion_menu.clone();
 2142                    drop(context_menu);
 2143
 2144                    let query = Self::completion_query(buffer, cursor_position);
 2145                    cx.spawn(move |this, mut cx| async move {
 2146                        completion_menu
 2147                            .filter(query.as_deref(), cx.background_executor().clone())
 2148                            .await;
 2149
 2150                        this.update(&mut cx, |this, cx| {
 2151                            let mut context_menu = this.context_menu.borrow_mut();
 2152                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2153                            else {
 2154                                return;
 2155                            };
 2156
 2157                            if menu.id > completion_menu.id {
 2158                                return;
 2159                            }
 2160
 2161                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2162                            drop(context_menu);
 2163                            cx.notify();
 2164                        })
 2165                    })
 2166                    .detach();
 2167
 2168                    if show_completions {
 2169                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2170                    }
 2171                } else {
 2172                    drop(context_menu);
 2173                    self.hide_context_menu(window, cx);
 2174                }
 2175            } else {
 2176                drop(context_menu);
 2177            }
 2178
 2179            hide_hover(self, cx);
 2180
 2181            if old_cursor_position.to_display_point(&display_map).row()
 2182                != new_cursor_position.to_display_point(&display_map).row()
 2183            {
 2184                self.available_code_actions.take();
 2185            }
 2186            self.refresh_code_actions(window, cx);
 2187            self.refresh_document_highlights(cx);
 2188            self.refresh_selected_text_highlights(window, cx);
 2189            refresh_matching_bracket_highlights(self, window, cx);
 2190            self.update_visible_inline_completion(window, cx);
 2191            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2192            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2193            if self.git_blame_inline_enabled {
 2194                self.start_inline_blame_timer(window, cx);
 2195            }
 2196        }
 2197
 2198        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2199        cx.emit(EditorEvent::SelectionsChanged { local });
 2200
 2201        let selections = &self.selections.disjoint;
 2202        if selections.len() == 1 {
 2203            cx.emit(SearchEvent::ActiveMatchChanged)
 2204        }
 2205        if local
 2206            && self.is_singleton(cx)
 2207            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2208        {
 2209            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2210                let background_executor = cx.background_executor().clone();
 2211                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2212                let snapshot = self.buffer().read(cx).snapshot(cx);
 2213                let selections = selections.clone();
 2214                self.serialize_selections = cx.background_spawn(async move {
 2215                    background_executor.timer(Duration::from_millis(100)).await;
 2216                    let selections = selections
 2217                        .iter()
 2218                        .map(|selection| {
 2219                            (
 2220                                selection.start.to_offset(&snapshot),
 2221                                selection.end.to_offset(&snapshot),
 2222                            )
 2223                        })
 2224                        .collect();
 2225                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2226                        .await
 2227                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2228                        .log_err();
 2229                });
 2230            }
 2231        }
 2232
 2233        cx.notify();
 2234    }
 2235
 2236    pub fn change_selections<R>(
 2237        &mut self,
 2238        autoscroll: Option<Autoscroll>,
 2239        window: &mut Window,
 2240        cx: &mut Context<Self>,
 2241        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2242    ) -> R {
 2243        self.change_selections_inner(autoscroll, true, window, cx, change)
 2244    }
 2245
 2246    fn change_selections_inner<R>(
 2247        &mut self,
 2248        autoscroll: Option<Autoscroll>,
 2249        request_completions: bool,
 2250        window: &mut Window,
 2251        cx: &mut Context<Self>,
 2252        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2253    ) -> R {
 2254        let old_cursor_position = self.selections.newest_anchor().head();
 2255        self.push_to_selection_history();
 2256
 2257        let (changed, result) = self.selections.change_with(cx, change);
 2258
 2259        if changed {
 2260            if let Some(autoscroll) = autoscroll {
 2261                self.request_autoscroll(autoscroll, cx);
 2262            }
 2263            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2264
 2265            if self.should_open_signature_help_automatically(
 2266                &old_cursor_position,
 2267                self.signature_help_state.backspace_pressed(),
 2268                cx,
 2269            ) {
 2270                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2271            }
 2272            self.signature_help_state.set_backspace_pressed(false);
 2273        }
 2274
 2275        result
 2276    }
 2277
 2278    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2279    where
 2280        I: IntoIterator<Item = (Range<S>, T)>,
 2281        S: ToOffset,
 2282        T: Into<Arc<str>>,
 2283    {
 2284        if self.read_only(cx) {
 2285            return;
 2286        }
 2287
 2288        self.buffer
 2289            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2290    }
 2291
 2292    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2293    where
 2294        I: IntoIterator<Item = (Range<S>, T)>,
 2295        S: ToOffset,
 2296        T: Into<Arc<str>>,
 2297    {
 2298        if self.read_only(cx) {
 2299            return;
 2300        }
 2301
 2302        self.buffer.update(cx, |buffer, cx| {
 2303            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2304        });
 2305    }
 2306
 2307    pub fn edit_with_block_indent<I, S, T>(
 2308        &mut self,
 2309        edits: I,
 2310        original_start_columns: Vec<u32>,
 2311        cx: &mut Context<Self>,
 2312    ) where
 2313        I: IntoIterator<Item = (Range<S>, T)>,
 2314        S: ToOffset,
 2315        T: Into<Arc<str>>,
 2316    {
 2317        if self.read_only(cx) {
 2318            return;
 2319        }
 2320
 2321        self.buffer.update(cx, |buffer, cx| {
 2322            buffer.edit(
 2323                edits,
 2324                Some(AutoindentMode::Block {
 2325                    original_start_columns,
 2326                }),
 2327                cx,
 2328            )
 2329        });
 2330    }
 2331
 2332    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2333        self.hide_context_menu(window, cx);
 2334
 2335        match phase {
 2336            SelectPhase::Begin {
 2337                position,
 2338                add,
 2339                click_count,
 2340            } => self.begin_selection(position, add, click_count, window, cx),
 2341            SelectPhase::BeginColumnar {
 2342                position,
 2343                goal_column,
 2344                reset,
 2345            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2346            SelectPhase::Extend {
 2347                position,
 2348                click_count,
 2349            } => self.extend_selection(position, click_count, window, cx),
 2350            SelectPhase::Update {
 2351                position,
 2352                goal_column,
 2353                scroll_delta,
 2354            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2355            SelectPhase::End => self.end_selection(window, cx),
 2356        }
 2357    }
 2358
 2359    fn extend_selection(
 2360        &mut self,
 2361        position: DisplayPoint,
 2362        click_count: usize,
 2363        window: &mut Window,
 2364        cx: &mut Context<Self>,
 2365    ) {
 2366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2367        let tail = self.selections.newest::<usize>(cx).tail();
 2368        self.begin_selection(position, false, click_count, window, cx);
 2369
 2370        let position = position.to_offset(&display_map, Bias::Left);
 2371        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2372
 2373        let mut pending_selection = self
 2374            .selections
 2375            .pending_anchor()
 2376            .expect("extend_selection not called with pending selection");
 2377        if position >= tail {
 2378            pending_selection.start = tail_anchor;
 2379        } else {
 2380            pending_selection.end = tail_anchor;
 2381            pending_selection.reversed = true;
 2382        }
 2383
 2384        let mut pending_mode = self.selections.pending_mode().unwrap();
 2385        match &mut pending_mode {
 2386            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2387            _ => {}
 2388        }
 2389
 2390        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2391            s.set_pending(pending_selection, pending_mode)
 2392        });
 2393    }
 2394
 2395    fn begin_selection(
 2396        &mut self,
 2397        position: DisplayPoint,
 2398        add: bool,
 2399        click_count: usize,
 2400        window: &mut Window,
 2401        cx: &mut Context<Self>,
 2402    ) {
 2403        if !self.focus_handle.is_focused(window) {
 2404            self.last_focused_descendant = None;
 2405            window.focus(&self.focus_handle);
 2406        }
 2407
 2408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2409        let buffer = &display_map.buffer_snapshot;
 2410        let newest_selection = self.selections.newest_anchor().clone();
 2411        let position = display_map.clip_point(position, Bias::Left);
 2412
 2413        let start;
 2414        let end;
 2415        let mode;
 2416        let mut auto_scroll;
 2417        match click_count {
 2418            1 => {
 2419                start = buffer.anchor_before(position.to_point(&display_map));
 2420                end = start;
 2421                mode = SelectMode::Character;
 2422                auto_scroll = true;
 2423            }
 2424            2 => {
 2425                let range = movement::surrounding_word(&display_map, position);
 2426                start = buffer.anchor_before(range.start.to_point(&display_map));
 2427                end = buffer.anchor_before(range.end.to_point(&display_map));
 2428                mode = SelectMode::Word(start..end);
 2429                auto_scroll = true;
 2430            }
 2431            3 => {
 2432                let position = display_map
 2433                    .clip_point(position, Bias::Left)
 2434                    .to_point(&display_map);
 2435                let line_start = display_map.prev_line_boundary(position).0;
 2436                let next_line_start = buffer.clip_point(
 2437                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2438                    Bias::Left,
 2439                );
 2440                start = buffer.anchor_before(line_start);
 2441                end = buffer.anchor_before(next_line_start);
 2442                mode = SelectMode::Line(start..end);
 2443                auto_scroll = true;
 2444            }
 2445            _ => {
 2446                start = buffer.anchor_before(0);
 2447                end = buffer.anchor_before(buffer.len());
 2448                mode = SelectMode::All;
 2449                auto_scroll = false;
 2450            }
 2451        }
 2452        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2453
 2454        let point_to_delete: Option<usize> = {
 2455            let selected_points: Vec<Selection<Point>> =
 2456                self.selections.disjoint_in_range(start..end, cx);
 2457
 2458            if !add || click_count > 1 {
 2459                None
 2460            } else if !selected_points.is_empty() {
 2461                Some(selected_points[0].id)
 2462            } else {
 2463                let clicked_point_already_selected =
 2464                    self.selections.disjoint.iter().find(|selection| {
 2465                        selection.start.to_point(buffer) == start.to_point(buffer)
 2466                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2467                    });
 2468
 2469                clicked_point_already_selected.map(|selection| selection.id)
 2470            }
 2471        };
 2472
 2473        let selections_count = self.selections.count();
 2474
 2475        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2476            if let Some(point_to_delete) = point_to_delete {
 2477                s.delete(point_to_delete);
 2478
 2479                if selections_count == 1 {
 2480                    s.set_pending_anchor_range(start..end, mode);
 2481                }
 2482            } else {
 2483                if !add {
 2484                    s.clear_disjoint();
 2485                } else if click_count > 1 {
 2486                    s.delete(newest_selection.id)
 2487                }
 2488
 2489                s.set_pending_anchor_range(start..end, mode);
 2490            }
 2491        });
 2492    }
 2493
 2494    fn begin_columnar_selection(
 2495        &mut self,
 2496        position: DisplayPoint,
 2497        goal_column: u32,
 2498        reset: bool,
 2499        window: &mut Window,
 2500        cx: &mut Context<Self>,
 2501    ) {
 2502        if !self.focus_handle.is_focused(window) {
 2503            self.last_focused_descendant = None;
 2504            window.focus(&self.focus_handle);
 2505        }
 2506
 2507        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2508
 2509        if reset {
 2510            let pointer_position = display_map
 2511                .buffer_snapshot
 2512                .anchor_before(position.to_point(&display_map));
 2513
 2514            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2515                s.clear_disjoint();
 2516                s.set_pending_anchor_range(
 2517                    pointer_position..pointer_position,
 2518                    SelectMode::Character,
 2519                );
 2520            });
 2521        }
 2522
 2523        let tail = self.selections.newest::<Point>(cx).tail();
 2524        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2525
 2526        if !reset {
 2527            self.select_columns(
 2528                tail.to_display_point(&display_map),
 2529                position,
 2530                goal_column,
 2531                &display_map,
 2532                window,
 2533                cx,
 2534            );
 2535        }
 2536    }
 2537
 2538    fn update_selection(
 2539        &mut self,
 2540        position: DisplayPoint,
 2541        goal_column: u32,
 2542        scroll_delta: gpui::Point<f32>,
 2543        window: &mut Window,
 2544        cx: &mut Context<Self>,
 2545    ) {
 2546        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2547
 2548        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2549            let tail = tail.to_display_point(&display_map);
 2550            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2551        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2552            let buffer = self.buffer.read(cx).snapshot(cx);
 2553            let head;
 2554            let tail;
 2555            let mode = self.selections.pending_mode().unwrap();
 2556            match &mode {
 2557                SelectMode::Character => {
 2558                    head = position.to_point(&display_map);
 2559                    tail = pending.tail().to_point(&buffer);
 2560                }
 2561                SelectMode::Word(original_range) => {
 2562                    let original_display_range = original_range.start.to_display_point(&display_map)
 2563                        ..original_range.end.to_display_point(&display_map);
 2564                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2565                        ..original_display_range.end.to_point(&display_map);
 2566                    if movement::is_inside_word(&display_map, position)
 2567                        || original_display_range.contains(&position)
 2568                    {
 2569                        let word_range = movement::surrounding_word(&display_map, position);
 2570                        if word_range.start < original_display_range.start {
 2571                            head = word_range.start.to_point(&display_map);
 2572                        } else {
 2573                            head = word_range.end.to_point(&display_map);
 2574                        }
 2575                    } else {
 2576                        head = position.to_point(&display_map);
 2577                    }
 2578
 2579                    if head <= original_buffer_range.start {
 2580                        tail = original_buffer_range.end;
 2581                    } else {
 2582                        tail = original_buffer_range.start;
 2583                    }
 2584                }
 2585                SelectMode::Line(original_range) => {
 2586                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2587
 2588                    let position = display_map
 2589                        .clip_point(position, Bias::Left)
 2590                        .to_point(&display_map);
 2591                    let line_start = display_map.prev_line_boundary(position).0;
 2592                    let next_line_start = buffer.clip_point(
 2593                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2594                        Bias::Left,
 2595                    );
 2596
 2597                    if line_start < original_range.start {
 2598                        head = line_start
 2599                    } else {
 2600                        head = next_line_start
 2601                    }
 2602
 2603                    if head <= original_range.start {
 2604                        tail = original_range.end;
 2605                    } else {
 2606                        tail = original_range.start;
 2607                    }
 2608                }
 2609                SelectMode::All => {
 2610                    return;
 2611                }
 2612            };
 2613
 2614            if head < tail {
 2615                pending.start = buffer.anchor_before(head);
 2616                pending.end = buffer.anchor_before(tail);
 2617                pending.reversed = true;
 2618            } else {
 2619                pending.start = buffer.anchor_before(tail);
 2620                pending.end = buffer.anchor_before(head);
 2621                pending.reversed = false;
 2622            }
 2623
 2624            self.change_selections(None, window, cx, |s| {
 2625                s.set_pending(pending, mode);
 2626            });
 2627        } else {
 2628            log::error!("update_selection dispatched with no pending selection");
 2629            return;
 2630        }
 2631
 2632        self.apply_scroll_delta(scroll_delta, window, cx);
 2633        cx.notify();
 2634    }
 2635
 2636    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2637        self.columnar_selection_tail.take();
 2638        if self.selections.pending_anchor().is_some() {
 2639            let selections = self.selections.all::<usize>(cx);
 2640            self.change_selections(None, window, cx, |s| {
 2641                s.select(selections);
 2642                s.clear_pending();
 2643            });
 2644        }
 2645    }
 2646
 2647    fn select_columns(
 2648        &mut self,
 2649        tail: DisplayPoint,
 2650        head: DisplayPoint,
 2651        goal_column: u32,
 2652        display_map: &DisplaySnapshot,
 2653        window: &mut Window,
 2654        cx: &mut Context<Self>,
 2655    ) {
 2656        let start_row = cmp::min(tail.row(), head.row());
 2657        let end_row = cmp::max(tail.row(), head.row());
 2658        let start_column = cmp::min(tail.column(), goal_column);
 2659        let end_column = cmp::max(tail.column(), goal_column);
 2660        let reversed = start_column < tail.column();
 2661
 2662        let selection_ranges = (start_row.0..=end_row.0)
 2663            .map(DisplayRow)
 2664            .filter_map(|row| {
 2665                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2666                    let start = display_map
 2667                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2668                        .to_point(display_map);
 2669                    let end = display_map
 2670                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2671                        .to_point(display_map);
 2672                    if reversed {
 2673                        Some(end..start)
 2674                    } else {
 2675                        Some(start..end)
 2676                    }
 2677                } else {
 2678                    None
 2679                }
 2680            })
 2681            .collect::<Vec<_>>();
 2682
 2683        self.change_selections(None, window, cx, |s| {
 2684            s.select_ranges(selection_ranges);
 2685        });
 2686        cx.notify();
 2687    }
 2688
 2689    pub fn has_pending_nonempty_selection(&self) -> bool {
 2690        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2691            Some(Selection { start, end, .. }) => start != end,
 2692            None => false,
 2693        };
 2694
 2695        pending_nonempty_selection
 2696            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2697    }
 2698
 2699    pub fn has_pending_selection(&self) -> bool {
 2700        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2701    }
 2702
 2703    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2704        self.selection_mark_mode = false;
 2705
 2706        if self.clear_expanded_diff_hunks(cx) {
 2707            cx.notify();
 2708            return;
 2709        }
 2710        if self.dismiss_menus_and_popups(true, window, cx) {
 2711            return;
 2712        }
 2713
 2714        if self.mode == EditorMode::Full
 2715            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2716        {
 2717            return;
 2718        }
 2719
 2720        cx.propagate();
 2721    }
 2722
 2723    pub fn dismiss_menus_and_popups(
 2724        &mut self,
 2725        is_user_requested: bool,
 2726        window: &mut Window,
 2727        cx: &mut Context<Self>,
 2728    ) -> bool {
 2729        if self.take_rename(false, window, cx).is_some() {
 2730            return true;
 2731        }
 2732
 2733        if hide_hover(self, cx) {
 2734            return true;
 2735        }
 2736
 2737        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2738            return true;
 2739        }
 2740
 2741        if self.hide_context_menu(window, cx).is_some() {
 2742            return true;
 2743        }
 2744
 2745        if self.mouse_context_menu.take().is_some() {
 2746            return true;
 2747        }
 2748
 2749        if is_user_requested && self.discard_inline_completion(true, cx) {
 2750            return true;
 2751        }
 2752
 2753        if self.snippet_stack.pop().is_some() {
 2754            return true;
 2755        }
 2756
 2757        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2758            self.dismiss_diagnostics(cx);
 2759            return true;
 2760        }
 2761
 2762        false
 2763    }
 2764
 2765    fn linked_editing_ranges_for(
 2766        &self,
 2767        selection: Range<text::Anchor>,
 2768        cx: &App,
 2769    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2770        if self.linked_edit_ranges.is_empty() {
 2771            return None;
 2772        }
 2773        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2774            selection.end.buffer_id.and_then(|end_buffer_id| {
 2775                if selection.start.buffer_id != Some(end_buffer_id) {
 2776                    return None;
 2777                }
 2778                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2779                let snapshot = buffer.read(cx).snapshot();
 2780                self.linked_edit_ranges
 2781                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2782                    .map(|ranges| (ranges, snapshot, buffer))
 2783            })?;
 2784        use text::ToOffset as TO;
 2785        // find offset from the start of current range to current cursor position
 2786        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2787
 2788        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2789        let start_difference = start_offset - start_byte_offset;
 2790        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2791        let end_difference = end_offset - start_byte_offset;
 2792        // Current range has associated linked ranges.
 2793        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2794        for range in linked_ranges.iter() {
 2795            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2796            let end_offset = start_offset + end_difference;
 2797            let start_offset = start_offset + start_difference;
 2798            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2799                continue;
 2800            }
 2801            if self.selections.disjoint_anchor_ranges().any(|s| {
 2802                if s.start.buffer_id != selection.start.buffer_id
 2803                    || s.end.buffer_id != selection.end.buffer_id
 2804                {
 2805                    return false;
 2806                }
 2807                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2808                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2809            }) {
 2810                continue;
 2811            }
 2812            let start = buffer_snapshot.anchor_after(start_offset);
 2813            let end = buffer_snapshot.anchor_after(end_offset);
 2814            linked_edits
 2815                .entry(buffer.clone())
 2816                .or_default()
 2817                .push(start..end);
 2818        }
 2819        Some(linked_edits)
 2820    }
 2821
 2822    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2823        let text: Arc<str> = text.into();
 2824
 2825        if self.read_only(cx) {
 2826            return;
 2827        }
 2828
 2829        let selections = self.selections.all_adjusted(cx);
 2830        let mut bracket_inserted = false;
 2831        let mut edits = Vec::new();
 2832        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2833        let mut new_selections = Vec::with_capacity(selections.len());
 2834        let mut new_autoclose_regions = Vec::new();
 2835        let snapshot = self.buffer.read(cx).read(cx);
 2836
 2837        for (selection, autoclose_region) in
 2838            self.selections_with_autoclose_regions(selections, &snapshot)
 2839        {
 2840            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2841                // Determine if the inserted text matches the opening or closing
 2842                // bracket of any of this language's bracket pairs.
 2843                let mut bracket_pair = None;
 2844                let mut is_bracket_pair_start = false;
 2845                let mut is_bracket_pair_end = false;
 2846                if !text.is_empty() {
 2847                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2848                    //  and they are removing the character that triggered IME popup.
 2849                    for (pair, enabled) in scope.brackets() {
 2850                        if !pair.close && !pair.surround {
 2851                            continue;
 2852                        }
 2853
 2854                        if enabled && pair.start.ends_with(text.as_ref()) {
 2855                            let prefix_len = pair.start.len() - text.len();
 2856                            let preceding_text_matches_prefix = prefix_len == 0
 2857                                || (selection.start.column >= (prefix_len as u32)
 2858                                    && snapshot.contains_str_at(
 2859                                        Point::new(
 2860                                            selection.start.row,
 2861                                            selection.start.column - (prefix_len as u32),
 2862                                        ),
 2863                                        &pair.start[..prefix_len],
 2864                                    ));
 2865                            if preceding_text_matches_prefix {
 2866                                bracket_pair = Some(pair.clone());
 2867                                is_bracket_pair_start = true;
 2868                                break;
 2869                            }
 2870                        }
 2871                        if pair.end.as_str() == text.as_ref() {
 2872                            bracket_pair = Some(pair.clone());
 2873                            is_bracket_pair_end = true;
 2874                            break;
 2875                        }
 2876                    }
 2877                }
 2878
 2879                if let Some(bracket_pair) = bracket_pair {
 2880                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2881                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2882                    let auto_surround =
 2883                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2884                    if selection.is_empty() {
 2885                        if is_bracket_pair_start {
 2886                            // If the inserted text is a suffix of an opening bracket and the
 2887                            // selection is preceded by the rest of the opening bracket, then
 2888                            // insert the closing bracket.
 2889                            let following_text_allows_autoclose = snapshot
 2890                                .chars_at(selection.start)
 2891                                .next()
 2892                                .map_or(true, |c| scope.should_autoclose_before(c));
 2893
 2894                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2895                                && bracket_pair.start.len() == 1
 2896                            {
 2897                                let target = bracket_pair.start.chars().next().unwrap();
 2898                                let current_line_count = snapshot
 2899                                    .reversed_chars_at(selection.start)
 2900                                    .take_while(|&c| c != '\n')
 2901                                    .filter(|&c| c == target)
 2902                                    .count();
 2903                                current_line_count % 2 == 1
 2904                            } else {
 2905                                false
 2906                            };
 2907
 2908                            if autoclose
 2909                                && bracket_pair.close
 2910                                && following_text_allows_autoclose
 2911                                && !is_closing_quote
 2912                            {
 2913                                let anchor = snapshot.anchor_before(selection.end);
 2914                                new_selections.push((selection.map(|_| anchor), text.len()));
 2915                                new_autoclose_regions.push((
 2916                                    anchor,
 2917                                    text.len(),
 2918                                    selection.id,
 2919                                    bracket_pair.clone(),
 2920                                ));
 2921                                edits.push((
 2922                                    selection.range(),
 2923                                    format!("{}{}", text, bracket_pair.end).into(),
 2924                                ));
 2925                                bracket_inserted = true;
 2926                                continue;
 2927                            }
 2928                        }
 2929
 2930                        if let Some(region) = autoclose_region {
 2931                            // If the selection is followed by an auto-inserted closing bracket,
 2932                            // then don't insert that closing bracket again; just move the selection
 2933                            // past the closing bracket.
 2934                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2935                                && text.as_ref() == region.pair.end.as_str();
 2936                            if should_skip {
 2937                                let anchor = snapshot.anchor_after(selection.end);
 2938                                new_selections
 2939                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2940                                continue;
 2941                            }
 2942                        }
 2943
 2944                        let always_treat_brackets_as_autoclosed = snapshot
 2945                            .settings_at(selection.start, cx)
 2946                            .always_treat_brackets_as_autoclosed;
 2947                        if always_treat_brackets_as_autoclosed
 2948                            && is_bracket_pair_end
 2949                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2950                        {
 2951                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2952                            // and the inserted text is a closing bracket and the selection is followed
 2953                            // by the closing bracket then move the selection past the closing bracket.
 2954                            let anchor = snapshot.anchor_after(selection.end);
 2955                            new_selections.push((selection.map(|_| anchor), text.len()));
 2956                            continue;
 2957                        }
 2958                    }
 2959                    // If an opening bracket is 1 character long and is typed while
 2960                    // text is selected, then surround that text with the bracket pair.
 2961                    else if auto_surround
 2962                        && bracket_pair.surround
 2963                        && is_bracket_pair_start
 2964                        && bracket_pair.start.chars().count() == 1
 2965                    {
 2966                        edits.push((selection.start..selection.start, text.clone()));
 2967                        edits.push((
 2968                            selection.end..selection.end,
 2969                            bracket_pair.end.as_str().into(),
 2970                        ));
 2971                        bracket_inserted = true;
 2972                        new_selections.push((
 2973                            Selection {
 2974                                id: selection.id,
 2975                                start: snapshot.anchor_after(selection.start),
 2976                                end: snapshot.anchor_before(selection.end),
 2977                                reversed: selection.reversed,
 2978                                goal: selection.goal,
 2979                            },
 2980                            0,
 2981                        ));
 2982                        continue;
 2983                    }
 2984                }
 2985            }
 2986
 2987            if self.auto_replace_emoji_shortcode
 2988                && selection.is_empty()
 2989                && text.as_ref().ends_with(':')
 2990            {
 2991                if let Some(possible_emoji_short_code) =
 2992                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2993                {
 2994                    if !possible_emoji_short_code.is_empty() {
 2995                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2996                            let emoji_shortcode_start = Point::new(
 2997                                selection.start.row,
 2998                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2999                            );
 3000
 3001                            // Remove shortcode from buffer
 3002                            edits.push((
 3003                                emoji_shortcode_start..selection.start,
 3004                                "".to_string().into(),
 3005                            ));
 3006                            new_selections.push((
 3007                                Selection {
 3008                                    id: selection.id,
 3009                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3010                                    end: snapshot.anchor_before(selection.start),
 3011                                    reversed: selection.reversed,
 3012                                    goal: selection.goal,
 3013                                },
 3014                                0,
 3015                            ));
 3016
 3017                            // Insert emoji
 3018                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3019                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3020                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3021
 3022                            continue;
 3023                        }
 3024                    }
 3025                }
 3026            }
 3027
 3028            // If not handling any auto-close operation, then just replace the selected
 3029            // text with the given input and move the selection to the end of the
 3030            // newly inserted text.
 3031            let anchor = snapshot.anchor_after(selection.end);
 3032            if !self.linked_edit_ranges.is_empty() {
 3033                let start_anchor = snapshot.anchor_before(selection.start);
 3034
 3035                let is_word_char = text.chars().next().map_or(true, |char| {
 3036                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3037                    classifier.is_word(char)
 3038                });
 3039
 3040                if is_word_char {
 3041                    if let Some(ranges) = self
 3042                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3043                    {
 3044                        for (buffer, edits) in ranges {
 3045                            linked_edits
 3046                                .entry(buffer.clone())
 3047                                .or_default()
 3048                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3049                        }
 3050                    }
 3051                }
 3052            }
 3053
 3054            new_selections.push((selection.map(|_| anchor), 0));
 3055            edits.push((selection.start..selection.end, text.clone()));
 3056        }
 3057
 3058        drop(snapshot);
 3059
 3060        self.transact(window, cx, |this, window, cx| {
 3061            this.buffer.update(cx, |buffer, cx| {
 3062                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3063            });
 3064            for (buffer, edits) in linked_edits {
 3065                buffer.update(cx, |buffer, cx| {
 3066                    let snapshot = buffer.snapshot();
 3067                    let edits = edits
 3068                        .into_iter()
 3069                        .map(|(range, text)| {
 3070                            use text::ToPoint as TP;
 3071                            let end_point = TP::to_point(&range.end, &snapshot);
 3072                            let start_point = TP::to_point(&range.start, &snapshot);
 3073                            (start_point..end_point, text)
 3074                        })
 3075                        .sorted_by_key(|(range, _)| range.start)
 3076                        .collect::<Vec<_>>();
 3077                    buffer.edit(edits, None, cx);
 3078                })
 3079            }
 3080            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3081            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3082            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3083            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3084                .zip(new_selection_deltas)
 3085                .map(|(selection, delta)| Selection {
 3086                    id: selection.id,
 3087                    start: selection.start + delta,
 3088                    end: selection.end + delta,
 3089                    reversed: selection.reversed,
 3090                    goal: SelectionGoal::None,
 3091                })
 3092                .collect::<Vec<_>>();
 3093
 3094            let mut i = 0;
 3095            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3096                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3097                let start = map.buffer_snapshot.anchor_before(position);
 3098                let end = map.buffer_snapshot.anchor_after(position);
 3099                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3100                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3101                        Ordering::Less => i += 1,
 3102                        Ordering::Greater => break,
 3103                        Ordering::Equal => {
 3104                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3105                                Ordering::Less => i += 1,
 3106                                Ordering::Equal => break,
 3107                                Ordering::Greater => break,
 3108                            }
 3109                        }
 3110                    }
 3111                }
 3112                this.autoclose_regions.insert(
 3113                    i,
 3114                    AutocloseRegion {
 3115                        selection_id,
 3116                        range: start..end,
 3117                        pair,
 3118                    },
 3119                );
 3120            }
 3121
 3122            let had_active_inline_completion = this.has_active_inline_completion();
 3123            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3124                s.select(new_selections)
 3125            });
 3126
 3127            if !bracket_inserted {
 3128                if let Some(on_type_format_task) =
 3129                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3130                {
 3131                    on_type_format_task.detach_and_log_err(cx);
 3132                }
 3133            }
 3134
 3135            let editor_settings = EditorSettings::get_global(cx);
 3136            if bracket_inserted
 3137                && (editor_settings.auto_signature_help
 3138                    || editor_settings.show_signature_help_after_edits)
 3139            {
 3140                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3141            }
 3142
 3143            let trigger_in_words =
 3144                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3145            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3146            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3147            this.refresh_inline_completion(true, false, window, cx);
 3148        });
 3149    }
 3150
 3151    fn find_possible_emoji_shortcode_at_position(
 3152        snapshot: &MultiBufferSnapshot,
 3153        position: Point,
 3154    ) -> Option<String> {
 3155        let mut chars = Vec::new();
 3156        let mut found_colon = false;
 3157        for char in snapshot.reversed_chars_at(position).take(100) {
 3158            // Found a possible emoji shortcode in the middle of the buffer
 3159            if found_colon {
 3160                if char.is_whitespace() {
 3161                    chars.reverse();
 3162                    return Some(chars.iter().collect());
 3163                }
 3164                // If the previous character is not a whitespace, we are in the middle of a word
 3165                // and we only want to complete the shortcode if the word is made up of other emojis
 3166                let mut containing_word = String::new();
 3167                for ch in snapshot
 3168                    .reversed_chars_at(position)
 3169                    .skip(chars.len() + 1)
 3170                    .take(100)
 3171                {
 3172                    if ch.is_whitespace() {
 3173                        break;
 3174                    }
 3175                    containing_word.push(ch);
 3176                }
 3177                let containing_word = containing_word.chars().rev().collect::<String>();
 3178                if util::word_consists_of_emojis(containing_word.as_str()) {
 3179                    chars.reverse();
 3180                    return Some(chars.iter().collect());
 3181                }
 3182            }
 3183
 3184            if char.is_whitespace() || !char.is_ascii() {
 3185                return None;
 3186            }
 3187            if char == ':' {
 3188                found_colon = true;
 3189            } else {
 3190                chars.push(char);
 3191            }
 3192        }
 3193        // Found a possible emoji shortcode at the beginning of the buffer
 3194        chars.reverse();
 3195        Some(chars.iter().collect())
 3196    }
 3197
 3198    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3199        self.transact(window, cx, |this, window, cx| {
 3200            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3201                let selections = this.selections.all::<usize>(cx);
 3202                let multi_buffer = this.buffer.read(cx);
 3203                let buffer = multi_buffer.snapshot(cx);
 3204                selections
 3205                    .iter()
 3206                    .map(|selection| {
 3207                        let start_point = selection.start.to_point(&buffer);
 3208                        let mut indent =
 3209                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3210                        indent.len = cmp::min(indent.len, start_point.column);
 3211                        let start = selection.start;
 3212                        let end = selection.end;
 3213                        let selection_is_empty = start == end;
 3214                        let language_scope = buffer.language_scope_at(start);
 3215                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3216                            &language_scope
 3217                        {
 3218                            let insert_extra_newline =
 3219                                insert_extra_newline_brackets(&buffer, start..end, language)
 3220                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3221
 3222                            // Comment extension on newline is allowed only for cursor selections
 3223                            let comment_delimiter = maybe!({
 3224                                if !selection_is_empty {
 3225                                    return None;
 3226                                }
 3227
 3228                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3229                                    return None;
 3230                                }
 3231
 3232                                let delimiters = language.line_comment_prefixes();
 3233                                let max_len_of_delimiter =
 3234                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3235                                let (snapshot, range) =
 3236                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3237
 3238                                let mut index_of_first_non_whitespace = 0;
 3239                                let comment_candidate = snapshot
 3240                                    .chars_for_range(range)
 3241                                    .skip_while(|c| {
 3242                                        let should_skip = c.is_whitespace();
 3243                                        if should_skip {
 3244                                            index_of_first_non_whitespace += 1;
 3245                                        }
 3246                                        should_skip
 3247                                    })
 3248                                    .take(max_len_of_delimiter)
 3249                                    .collect::<String>();
 3250                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3251                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3252                                })?;
 3253                                let cursor_is_placed_after_comment_marker =
 3254                                    index_of_first_non_whitespace + comment_prefix.len()
 3255                                        <= start_point.column as usize;
 3256                                if cursor_is_placed_after_comment_marker {
 3257                                    Some(comment_prefix.clone())
 3258                                } else {
 3259                                    None
 3260                                }
 3261                            });
 3262                            (comment_delimiter, insert_extra_newline)
 3263                        } else {
 3264                            (None, false)
 3265                        };
 3266
 3267                        let capacity_for_delimiter = comment_delimiter
 3268                            .as_deref()
 3269                            .map(str::len)
 3270                            .unwrap_or_default();
 3271                        let mut new_text =
 3272                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3273                        new_text.push('\n');
 3274                        new_text.extend(indent.chars());
 3275                        if let Some(delimiter) = &comment_delimiter {
 3276                            new_text.push_str(delimiter);
 3277                        }
 3278                        if insert_extra_newline {
 3279                            new_text = new_text.repeat(2);
 3280                        }
 3281
 3282                        let anchor = buffer.anchor_after(end);
 3283                        let new_selection = selection.map(|_| anchor);
 3284                        (
 3285                            (start..end, new_text),
 3286                            (insert_extra_newline, new_selection),
 3287                        )
 3288                    })
 3289                    .unzip()
 3290            };
 3291
 3292            this.edit_with_autoindent(edits, cx);
 3293            let buffer = this.buffer.read(cx).snapshot(cx);
 3294            let new_selections = selection_fixup_info
 3295                .into_iter()
 3296                .map(|(extra_newline_inserted, new_selection)| {
 3297                    let mut cursor = new_selection.end.to_point(&buffer);
 3298                    if extra_newline_inserted {
 3299                        cursor.row -= 1;
 3300                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3301                    }
 3302                    new_selection.map(|_| cursor)
 3303                })
 3304                .collect();
 3305
 3306            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3307                s.select(new_selections)
 3308            });
 3309            this.refresh_inline_completion(true, false, window, cx);
 3310        });
 3311    }
 3312
 3313    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3314        let buffer = self.buffer.read(cx);
 3315        let snapshot = buffer.snapshot(cx);
 3316
 3317        let mut edits = Vec::new();
 3318        let mut rows = Vec::new();
 3319
 3320        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3321            let cursor = selection.head();
 3322            let row = cursor.row;
 3323
 3324            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3325
 3326            let newline = "\n".to_string();
 3327            edits.push((start_of_line..start_of_line, newline));
 3328
 3329            rows.push(row + rows_inserted as u32);
 3330        }
 3331
 3332        self.transact(window, cx, |editor, window, cx| {
 3333            editor.edit(edits, cx);
 3334
 3335            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3336                let mut index = 0;
 3337                s.move_cursors_with(|map, _, _| {
 3338                    let row = rows[index];
 3339                    index += 1;
 3340
 3341                    let point = Point::new(row, 0);
 3342                    let boundary = map.next_line_boundary(point).1;
 3343                    let clipped = map.clip_point(boundary, Bias::Left);
 3344
 3345                    (clipped, SelectionGoal::None)
 3346                });
 3347            });
 3348
 3349            let mut indent_edits = Vec::new();
 3350            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3351            for row in rows {
 3352                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3353                for (row, indent) in indents {
 3354                    if indent.len == 0 {
 3355                        continue;
 3356                    }
 3357
 3358                    let text = match indent.kind {
 3359                        IndentKind::Space => " ".repeat(indent.len as usize),
 3360                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3361                    };
 3362                    let point = Point::new(row.0, 0);
 3363                    indent_edits.push((point..point, text));
 3364                }
 3365            }
 3366            editor.edit(indent_edits, cx);
 3367        });
 3368    }
 3369
 3370    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3371        let buffer = self.buffer.read(cx);
 3372        let snapshot = buffer.snapshot(cx);
 3373
 3374        let mut edits = Vec::new();
 3375        let mut rows = Vec::new();
 3376        let mut rows_inserted = 0;
 3377
 3378        for selection in self.selections.all_adjusted(cx) {
 3379            let cursor = selection.head();
 3380            let row = cursor.row;
 3381
 3382            let point = Point::new(row + 1, 0);
 3383            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3384
 3385            let newline = "\n".to_string();
 3386            edits.push((start_of_line..start_of_line, newline));
 3387
 3388            rows_inserted += 1;
 3389            rows.push(row + rows_inserted);
 3390        }
 3391
 3392        self.transact(window, cx, |editor, window, cx| {
 3393            editor.edit(edits, cx);
 3394
 3395            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3396                let mut index = 0;
 3397                s.move_cursors_with(|map, _, _| {
 3398                    let row = rows[index];
 3399                    index += 1;
 3400
 3401                    let point = Point::new(row, 0);
 3402                    let boundary = map.next_line_boundary(point).1;
 3403                    let clipped = map.clip_point(boundary, Bias::Left);
 3404
 3405                    (clipped, SelectionGoal::None)
 3406                });
 3407            });
 3408
 3409            let mut indent_edits = Vec::new();
 3410            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3411            for row in rows {
 3412                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3413                for (row, indent) in indents {
 3414                    if indent.len == 0 {
 3415                        continue;
 3416                    }
 3417
 3418                    let text = match indent.kind {
 3419                        IndentKind::Space => " ".repeat(indent.len as usize),
 3420                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3421                    };
 3422                    let point = Point::new(row.0, 0);
 3423                    indent_edits.push((point..point, text));
 3424                }
 3425            }
 3426            editor.edit(indent_edits, cx);
 3427        });
 3428    }
 3429
 3430    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3431        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3432            original_start_columns: Vec::new(),
 3433        });
 3434        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3435    }
 3436
 3437    fn insert_with_autoindent_mode(
 3438        &mut self,
 3439        text: &str,
 3440        autoindent_mode: Option<AutoindentMode>,
 3441        window: &mut Window,
 3442        cx: &mut Context<Self>,
 3443    ) {
 3444        if self.read_only(cx) {
 3445            return;
 3446        }
 3447
 3448        let text: Arc<str> = text.into();
 3449        self.transact(window, cx, |this, window, cx| {
 3450            let old_selections = this.selections.all_adjusted(cx);
 3451            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3452                let anchors = {
 3453                    let snapshot = buffer.read(cx);
 3454                    old_selections
 3455                        .iter()
 3456                        .map(|s| {
 3457                            let anchor = snapshot.anchor_after(s.head());
 3458                            s.map(|_| anchor)
 3459                        })
 3460                        .collect::<Vec<_>>()
 3461                };
 3462                buffer.edit(
 3463                    old_selections
 3464                        .iter()
 3465                        .map(|s| (s.start..s.end, text.clone())),
 3466                    autoindent_mode,
 3467                    cx,
 3468                );
 3469                anchors
 3470            });
 3471
 3472            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3473                s.select_anchors(selection_anchors);
 3474            });
 3475
 3476            cx.notify();
 3477        });
 3478    }
 3479
 3480    fn trigger_completion_on_input(
 3481        &mut self,
 3482        text: &str,
 3483        trigger_in_words: bool,
 3484        window: &mut Window,
 3485        cx: &mut Context<Self>,
 3486    ) {
 3487        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3488            self.show_completions(
 3489                &ShowCompletions {
 3490                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3491                },
 3492                window,
 3493                cx,
 3494            );
 3495        } else {
 3496            self.hide_context_menu(window, cx);
 3497        }
 3498    }
 3499
 3500    fn is_completion_trigger(
 3501        &self,
 3502        text: &str,
 3503        trigger_in_words: bool,
 3504        cx: &mut Context<Self>,
 3505    ) -> bool {
 3506        let position = self.selections.newest_anchor().head();
 3507        let multibuffer = self.buffer.read(cx);
 3508        let Some(buffer) = position
 3509            .buffer_id
 3510            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3511        else {
 3512            return false;
 3513        };
 3514
 3515        if let Some(completion_provider) = &self.completion_provider {
 3516            completion_provider.is_completion_trigger(
 3517                &buffer,
 3518                position.text_anchor,
 3519                text,
 3520                trigger_in_words,
 3521                cx,
 3522            )
 3523        } else {
 3524            false
 3525        }
 3526    }
 3527
 3528    /// If any empty selections is touching the start of its innermost containing autoclose
 3529    /// region, expand it to select the brackets.
 3530    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3531        let selections = self.selections.all::<usize>(cx);
 3532        let buffer = self.buffer.read(cx).read(cx);
 3533        let new_selections = self
 3534            .selections_with_autoclose_regions(selections, &buffer)
 3535            .map(|(mut selection, region)| {
 3536                if !selection.is_empty() {
 3537                    return selection;
 3538                }
 3539
 3540                if let Some(region) = region {
 3541                    let mut range = region.range.to_offset(&buffer);
 3542                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3543                        range.start -= region.pair.start.len();
 3544                        if buffer.contains_str_at(range.start, &region.pair.start)
 3545                            && buffer.contains_str_at(range.end, &region.pair.end)
 3546                        {
 3547                            range.end += region.pair.end.len();
 3548                            selection.start = range.start;
 3549                            selection.end = range.end;
 3550
 3551                            return selection;
 3552                        }
 3553                    }
 3554                }
 3555
 3556                let always_treat_brackets_as_autoclosed = buffer
 3557                    .settings_at(selection.start, cx)
 3558                    .always_treat_brackets_as_autoclosed;
 3559
 3560                if !always_treat_brackets_as_autoclosed {
 3561                    return selection;
 3562                }
 3563
 3564                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3565                    for (pair, enabled) in scope.brackets() {
 3566                        if !enabled || !pair.close {
 3567                            continue;
 3568                        }
 3569
 3570                        if buffer.contains_str_at(selection.start, &pair.end) {
 3571                            let pair_start_len = pair.start.len();
 3572                            if buffer.contains_str_at(
 3573                                selection.start.saturating_sub(pair_start_len),
 3574                                &pair.start,
 3575                            ) {
 3576                                selection.start -= pair_start_len;
 3577                                selection.end += pair.end.len();
 3578
 3579                                return selection;
 3580                            }
 3581                        }
 3582                    }
 3583                }
 3584
 3585                selection
 3586            })
 3587            .collect();
 3588
 3589        drop(buffer);
 3590        self.change_selections(None, window, cx, |selections| {
 3591            selections.select(new_selections)
 3592        });
 3593    }
 3594
 3595    /// Iterate the given selections, and for each one, find the smallest surrounding
 3596    /// autoclose region. This uses the ordering of the selections and the autoclose
 3597    /// regions to avoid repeated comparisons.
 3598    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3599        &'a self,
 3600        selections: impl IntoIterator<Item = Selection<D>>,
 3601        buffer: &'a MultiBufferSnapshot,
 3602    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3603        let mut i = 0;
 3604        let mut regions = self.autoclose_regions.as_slice();
 3605        selections.into_iter().map(move |selection| {
 3606            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3607
 3608            let mut enclosing = None;
 3609            while let Some(pair_state) = regions.get(i) {
 3610                if pair_state.range.end.to_offset(buffer) < range.start {
 3611                    regions = &regions[i + 1..];
 3612                    i = 0;
 3613                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3614                    break;
 3615                } else {
 3616                    if pair_state.selection_id == selection.id {
 3617                        enclosing = Some(pair_state);
 3618                    }
 3619                    i += 1;
 3620                }
 3621            }
 3622
 3623            (selection, enclosing)
 3624        })
 3625    }
 3626
 3627    /// Remove any autoclose regions that no longer contain their selection.
 3628    fn invalidate_autoclose_regions(
 3629        &mut self,
 3630        mut selections: &[Selection<Anchor>],
 3631        buffer: &MultiBufferSnapshot,
 3632    ) {
 3633        self.autoclose_regions.retain(|state| {
 3634            let mut i = 0;
 3635            while let Some(selection) = selections.get(i) {
 3636                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3637                    selections = &selections[1..];
 3638                    continue;
 3639                }
 3640                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3641                    break;
 3642                }
 3643                if selection.id == state.selection_id {
 3644                    return true;
 3645                } else {
 3646                    i += 1;
 3647                }
 3648            }
 3649            false
 3650        });
 3651    }
 3652
 3653    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3654        let offset = position.to_offset(buffer);
 3655        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3656        if offset > word_range.start && kind == Some(CharKind::Word) {
 3657            Some(
 3658                buffer
 3659                    .text_for_range(word_range.start..offset)
 3660                    .collect::<String>(),
 3661            )
 3662        } else {
 3663            None
 3664        }
 3665    }
 3666
 3667    pub fn toggle_inlay_hints(
 3668        &mut self,
 3669        _: &ToggleInlayHints,
 3670        _: &mut Window,
 3671        cx: &mut Context<Self>,
 3672    ) {
 3673        self.refresh_inlay_hints(
 3674            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3675            cx,
 3676        );
 3677    }
 3678
 3679    pub fn inlay_hints_enabled(&self) -> bool {
 3680        self.inlay_hint_cache.enabled
 3681    }
 3682
 3683    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3684        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3685            return;
 3686        }
 3687
 3688        let reason_description = reason.description();
 3689        let ignore_debounce = matches!(
 3690            reason,
 3691            InlayHintRefreshReason::SettingsChange(_)
 3692                | InlayHintRefreshReason::Toggle(_)
 3693                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3694                | InlayHintRefreshReason::ModifiersChanged(_)
 3695        );
 3696        let (invalidate_cache, required_languages) = match reason {
 3697            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3698                match self.inlay_hint_cache.modifiers_override(enabled) {
 3699                    Some(enabled) => {
 3700                        if enabled {
 3701                            (InvalidationStrategy::RefreshRequested, None)
 3702                        } else {
 3703                            self.splice_inlays(
 3704                                &self
 3705                                    .visible_inlay_hints(cx)
 3706                                    .iter()
 3707                                    .map(|inlay| inlay.id)
 3708                                    .collect::<Vec<InlayId>>(),
 3709                                Vec::new(),
 3710                                cx,
 3711                            );
 3712                            return;
 3713                        }
 3714                    }
 3715                    None => return,
 3716                }
 3717            }
 3718            InlayHintRefreshReason::Toggle(enabled) => {
 3719                if self.inlay_hint_cache.toggle(enabled) {
 3720                    if enabled {
 3721                        (InvalidationStrategy::RefreshRequested, None)
 3722                    } else {
 3723                        self.splice_inlays(
 3724                            &self
 3725                                .visible_inlay_hints(cx)
 3726                                .iter()
 3727                                .map(|inlay| inlay.id)
 3728                                .collect::<Vec<InlayId>>(),
 3729                            Vec::new(),
 3730                            cx,
 3731                        );
 3732                        return;
 3733                    }
 3734                } else {
 3735                    return;
 3736                }
 3737            }
 3738            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3739                match self.inlay_hint_cache.update_settings(
 3740                    &self.buffer,
 3741                    new_settings,
 3742                    self.visible_inlay_hints(cx),
 3743                    cx,
 3744                ) {
 3745                    ControlFlow::Break(Some(InlaySplice {
 3746                        to_remove,
 3747                        to_insert,
 3748                    })) => {
 3749                        self.splice_inlays(&to_remove, to_insert, cx);
 3750                        return;
 3751                    }
 3752                    ControlFlow::Break(None) => return,
 3753                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3754                }
 3755            }
 3756            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3757                if let Some(InlaySplice {
 3758                    to_remove,
 3759                    to_insert,
 3760                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3761                {
 3762                    self.splice_inlays(&to_remove, to_insert, cx);
 3763                }
 3764                return;
 3765            }
 3766            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3767            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3768                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3769            }
 3770            InlayHintRefreshReason::RefreshRequested => {
 3771                (InvalidationStrategy::RefreshRequested, None)
 3772            }
 3773        };
 3774
 3775        if let Some(InlaySplice {
 3776            to_remove,
 3777            to_insert,
 3778        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3779            reason_description,
 3780            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3781            invalidate_cache,
 3782            ignore_debounce,
 3783            cx,
 3784        ) {
 3785            self.splice_inlays(&to_remove, to_insert, cx);
 3786        }
 3787    }
 3788
 3789    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3790        self.display_map
 3791            .read(cx)
 3792            .current_inlays()
 3793            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3794            .cloned()
 3795            .collect()
 3796    }
 3797
 3798    pub fn excerpts_for_inlay_hints_query(
 3799        &self,
 3800        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3801        cx: &mut Context<Editor>,
 3802    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3803        let Some(project) = self.project.as_ref() else {
 3804            return HashMap::default();
 3805        };
 3806        let project = project.read(cx);
 3807        let multi_buffer = self.buffer().read(cx);
 3808        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3809        let multi_buffer_visible_start = self
 3810            .scroll_manager
 3811            .anchor()
 3812            .anchor
 3813            .to_point(&multi_buffer_snapshot);
 3814        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3815            multi_buffer_visible_start
 3816                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3817            Bias::Left,
 3818        );
 3819        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3820        multi_buffer_snapshot
 3821            .range_to_buffer_ranges(multi_buffer_visible_range)
 3822            .into_iter()
 3823            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3824            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3825                let buffer_file = project::File::from_dyn(buffer.file())?;
 3826                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3827                let worktree_entry = buffer_worktree
 3828                    .read(cx)
 3829                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3830                if worktree_entry.is_ignored {
 3831                    return None;
 3832                }
 3833
 3834                let language = buffer.language()?;
 3835                if let Some(restrict_to_languages) = restrict_to_languages {
 3836                    if !restrict_to_languages.contains(language) {
 3837                        return None;
 3838                    }
 3839                }
 3840                Some((
 3841                    excerpt_id,
 3842                    (
 3843                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3844                        buffer.version().clone(),
 3845                        excerpt_visible_range,
 3846                    ),
 3847                ))
 3848            })
 3849            .collect()
 3850    }
 3851
 3852    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3853        TextLayoutDetails {
 3854            text_system: window.text_system().clone(),
 3855            editor_style: self.style.clone().unwrap(),
 3856            rem_size: window.rem_size(),
 3857            scroll_anchor: self.scroll_manager.anchor(),
 3858            visible_rows: self.visible_line_count(),
 3859            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3860        }
 3861    }
 3862
 3863    pub fn splice_inlays(
 3864        &self,
 3865        to_remove: &[InlayId],
 3866        to_insert: Vec<Inlay>,
 3867        cx: &mut Context<Self>,
 3868    ) {
 3869        self.display_map.update(cx, |display_map, cx| {
 3870            display_map.splice_inlays(to_remove, to_insert, cx)
 3871        });
 3872        cx.notify();
 3873    }
 3874
 3875    fn trigger_on_type_formatting(
 3876        &self,
 3877        input: String,
 3878        window: &mut Window,
 3879        cx: &mut Context<Self>,
 3880    ) -> Option<Task<Result<()>>> {
 3881        if input.len() != 1 {
 3882            return None;
 3883        }
 3884
 3885        let project = self.project.as_ref()?;
 3886        let position = self.selections.newest_anchor().head();
 3887        let (buffer, buffer_position) = self
 3888            .buffer
 3889            .read(cx)
 3890            .text_anchor_for_position(position, cx)?;
 3891
 3892        let settings = language_settings::language_settings(
 3893            buffer
 3894                .read(cx)
 3895                .language_at(buffer_position)
 3896                .map(|l| l.name()),
 3897            buffer.read(cx).file(),
 3898            cx,
 3899        );
 3900        if !settings.use_on_type_format {
 3901            return None;
 3902        }
 3903
 3904        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3905        // hence we do LSP request & edit on host side only — add formats to host's history.
 3906        let push_to_lsp_host_history = true;
 3907        // If this is not the host, append its history with new edits.
 3908        let push_to_client_history = project.read(cx).is_via_collab();
 3909
 3910        let on_type_formatting = project.update(cx, |project, cx| {
 3911            project.on_type_format(
 3912                buffer.clone(),
 3913                buffer_position,
 3914                input,
 3915                push_to_lsp_host_history,
 3916                cx,
 3917            )
 3918        });
 3919        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3920            if let Some(transaction) = on_type_formatting.await? {
 3921                if push_to_client_history {
 3922                    buffer
 3923                        .update(&mut cx, |buffer, _| {
 3924                            buffer.push_transaction(transaction, Instant::now());
 3925                        })
 3926                        .ok();
 3927                }
 3928                editor.update(&mut cx, |editor, cx| {
 3929                    editor.refresh_document_highlights(cx);
 3930                })?;
 3931            }
 3932            Ok(())
 3933        }))
 3934    }
 3935
 3936    pub fn show_completions(
 3937        &mut self,
 3938        options: &ShowCompletions,
 3939        window: &mut Window,
 3940        cx: &mut Context<Self>,
 3941    ) {
 3942        if self.pending_rename.is_some() {
 3943            return;
 3944        }
 3945
 3946        let Some(provider) = self.completion_provider.as_ref() else {
 3947            return;
 3948        };
 3949
 3950        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3951            return;
 3952        }
 3953
 3954        let position = self.selections.newest_anchor().head();
 3955        if position.diff_base_anchor.is_some() {
 3956            return;
 3957        }
 3958        let (buffer, buffer_position) =
 3959            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3960                output
 3961            } else {
 3962                return;
 3963            };
 3964        let show_completion_documentation = buffer
 3965            .read(cx)
 3966            .snapshot()
 3967            .settings_at(buffer_position, cx)
 3968            .show_completion_documentation;
 3969
 3970        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3971
 3972        let trigger_kind = match &options.trigger {
 3973            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3974                CompletionTriggerKind::TRIGGER_CHARACTER
 3975            }
 3976            _ => CompletionTriggerKind::INVOKED,
 3977        };
 3978        let completion_context = CompletionContext {
 3979            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3980                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3981                    Some(String::from(trigger))
 3982                } else {
 3983                    None
 3984                }
 3985            }),
 3986            trigger_kind,
 3987        };
 3988        let completions =
 3989            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3990        let sort_completions = provider.sort_completions();
 3991
 3992        let id = post_inc(&mut self.next_completion_id);
 3993        let task = cx.spawn_in(window, |editor, mut cx| {
 3994            async move {
 3995                editor.update(&mut cx, |this, _| {
 3996                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3997                })?;
 3998                let completions = completions.await.log_err();
 3999                let menu = if let Some(completions) = completions {
 4000                    let mut menu = CompletionsMenu::new(
 4001                        id,
 4002                        sort_completions,
 4003                        show_completion_documentation,
 4004                        position,
 4005                        buffer.clone(),
 4006                        completions.into(),
 4007                    );
 4008
 4009                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4010                        .await;
 4011
 4012                    menu.visible().then_some(menu)
 4013                } else {
 4014                    None
 4015                };
 4016
 4017                editor.update_in(&mut cx, |editor, window, cx| {
 4018                    match editor.context_menu.borrow().as_ref() {
 4019                        None => {}
 4020                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4021                            if prev_menu.id > id {
 4022                                return;
 4023                            }
 4024                        }
 4025                        _ => return,
 4026                    }
 4027
 4028                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4029                        let mut menu = menu.unwrap();
 4030                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4031
 4032                        *editor.context_menu.borrow_mut() =
 4033                            Some(CodeContextMenu::Completions(menu));
 4034
 4035                        if editor.show_edit_predictions_in_menu() {
 4036                            editor.update_visible_inline_completion(window, cx);
 4037                        } else {
 4038                            editor.discard_inline_completion(false, cx);
 4039                        }
 4040
 4041                        cx.notify();
 4042                    } else if editor.completion_tasks.len() <= 1 {
 4043                        // If there are no more completion tasks and the last menu was
 4044                        // empty, we should hide it.
 4045                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4046                        // If it was already hidden and we don't show inline
 4047                        // completions in the menu, we should also show the
 4048                        // inline-completion when available.
 4049                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4050                            editor.update_visible_inline_completion(window, cx);
 4051                        }
 4052                    }
 4053                })?;
 4054
 4055                Ok::<_, anyhow::Error>(())
 4056            }
 4057            .log_err()
 4058        });
 4059
 4060        self.completion_tasks.push((id, task));
 4061    }
 4062
 4063    pub fn confirm_completion(
 4064        &mut self,
 4065        action: &ConfirmCompletion,
 4066        window: &mut Window,
 4067        cx: &mut Context<Self>,
 4068    ) -> Option<Task<Result<()>>> {
 4069        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4070    }
 4071
 4072    pub fn compose_completion(
 4073        &mut self,
 4074        action: &ComposeCompletion,
 4075        window: &mut Window,
 4076        cx: &mut Context<Self>,
 4077    ) -> Option<Task<Result<()>>> {
 4078        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4079    }
 4080
 4081    fn do_completion(
 4082        &mut self,
 4083        item_ix: Option<usize>,
 4084        intent: CompletionIntent,
 4085        window: &mut Window,
 4086        cx: &mut Context<Editor>,
 4087    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4088        use language::ToOffset as _;
 4089
 4090        let completions_menu =
 4091            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4092                menu
 4093            } else {
 4094                return None;
 4095            };
 4096
 4097        let entries = completions_menu.entries.borrow();
 4098        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4099        if self.show_edit_predictions_in_menu() {
 4100            self.discard_inline_completion(true, cx);
 4101        }
 4102        let candidate_id = mat.candidate_id;
 4103        drop(entries);
 4104
 4105        let buffer_handle = completions_menu.buffer;
 4106        let completion = completions_menu
 4107            .completions
 4108            .borrow()
 4109            .get(candidate_id)?
 4110            .clone();
 4111        cx.stop_propagation();
 4112
 4113        let snippet;
 4114        let text;
 4115
 4116        if completion.is_snippet() {
 4117            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4118            text = snippet.as_ref().unwrap().text.clone();
 4119        } else {
 4120            snippet = None;
 4121            text = completion.new_text.clone();
 4122        };
 4123        let selections = self.selections.all::<usize>(cx);
 4124        let buffer = buffer_handle.read(cx);
 4125        let old_range = completion.old_range.to_offset(buffer);
 4126        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4127
 4128        let newest_selection = self.selections.newest_anchor();
 4129        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4130            return None;
 4131        }
 4132
 4133        let lookbehind = newest_selection
 4134            .start
 4135            .text_anchor
 4136            .to_offset(buffer)
 4137            .saturating_sub(old_range.start);
 4138        let lookahead = old_range
 4139            .end
 4140            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4141        let mut common_prefix_len = old_text
 4142            .bytes()
 4143            .zip(text.bytes())
 4144            .take_while(|(a, b)| a == b)
 4145            .count();
 4146
 4147        let snapshot = self.buffer.read(cx).snapshot(cx);
 4148        let mut range_to_replace: Option<Range<isize>> = None;
 4149        let mut ranges = Vec::new();
 4150        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4151        for selection in &selections {
 4152            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4153                let start = selection.start.saturating_sub(lookbehind);
 4154                let end = selection.end + lookahead;
 4155                if selection.id == newest_selection.id {
 4156                    range_to_replace = Some(
 4157                        ((start + common_prefix_len) as isize - selection.start as isize)
 4158                            ..(end as isize - selection.start as isize),
 4159                    );
 4160                }
 4161                ranges.push(start + common_prefix_len..end);
 4162            } else {
 4163                common_prefix_len = 0;
 4164                ranges.clear();
 4165                ranges.extend(selections.iter().map(|s| {
 4166                    if s.id == newest_selection.id {
 4167                        range_to_replace = Some(
 4168                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4169                                - selection.start as isize
 4170                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4171                                    - selection.start as isize,
 4172                        );
 4173                        old_range.clone()
 4174                    } else {
 4175                        s.start..s.end
 4176                    }
 4177                }));
 4178                break;
 4179            }
 4180            if !self.linked_edit_ranges.is_empty() {
 4181                let start_anchor = snapshot.anchor_before(selection.head());
 4182                let end_anchor = snapshot.anchor_after(selection.tail());
 4183                if let Some(ranges) = self
 4184                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4185                {
 4186                    for (buffer, edits) in ranges {
 4187                        linked_edits.entry(buffer.clone()).or_default().extend(
 4188                            edits
 4189                                .into_iter()
 4190                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4191                        );
 4192                    }
 4193                }
 4194            }
 4195        }
 4196        let text = &text[common_prefix_len..];
 4197
 4198        cx.emit(EditorEvent::InputHandled {
 4199            utf16_range_to_replace: range_to_replace,
 4200            text: text.into(),
 4201        });
 4202
 4203        self.transact(window, cx, |this, window, cx| {
 4204            if let Some(mut snippet) = snippet {
 4205                snippet.text = text.to_string();
 4206                for tabstop in snippet
 4207                    .tabstops
 4208                    .iter_mut()
 4209                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4210                {
 4211                    tabstop.start -= common_prefix_len as isize;
 4212                    tabstop.end -= common_prefix_len as isize;
 4213                }
 4214
 4215                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4216            } else {
 4217                this.buffer.update(cx, |buffer, cx| {
 4218                    buffer.edit(
 4219                        ranges.iter().map(|range| (range.clone(), text)),
 4220                        this.autoindent_mode.clone(),
 4221                        cx,
 4222                    );
 4223                });
 4224            }
 4225            for (buffer, edits) in linked_edits {
 4226                buffer.update(cx, |buffer, cx| {
 4227                    let snapshot = buffer.snapshot();
 4228                    let edits = edits
 4229                        .into_iter()
 4230                        .map(|(range, text)| {
 4231                            use text::ToPoint as TP;
 4232                            let end_point = TP::to_point(&range.end, &snapshot);
 4233                            let start_point = TP::to_point(&range.start, &snapshot);
 4234                            (start_point..end_point, text)
 4235                        })
 4236                        .sorted_by_key(|(range, _)| range.start)
 4237                        .collect::<Vec<_>>();
 4238                    buffer.edit(edits, None, cx);
 4239                })
 4240            }
 4241
 4242            this.refresh_inline_completion(true, false, window, cx);
 4243        });
 4244
 4245        let show_new_completions_on_confirm = completion
 4246            .confirm
 4247            .as_ref()
 4248            .map_or(false, |confirm| confirm(intent, window, cx));
 4249        if show_new_completions_on_confirm {
 4250            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4251        }
 4252
 4253        let provider = self.completion_provider.as_ref()?;
 4254        drop(completion);
 4255        let apply_edits = provider.apply_additional_edits_for_completion(
 4256            buffer_handle,
 4257            completions_menu.completions.clone(),
 4258            candidate_id,
 4259            true,
 4260            cx,
 4261        );
 4262
 4263        let editor_settings = EditorSettings::get_global(cx);
 4264        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4265            // After the code completion is finished, users often want to know what signatures are needed.
 4266            // so we should automatically call signature_help
 4267            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4268        }
 4269
 4270        Some(cx.foreground_executor().spawn(async move {
 4271            apply_edits.await?;
 4272            Ok(())
 4273        }))
 4274    }
 4275
 4276    pub fn toggle_code_actions(
 4277        &mut self,
 4278        action: &ToggleCodeActions,
 4279        window: &mut Window,
 4280        cx: &mut Context<Self>,
 4281    ) {
 4282        let mut context_menu = self.context_menu.borrow_mut();
 4283        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4284            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4285                // Toggle if we're selecting the same one
 4286                *context_menu = None;
 4287                cx.notify();
 4288                return;
 4289            } else {
 4290                // Otherwise, clear it and start a new one
 4291                *context_menu = None;
 4292                cx.notify();
 4293            }
 4294        }
 4295        drop(context_menu);
 4296        let snapshot = self.snapshot(window, cx);
 4297        let deployed_from_indicator = action.deployed_from_indicator;
 4298        let mut task = self.code_actions_task.take();
 4299        let action = action.clone();
 4300        cx.spawn_in(window, |editor, mut cx| async move {
 4301            while let Some(prev_task) = task {
 4302                prev_task.await.log_err();
 4303                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4304            }
 4305
 4306            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4307                if editor.focus_handle.is_focused(window) {
 4308                    let multibuffer_point = action
 4309                        .deployed_from_indicator
 4310                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4311                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4312                    let (buffer, buffer_row) = snapshot
 4313                        .buffer_snapshot
 4314                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4315                        .and_then(|(buffer_snapshot, range)| {
 4316                            editor
 4317                                .buffer
 4318                                .read(cx)
 4319                                .buffer(buffer_snapshot.remote_id())
 4320                                .map(|buffer| (buffer, range.start.row))
 4321                        })?;
 4322                    let (_, code_actions) = editor
 4323                        .available_code_actions
 4324                        .clone()
 4325                        .and_then(|(location, code_actions)| {
 4326                            let snapshot = location.buffer.read(cx).snapshot();
 4327                            let point_range = location.range.to_point(&snapshot);
 4328                            let point_range = point_range.start.row..=point_range.end.row;
 4329                            if point_range.contains(&buffer_row) {
 4330                                Some((location, code_actions))
 4331                            } else {
 4332                                None
 4333                            }
 4334                        })
 4335                        .unzip();
 4336                    let buffer_id = buffer.read(cx).remote_id();
 4337                    let tasks = editor
 4338                        .tasks
 4339                        .get(&(buffer_id, buffer_row))
 4340                        .map(|t| Arc::new(t.to_owned()));
 4341                    if tasks.is_none() && code_actions.is_none() {
 4342                        return None;
 4343                    }
 4344
 4345                    editor.completion_tasks.clear();
 4346                    editor.discard_inline_completion(false, cx);
 4347                    let task_context =
 4348                        tasks
 4349                            .as_ref()
 4350                            .zip(editor.project.clone())
 4351                            .map(|(tasks, project)| {
 4352                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4353                            });
 4354
 4355                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4356                        let task_context = match task_context {
 4357                            Some(task_context) => task_context.await,
 4358                            None => None,
 4359                        };
 4360                        let resolved_tasks =
 4361                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4362                                Rc::new(ResolvedTasks {
 4363                                    templates: tasks.resolve(&task_context).collect(),
 4364                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4365                                        multibuffer_point.row,
 4366                                        tasks.column,
 4367                                    )),
 4368                                })
 4369                            });
 4370                        let spawn_straight_away = resolved_tasks
 4371                            .as_ref()
 4372                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4373                            && code_actions
 4374                                .as_ref()
 4375                                .map_or(true, |actions| actions.is_empty());
 4376                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4377                            *editor.context_menu.borrow_mut() =
 4378                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4379                                    buffer,
 4380                                    actions: CodeActionContents {
 4381                                        tasks: resolved_tasks,
 4382                                        actions: code_actions,
 4383                                    },
 4384                                    selected_item: Default::default(),
 4385                                    scroll_handle: UniformListScrollHandle::default(),
 4386                                    deployed_from_indicator,
 4387                                }));
 4388                            if spawn_straight_away {
 4389                                if let Some(task) = editor.confirm_code_action(
 4390                                    &ConfirmCodeAction { item_ix: Some(0) },
 4391                                    window,
 4392                                    cx,
 4393                                ) {
 4394                                    cx.notify();
 4395                                    return task;
 4396                                }
 4397                            }
 4398                            cx.notify();
 4399                            Task::ready(Ok(()))
 4400                        }) {
 4401                            task.await
 4402                        } else {
 4403                            Ok(())
 4404                        }
 4405                    }))
 4406                } else {
 4407                    Some(Task::ready(Ok(())))
 4408                }
 4409            })?;
 4410            if let Some(task) = spawned_test_task {
 4411                task.await?;
 4412            }
 4413
 4414            Ok::<_, anyhow::Error>(())
 4415        })
 4416        .detach_and_log_err(cx);
 4417    }
 4418
 4419    pub fn confirm_code_action(
 4420        &mut self,
 4421        action: &ConfirmCodeAction,
 4422        window: &mut Window,
 4423        cx: &mut Context<Self>,
 4424    ) -> Option<Task<Result<()>>> {
 4425        let actions_menu =
 4426            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4427                menu
 4428            } else {
 4429                return None;
 4430            };
 4431        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4432        let action = actions_menu.actions.get(action_ix)?;
 4433        let title = action.label();
 4434        let buffer = actions_menu.buffer;
 4435        let workspace = self.workspace()?;
 4436
 4437        match action {
 4438            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4439                workspace.update(cx, |workspace, cx| {
 4440                    workspace::tasks::schedule_resolved_task(
 4441                        workspace,
 4442                        task_source_kind,
 4443                        resolved_task,
 4444                        false,
 4445                        cx,
 4446                    );
 4447
 4448                    Some(Task::ready(Ok(())))
 4449                })
 4450            }
 4451            CodeActionsItem::CodeAction {
 4452                excerpt_id,
 4453                action,
 4454                provider,
 4455            } => {
 4456                let apply_code_action =
 4457                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4458                let workspace = workspace.downgrade();
 4459                Some(cx.spawn_in(window, |editor, cx| async move {
 4460                    let project_transaction = apply_code_action.await?;
 4461                    Self::open_project_transaction(
 4462                        &editor,
 4463                        workspace,
 4464                        project_transaction,
 4465                        title,
 4466                        cx,
 4467                    )
 4468                    .await
 4469                }))
 4470            }
 4471        }
 4472    }
 4473
 4474    pub async fn open_project_transaction(
 4475        this: &WeakEntity<Editor>,
 4476        workspace: WeakEntity<Workspace>,
 4477        transaction: ProjectTransaction,
 4478        title: String,
 4479        mut cx: AsyncWindowContext,
 4480    ) -> Result<()> {
 4481        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4482        cx.update(|_, cx| {
 4483            entries.sort_unstable_by_key(|(buffer, _)| {
 4484                buffer.read(cx).file().map(|f| f.path().clone())
 4485            });
 4486        })?;
 4487
 4488        // If the project transaction's edits are all contained within this editor, then
 4489        // avoid opening a new editor to display them.
 4490
 4491        if let Some((buffer, transaction)) = entries.first() {
 4492            if entries.len() == 1 {
 4493                let excerpt = this.update(&mut cx, |editor, cx| {
 4494                    editor
 4495                        .buffer()
 4496                        .read(cx)
 4497                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4498                })?;
 4499                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4500                    if excerpted_buffer == *buffer {
 4501                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4502                            let excerpt_range = excerpt_range.to_offset(buffer);
 4503                            buffer
 4504                                .edited_ranges_for_transaction::<usize>(transaction)
 4505                                .all(|range| {
 4506                                    excerpt_range.start <= range.start
 4507                                        && excerpt_range.end >= range.end
 4508                                })
 4509                        })?;
 4510
 4511                        if all_edits_within_excerpt {
 4512                            return Ok(());
 4513                        }
 4514                    }
 4515                }
 4516            }
 4517        } else {
 4518            return Ok(());
 4519        }
 4520
 4521        let mut ranges_to_highlight = Vec::new();
 4522        let excerpt_buffer = cx.new(|cx| {
 4523            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4524            for (buffer_handle, transaction) in &entries {
 4525                let buffer = buffer_handle.read(cx);
 4526                ranges_to_highlight.extend(
 4527                    multibuffer.push_excerpts_with_context_lines(
 4528                        buffer_handle.clone(),
 4529                        buffer
 4530                            .edited_ranges_for_transaction::<usize>(transaction)
 4531                            .collect(),
 4532                        DEFAULT_MULTIBUFFER_CONTEXT,
 4533                        cx,
 4534                    ),
 4535                );
 4536            }
 4537            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4538            multibuffer
 4539        })?;
 4540
 4541        workspace.update_in(&mut cx, |workspace, window, cx| {
 4542            let project = workspace.project().clone();
 4543            let editor = cx
 4544                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4545            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4546            editor.update(cx, |editor, cx| {
 4547                editor.highlight_background::<Self>(
 4548                    &ranges_to_highlight,
 4549                    |theme| theme.editor_highlighted_line_background,
 4550                    cx,
 4551                );
 4552            });
 4553        })?;
 4554
 4555        Ok(())
 4556    }
 4557
 4558    pub fn clear_code_action_providers(&mut self) {
 4559        self.code_action_providers.clear();
 4560        self.available_code_actions.take();
 4561    }
 4562
 4563    pub fn add_code_action_provider(
 4564        &mut self,
 4565        provider: Rc<dyn CodeActionProvider>,
 4566        window: &mut Window,
 4567        cx: &mut Context<Self>,
 4568    ) {
 4569        if self
 4570            .code_action_providers
 4571            .iter()
 4572            .any(|existing_provider| existing_provider.id() == provider.id())
 4573        {
 4574            return;
 4575        }
 4576
 4577        self.code_action_providers.push(provider);
 4578        self.refresh_code_actions(window, cx);
 4579    }
 4580
 4581    pub fn remove_code_action_provider(
 4582        &mut self,
 4583        id: Arc<str>,
 4584        window: &mut Window,
 4585        cx: &mut Context<Self>,
 4586    ) {
 4587        self.code_action_providers
 4588            .retain(|provider| provider.id() != id);
 4589        self.refresh_code_actions(window, cx);
 4590    }
 4591
 4592    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4593        let buffer = self.buffer.read(cx);
 4594        let newest_selection = self.selections.newest_anchor().clone();
 4595        if newest_selection.head().diff_base_anchor.is_some() {
 4596            return None;
 4597        }
 4598        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4599        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4600        if start_buffer != end_buffer {
 4601            return None;
 4602        }
 4603
 4604        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4605            cx.background_executor()
 4606                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4607                .await;
 4608
 4609            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4610                let providers = this.code_action_providers.clone();
 4611                let tasks = this
 4612                    .code_action_providers
 4613                    .iter()
 4614                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4615                    .collect::<Vec<_>>();
 4616                (providers, tasks)
 4617            })?;
 4618
 4619            let mut actions = Vec::new();
 4620            for (provider, provider_actions) in
 4621                providers.into_iter().zip(future::join_all(tasks).await)
 4622            {
 4623                if let Some(provider_actions) = provider_actions.log_err() {
 4624                    actions.extend(provider_actions.into_iter().map(|action| {
 4625                        AvailableCodeAction {
 4626                            excerpt_id: newest_selection.start.excerpt_id,
 4627                            action,
 4628                            provider: provider.clone(),
 4629                        }
 4630                    }));
 4631                }
 4632            }
 4633
 4634            this.update(&mut cx, |this, cx| {
 4635                this.available_code_actions = if actions.is_empty() {
 4636                    None
 4637                } else {
 4638                    Some((
 4639                        Location {
 4640                            buffer: start_buffer,
 4641                            range: start..end,
 4642                        },
 4643                        actions.into(),
 4644                    ))
 4645                };
 4646                cx.notify();
 4647            })
 4648        }));
 4649        None
 4650    }
 4651
 4652    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4653        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4654            self.show_git_blame_inline = false;
 4655
 4656            self.show_git_blame_inline_delay_task =
 4657                Some(cx.spawn_in(window, |this, mut cx| async move {
 4658                    cx.background_executor().timer(delay).await;
 4659
 4660                    this.update(&mut cx, |this, cx| {
 4661                        this.show_git_blame_inline = true;
 4662                        cx.notify();
 4663                    })
 4664                    .log_err();
 4665                }));
 4666        }
 4667    }
 4668
 4669    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4670        if self.pending_rename.is_some() {
 4671            return None;
 4672        }
 4673
 4674        let provider = self.semantics_provider.clone()?;
 4675        let buffer = self.buffer.read(cx);
 4676        let newest_selection = self.selections.newest_anchor().clone();
 4677        let cursor_position = newest_selection.head();
 4678        let (cursor_buffer, cursor_buffer_position) =
 4679            buffer.text_anchor_for_position(cursor_position, cx)?;
 4680        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4681        if cursor_buffer != tail_buffer {
 4682            return None;
 4683        }
 4684        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4685        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4686            cx.background_executor()
 4687                .timer(Duration::from_millis(debounce))
 4688                .await;
 4689
 4690            let highlights = if let Some(highlights) = cx
 4691                .update(|cx| {
 4692                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4693                })
 4694                .ok()
 4695                .flatten()
 4696            {
 4697                highlights.await.log_err()
 4698            } else {
 4699                None
 4700            };
 4701
 4702            if let Some(highlights) = highlights {
 4703                this.update(&mut cx, |this, cx| {
 4704                    if this.pending_rename.is_some() {
 4705                        return;
 4706                    }
 4707
 4708                    let buffer_id = cursor_position.buffer_id;
 4709                    let buffer = this.buffer.read(cx);
 4710                    if !buffer
 4711                        .text_anchor_for_position(cursor_position, cx)
 4712                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4713                    {
 4714                        return;
 4715                    }
 4716
 4717                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4718                    let mut write_ranges = Vec::new();
 4719                    let mut read_ranges = Vec::new();
 4720                    for highlight in highlights {
 4721                        for (excerpt_id, excerpt_range) in
 4722                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4723                        {
 4724                            let start = highlight
 4725                                .range
 4726                                .start
 4727                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4728                            let end = highlight
 4729                                .range
 4730                                .end
 4731                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4732                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4733                                continue;
 4734                            }
 4735
 4736                            let range = Anchor {
 4737                                buffer_id,
 4738                                excerpt_id,
 4739                                text_anchor: start,
 4740                                diff_base_anchor: None,
 4741                            }..Anchor {
 4742                                buffer_id,
 4743                                excerpt_id,
 4744                                text_anchor: end,
 4745                                diff_base_anchor: None,
 4746                            };
 4747                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4748                                write_ranges.push(range);
 4749                            } else {
 4750                                read_ranges.push(range);
 4751                            }
 4752                        }
 4753                    }
 4754
 4755                    this.highlight_background::<DocumentHighlightRead>(
 4756                        &read_ranges,
 4757                        |theme| theme.editor_document_highlight_read_background,
 4758                        cx,
 4759                    );
 4760                    this.highlight_background::<DocumentHighlightWrite>(
 4761                        &write_ranges,
 4762                        |theme| theme.editor_document_highlight_write_background,
 4763                        cx,
 4764                    );
 4765                    cx.notify();
 4766                })
 4767                .log_err();
 4768            }
 4769        }));
 4770        None
 4771    }
 4772
 4773    pub fn refresh_selected_text_highlights(
 4774        &mut self,
 4775        window: &mut Window,
 4776        cx: &mut Context<Editor>,
 4777    ) {
 4778        self.selection_highlight_task.take();
 4779        if !EditorSettings::get_global(cx).selection_highlight {
 4780            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4781            return;
 4782        }
 4783        if self.selections.count() != 1 || self.selections.line_mode {
 4784            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4785            return;
 4786        }
 4787        let selection = self.selections.newest::<Point>(cx);
 4788        if selection.is_empty() || selection.start.row != selection.end.row {
 4789            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4790            return;
 4791        }
 4792        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4793        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4794            cx.background_executor()
 4795                .timer(Duration::from_millis(debounce))
 4796                .await;
 4797            let Some(Some(matches_task)) = editor
 4798                .update_in(&mut cx, |editor, _, cx| {
 4799                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4800                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4801                        return None;
 4802                    }
 4803                    let selection = editor.selections.newest::<Point>(cx);
 4804                    if selection.is_empty() || selection.start.row != selection.end.row {
 4805                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4806                        return None;
 4807                    }
 4808                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4809                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4810                    if query.trim().is_empty() {
 4811                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4812                        return None;
 4813                    }
 4814                    Some(cx.background_spawn(async move {
 4815                        let mut ranges = Vec::new();
 4816                        let selection_anchors = selection.range().to_anchors(&buffer);
 4817                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4818                            for (search_buffer, search_range, excerpt_id) in
 4819                                buffer.range_to_buffer_ranges(range)
 4820                            {
 4821                                ranges.extend(
 4822                                    project::search::SearchQuery::text(
 4823                                        query.clone(),
 4824                                        false,
 4825                                        false,
 4826                                        false,
 4827                                        Default::default(),
 4828                                        Default::default(),
 4829                                        None,
 4830                                    )
 4831                                    .unwrap()
 4832                                    .search(search_buffer, Some(search_range.clone()))
 4833                                    .await
 4834                                    .into_iter()
 4835                                    .filter_map(
 4836                                        |match_range| {
 4837                                            let start = search_buffer.anchor_after(
 4838                                                search_range.start + match_range.start,
 4839                                            );
 4840                                            let end = search_buffer.anchor_before(
 4841                                                search_range.start + match_range.end,
 4842                                            );
 4843                                            let range = Anchor::range_in_buffer(
 4844                                                excerpt_id,
 4845                                                search_buffer.remote_id(),
 4846                                                start..end,
 4847                                            );
 4848                                            (range != selection_anchors).then_some(range)
 4849                                        },
 4850                                    ),
 4851                                );
 4852                            }
 4853                        }
 4854                        ranges
 4855                    }))
 4856                })
 4857                .log_err()
 4858            else {
 4859                return;
 4860            };
 4861            let matches = matches_task.await;
 4862            editor
 4863                .update_in(&mut cx, |editor, _, cx| {
 4864                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4865                    if !matches.is_empty() {
 4866                        editor.highlight_background::<SelectedTextHighlight>(
 4867                            &matches,
 4868                            |theme| theme.editor_document_highlight_bracket_background,
 4869                            cx,
 4870                        )
 4871                    }
 4872                })
 4873                .log_err();
 4874        }));
 4875    }
 4876
 4877    pub fn refresh_inline_completion(
 4878        &mut self,
 4879        debounce: bool,
 4880        user_requested: bool,
 4881        window: &mut Window,
 4882        cx: &mut Context<Self>,
 4883    ) -> Option<()> {
 4884        let provider = self.edit_prediction_provider()?;
 4885        let cursor = self.selections.newest_anchor().head();
 4886        let (buffer, cursor_buffer_position) =
 4887            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4888
 4889        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4890            self.discard_inline_completion(false, cx);
 4891            return None;
 4892        }
 4893
 4894        if !user_requested
 4895            && (!self.should_show_edit_predictions()
 4896                || !self.is_focused(window)
 4897                || buffer.read(cx).is_empty())
 4898        {
 4899            self.discard_inline_completion(false, cx);
 4900            return None;
 4901        }
 4902
 4903        self.update_visible_inline_completion(window, cx);
 4904        provider.refresh(
 4905            self.project.clone(),
 4906            buffer,
 4907            cursor_buffer_position,
 4908            debounce,
 4909            cx,
 4910        );
 4911        Some(())
 4912    }
 4913
 4914    fn show_edit_predictions_in_menu(&self) -> bool {
 4915        match self.edit_prediction_settings {
 4916            EditPredictionSettings::Disabled => false,
 4917            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4918        }
 4919    }
 4920
 4921    pub fn edit_predictions_enabled(&self) -> bool {
 4922        match self.edit_prediction_settings {
 4923            EditPredictionSettings::Disabled => false,
 4924            EditPredictionSettings::Enabled { .. } => true,
 4925        }
 4926    }
 4927
 4928    fn edit_prediction_requires_modifier(&self) -> bool {
 4929        match self.edit_prediction_settings {
 4930            EditPredictionSettings::Disabled => false,
 4931            EditPredictionSettings::Enabled {
 4932                preview_requires_modifier,
 4933                ..
 4934            } => preview_requires_modifier,
 4935        }
 4936    }
 4937
 4938    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4939        if self.edit_prediction_provider.is_none() {
 4940            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4941        } else {
 4942            let selection = self.selections.newest_anchor();
 4943            let cursor = selection.head();
 4944
 4945            if let Some((buffer, cursor_buffer_position)) =
 4946                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4947            {
 4948                self.edit_prediction_settings =
 4949                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4950            }
 4951        }
 4952    }
 4953
 4954    fn edit_prediction_settings_at_position(
 4955        &self,
 4956        buffer: &Entity<Buffer>,
 4957        buffer_position: language::Anchor,
 4958        cx: &App,
 4959    ) -> EditPredictionSettings {
 4960        if self.mode != EditorMode::Full
 4961            || !self.show_inline_completions_override.unwrap_or(true)
 4962            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4963        {
 4964            return EditPredictionSettings::Disabled;
 4965        }
 4966
 4967        let buffer = buffer.read(cx);
 4968
 4969        let file = buffer.file();
 4970
 4971        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4972            return EditPredictionSettings::Disabled;
 4973        };
 4974
 4975        let by_provider = matches!(
 4976            self.menu_inline_completions_policy,
 4977            MenuInlineCompletionsPolicy::ByProvider
 4978        );
 4979
 4980        let show_in_menu = by_provider
 4981            && self
 4982                .edit_prediction_provider
 4983                .as_ref()
 4984                .map_or(false, |provider| {
 4985                    provider.provider.show_completions_in_menu()
 4986                });
 4987
 4988        let preview_requires_modifier =
 4989            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 4990
 4991        EditPredictionSettings::Enabled {
 4992            show_in_menu,
 4993            preview_requires_modifier,
 4994        }
 4995    }
 4996
 4997    fn should_show_edit_predictions(&self) -> bool {
 4998        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4999    }
 5000
 5001    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5002        matches!(
 5003            self.edit_prediction_preview,
 5004            EditPredictionPreview::Active { .. }
 5005        )
 5006    }
 5007
 5008    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5009        let cursor = self.selections.newest_anchor().head();
 5010        if let Some((buffer, cursor_position)) =
 5011            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5012        {
 5013            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5014        } else {
 5015            false
 5016        }
 5017    }
 5018
 5019    fn edit_predictions_enabled_in_buffer(
 5020        &self,
 5021        buffer: &Entity<Buffer>,
 5022        buffer_position: language::Anchor,
 5023        cx: &App,
 5024    ) -> bool {
 5025        maybe!({
 5026            let provider = self.edit_prediction_provider()?;
 5027            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5028                return Some(false);
 5029            }
 5030            let buffer = buffer.read(cx);
 5031            let Some(file) = buffer.file() else {
 5032                return Some(true);
 5033            };
 5034            let settings = all_language_settings(Some(file), cx);
 5035            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5036        })
 5037        .unwrap_or(false)
 5038    }
 5039
 5040    fn cycle_inline_completion(
 5041        &mut self,
 5042        direction: Direction,
 5043        window: &mut Window,
 5044        cx: &mut Context<Self>,
 5045    ) -> Option<()> {
 5046        let provider = self.edit_prediction_provider()?;
 5047        let cursor = self.selections.newest_anchor().head();
 5048        let (buffer, cursor_buffer_position) =
 5049            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5050        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5051            return None;
 5052        }
 5053
 5054        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5055        self.update_visible_inline_completion(window, cx);
 5056
 5057        Some(())
 5058    }
 5059
 5060    pub fn show_inline_completion(
 5061        &mut self,
 5062        _: &ShowEditPrediction,
 5063        window: &mut Window,
 5064        cx: &mut Context<Self>,
 5065    ) {
 5066        if !self.has_active_inline_completion() {
 5067            self.refresh_inline_completion(false, true, window, cx);
 5068            return;
 5069        }
 5070
 5071        self.update_visible_inline_completion(window, cx);
 5072    }
 5073
 5074    pub fn display_cursor_names(
 5075        &mut self,
 5076        _: &DisplayCursorNames,
 5077        window: &mut Window,
 5078        cx: &mut Context<Self>,
 5079    ) {
 5080        self.show_cursor_names(window, cx);
 5081    }
 5082
 5083    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5084        self.show_cursor_names = true;
 5085        cx.notify();
 5086        cx.spawn_in(window, |this, mut cx| async move {
 5087            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5088            this.update(&mut cx, |this, cx| {
 5089                this.show_cursor_names = false;
 5090                cx.notify()
 5091            })
 5092            .ok()
 5093        })
 5094        .detach();
 5095    }
 5096
 5097    pub fn next_edit_prediction(
 5098        &mut self,
 5099        _: &NextEditPrediction,
 5100        window: &mut Window,
 5101        cx: &mut Context<Self>,
 5102    ) {
 5103        if self.has_active_inline_completion() {
 5104            self.cycle_inline_completion(Direction::Next, window, cx);
 5105        } else {
 5106            let is_copilot_disabled = self
 5107                .refresh_inline_completion(false, true, window, cx)
 5108                .is_none();
 5109            if is_copilot_disabled {
 5110                cx.propagate();
 5111            }
 5112        }
 5113    }
 5114
 5115    pub fn previous_edit_prediction(
 5116        &mut self,
 5117        _: &PreviousEditPrediction,
 5118        window: &mut Window,
 5119        cx: &mut Context<Self>,
 5120    ) {
 5121        if self.has_active_inline_completion() {
 5122            self.cycle_inline_completion(Direction::Prev, window, cx);
 5123        } else {
 5124            let is_copilot_disabled = self
 5125                .refresh_inline_completion(false, true, window, cx)
 5126                .is_none();
 5127            if is_copilot_disabled {
 5128                cx.propagate();
 5129            }
 5130        }
 5131    }
 5132
 5133    pub fn accept_edit_prediction(
 5134        &mut self,
 5135        _: &AcceptEditPrediction,
 5136        window: &mut Window,
 5137        cx: &mut Context<Self>,
 5138    ) {
 5139        if self.show_edit_predictions_in_menu() {
 5140            self.hide_context_menu(window, cx);
 5141        }
 5142
 5143        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5144            return;
 5145        };
 5146
 5147        self.report_inline_completion_event(
 5148            active_inline_completion.completion_id.clone(),
 5149            true,
 5150            cx,
 5151        );
 5152
 5153        match &active_inline_completion.completion {
 5154            InlineCompletion::Move { target, .. } => {
 5155                let target = *target;
 5156
 5157                if let Some(position_map) = &self.last_position_map {
 5158                    if position_map
 5159                        .visible_row_range
 5160                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5161                        || !self.edit_prediction_requires_modifier()
 5162                    {
 5163                        self.unfold_ranges(&[target..target], true, false, cx);
 5164                        // Note that this is also done in vim's handler of the Tab action.
 5165                        self.change_selections(
 5166                            Some(Autoscroll::newest()),
 5167                            window,
 5168                            cx,
 5169                            |selections| {
 5170                                selections.select_anchor_ranges([target..target]);
 5171                            },
 5172                        );
 5173                        self.clear_row_highlights::<EditPredictionPreview>();
 5174
 5175                        self.edit_prediction_preview
 5176                            .set_previous_scroll_position(None);
 5177                    } else {
 5178                        self.edit_prediction_preview
 5179                            .set_previous_scroll_position(Some(
 5180                                position_map.snapshot.scroll_anchor,
 5181                            ));
 5182
 5183                        self.highlight_rows::<EditPredictionPreview>(
 5184                            target..target,
 5185                            cx.theme().colors().editor_highlighted_line_background,
 5186                            true,
 5187                            cx,
 5188                        );
 5189                        self.request_autoscroll(Autoscroll::fit(), cx);
 5190                    }
 5191                }
 5192            }
 5193            InlineCompletion::Edit { edits, .. } => {
 5194                if let Some(provider) = self.edit_prediction_provider() {
 5195                    provider.accept(cx);
 5196                }
 5197
 5198                let snapshot = self.buffer.read(cx).snapshot(cx);
 5199                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5200
 5201                self.buffer.update(cx, |buffer, cx| {
 5202                    buffer.edit(edits.iter().cloned(), None, cx)
 5203                });
 5204
 5205                self.change_selections(None, window, cx, |s| {
 5206                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5207                });
 5208
 5209                self.update_visible_inline_completion(window, cx);
 5210                if self.active_inline_completion.is_none() {
 5211                    self.refresh_inline_completion(true, true, window, cx);
 5212                }
 5213
 5214                cx.notify();
 5215            }
 5216        }
 5217
 5218        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5219    }
 5220
 5221    pub fn accept_partial_inline_completion(
 5222        &mut self,
 5223        _: &AcceptPartialEditPrediction,
 5224        window: &mut Window,
 5225        cx: &mut Context<Self>,
 5226    ) {
 5227        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5228            return;
 5229        };
 5230        if self.selections.count() != 1 {
 5231            return;
 5232        }
 5233
 5234        self.report_inline_completion_event(
 5235            active_inline_completion.completion_id.clone(),
 5236            true,
 5237            cx,
 5238        );
 5239
 5240        match &active_inline_completion.completion {
 5241            InlineCompletion::Move { target, .. } => {
 5242                let target = *target;
 5243                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5244                    selections.select_anchor_ranges([target..target]);
 5245                });
 5246            }
 5247            InlineCompletion::Edit { edits, .. } => {
 5248                // Find an insertion that starts at the cursor position.
 5249                let snapshot = self.buffer.read(cx).snapshot(cx);
 5250                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5251                let insertion = edits.iter().find_map(|(range, text)| {
 5252                    let range = range.to_offset(&snapshot);
 5253                    if range.is_empty() && range.start == cursor_offset {
 5254                        Some(text)
 5255                    } else {
 5256                        None
 5257                    }
 5258                });
 5259
 5260                if let Some(text) = insertion {
 5261                    let mut partial_completion = text
 5262                        .chars()
 5263                        .by_ref()
 5264                        .take_while(|c| c.is_alphabetic())
 5265                        .collect::<String>();
 5266                    if partial_completion.is_empty() {
 5267                        partial_completion = text
 5268                            .chars()
 5269                            .by_ref()
 5270                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5271                            .collect::<String>();
 5272                    }
 5273
 5274                    cx.emit(EditorEvent::InputHandled {
 5275                        utf16_range_to_replace: None,
 5276                        text: partial_completion.clone().into(),
 5277                    });
 5278
 5279                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5280
 5281                    self.refresh_inline_completion(true, true, window, cx);
 5282                    cx.notify();
 5283                } else {
 5284                    self.accept_edit_prediction(&Default::default(), window, cx);
 5285                }
 5286            }
 5287        }
 5288    }
 5289
 5290    fn discard_inline_completion(
 5291        &mut self,
 5292        should_report_inline_completion_event: bool,
 5293        cx: &mut Context<Self>,
 5294    ) -> bool {
 5295        if should_report_inline_completion_event {
 5296            let completion_id = self
 5297                .active_inline_completion
 5298                .as_ref()
 5299                .and_then(|active_completion| active_completion.completion_id.clone());
 5300
 5301            self.report_inline_completion_event(completion_id, false, cx);
 5302        }
 5303
 5304        if let Some(provider) = self.edit_prediction_provider() {
 5305            provider.discard(cx);
 5306        }
 5307
 5308        self.take_active_inline_completion(cx)
 5309    }
 5310
 5311    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5312        let Some(provider) = self.edit_prediction_provider() else {
 5313            return;
 5314        };
 5315
 5316        let Some((_, buffer, _)) = self
 5317            .buffer
 5318            .read(cx)
 5319            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5320        else {
 5321            return;
 5322        };
 5323
 5324        let extension = buffer
 5325            .read(cx)
 5326            .file()
 5327            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5328
 5329        let event_type = match accepted {
 5330            true => "Edit Prediction Accepted",
 5331            false => "Edit Prediction Discarded",
 5332        };
 5333        telemetry::event!(
 5334            event_type,
 5335            provider = provider.name(),
 5336            prediction_id = id,
 5337            suggestion_accepted = accepted,
 5338            file_extension = extension,
 5339        );
 5340    }
 5341
 5342    pub fn has_active_inline_completion(&self) -> bool {
 5343        self.active_inline_completion.is_some()
 5344    }
 5345
 5346    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5347        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5348            return false;
 5349        };
 5350
 5351        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5352        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5353        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5354        true
 5355    }
 5356
 5357    /// Returns true when we're displaying the edit prediction popover below the cursor
 5358    /// like we are not previewing and the LSP autocomplete menu is visible
 5359    /// or we are in `when_holding_modifier` mode.
 5360    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5361        if self.edit_prediction_preview_is_active()
 5362            || !self.show_edit_predictions_in_menu()
 5363            || !self.edit_predictions_enabled()
 5364        {
 5365            return false;
 5366        }
 5367
 5368        if self.has_visible_completions_menu() {
 5369            return true;
 5370        }
 5371
 5372        has_completion && self.edit_prediction_requires_modifier()
 5373    }
 5374
 5375    fn handle_modifiers_changed(
 5376        &mut self,
 5377        modifiers: Modifiers,
 5378        position_map: &PositionMap,
 5379        window: &mut Window,
 5380        cx: &mut Context<Self>,
 5381    ) {
 5382        if self.show_edit_predictions_in_menu() {
 5383            self.update_edit_prediction_preview(&modifiers, window, cx);
 5384        }
 5385
 5386        self.update_selection_mode(&modifiers, position_map, window, cx);
 5387
 5388        let mouse_position = window.mouse_position();
 5389        if !position_map.text_hitbox.is_hovered(window) {
 5390            return;
 5391        }
 5392
 5393        self.update_hovered_link(
 5394            position_map.point_for_position(mouse_position),
 5395            &position_map.snapshot,
 5396            modifiers,
 5397            window,
 5398            cx,
 5399        )
 5400    }
 5401
 5402    fn update_selection_mode(
 5403        &mut self,
 5404        modifiers: &Modifiers,
 5405        position_map: &PositionMap,
 5406        window: &mut Window,
 5407        cx: &mut Context<Self>,
 5408    ) {
 5409        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5410            return;
 5411        }
 5412
 5413        let mouse_position = window.mouse_position();
 5414        let point_for_position = position_map.point_for_position(mouse_position);
 5415        let position = point_for_position.previous_valid;
 5416
 5417        self.select(
 5418            SelectPhase::BeginColumnar {
 5419                position,
 5420                reset: false,
 5421                goal_column: point_for_position.exact_unclipped.column(),
 5422            },
 5423            window,
 5424            cx,
 5425        );
 5426    }
 5427
 5428    fn update_edit_prediction_preview(
 5429        &mut self,
 5430        modifiers: &Modifiers,
 5431        window: &mut Window,
 5432        cx: &mut Context<Self>,
 5433    ) {
 5434        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5435        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5436            return;
 5437        };
 5438
 5439        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5440            if matches!(
 5441                self.edit_prediction_preview,
 5442                EditPredictionPreview::Inactive { .. }
 5443            ) {
 5444                self.edit_prediction_preview = EditPredictionPreview::Active {
 5445                    previous_scroll_position: None,
 5446                    since: Instant::now(),
 5447                };
 5448
 5449                self.update_visible_inline_completion(window, cx);
 5450                cx.notify();
 5451            }
 5452        } else if let EditPredictionPreview::Active {
 5453            previous_scroll_position,
 5454            since,
 5455        } = self.edit_prediction_preview
 5456        {
 5457            if let (Some(previous_scroll_position), Some(position_map)) =
 5458                (previous_scroll_position, self.last_position_map.as_ref())
 5459            {
 5460                self.set_scroll_position(
 5461                    previous_scroll_position
 5462                        .scroll_position(&position_map.snapshot.display_snapshot),
 5463                    window,
 5464                    cx,
 5465                );
 5466            }
 5467
 5468            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5469                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5470            };
 5471            self.clear_row_highlights::<EditPredictionPreview>();
 5472            self.update_visible_inline_completion(window, cx);
 5473            cx.notify();
 5474        }
 5475    }
 5476
 5477    fn update_visible_inline_completion(
 5478        &mut self,
 5479        _window: &mut Window,
 5480        cx: &mut Context<Self>,
 5481    ) -> Option<()> {
 5482        let selection = self.selections.newest_anchor();
 5483        let cursor = selection.head();
 5484        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5485        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5486        let excerpt_id = cursor.excerpt_id;
 5487
 5488        let show_in_menu = self.show_edit_predictions_in_menu();
 5489        let completions_menu_has_precedence = !show_in_menu
 5490            && (self.context_menu.borrow().is_some()
 5491                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5492
 5493        if completions_menu_has_precedence
 5494            || !offset_selection.is_empty()
 5495            || self
 5496                .active_inline_completion
 5497                .as_ref()
 5498                .map_or(false, |completion| {
 5499                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5500                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5501                    !invalidation_range.contains(&offset_selection.head())
 5502                })
 5503        {
 5504            self.discard_inline_completion(false, cx);
 5505            return None;
 5506        }
 5507
 5508        self.take_active_inline_completion(cx);
 5509        let Some(provider) = self.edit_prediction_provider() else {
 5510            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5511            return None;
 5512        };
 5513
 5514        let (buffer, cursor_buffer_position) =
 5515            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5516
 5517        self.edit_prediction_settings =
 5518            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5519
 5520        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5521
 5522        if self.edit_prediction_indent_conflict {
 5523            let cursor_point = cursor.to_point(&multibuffer);
 5524
 5525            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5526
 5527            if let Some((_, indent)) = indents.iter().next() {
 5528                if indent.len == cursor_point.column {
 5529                    self.edit_prediction_indent_conflict = false;
 5530                }
 5531            }
 5532        }
 5533
 5534        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5535        let edits = inline_completion
 5536            .edits
 5537            .into_iter()
 5538            .flat_map(|(range, new_text)| {
 5539                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5540                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5541                Some((start..end, new_text))
 5542            })
 5543            .collect::<Vec<_>>();
 5544        if edits.is_empty() {
 5545            return None;
 5546        }
 5547
 5548        let first_edit_start = edits.first().unwrap().0.start;
 5549        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5550        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5551
 5552        let last_edit_end = edits.last().unwrap().0.end;
 5553        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5554        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5555
 5556        let cursor_row = cursor.to_point(&multibuffer).row;
 5557
 5558        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5559
 5560        let mut inlay_ids = Vec::new();
 5561        let invalidation_row_range;
 5562        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5563            Some(cursor_row..edit_end_row)
 5564        } else if cursor_row > edit_end_row {
 5565            Some(edit_start_row..cursor_row)
 5566        } else {
 5567            None
 5568        };
 5569        let is_move =
 5570            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5571        let completion = if is_move {
 5572            invalidation_row_range =
 5573                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5574            let target = first_edit_start;
 5575            InlineCompletion::Move { target, snapshot }
 5576        } else {
 5577            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5578                && !self.inline_completions_hidden_for_vim_mode;
 5579
 5580            if show_completions_in_buffer {
 5581                if edits
 5582                    .iter()
 5583                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5584                {
 5585                    let mut inlays = Vec::new();
 5586                    for (range, new_text) in &edits {
 5587                        let inlay = Inlay::inline_completion(
 5588                            post_inc(&mut self.next_inlay_id),
 5589                            range.start,
 5590                            new_text.as_str(),
 5591                        );
 5592                        inlay_ids.push(inlay.id);
 5593                        inlays.push(inlay);
 5594                    }
 5595
 5596                    self.splice_inlays(&[], inlays, cx);
 5597                } else {
 5598                    let background_color = cx.theme().status().deleted_background;
 5599                    self.highlight_text::<InlineCompletionHighlight>(
 5600                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5601                        HighlightStyle {
 5602                            background_color: Some(background_color),
 5603                            ..Default::default()
 5604                        },
 5605                        cx,
 5606                    );
 5607                }
 5608            }
 5609
 5610            invalidation_row_range = edit_start_row..edit_end_row;
 5611
 5612            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5613                if provider.show_tab_accept_marker() {
 5614                    EditDisplayMode::TabAccept
 5615                } else {
 5616                    EditDisplayMode::Inline
 5617                }
 5618            } else {
 5619                EditDisplayMode::DiffPopover
 5620            };
 5621
 5622            InlineCompletion::Edit {
 5623                edits,
 5624                edit_preview: inline_completion.edit_preview,
 5625                display_mode,
 5626                snapshot,
 5627            }
 5628        };
 5629
 5630        let invalidation_range = multibuffer
 5631            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5632            ..multibuffer.anchor_after(Point::new(
 5633                invalidation_row_range.end,
 5634                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5635            ));
 5636
 5637        self.stale_inline_completion_in_menu = None;
 5638        self.active_inline_completion = Some(InlineCompletionState {
 5639            inlay_ids,
 5640            completion,
 5641            completion_id: inline_completion.id,
 5642            invalidation_range,
 5643        });
 5644
 5645        cx.notify();
 5646
 5647        Some(())
 5648    }
 5649
 5650    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5651        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5652    }
 5653
 5654    fn render_code_actions_indicator(
 5655        &self,
 5656        _style: &EditorStyle,
 5657        row: DisplayRow,
 5658        is_active: bool,
 5659        cx: &mut Context<Self>,
 5660    ) -> Option<IconButton> {
 5661        if self.available_code_actions.is_some() {
 5662            Some(
 5663                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5664                    .shape(ui::IconButtonShape::Square)
 5665                    .icon_size(IconSize::XSmall)
 5666                    .icon_color(Color::Muted)
 5667                    .toggle_state(is_active)
 5668                    .tooltip({
 5669                        let focus_handle = self.focus_handle.clone();
 5670                        move |window, cx| {
 5671                            Tooltip::for_action_in(
 5672                                "Toggle Code Actions",
 5673                                &ToggleCodeActions {
 5674                                    deployed_from_indicator: None,
 5675                                },
 5676                                &focus_handle,
 5677                                window,
 5678                                cx,
 5679                            )
 5680                        }
 5681                    })
 5682                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5683                        window.focus(&editor.focus_handle(cx));
 5684                        editor.toggle_code_actions(
 5685                            &ToggleCodeActions {
 5686                                deployed_from_indicator: Some(row),
 5687                            },
 5688                            window,
 5689                            cx,
 5690                        );
 5691                    })),
 5692            )
 5693        } else {
 5694            None
 5695        }
 5696    }
 5697
 5698    fn clear_tasks(&mut self) {
 5699        self.tasks.clear()
 5700    }
 5701
 5702    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5703        if self.tasks.insert(key, value).is_some() {
 5704            // This case should hopefully be rare, but just in case...
 5705            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5706        }
 5707    }
 5708
 5709    fn build_tasks_context(
 5710        project: &Entity<Project>,
 5711        buffer: &Entity<Buffer>,
 5712        buffer_row: u32,
 5713        tasks: &Arc<RunnableTasks>,
 5714        cx: &mut Context<Self>,
 5715    ) -> Task<Option<task::TaskContext>> {
 5716        let position = Point::new(buffer_row, tasks.column);
 5717        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5718        let location = Location {
 5719            buffer: buffer.clone(),
 5720            range: range_start..range_start,
 5721        };
 5722        // Fill in the environmental variables from the tree-sitter captures
 5723        let mut captured_task_variables = TaskVariables::default();
 5724        for (capture_name, value) in tasks.extra_variables.clone() {
 5725            captured_task_variables.insert(
 5726                task::VariableName::Custom(capture_name.into()),
 5727                value.clone(),
 5728            );
 5729        }
 5730        project.update(cx, |project, cx| {
 5731            project.task_store().update(cx, |task_store, cx| {
 5732                task_store.task_context_for_location(captured_task_variables, location, cx)
 5733            })
 5734        })
 5735    }
 5736
 5737    pub fn spawn_nearest_task(
 5738        &mut self,
 5739        action: &SpawnNearestTask,
 5740        window: &mut Window,
 5741        cx: &mut Context<Self>,
 5742    ) {
 5743        let Some((workspace, _)) = self.workspace.clone() else {
 5744            return;
 5745        };
 5746        let Some(project) = self.project.clone() else {
 5747            return;
 5748        };
 5749
 5750        // Try to find a closest, enclosing node using tree-sitter that has a
 5751        // task
 5752        let Some((buffer, buffer_row, tasks)) = self
 5753            .find_enclosing_node_task(cx)
 5754            // Or find the task that's closest in row-distance.
 5755            .or_else(|| self.find_closest_task(cx))
 5756        else {
 5757            return;
 5758        };
 5759
 5760        let reveal_strategy = action.reveal;
 5761        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5762        cx.spawn_in(window, |_, mut cx| async move {
 5763            let context = task_context.await?;
 5764            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5765
 5766            let resolved = resolved_task.resolved.as_mut()?;
 5767            resolved.reveal = reveal_strategy;
 5768
 5769            workspace
 5770                .update(&mut cx, |workspace, cx| {
 5771                    workspace::tasks::schedule_resolved_task(
 5772                        workspace,
 5773                        task_source_kind,
 5774                        resolved_task,
 5775                        false,
 5776                        cx,
 5777                    );
 5778                })
 5779                .ok()
 5780        })
 5781        .detach();
 5782    }
 5783
 5784    fn find_closest_task(
 5785        &mut self,
 5786        cx: &mut Context<Self>,
 5787    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5788        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5789
 5790        let ((buffer_id, row), tasks) = self
 5791            .tasks
 5792            .iter()
 5793            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5794
 5795        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5796        let tasks = Arc::new(tasks.to_owned());
 5797        Some((buffer, *row, tasks))
 5798    }
 5799
 5800    fn find_enclosing_node_task(
 5801        &mut self,
 5802        cx: &mut Context<Self>,
 5803    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5804        let snapshot = self.buffer.read(cx).snapshot(cx);
 5805        let offset = self.selections.newest::<usize>(cx).head();
 5806        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5807        let buffer_id = excerpt.buffer().remote_id();
 5808
 5809        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5810        let mut cursor = layer.node().walk();
 5811
 5812        while cursor.goto_first_child_for_byte(offset).is_some() {
 5813            if cursor.node().end_byte() == offset {
 5814                cursor.goto_next_sibling();
 5815            }
 5816        }
 5817
 5818        // Ascend to the smallest ancestor that contains the range and has a task.
 5819        loop {
 5820            let node = cursor.node();
 5821            let node_range = node.byte_range();
 5822            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5823
 5824            // Check if this node contains our offset
 5825            if node_range.start <= offset && node_range.end >= offset {
 5826                // If it contains offset, check for task
 5827                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5828                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5829                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5830                }
 5831            }
 5832
 5833            if !cursor.goto_parent() {
 5834                break;
 5835            }
 5836        }
 5837        None
 5838    }
 5839
 5840    fn render_run_indicator(
 5841        &self,
 5842        _style: &EditorStyle,
 5843        is_active: bool,
 5844        row: DisplayRow,
 5845        cx: &mut Context<Self>,
 5846    ) -> IconButton {
 5847        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5848            .shape(ui::IconButtonShape::Square)
 5849            .icon_size(IconSize::XSmall)
 5850            .icon_color(Color::Muted)
 5851            .toggle_state(is_active)
 5852            .on_click(cx.listener(move |editor, _e, window, cx| {
 5853                window.focus(&editor.focus_handle(cx));
 5854                editor.toggle_code_actions(
 5855                    &ToggleCodeActions {
 5856                        deployed_from_indicator: Some(row),
 5857                    },
 5858                    window,
 5859                    cx,
 5860                );
 5861            }))
 5862    }
 5863
 5864    pub fn context_menu_visible(&self) -> bool {
 5865        !self.edit_prediction_preview_is_active()
 5866            && self
 5867                .context_menu
 5868                .borrow()
 5869                .as_ref()
 5870                .map_or(false, |menu| menu.visible())
 5871    }
 5872
 5873    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5874        self.context_menu
 5875            .borrow()
 5876            .as_ref()
 5877            .map(|menu| menu.origin())
 5878    }
 5879
 5880    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5881    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5882
 5883    #[allow(clippy::too_many_arguments)]
 5884    fn render_edit_prediction_popover(
 5885        &mut self,
 5886        text_bounds: &Bounds<Pixels>,
 5887        content_origin: gpui::Point<Pixels>,
 5888        editor_snapshot: &EditorSnapshot,
 5889        visible_row_range: Range<DisplayRow>,
 5890        scroll_top: f32,
 5891        scroll_bottom: f32,
 5892        line_layouts: &[LineWithInvisibles],
 5893        line_height: Pixels,
 5894        scroll_pixel_position: gpui::Point<Pixels>,
 5895        newest_selection_head: Option<DisplayPoint>,
 5896        editor_width: Pixels,
 5897        style: &EditorStyle,
 5898        window: &mut Window,
 5899        cx: &mut App,
 5900    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5901        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5902
 5903        if self.edit_prediction_visible_in_cursor_popover(true) {
 5904            return None;
 5905        }
 5906
 5907        match &active_inline_completion.completion {
 5908            InlineCompletion::Move { target, .. } => {
 5909                let target_display_point = target.to_display_point(editor_snapshot);
 5910
 5911                if self.edit_prediction_requires_modifier() {
 5912                    if !self.edit_prediction_preview_is_active() {
 5913                        return None;
 5914                    }
 5915
 5916                    self.render_edit_prediction_modifier_jump_popover(
 5917                        text_bounds,
 5918                        content_origin,
 5919                        visible_row_range,
 5920                        line_layouts,
 5921                        line_height,
 5922                        scroll_pixel_position,
 5923                        newest_selection_head,
 5924                        target_display_point,
 5925                        window,
 5926                        cx,
 5927                    )
 5928                } else {
 5929                    self.render_edit_prediction_eager_jump_popover(
 5930                        text_bounds,
 5931                        content_origin,
 5932                        editor_snapshot,
 5933                        visible_row_range,
 5934                        scroll_top,
 5935                        scroll_bottom,
 5936                        line_height,
 5937                        scroll_pixel_position,
 5938                        target_display_point,
 5939                        editor_width,
 5940                        window,
 5941                        cx,
 5942                    )
 5943                }
 5944            }
 5945            InlineCompletion::Edit {
 5946                display_mode: EditDisplayMode::Inline,
 5947                ..
 5948            } => None,
 5949            InlineCompletion::Edit {
 5950                display_mode: EditDisplayMode::TabAccept,
 5951                edits,
 5952                ..
 5953            } => {
 5954                let range = &edits.first()?.0;
 5955                let target_display_point = range.end.to_display_point(editor_snapshot);
 5956
 5957                self.render_edit_prediction_end_of_line_popover(
 5958                    "Accept",
 5959                    editor_snapshot,
 5960                    visible_row_range,
 5961                    target_display_point,
 5962                    line_height,
 5963                    scroll_pixel_position,
 5964                    content_origin,
 5965                    editor_width,
 5966                    window,
 5967                    cx,
 5968                )
 5969            }
 5970            InlineCompletion::Edit {
 5971                edits,
 5972                edit_preview,
 5973                display_mode: EditDisplayMode::DiffPopover,
 5974                snapshot,
 5975            } => self.render_edit_prediction_diff_popover(
 5976                text_bounds,
 5977                content_origin,
 5978                editor_snapshot,
 5979                visible_row_range,
 5980                line_layouts,
 5981                line_height,
 5982                scroll_pixel_position,
 5983                newest_selection_head,
 5984                editor_width,
 5985                style,
 5986                edits,
 5987                edit_preview,
 5988                snapshot,
 5989                window,
 5990                cx,
 5991            ),
 5992        }
 5993    }
 5994
 5995    #[allow(clippy::too_many_arguments)]
 5996    fn render_edit_prediction_modifier_jump_popover(
 5997        &mut self,
 5998        text_bounds: &Bounds<Pixels>,
 5999        content_origin: gpui::Point<Pixels>,
 6000        visible_row_range: Range<DisplayRow>,
 6001        line_layouts: &[LineWithInvisibles],
 6002        line_height: Pixels,
 6003        scroll_pixel_position: gpui::Point<Pixels>,
 6004        newest_selection_head: Option<DisplayPoint>,
 6005        target_display_point: DisplayPoint,
 6006        window: &mut Window,
 6007        cx: &mut App,
 6008    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6009        let scrolled_content_origin =
 6010            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6011
 6012        const SCROLL_PADDING_Y: Pixels = px(12.);
 6013
 6014        if target_display_point.row() < visible_row_range.start {
 6015            return self.render_edit_prediction_scroll_popover(
 6016                |_| SCROLL_PADDING_Y,
 6017                IconName::ArrowUp,
 6018                visible_row_range,
 6019                line_layouts,
 6020                newest_selection_head,
 6021                scrolled_content_origin,
 6022                window,
 6023                cx,
 6024            );
 6025        } else if target_display_point.row() >= visible_row_range.end {
 6026            return self.render_edit_prediction_scroll_popover(
 6027                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6028                IconName::ArrowDown,
 6029                visible_row_range,
 6030                line_layouts,
 6031                newest_selection_head,
 6032                scrolled_content_origin,
 6033                window,
 6034                cx,
 6035            );
 6036        }
 6037
 6038        const POLE_WIDTH: Pixels = px(2.);
 6039
 6040        let line_layout =
 6041            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6042        let target_column = target_display_point.column() as usize;
 6043
 6044        let target_x = line_layout.x_for_index(target_column);
 6045        let target_y =
 6046            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6047
 6048        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6049
 6050        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6051        border_color.l += 0.001;
 6052
 6053        let mut element = v_flex()
 6054            .items_end()
 6055            .when(flag_on_right, |el| el.items_start())
 6056            .child(if flag_on_right {
 6057                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6058                    .rounded_bl(px(0.))
 6059                    .rounded_tl(px(0.))
 6060                    .border_l_2()
 6061                    .border_color(border_color)
 6062            } else {
 6063                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6064                    .rounded_br(px(0.))
 6065                    .rounded_tr(px(0.))
 6066                    .border_r_2()
 6067                    .border_color(border_color)
 6068            })
 6069            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6070            .into_any();
 6071
 6072        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6073
 6074        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6075            - point(
 6076                if flag_on_right {
 6077                    POLE_WIDTH
 6078                } else {
 6079                    size.width - POLE_WIDTH
 6080                },
 6081                size.height - line_height,
 6082            );
 6083
 6084        origin.x = origin.x.max(content_origin.x);
 6085
 6086        element.prepaint_at(origin, window, cx);
 6087
 6088        Some((element, origin))
 6089    }
 6090
 6091    #[allow(clippy::too_many_arguments)]
 6092    fn render_edit_prediction_scroll_popover(
 6093        &mut self,
 6094        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6095        scroll_icon: IconName,
 6096        visible_row_range: Range<DisplayRow>,
 6097        line_layouts: &[LineWithInvisibles],
 6098        newest_selection_head: Option<DisplayPoint>,
 6099        scrolled_content_origin: gpui::Point<Pixels>,
 6100        window: &mut Window,
 6101        cx: &mut App,
 6102    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6103        let mut element = self
 6104            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6105            .into_any();
 6106
 6107        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6108
 6109        let cursor = newest_selection_head?;
 6110        let cursor_row_layout =
 6111            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6112        let cursor_column = cursor.column() as usize;
 6113
 6114        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6115
 6116        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6117
 6118        element.prepaint_at(origin, window, cx);
 6119        Some((element, origin))
 6120    }
 6121
 6122    #[allow(clippy::too_many_arguments)]
 6123    fn render_edit_prediction_eager_jump_popover(
 6124        &mut self,
 6125        text_bounds: &Bounds<Pixels>,
 6126        content_origin: gpui::Point<Pixels>,
 6127        editor_snapshot: &EditorSnapshot,
 6128        visible_row_range: Range<DisplayRow>,
 6129        scroll_top: f32,
 6130        scroll_bottom: f32,
 6131        line_height: Pixels,
 6132        scroll_pixel_position: gpui::Point<Pixels>,
 6133        target_display_point: DisplayPoint,
 6134        editor_width: Pixels,
 6135        window: &mut Window,
 6136        cx: &mut App,
 6137    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6138        if target_display_point.row().as_f32() < scroll_top {
 6139            let mut element = self
 6140                .render_edit_prediction_line_popover(
 6141                    "Jump to Edit",
 6142                    Some(IconName::ArrowUp),
 6143                    window,
 6144                    cx,
 6145                )?
 6146                .into_any();
 6147
 6148            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6149            let offset = point(
 6150                (text_bounds.size.width - size.width) / 2.,
 6151                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6152            );
 6153
 6154            let origin = text_bounds.origin + offset;
 6155            element.prepaint_at(origin, window, cx);
 6156            Some((element, origin))
 6157        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6158            let mut element = self
 6159                .render_edit_prediction_line_popover(
 6160                    "Jump to Edit",
 6161                    Some(IconName::ArrowDown),
 6162                    window,
 6163                    cx,
 6164                )?
 6165                .into_any();
 6166
 6167            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6168            let offset = point(
 6169                (text_bounds.size.width - size.width) / 2.,
 6170                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6171            );
 6172
 6173            let origin = text_bounds.origin + offset;
 6174            element.prepaint_at(origin, window, cx);
 6175            Some((element, origin))
 6176        } else {
 6177            self.render_edit_prediction_end_of_line_popover(
 6178                "Jump to Edit",
 6179                editor_snapshot,
 6180                visible_row_range,
 6181                target_display_point,
 6182                line_height,
 6183                scroll_pixel_position,
 6184                content_origin,
 6185                editor_width,
 6186                window,
 6187                cx,
 6188            )
 6189        }
 6190    }
 6191
 6192    #[allow(clippy::too_many_arguments)]
 6193    fn render_edit_prediction_end_of_line_popover(
 6194        self: &mut Editor,
 6195        label: &'static str,
 6196        editor_snapshot: &EditorSnapshot,
 6197        visible_row_range: Range<DisplayRow>,
 6198        target_display_point: DisplayPoint,
 6199        line_height: Pixels,
 6200        scroll_pixel_position: gpui::Point<Pixels>,
 6201        content_origin: gpui::Point<Pixels>,
 6202        editor_width: Pixels,
 6203        window: &mut Window,
 6204        cx: &mut App,
 6205    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6206        let target_line_end = DisplayPoint::new(
 6207            target_display_point.row(),
 6208            editor_snapshot.line_len(target_display_point.row()),
 6209        );
 6210
 6211        let mut element = self
 6212            .render_edit_prediction_line_popover(label, None, window, cx)?
 6213            .into_any();
 6214
 6215        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6216
 6217        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6218
 6219        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6220        let mut origin = start_point
 6221            + line_origin
 6222            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6223        origin.x = origin.x.max(content_origin.x);
 6224
 6225        let max_x = content_origin.x + editor_width - size.width;
 6226
 6227        if origin.x > max_x {
 6228            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6229
 6230            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6231                origin.y += offset;
 6232                IconName::ArrowUp
 6233            } else {
 6234                origin.y -= offset;
 6235                IconName::ArrowDown
 6236            };
 6237
 6238            element = self
 6239                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6240                .into_any();
 6241
 6242            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6243
 6244            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6245        }
 6246
 6247        element.prepaint_at(origin, window, cx);
 6248        Some((element, origin))
 6249    }
 6250
 6251    #[allow(clippy::too_many_arguments)]
 6252    fn render_edit_prediction_diff_popover(
 6253        self: &Editor,
 6254        text_bounds: &Bounds<Pixels>,
 6255        content_origin: gpui::Point<Pixels>,
 6256        editor_snapshot: &EditorSnapshot,
 6257        visible_row_range: Range<DisplayRow>,
 6258        line_layouts: &[LineWithInvisibles],
 6259        line_height: Pixels,
 6260        scroll_pixel_position: gpui::Point<Pixels>,
 6261        newest_selection_head: Option<DisplayPoint>,
 6262        editor_width: Pixels,
 6263        style: &EditorStyle,
 6264        edits: &Vec<(Range<Anchor>, String)>,
 6265        edit_preview: &Option<language::EditPreview>,
 6266        snapshot: &language::BufferSnapshot,
 6267        window: &mut Window,
 6268        cx: &mut App,
 6269    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6270        let edit_start = edits
 6271            .first()
 6272            .unwrap()
 6273            .0
 6274            .start
 6275            .to_display_point(editor_snapshot);
 6276        let edit_end = edits
 6277            .last()
 6278            .unwrap()
 6279            .0
 6280            .end
 6281            .to_display_point(editor_snapshot);
 6282
 6283        let is_visible = visible_row_range.contains(&edit_start.row())
 6284            || visible_row_range.contains(&edit_end.row());
 6285        if !is_visible {
 6286            return None;
 6287        }
 6288
 6289        let highlighted_edits =
 6290            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6291
 6292        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6293        let line_count = highlighted_edits.text.lines().count();
 6294
 6295        const BORDER_WIDTH: Pixels = px(1.);
 6296
 6297        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6298        let has_keybind = keybind.is_some();
 6299
 6300        let mut element = h_flex()
 6301            .items_start()
 6302            .child(
 6303                h_flex()
 6304                    .bg(cx.theme().colors().editor_background)
 6305                    .border(BORDER_WIDTH)
 6306                    .shadow_sm()
 6307                    .border_color(cx.theme().colors().border)
 6308                    .rounded_l_lg()
 6309                    .when(line_count > 1, |el| el.rounded_br_lg())
 6310                    .pr_1()
 6311                    .child(styled_text),
 6312            )
 6313            .child(
 6314                h_flex()
 6315                    .h(line_height + BORDER_WIDTH * px(2.))
 6316                    .px_1p5()
 6317                    .gap_1()
 6318                    // Workaround: For some reason, there's a gap if we don't do this
 6319                    .ml(-BORDER_WIDTH)
 6320                    .shadow(smallvec![gpui::BoxShadow {
 6321                        color: gpui::black().opacity(0.05),
 6322                        offset: point(px(1.), px(1.)),
 6323                        blur_radius: px(2.),
 6324                        spread_radius: px(0.),
 6325                    }])
 6326                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6327                    .border(BORDER_WIDTH)
 6328                    .border_color(cx.theme().colors().border)
 6329                    .rounded_r_lg()
 6330                    .id("edit_prediction_diff_popover_keybind")
 6331                    .when(!has_keybind, |el| {
 6332                        let status_colors = cx.theme().status();
 6333
 6334                        el.bg(status_colors.error_background)
 6335                            .border_color(status_colors.error.opacity(0.6))
 6336                            .child(Icon::new(IconName::Info).color(Color::Error))
 6337                            .cursor_default()
 6338                            .hoverable_tooltip(move |_window, cx| {
 6339                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6340                            })
 6341                    })
 6342                    .children(keybind),
 6343            )
 6344            .into_any();
 6345
 6346        let longest_row =
 6347            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6348        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6349            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6350        } else {
 6351            layout_line(
 6352                longest_row,
 6353                editor_snapshot,
 6354                style,
 6355                editor_width,
 6356                |_| false,
 6357                window,
 6358                cx,
 6359            )
 6360            .width
 6361        };
 6362
 6363        let viewport_bounds =
 6364            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6365                right: -EditorElement::SCROLLBAR_WIDTH,
 6366                ..Default::default()
 6367            });
 6368
 6369        let x_after_longest =
 6370            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6371                - scroll_pixel_position.x;
 6372
 6373        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6374
 6375        // Fully visible if it can be displayed within the window (allow overlapping other
 6376        // panes). However, this is only allowed if the popover starts within text_bounds.
 6377        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6378            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6379
 6380        let mut origin = if can_position_to_the_right {
 6381            point(
 6382                x_after_longest,
 6383                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6384                    - scroll_pixel_position.y,
 6385            )
 6386        } else {
 6387            let cursor_row = newest_selection_head.map(|head| head.row());
 6388            let above_edit = edit_start
 6389                .row()
 6390                .0
 6391                .checked_sub(line_count as u32)
 6392                .map(DisplayRow);
 6393            let below_edit = Some(edit_end.row() + 1);
 6394            let above_cursor =
 6395                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6396            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6397
 6398            // Place the edit popover adjacent to the edit if there is a location
 6399            // available that is onscreen and does not obscure the cursor. Otherwise,
 6400            // place it adjacent to the cursor.
 6401            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6402                .into_iter()
 6403                .flatten()
 6404                .find(|&start_row| {
 6405                    let end_row = start_row + line_count as u32;
 6406                    visible_row_range.contains(&start_row)
 6407                        && visible_row_range.contains(&end_row)
 6408                        && cursor_row.map_or(true, |cursor_row| {
 6409                            !((start_row..end_row).contains(&cursor_row))
 6410                        })
 6411                })?;
 6412
 6413            content_origin
 6414                + point(
 6415                    -scroll_pixel_position.x,
 6416                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6417                )
 6418        };
 6419
 6420        origin.x -= BORDER_WIDTH;
 6421
 6422        window.defer_draw(element, origin, 1);
 6423
 6424        // Do not return an element, since it will already be drawn due to defer_draw.
 6425        None
 6426    }
 6427
 6428    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6429        px(30.)
 6430    }
 6431
 6432    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6433        if self.read_only(cx) {
 6434            cx.theme().players().read_only()
 6435        } else {
 6436            self.style.as_ref().unwrap().local_player
 6437        }
 6438    }
 6439
 6440    fn render_edit_prediction_accept_keybind(
 6441        &self,
 6442        window: &mut Window,
 6443        cx: &App,
 6444    ) -> Option<AnyElement> {
 6445        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6446        let accept_keystroke = accept_binding.keystroke()?;
 6447
 6448        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6449
 6450        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6451            Color::Accent
 6452        } else {
 6453            Color::Muted
 6454        };
 6455
 6456        h_flex()
 6457            .px_0p5()
 6458            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6459            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6460            .text_size(TextSize::XSmall.rems(cx))
 6461            .child(h_flex().children(ui::render_modifiers(
 6462                &accept_keystroke.modifiers,
 6463                PlatformStyle::platform(),
 6464                Some(modifiers_color),
 6465                Some(IconSize::XSmall.rems().into()),
 6466                true,
 6467            )))
 6468            .when(is_platform_style_mac, |parent| {
 6469                parent.child(accept_keystroke.key.clone())
 6470            })
 6471            .when(!is_platform_style_mac, |parent| {
 6472                parent.child(
 6473                    Key::new(
 6474                        util::capitalize(&accept_keystroke.key),
 6475                        Some(Color::Default),
 6476                    )
 6477                    .size(Some(IconSize::XSmall.rems().into())),
 6478                )
 6479            })
 6480            .into_any()
 6481            .into()
 6482    }
 6483
 6484    fn render_edit_prediction_line_popover(
 6485        &self,
 6486        label: impl Into<SharedString>,
 6487        icon: Option<IconName>,
 6488        window: &mut Window,
 6489        cx: &App,
 6490    ) -> Option<Stateful<Div>> {
 6491        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6492
 6493        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6494        let has_keybind = keybind.is_some();
 6495
 6496        let result = h_flex()
 6497            .id("ep-line-popover")
 6498            .py_0p5()
 6499            .pl_1()
 6500            .pr(padding_right)
 6501            .gap_1()
 6502            .rounded(px(6.))
 6503            .border_1()
 6504            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6505            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6506            .shadow_sm()
 6507            .when(!has_keybind, |el| {
 6508                let status_colors = cx.theme().status();
 6509
 6510                el.bg(status_colors.error_background)
 6511                    .border_color(status_colors.error.opacity(0.6))
 6512                    .pl_2()
 6513                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 6514                    .cursor_default()
 6515                    .hoverable_tooltip(move |_window, cx| {
 6516                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6517                    })
 6518            })
 6519            .children(keybind)
 6520            .child(
 6521                Label::new(label)
 6522                    .size(LabelSize::Small)
 6523                    .when(!has_keybind, |el| {
 6524                        el.color(cx.theme().status().error.into()).strikethrough()
 6525                    }),
 6526            )
 6527            .when(!has_keybind, |el| {
 6528                el.child(
 6529                    h_flex().ml_1().child(
 6530                        Icon::new(IconName::Info)
 6531                            .size(IconSize::Small)
 6532                            .color(cx.theme().status().error.into()),
 6533                    ),
 6534                )
 6535            })
 6536            .when_some(icon, |element, icon| {
 6537                element.child(
 6538                    div()
 6539                        .mt(px(1.5))
 6540                        .child(Icon::new(icon).size(IconSize::Small)),
 6541                )
 6542            });
 6543
 6544        Some(result)
 6545    }
 6546
 6547    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6548        let accent_color = cx.theme().colors().text_accent;
 6549        let editor_bg_color = cx.theme().colors().editor_background;
 6550        editor_bg_color.blend(accent_color.opacity(0.1))
 6551    }
 6552
 6553    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6554        let accent_color = cx.theme().colors().text_accent;
 6555        let editor_bg_color = cx.theme().colors().editor_background;
 6556        editor_bg_color.blend(accent_color.opacity(0.6))
 6557    }
 6558
 6559    #[allow(clippy::too_many_arguments)]
 6560    fn render_edit_prediction_cursor_popover(
 6561        &self,
 6562        min_width: Pixels,
 6563        max_width: Pixels,
 6564        cursor_point: Point,
 6565        style: &EditorStyle,
 6566        accept_keystroke: Option<&gpui::Keystroke>,
 6567        _window: &Window,
 6568        cx: &mut Context<Editor>,
 6569    ) -> Option<AnyElement> {
 6570        let provider = self.edit_prediction_provider.as_ref()?;
 6571
 6572        if provider.provider.needs_terms_acceptance(cx) {
 6573            return Some(
 6574                h_flex()
 6575                    .min_w(min_width)
 6576                    .flex_1()
 6577                    .px_2()
 6578                    .py_1()
 6579                    .gap_3()
 6580                    .elevation_2(cx)
 6581                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6582                    .id("accept-terms")
 6583                    .cursor_pointer()
 6584                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6585                    .on_click(cx.listener(|this, _event, window, cx| {
 6586                        cx.stop_propagation();
 6587                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6588                        window.dispatch_action(
 6589                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6590                            cx,
 6591                        );
 6592                    }))
 6593                    .child(
 6594                        h_flex()
 6595                            .flex_1()
 6596                            .gap_2()
 6597                            .child(Icon::new(IconName::ZedPredict))
 6598                            .child(Label::new("Accept Terms of Service"))
 6599                            .child(div().w_full())
 6600                            .child(
 6601                                Icon::new(IconName::ArrowUpRight)
 6602                                    .color(Color::Muted)
 6603                                    .size(IconSize::Small),
 6604                            )
 6605                            .into_any_element(),
 6606                    )
 6607                    .into_any(),
 6608            );
 6609        }
 6610
 6611        let is_refreshing = provider.provider.is_refreshing(cx);
 6612
 6613        fn pending_completion_container() -> Div {
 6614            h_flex()
 6615                .h_full()
 6616                .flex_1()
 6617                .gap_2()
 6618                .child(Icon::new(IconName::ZedPredict))
 6619        }
 6620
 6621        let completion = match &self.active_inline_completion {
 6622            Some(prediction) => {
 6623                if !self.has_visible_completions_menu() {
 6624                    const RADIUS: Pixels = px(6.);
 6625                    const BORDER_WIDTH: Pixels = px(1.);
 6626
 6627                    return Some(
 6628                        h_flex()
 6629                            .elevation_2(cx)
 6630                            .border(BORDER_WIDTH)
 6631                            .border_color(cx.theme().colors().border)
 6632                            .when(accept_keystroke.is_none(), |el| {
 6633                                el.border_color(cx.theme().status().error)
 6634                            })
 6635                            .rounded(RADIUS)
 6636                            .rounded_tl(px(0.))
 6637                            .overflow_hidden()
 6638                            .child(div().px_1p5().child(match &prediction.completion {
 6639                                InlineCompletion::Move { target, snapshot } => {
 6640                                    use text::ToPoint as _;
 6641                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6642                                    {
 6643                                        Icon::new(IconName::ZedPredictDown)
 6644                                    } else {
 6645                                        Icon::new(IconName::ZedPredictUp)
 6646                                    }
 6647                                }
 6648                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6649                            }))
 6650                            .child(
 6651                                h_flex()
 6652                                    .gap_1()
 6653                                    .py_1()
 6654                                    .px_2()
 6655                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6656                                    .border_l_1()
 6657                                    .border_color(cx.theme().colors().border)
 6658                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6659                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6660                                        el.child(
 6661                                            Label::new("Hold")
 6662                                                .size(LabelSize::Small)
 6663                                                .when(accept_keystroke.is_none(), |el| {
 6664                                                    el.strikethrough()
 6665                                                })
 6666                                                .line_height_style(LineHeightStyle::UiLabel),
 6667                                        )
 6668                                    })
 6669                                    .id("edit_prediction_cursor_popover_keybind")
 6670                                    .when(accept_keystroke.is_none(), |el| {
 6671                                        let status_colors = cx.theme().status();
 6672
 6673                                        el.bg(status_colors.error_background)
 6674                                            .border_color(status_colors.error.opacity(0.6))
 6675                                            .child(Icon::new(IconName::Info).color(Color::Error))
 6676                                            .cursor_default()
 6677                                            .hoverable_tooltip(move |_window, cx| {
 6678                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 6679                                                    .into()
 6680                                            })
 6681                                    })
 6682                                    .when_some(
 6683                                        accept_keystroke.as_ref(),
 6684                                        |el, accept_keystroke| {
 6685                                            el.child(h_flex().children(ui::render_modifiers(
 6686                                                &accept_keystroke.modifiers,
 6687                                                PlatformStyle::platform(),
 6688                                                Some(Color::Default),
 6689                                                Some(IconSize::XSmall.rems().into()),
 6690                                                false,
 6691                                            )))
 6692                                        },
 6693                                    ),
 6694                            )
 6695                            .into_any(),
 6696                    );
 6697                }
 6698
 6699                self.render_edit_prediction_cursor_popover_preview(
 6700                    prediction,
 6701                    cursor_point,
 6702                    style,
 6703                    cx,
 6704                )?
 6705            }
 6706
 6707            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6708                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6709                    stale_completion,
 6710                    cursor_point,
 6711                    style,
 6712                    cx,
 6713                )?,
 6714
 6715                None => {
 6716                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6717                }
 6718            },
 6719
 6720            None => pending_completion_container().child(Label::new("No Prediction")),
 6721        };
 6722
 6723        let completion = if is_refreshing {
 6724            completion
 6725                .with_animation(
 6726                    "loading-completion",
 6727                    Animation::new(Duration::from_secs(2))
 6728                        .repeat()
 6729                        .with_easing(pulsating_between(0.4, 0.8)),
 6730                    |label, delta| label.opacity(delta),
 6731                )
 6732                .into_any_element()
 6733        } else {
 6734            completion.into_any_element()
 6735        };
 6736
 6737        let has_completion = self.active_inline_completion.is_some();
 6738
 6739        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6740        Some(
 6741            h_flex()
 6742                .min_w(min_width)
 6743                .max_w(max_width)
 6744                .flex_1()
 6745                .elevation_2(cx)
 6746                .border_color(cx.theme().colors().border)
 6747                .child(
 6748                    div()
 6749                        .flex_1()
 6750                        .py_1()
 6751                        .px_2()
 6752                        .overflow_hidden()
 6753                        .child(completion),
 6754                )
 6755                .when_some(accept_keystroke, |el, accept_keystroke| {
 6756                    if !accept_keystroke.modifiers.modified() {
 6757                        return el;
 6758                    }
 6759
 6760                    el.child(
 6761                        h_flex()
 6762                            .h_full()
 6763                            .border_l_1()
 6764                            .rounded_r_lg()
 6765                            .border_color(cx.theme().colors().border)
 6766                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6767                            .gap_1()
 6768                            .py_1()
 6769                            .px_2()
 6770                            .child(
 6771                                h_flex()
 6772                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6773                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6774                                    .child(h_flex().children(ui::render_modifiers(
 6775                                        &accept_keystroke.modifiers,
 6776                                        PlatformStyle::platform(),
 6777                                        Some(if !has_completion {
 6778                                            Color::Muted
 6779                                        } else {
 6780                                            Color::Default
 6781                                        }),
 6782                                        None,
 6783                                        false,
 6784                                    ))),
 6785                            )
 6786                            .child(Label::new("Preview").into_any_element())
 6787                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6788                    )
 6789                })
 6790                .into_any(),
 6791        )
 6792    }
 6793
 6794    fn render_edit_prediction_cursor_popover_preview(
 6795        &self,
 6796        completion: &InlineCompletionState,
 6797        cursor_point: Point,
 6798        style: &EditorStyle,
 6799        cx: &mut Context<Editor>,
 6800    ) -> Option<Div> {
 6801        use text::ToPoint as _;
 6802
 6803        fn render_relative_row_jump(
 6804            prefix: impl Into<String>,
 6805            current_row: u32,
 6806            target_row: u32,
 6807        ) -> Div {
 6808            let (row_diff, arrow) = if target_row < current_row {
 6809                (current_row - target_row, IconName::ArrowUp)
 6810            } else {
 6811                (target_row - current_row, IconName::ArrowDown)
 6812            };
 6813
 6814            h_flex()
 6815                .child(
 6816                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6817                        .color(Color::Muted)
 6818                        .size(LabelSize::Small),
 6819                )
 6820                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6821        }
 6822
 6823        match &completion.completion {
 6824            InlineCompletion::Move {
 6825                target, snapshot, ..
 6826            } => Some(
 6827                h_flex()
 6828                    .px_2()
 6829                    .gap_2()
 6830                    .flex_1()
 6831                    .child(
 6832                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6833                            Icon::new(IconName::ZedPredictDown)
 6834                        } else {
 6835                            Icon::new(IconName::ZedPredictUp)
 6836                        },
 6837                    )
 6838                    .child(Label::new("Jump to Edit")),
 6839            ),
 6840
 6841            InlineCompletion::Edit {
 6842                edits,
 6843                edit_preview,
 6844                snapshot,
 6845                display_mode: _,
 6846            } => {
 6847                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6848
 6849                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6850                    &snapshot,
 6851                    &edits,
 6852                    edit_preview.as_ref()?,
 6853                    true,
 6854                    cx,
 6855                )
 6856                .first_line_preview();
 6857
 6858                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6859                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 6860
 6861                let preview = h_flex()
 6862                    .gap_1()
 6863                    .min_w_16()
 6864                    .child(styled_text)
 6865                    .when(has_more_lines, |parent| parent.child(""));
 6866
 6867                let left = if first_edit_row != cursor_point.row {
 6868                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6869                        .into_any_element()
 6870                } else {
 6871                    Icon::new(IconName::ZedPredict).into_any_element()
 6872                };
 6873
 6874                Some(
 6875                    h_flex()
 6876                        .h_full()
 6877                        .flex_1()
 6878                        .gap_2()
 6879                        .pr_1()
 6880                        .overflow_x_hidden()
 6881                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6882                        .child(left)
 6883                        .child(preview),
 6884                )
 6885            }
 6886        }
 6887    }
 6888
 6889    fn render_context_menu(
 6890        &self,
 6891        style: &EditorStyle,
 6892        max_height_in_lines: u32,
 6893        y_flipped: bool,
 6894        window: &mut Window,
 6895        cx: &mut Context<Editor>,
 6896    ) -> Option<AnyElement> {
 6897        let menu = self.context_menu.borrow();
 6898        let menu = menu.as_ref()?;
 6899        if !menu.visible() {
 6900            return None;
 6901        };
 6902        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6903    }
 6904
 6905    fn render_context_menu_aside(
 6906        &mut self,
 6907        max_size: Size<Pixels>,
 6908        window: &mut Window,
 6909        cx: &mut Context<Editor>,
 6910    ) -> Option<AnyElement> {
 6911        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6912            if menu.visible() {
 6913                menu.render_aside(self, max_size, window, cx)
 6914            } else {
 6915                None
 6916            }
 6917        })
 6918    }
 6919
 6920    fn hide_context_menu(
 6921        &mut self,
 6922        window: &mut Window,
 6923        cx: &mut Context<Self>,
 6924    ) -> Option<CodeContextMenu> {
 6925        cx.notify();
 6926        self.completion_tasks.clear();
 6927        let context_menu = self.context_menu.borrow_mut().take();
 6928        self.stale_inline_completion_in_menu.take();
 6929        self.update_visible_inline_completion(window, cx);
 6930        context_menu
 6931    }
 6932
 6933    fn show_snippet_choices(
 6934        &mut self,
 6935        choices: &Vec<String>,
 6936        selection: Range<Anchor>,
 6937        cx: &mut Context<Self>,
 6938    ) {
 6939        if selection.start.buffer_id.is_none() {
 6940            return;
 6941        }
 6942        let buffer_id = selection.start.buffer_id.unwrap();
 6943        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6944        let id = post_inc(&mut self.next_completion_id);
 6945
 6946        if let Some(buffer) = buffer {
 6947            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6948                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6949            ));
 6950        }
 6951    }
 6952
 6953    pub fn insert_snippet(
 6954        &mut self,
 6955        insertion_ranges: &[Range<usize>],
 6956        snippet: Snippet,
 6957        window: &mut Window,
 6958        cx: &mut Context<Self>,
 6959    ) -> Result<()> {
 6960        struct Tabstop<T> {
 6961            is_end_tabstop: bool,
 6962            ranges: Vec<Range<T>>,
 6963            choices: Option<Vec<String>>,
 6964        }
 6965
 6966        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6967            let snippet_text: Arc<str> = snippet.text.clone().into();
 6968            buffer.edit(
 6969                insertion_ranges
 6970                    .iter()
 6971                    .cloned()
 6972                    .map(|range| (range, snippet_text.clone())),
 6973                Some(AutoindentMode::EachLine),
 6974                cx,
 6975            );
 6976
 6977            let snapshot = &*buffer.read(cx);
 6978            let snippet = &snippet;
 6979            snippet
 6980                .tabstops
 6981                .iter()
 6982                .map(|tabstop| {
 6983                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6984                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6985                    });
 6986                    let mut tabstop_ranges = tabstop
 6987                        .ranges
 6988                        .iter()
 6989                        .flat_map(|tabstop_range| {
 6990                            let mut delta = 0_isize;
 6991                            insertion_ranges.iter().map(move |insertion_range| {
 6992                                let insertion_start = insertion_range.start as isize + delta;
 6993                                delta +=
 6994                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6995
 6996                                let start = ((insertion_start + tabstop_range.start) as usize)
 6997                                    .min(snapshot.len());
 6998                                let end = ((insertion_start + tabstop_range.end) as usize)
 6999                                    .min(snapshot.len());
 7000                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7001                            })
 7002                        })
 7003                        .collect::<Vec<_>>();
 7004                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7005
 7006                    Tabstop {
 7007                        is_end_tabstop,
 7008                        ranges: tabstop_ranges,
 7009                        choices: tabstop.choices.clone(),
 7010                    }
 7011                })
 7012                .collect::<Vec<_>>()
 7013        });
 7014        if let Some(tabstop) = tabstops.first() {
 7015            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7016                s.select_ranges(tabstop.ranges.iter().cloned());
 7017            });
 7018
 7019            if let Some(choices) = &tabstop.choices {
 7020                if let Some(selection) = tabstop.ranges.first() {
 7021                    self.show_snippet_choices(choices, selection.clone(), cx)
 7022                }
 7023            }
 7024
 7025            // If we're already at the last tabstop and it's at the end of the snippet,
 7026            // we're done, we don't need to keep the state around.
 7027            if !tabstop.is_end_tabstop {
 7028                let choices = tabstops
 7029                    .iter()
 7030                    .map(|tabstop| tabstop.choices.clone())
 7031                    .collect();
 7032
 7033                let ranges = tabstops
 7034                    .into_iter()
 7035                    .map(|tabstop| tabstop.ranges)
 7036                    .collect::<Vec<_>>();
 7037
 7038                self.snippet_stack.push(SnippetState {
 7039                    active_index: 0,
 7040                    ranges,
 7041                    choices,
 7042                });
 7043            }
 7044
 7045            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7046            if self.autoclose_regions.is_empty() {
 7047                let snapshot = self.buffer.read(cx).snapshot(cx);
 7048                for selection in &mut self.selections.all::<Point>(cx) {
 7049                    let selection_head = selection.head();
 7050                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7051                        continue;
 7052                    };
 7053
 7054                    let mut bracket_pair = None;
 7055                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7056                    let prev_chars = snapshot
 7057                        .reversed_chars_at(selection_head)
 7058                        .collect::<String>();
 7059                    for (pair, enabled) in scope.brackets() {
 7060                        if enabled
 7061                            && pair.close
 7062                            && prev_chars.starts_with(pair.start.as_str())
 7063                            && next_chars.starts_with(pair.end.as_str())
 7064                        {
 7065                            bracket_pair = Some(pair.clone());
 7066                            break;
 7067                        }
 7068                    }
 7069                    if let Some(pair) = bracket_pair {
 7070                        let start = snapshot.anchor_after(selection_head);
 7071                        let end = snapshot.anchor_after(selection_head);
 7072                        self.autoclose_regions.push(AutocloseRegion {
 7073                            selection_id: selection.id,
 7074                            range: start..end,
 7075                            pair,
 7076                        });
 7077                    }
 7078                }
 7079            }
 7080        }
 7081        Ok(())
 7082    }
 7083
 7084    pub fn move_to_next_snippet_tabstop(
 7085        &mut self,
 7086        window: &mut Window,
 7087        cx: &mut Context<Self>,
 7088    ) -> bool {
 7089        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7090    }
 7091
 7092    pub fn move_to_prev_snippet_tabstop(
 7093        &mut self,
 7094        window: &mut Window,
 7095        cx: &mut Context<Self>,
 7096    ) -> bool {
 7097        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7098    }
 7099
 7100    pub fn move_to_snippet_tabstop(
 7101        &mut self,
 7102        bias: Bias,
 7103        window: &mut Window,
 7104        cx: &mut Context<Self>,
 7105    ) -> bool {
 7106        if let Some(mut snippet) = self.snippet_stack.pop() {
 7107            match bias {
 7108                Bias::Left => {
 7109                    if snippet.active_index > 0 {
 7110                        snippet.active_index -= 1;
 7111                    } else {
 7112                        self.snippet_stack.push(snippet);
 7113                        return false;
 7114                    }
 7115                }
 7116                Bias::Right => {
 7117                    if snippet.active_index + 1 < snippet.ranges.len() {
 7118                        snippet.active_index += 1;
 7119                    } else {
 7120                        self.snippet_stack.push(snippet);
 7121                        return false;
 7122                    }
 7123                }
 7124            }
 7125            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7126                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7127                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7128                });
 7129
 7130                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7131                    if let Some(selection) = current_ranges.first() {
 7132                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7133                    }
 7134                }
 7135
 7136                // If snippet state is not at the last tabstop, push it back on the stack
 7137                if snippet.active_index + 1 < snippet.ranges.len() {
 7138                    self.snippet_stack.push(snippet);
 7139                }
 7140                return true;
 7141            }
 7142        }
 7143
 7144        false
 7145    }
 7146
 7147    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7148        self.transact(window, cx, |this, window, cx| {
 7149            this.select_all(&SelectAll, window, cx);
 7150            this.insert("", window, cx);
 7151        });
 7152    }
 7153
 7154    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7155        self.transact(window, cx, |this, window, cx| {
 7156            this.select_autoclose_pair(window, cx);
 7157            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7158            if !this.linked_edit_ranges.is_empty() {
 7159                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7160                let snapshot = this.buffer.read(cx).snapshot(cx);
 7161
 7162                for selection in selections.iter() {
 7163                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7164                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7165                    if selection_start.buffer_id != selection_end.buffer_id {
 7166                        continue;
 7167                    }
 7168                    if let Some(ranges) =
 7169                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7170                    {
 7171                        for (buffer, entries) in ranges {
 7172                            linked_ranges.entry(buffer).or_default().extend(entries);
 7173                        }
 7174                    }
 7175                }
 7176            }
 7177
 7178            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7179            if !this.selections.line_mode {
 7180                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7181                for selection in &mut selections {
 7182                    if selection.is_empty() {
 7183                        let old_head = selection.head();
 7184                        let mut new_head =
 7185                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7186                                .to_point(&display_map);
 7187                        if let Some((buffer, line_buffer_range)) = display_map
 7188                            .buffer_snapshot
 7189                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7190                        {
 7191                            let indent_size =
 7192                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7193                            let indent_len = match indent_size.kind {
 7194                                IndentKind::Space => {
 7195                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7196                                }
 7197                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7198                            };
 7199                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7200                                let indent_len = indent_len.get();
 7201                                new_head = cmp::min(
 7202                                    new_head,
 7203                                    MultiBufferPoint::new(
 7204                                        old_head.row,
 7205                                        ((old_head.column - 1) / indent_len) * indent_len,
 7206                                    ),
 7207                                );
 7208                            }
 7209                        }
 7210
 7211                        selection.set_head(new_head, SelectionGoal::None);
 7212                    }
 7213                }
 7214            }
 7215
 7216            this.signature_help_state.set_backspace_pressed(true);
 7217            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7218                s.select(selections)
 7219            });
 7220            this.insert("", window, cx);
 7221            let empty_str: Arc<str> = Arc::from("");
 7222            for (buffer, edits) in linked_ranges {
 7223                let snapshot = buffer.read(cx).snapshot();
 7224                use text::ToPoint as TP;
 7225
 7226                let edits = edits
 7227                    .into_iter()
 7228                    .map(|range| {
 7229                        let end_point = TP::to_point(&range.end, &snapshot);
 7230                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7231
 7232                        if end_point == start_point {
 7233                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7234                                .saturating_sub(1);
 7235                            start_point =
 7236                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7237                        };
 7238
 7239                        (start_point..end_point, empty_str.clone())
 7240                    })
 7241                    .sorted_by_key(|(range, _)| range.start)
 7242                    .collect::<Vec<_>>();
 7243                buffer.update(cx, |this, cx| {
 7244                    this.edit(edits, None, cx);
 7245                })
 7246            }
 7247            this.refresh_inline_completion(true, false, window, cx);
 7248            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7249        });
 7250    }
 7251
 7252    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7253        self.transact(window, cx, |this, window, cx| {
 7254            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7255                let line_mode = s.line_mode;
 7256                s.move_with(|map, selection| {
 7257                    if selection.is_empty() && !line_mode {
 7258                        let cursor = movement::right(map, selection.head());
 7259                        selection.end = cursor;
 7260                        selection.reversed = true;
 7261                        selection.goal = SelectionGoal::None;
 7262                    }
 7263                })
 7264            });
 7265            this.insert("", window, cx);
 7266            this.refresh_inline_completion(true, false, window, cx);
 7267        });
 7268    }
 7269
 7270    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7271        if self.move_to_prev_snippet_tabstop(window, cx) {
 7272            return;
 7273        }
 7274
 7275        self.outdent(&Outdent, window, cx);
 7276    }
 7277
 7278    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7279        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7280            return;
 7281        }
 7282
 7283        let mut selections = self.selections.all_adjusted(cx);
 7284        let buffer = self.buffer.read(cx);
 7285        let snapshot = buffer.snapshot(cx);
 7286        let rows_iter = selections.iter().map(|s| s.head().row);
 7287        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7288
 7289        let mut edits = Vec::new();
 7290        let mut prev_edited_row = 0;
 7291        let mut row_delta = 0;
 7292        for selection in &mut selections {
 7293            if selection.start.row != prev_edited_row {
 7294                row_delta = 0;
 7295            }
 7296            prev_edited_row = selection.end.row;
 7297
 7298            // If the selection is non-empty, then increase the indentation of the selected lines.
 7299            if !selection.is_empty() {
 7300                row_delta =
 7301                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7302                continue;
 7303            }
 7304
 7305            // If the selection is empty and the cursor is in the leading whitespace before the
 7306            // suggested indentation, then auto-indent the line.
 7307            let cursor = selection.head();
 7308            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7309            if let Some(suggested_indent) =
 7310                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7311            {
 7312                if cursor.column < suggested_indent.len
 7313                    && cursor.column <= current_indent.len
 7314                    && current_indent.len <= suggested_indent.len
 7315                {
 7316                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7317                    selection.end = selection.start;
 7318                    if row_delta == 0 {
 7319                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7320                            cursor.row,
 7321                            current_indent,
 7322                            suggested_indent,
 7323                        ));
 7324                        row_delta = suggested_indent.len - current_indent.len;
 7325                    }
 7326                    continue;
 7327                }
 7328            }
 7329
 7330            // Otherwise, insert a hard or soft tab.
 7331            let settings = buffer.settings_at(cursor, cx);
 7332            let tab_size = if settings.hard_tabs {
 7333                IndentSize::tab()
 7334            } else {
 7335                let tab_size = settings.tab_size.get();
 7336                let char_column = snapshot
 7337                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7338                    .flat_map(str::chars)
 7339                    .count()
 7340                    + row_delta as usize;
 7341                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7342                IndentSize::spaces(chars_to_next_tab_stop)
 7343            };
 7344            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7345            selection.end = selection.start;
 7346            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7347            row_delta += tab_size.len;
 7348        }
 7349
 7350        self.transact(window, cx, |this, window, cx| {
 7351            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7352            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7353                s.select(selections)
 7354            });
 7355            this.refresh_inline_completion(true, false, window, cx);
 7356        });
 7357    }
 7358
 7359    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7360        if self.read_only(cx) {
 7361            return;
 7362        }
 7363        let mut selections = self.selections.all::<Point>(cx);
 7364        let mut prev_edited_row = 0;
 7365        let mut row_delta = 0;
 7366        let mut edits = Vec::new();
 7367        let buffer = self.buffer.read(cx);
 7368        let snapshot = buffer.snapshot(cx);
 7369        for selection in &mut selections {
 7370            if selection.start.row != prev_edited_row {
 7371                row_delta = 0;
 7372            }
 7373            prev_edited_row = selection.end.row;
 7374
 7375            row_delta =
 7376                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7377        }
 7378
 7379        self.transact(window, cx, |this, window, cx| {
 7380            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7381            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7382                s.select(selections)
 7383            });
 7384        });
 7385    }
 7386
 7387    fn indent_selection(
 7388        buffer: &MultiBuffer,
 7389        snapshot: &MultiBufferSnapshot,
 7390        selection: &mut Selection<Point>,
 7391        edits: &mut Vec<(Range<Point>, String)>,
 7392        delta_for_start_row: u32,
 7393        cx: &App,
 7394    ) -> u32 {
 7395        let settings = buffer.settings_at(selection.start, cx);
 7396        let tab_size = settings.tab_size.get();
 7397        let indent_kind = if settings.hard_tabs {
 7398            IndentKind::Tab
 7399        } else {
 7400            IndentKind::Space
 7401        };
 7402        let mut start_row = selection.start.row;
 7403        let mut end_row = selection.end.row + 1;
 7404
 7405        // If a selection ends at the beginning of a line, don't indent
 7406        // that last line.
 7407        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7408            end_row -= 1;
 7409        }
 7410
 7411        // Avoid re-indenting a row that has already been indented by a
 7412        // previous selection, but still update this selection's column
 7413        // to reflect that indentation.
 7414        if delta_for_start_row > 0 {
 7415            start_row += 1;
 7416            selection.start.column += delta_for_start_row;
 7417            if selection.end.row == selection.start.row {
 7418                selection.end.column += delta_for_start_row;
 7419            }
 7420        }
 7421
 7422        let mut delta_for_end_row = 0;
 7423        let has_multiple_rows = start_row + 1 != end_row;
 7424        for row in start_row..end_row {
 7425            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7426            let indent_delta = match (current_indent.kind, indent_kind) {
 7427                (IndentKind::Space, IndentKind::Space) => {
 7428                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7429                    IndentSize::spaces(columns_to_next_tab_stop)
 7430                }
 7431                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7432                (_, IndentKind::Tab) => IndentSize::tab(),
 7433            };
 7434
 7435            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7436                0
 7437            } else {
 7438                selection.start.column
 7439            };
 7440            let row_start = Point::new(row, start);
 7441            edits.push((
 7442                row_start..row_start,
 7443                indent_delta.chars().collect::<String>(),
 7444            ));
 7445
 7446            // Update this selection's endpoints to reflect the indentation.
 7447            if row == selection.start.row {
 7448                selection.start.column += indent_delta.len;
 7449            }
 7450            if row == selection.end.row {
 7451                selection.end.column += indent_delta.len;
 7452                delta_for_end_row = indent_delta.len;
 7453            }
 7454        }
 7455
 7456        if selection.start.row == selection.end.row {
 7457            delta_for_start_row + delta_for_end_row
 7458        } else {
 7459            delta_for_end_row
 7460        }
 7461    }
 7462
 7463    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7464        if self.read_only(cx) {
 7465            return;
 7466        }
 7467        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7468        let selections = self.selections.all::<Point>(cx);
 7469        let mut deletion_ranges = Vec::new();
 7470        let mut last_outdent = None;
 7471        {
 7472            let buffer = self.buffer.read(cx);
 7473            let snapshot = buffer.snapshot(cx);
 7474            for selection in &selections {
 7475                let settings = buffer.settings_at(selection.start, cx);
 7476                let tab_size = settings.tab_size.get();
 7477                let mut rows = selection.spanned_rows(false, &display_map);
 7478
 7479                // Avoid re-outdenting a row that has already been outdented by a
 7480                // previous selection.
 7481                if let Some(last_row) = last_outdent {
 7482                    if last_row == rows.start {
 7483                        rows.start = rows.start.next_row();
 7484                    }
 7485                }
 7486                let has_multiple_rows = rows.len() > 1;
 7487                for row in rows.iter_rows() {
 7488                    let indent_size = snapshot.indent_size_for_line(row);
 7489                    if indent_size.len > 0 {
 7490                        let deletion_len = match indent_size.kind {
 7491                            IndentKind::Space => {
 7492                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7493                                if columns_to_prev_tab_stop == 0 {
 7494                                    tab_size
 7495                                } else {
 7496                                    columns_to_prev_tab_stop
 7497                                }
 7498                            }
 7499                            IndentKind::Tab => 1,
 7500                        };
 7501                        let start = if has_multiple_rows
 7502                            || deletion_len > selection.start.column
 7503                            || indent_size.len < selection.start.column
 7504                        {
 7505                            0
 7506                        } else {
 7507                            selection.start.column - deletion_len
 7508                        };
 7509                        deletion_ranges.push(
 7510                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7511                        );
 7512                        last_outdent = Some(row);
 7513                    }
 7514                }
 7515            }
 7516        }
 7517
 7518        self.transact(window, cx, |this, window, cx| {
 7519            this.buffer.update(cx, |buffer, cx| {
 7520                let empty_str: Arc<str> = Arc::default();
 7521                buffer.edit(
 7522                    deletion_ranges
 7523                        .into_iter()
 7524                        .map(|range| (range, empty_str.clone())),
 7525                    None,
 7526                    cx,
 7527                );
 7528            });
 7529            let selections = this.selections.all::<usize>(cx);
 7530            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7531                s.select(selections)
 7532            });
 7533        });
 7534    }
 7535
 7536    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7537        if self.read_only(cx) {
 7538            return;
 7539        }
 7540        let selections = self
 7541            .selections
 7542            .all::<usize>(cx)
 7543            .into_iter()
 7544            .map(|s| s.range());
 7545
 7546        self.transact(window, cx, |this, window, cx| {
 7547            this.buffer.update(cx, |buffer, cx| {
 7548                buffer.autoindent_ranges(selections, cx);
 7549            });
 7550            let selections = this.selections.all::<usize>(cx);
 7551            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7552                s.select(selections)
 7553            });
 7554        });
 7555    }
 7556
 7557    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7558        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7559        let selections = self.selections.all::<Point>(cx);
 7560
 7561        let mut new_cursors = Vec::new();
 7562        let mut edit_ranges = Vec::new();
 7563        let mut selections = selections.iter().peekable();
 7564        while let Some(selection) = selections.next() {
 7565            let mut rows = selection.spanned_rows(false, &display_map);
 7566            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7567
 7568            // Accumulate contiguous regions of rows that we want to delete.
 7569            while let Some(next_selection) = selections.peek() {
 7570                let next_rows = next_selection.spanned_rows(false, &display_map);
 7571                if next_rows.start <= rows.end {
 7572                    rows.end = next_rows.end;
 7573                    selections.next().unwrap();
 7574                } else {
 7575                    break;
 7576                }
 7577            }
 7578
 7579            let buffer = &display_map.buffer_snapshot;
 7580            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7581            let edit_end;
 7582            let cursor_buffer_row;
 7583            if buffer.max_point().row >= rows.end.0 {
 7584                // If there's a line after the range, delete the \n from the end of the row range
 7585                // and position the cursor on the next line.
 7586                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7587                cursor_buffer_row = rows.end;
 7588            } else {
 7589                // If there isn't a line after the range, delete the \n from the line before the
 7590                // start of the row range and position the cursor there.
 7591                edit_start = edit_start.saturating_sub(1);
 7592                edit_end = buffer.len();
 7593                cursor_buffer_row = rows.start.previous_row();
 7594            }
 7595
 7596            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7597            *cursor.column_mut() =
 7598                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7599
 7600            new_cursors.push((
 7601                selection.id,
 7602                buffer.anchor_after(cursor.to_point(&display_map)),
 7603            ));
 7604            edit_ranges.push(edit_start..edit_end);
 7605        }
 7606
 7607        self.transact(window, cx, |this, window, cx| {
 7608            let buffer = this.buffer.update(cx, |buffer, cx| {
 7609                let empty_str: Arc<str> = Arc::default();
 7610                buffer.edit(
 7611                    edit_ranges
 7612                        .into_iter()
 7613                        .map(|range| (range, empty_str.clone())),
 7614                    None,
 7615                    cx,
 7616                );
 7617                buffer.snapshot(cx)
 7618            });
 7619            let new_selections = new_cursors
 7620                .into_iter()
 7621                .map(|(id, cursor)| {
 7622                    let cursor = cursor.to_point(&buffer);
 7623                    Selection {
 7624                        id,
 7625                        start: cursor,
 7626                        end: cursor,
 7627                        reversed: false,
 7628                        goal: SelectionGoal::None,
 7629                    }
 7630                })
 7631                .collect();
 7632
 7633            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7634                s.select(new_selections);
 7635            });
 7636        });
 7637    }
 7638
 7639    pub fn join_lines_impl(
 7640        &mut self,
 7641        insert_whitespace: bool,
 7642        window: &mut Window,
 7643        cx: &mut Context<Self>,
 7644    ) {
 7645        if self.read_only(cx) {
 7646            return;
 7647        }
 7648        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7649        for selection in self.selections.all::<Point>(cx) {
 7650            let start = MultiBufferRow(selection.start.row);
 7651            // Treat single line selections as if they include the next line. Otherwise this action
 7652            // would do nothing for single line selections individual cursors.
 7653            let end = if selection.start.row == selection.end.row {
 7654                MultiBufferRow(selection.start.row + 1)
 7655            } else {
 7656                MultiBufferRow(selection.end.row)
 7657            };
 7658
 7659            if let Some(last_row_range) = row_ranges.last_mut() {
 7660                if start <= last_row_range.end {
 7661                    last_row_range.end = end;
 7662                    continue;
 7663                }
 7664            }
 7665            row_ranges.push(start..end);
 7666        }
 7667
 7668        let snapshot = self.buffer.read(cx).snapshot(cx);
 7669        let mut cursor_positions = Vec::new();
 7670        for row_range in &row_ranges {
 7671            let anchor = snapshot.anchor_before(Point::new(
 7672                row_range.end.previous_row().0,
 7673                snapshot.line_len(row_range.end.previous_row()),
 7674            ));
 7675            cursor_positions.push(anchor..anchor);
 7676        }
 7677
 7678        self.transact(window, cx, |this, window, cx| {
 7679            for row_range in row_ranges.into_iter().rev() {
 7680                for row in row_range.iter_rows().rev() {
 7681                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7682                    let next_line_row = row.next_row();
 7683                    let indent = snapshot.indent_size_for_line(next_line_row);
 7684                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7685
 7686                    let replace =
 7687                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7688                            " "
 7689                        } else {
 7690                            ""
 7691                        };
 7692
 7693                    this.buffer.update(cx, |buffer, cx| {
 7694                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7695                    });
 7696                }
 7697            }
 7698
 7699            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7700                s.select_anchor_ranges(cursor_positions)
 7701            });
 7702        });
 7703    }
 7704
 7705    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7706        self.join_lines_impl(true, window, cx);
 7707    }
 7708
 7709    pub fn sort_lines_case_sensitive(
 7710        &mut self,
 7711        _: &SortLinesCaseSensitive,
 7712        window: &mut Window,
 7713        cx: &mut Context<Self>,
 7714    ) {
 7715        self.manipulate_lines(window, cx, |lines| lines.sort())
 7716    }
 7717
 7718    pub fn sort_lines_case_insensitive(
 7719        &mut self,
 7720        _: &SortLinesCaseInsensitive,
 7721        window: &mut Window,
 7722        cx: &mut Context<Self>,
 7723    ) {
 7724        self.manipulate_lines(window, cx, |lines| {
 7725            lines.sort_by_key(|line| line.to_lowercase())
 7726        })
 7727    }
 7728
 7729    pub fn unique_lines_case_insensitive(
 7730        &mut self,
 7731        _: &UniqueLinesCaseInsensitive,
 7732        window: &mut Window,
 7733        cx: &mut Context<Self>,
 7734    ) {
 7735        self.manipulate_lines(window, cx, |lines| {
 7736            let mut seen = HashSet::default();
 7737            lines.retain(|line| seen.insert(line.to_lowercase()));
 7738        })
 7739    }
 7740
 7741    pub fn unique_lines_case_sensitive(
 7742        &mut self,
 7743        _: &UniqueLinesCaseSensitive,
 7744        window: &mut Window,
 7745        cx: &mut Context<Self>,
 7746    ) {
 7747        self.manipulate_lines(window, cx, |lines| {
 7748            let mut seen = HashSet::default();
 7749            lines.retain(|line| seen.insert(*line));
 7750        })
 7751    }
 7752
 7753    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7754        let Some(project) = self.project.clone() else {
 7755            return;
 7756        };
 7757        self.reload(project, window, cx)
 7758            .detach_and_notify_err(window, cx);
 7759    }
 7760
 7761    pub fn restore_file(
 7762        &mut self,
 7763        _: &::git::RestoreFile,
 7764        window: &mut Window,
 7765        cx: &mut Context<Self>,
 7766    ) {
 7767        let mut buffer_ids = HashSet::default();
 7768        let snapshot = self.buffer().read(cx).snapshot(cx);
 7769        for selection in self.selections.all::<usize>(cx) {
 7770            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7771        }
 7772
 7773        let buffer = self.buffer().read(cx);
 7774        let ranges = buffer_ids
 7775            .into_iter()
 7776            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7777            .collect::<Vec<_>>();
 7778
 7779        self.restore_hunks_in_ranges(ranges, window, cx);
 7780    }
 7781
 7782    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7783        let selections = self
 7784            .selections
 7785            .all(cx)
 7786            .into_iter()
 7787            .map(|s| s.range())
 7788            .collect();
 7789        self.restore_hunks_in_ranges(selections, window, cx);
 7790    }
 7791
 7792    fn restore_hunks_in_ranges(
 7793        &mut self,
 7794        ranges: Vec<Range<Point>>,
 7795        window: &mut Window,
 7796        cx: &mut Context<Editor>,
 7797    ) {
 7798        let mut revert_changes = HashMap::default();
 7799        let chunk_by = self
 7800            .snapshot(window, cx)
 7801            .hunks_for_ranges(ranges)
 7802            .into_iter()
 7803            .chunk_by(|hunk| hunk.buffer_id);
 7804        for (buffer_id, hunks) in &chunk_by {
 7805            let hunks = hunks.collect::<Vec<_>>();
 7806            for hunk in &hunks {
 7807                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7808            }
 7809            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), window, cx);
 7810        }
 7811        drop(chunk_by);
 7812        if !revert_changes.is_empty() {
 7813            self.transact(window, cx, |editor, window, cx| {
 7814                editor.restore(revert_changes, window, cx);
 7815            });
 7816        }
 7817    }
 7818
 7819    pub fn open_active_item_in_terminal(
 7820        &mut self,
 7821        _: &OpenInTerminal,
 7822        window: &mut Window,
 7823        cx: &mut Context<Self>,
 7824    ) {
 7825        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7826            let project_path = buffer.read(cx).project_path(cx)?;
 7827            let project = self.project.as_ref()?.read(cx);
 7828            let entry = project.entry_for_path(&project_path, cx)?;
 7829            let parent = match &entry.canonical_path {
 7830                Some(canonical_path) => canonical_path.to_path_buf(),
 7831                None => project.absolute_path(&project_path, cx)?,
 7832            }
 7833            .parent()?
 7834            .to_path_buf();
 7835            Some(parent)
 7836        }) {
 7837            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7838        }
 7839    }
 7840
 7841    pub fn prepare_restore_change(
 7842        &self,
 7843        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7844        hunk: &MultiBufferDiffHunk,
 7845        cx: &mut App,
 7846    ) -> Option<()> {
 7847        let buffer = self.buffer.read(cx);
 7848        let diff = buffer.diff_for(hunk.buffer_id)?;
 7849        let buffer = buffer.buffer(hunk.buffer_id)?;
 7850        let buffer = buffer.read(cx);
 7851        let original_text = diff
 7852            .read(cx)
 7853            .base_text()
 7854            .as_rope()
 7855            .slice(hunk.diff_base_byte_range.clone());
 7856        let buffer_snapshot = buffer.snapshot();
 7857        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7858        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7859            probe
 7860                .0
 7861                .start
 7862                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7863                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7864        }) {
 7865            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7866            Some(())
 7867        } else {
 7868            None
 7869        }
 7870    }
 7871
 7872    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7873        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7874    }
 7875
 7876    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7877        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7878    }
 7879
 7880    fn manipulate_lines<Fn>(
 7881        &mut self,
 7882        window: &mut Window,
 7883        cx: &mut Context<Self>,
 7884        mut callback: Fn,
 7885    ) where
 7886        Fn: FnMut(&mut Vec<&str>),
 7887    {
 7888        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7889        let buffer = self.buffer.read(cx).snapshot(cx);
 7890
 7891        let mut edits = Vec::new();
 7892
 7893        let selections = self.selections.all::<Point>(cx);
 7894        let mut selections = selections.iter().peekable();
 7895        let mut contiguous_row_selections = Vec::new();
 7896        let mut new_selections = Vec::new();
 7897        let mut added_lines = 0;
 7898        let mut removed_lines = 0;
 7899
 7900        while let Some(selection) = selections.next() {
 7901            let (start_row, end_row) = consume_contiguous_rows(
 7902                &mut contiguous_row_selections,
 7903                selection,
 7904                &display_map,
 7905                &mut selections,
 7906            );
 7907
 7908            let start_point = Point::new(start_row.0, 0);
 7909            let end_point = Point::new(
 7910                end_row.previous_row().0,
 7911                buffer.line_len(end_row.previous_row()),
 7912            );
 7913            let text = buffer
 7914                .text_for_range(start_point..end_point)
 7915                .collect::<String>();
 7916
 7917            let mut lines = text.split('\n').collect_vec();
 7918
 7919            let lines_before = lines.len();
 7920            callback(&mut lines);
 7921            let lines_after = lines.len();
 7922
 7923            edits.push((start_point..end_point, lines.join("\n")));
 7924
 7925            // Selections must change based on added and removed line count
 7926            let start_row =
 7927                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7928            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7929            new_selections.push(Selection {
 7930                id: selection.id,
 7931                start: start_row,
 7932                end: end_row,
 7933                goal: SelectionGoal::None,
 7934                reversed: selection.reversed,
 7935            });
 7936
 7937            if lines_after > lines_before {
 7938                added_lines += lines_after - lines_before;
 7939            } else if lines_before > lines_after {
 7940                removed_lines += lines_before - lines_after;
 7941            }
 7942        }
 7943
 7944        self.transact(window, cx, |this, window, cx| {
 7945            let buffer = this.buffer.update(cx, |buffer, cx| {
 7946                buffer.edit(edits, None, cx);
 7947                buffer.snapshot(cx)
 7948            });
 7949
 7950            // Recalculate offsets on newly edited buffer
 7951            let new_selections = new_selections
 7952                .iter()
 7953                .map(|s| {
 7954                    let start_point = Point::new(s.start.0, 0);
 7955                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7956                    Selection {
 7957                        id: s.id,
 7958                        start: buffer.point_to_offset(start_point),
 7959                        end: buffer.point_to_offset(end_point),
 7960                        goal: s.goal,
 7961                        reversed: s.reversed,
 7962                    }
 7963                })
 7964                .collect();
 7965
 7966            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7967                s.select(new_selections);
 7968            });
 7969
 7970            this.request_autoscroll(Autoscroll::fit(), cx);
 7971        });
 7972    }
 7973
 7974    pub fn convert_to_upper_case(
 7975        &mut self,
 7976        _: &ConvertToUpperCase,
 7977        window: &mut Window,
 7978        cx: &mut Context<Self>,
 7979    ) {
 7980        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7981    }
 7982
 7983    pub fn convert_to_lower_case(
 7984        &mut self,
 7985        _: &ConvertToLowerCase,
 7986        window: &mut Window,
 7987        cx: &mut Context<Self>,
 7988    ) {
 7989        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7990    }
 7991
 7992    pub fn convert_to_title_case(
 7993        &mut self,
 7994        _: &ConvertToTitleCase,
 7995        window: &mut Window,
 7996        cx: &mut Context<Self>,
 7997    ) {
 7998        self.manipulate_text(window, cx, |text| {
 7999            text.split('\n')
 8000                .map(|line| line.to_case(Case::Title))
 8001                .join("\n")
 8002        })
 8003    }
 8004
 8005    pub fn convert_to_snake_case(
 8006        &mut self,
 8007        _: &ConvertToSnakeCase,
 8008        window: &mut Window,
 8009        cx: &mut Context<Self>,
 8010    ) {
 8011        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8012    }
 8013
 8014    pub fn convert_to_kebab_case(
 8015        &mut self,
 8016        _: &ConvertToKebabCase,
 8017        window: &mut Window,
 8018        cx: &mut Context<Self>,
 8019    ) {
 8020        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8021    }
 8022
 8023    pub fn convert_to_upper_camel_case(
 8024        &mut self,
 8025        _: &ConvertToUpperCamelCase,
 8026        window: &mut Window,
 8027        cx: &mut Context<Self>,
 8028    ) {
 8029        self.manipulate_text(window, cx, |text| {
 8030            text.split('\n')
 8031                .map(|line| line.to_case(Case::UpperCamel))
 8032                .join("\n")
 8033        })
 8034    }
 8035
 8036    pub fn convert_to_lower_camel_case(
 8037        &mut self,
 8038        _: &ConvertToLowerCamelCase,
 8039        window: &mut Window,
 8040        cx: &mut Context<Self>,
 8041    ) {
 8042        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8043    }
 8044
 8045    pub fn convert_to_opposite_case(
 8046        &mut self,
 8047        _: &ConvertToOppositeCase,
 8048        window: &mut Window,
 8049        cx: &mut Context<Self>,
 8050    ) {
 8051        self.manipulate_text(window, cx, |text| {
 8052            text.chars()
 8053                .fold(String::with_capacity(text.len()), |mut t, c| {
 8054                    if c.is_uppercase() {
 8055                        t.extend(c.to_lowercase());
 8056                    } else {
 8057                        t.extend(c.to_uppercase());
 8058                    }
 8059                    t
 8060                })
 8061        })
 8062    }
 8063
 8064    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8065    where
 8066        Fn: FnMut(&str) -> String,
 8067    {
 8068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8069        let buffer = self.buffer.read(cx).snapshot(cx);
 8070
 8071        let mut new_selections = Vec::new();
 8072        let mut edits = Vec::new();
 8073        let mut selection_adjustment = 0i32;
 8074
 8075        for selection in self.selections.all::<usize>(cx) {
 8076            let selection_is_empty = selection.is_empty();
 8077
 8078            let (start, end) = if selection_is_empty {
 8079                let word_range = movement::surrounding_word(
 8080                    &display_map,
 8081                    selection.start.to_display_point(&display_map),
 8082                );
 8083                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8084                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8085                (start, end)
 8086            } else {
 8087                (selection.start, selection.end)
 8088            };
 8089
 8090            let text = buffer.text_for_range(start..end).collect::<String>();
 8091            let old_length = text.len() as i32;
 8092            let text = callback(&text);
 8093
 8094            new_selections.push(Selection {
 8095                start: (start as i32 - selection_adjustment) as usize,
 8096                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8097                goal: SelectionGoal::None,
 8098                ..selection
 8099            });
 8100
 8101            selection_adjustment += old_length - text.len() as i32;
 8102
 8103            edits.push((start..end, text));
 8104        }
 8105
 8106        self.transact(window, cx, |this, window, cx| {
 8107            this.buffer.update(cx, |buffer, cx| {
 8108                buffer.edit(edits, None, cx);
 8109            });
 8110
 8111            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8112                s.select(new_selections);
 8113            });
 8114
 8115            this.request_autoscroll(Autoscroll::fit(), cx);
 8116        });
 8117    }
 8118
 8119    pub fn duplicate(
 8120        &mut self,
 8121        upwards: bool,
 8122        whole_lines: bool,
 8123        window: &mut Window,
 8124        cx: &mut Context<Self>,
 8125    ) {
 8126        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8127        let buffer = &display_map.buffer_snapshot;
 8128        let selections = self.selections.all::<Point>(cx);
 8129
 8130        let mut edits = Vec::new();
 8131        let mut selections_iter = selections.iter().peekable();
 8132        while let Some(selection) = selections_iter.next() {
 8133            let mut rows = selection.spanned_rows(false, &display_map);
 8134            // duplicate line-wise
 8135            if whole_lines || selection.start == selection.end {
 8136                // Avoid duplicating the same lines twice.
 8137                while let Some(next_selection) = selections_iter.peek() {
 8138                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8139                    if next_rows.start < rows.end {
 8140                        rows.end = next_rows.end;
 8141                        selections_iter.next().unwrap();
 8142                    } else {
 8143                        break;
 8144                    }
 8145                }
 8146
 8147                // Copy the text from the selected row region and splice it either at the start
 8148                // or end of the region.
 8149                let start = Point::new(rows.start.0, 0);
 8150                let end = Point::new(
 8151                    rows.end.previous_row().0,
 8152                    buffer.line_len(rows.end.previous_row()),
 8153                );
 8154                let text = buffer
 8155                    .text_for_range(start..end)
 8156                    .chain(Some("\n"))
 8157                    .collect::<String>();
 8158                let insert_location = if upwards {
 8159                    Point::new(rows.end.0, 0)
 8160                } else {
 8161                    start
 8162                };
 8163                edits.push((insert_location..insert_location, text));
 8164            } else {
 8165                // duplicate character-wise
 8166                let start = selection.start;
 8167                let end = selection.end;
 8168                let text = buffer.text_for_range(start..end).collect::<String>();
 8169                edits.push((selection.end..selection.end, text));
 8170            }
 8171        }
 8172
 8173        self.transact(window, cx, |this, _, cx| {
 8174            this.buffer.update(cx, |buffer, cx| {
 8175                buffer.edit(edits, None, cx);
 8176            });
 8177
 8178            this.request_autoscroll(Autoscroll::fit(), cx);
 8179        });
 8180    }
 8181
 8182    pub fn duplicate_line_up(
 8183        &mut self,
 8184        _: &DuplicateLineUp,
 8185        window: &mut Window,
 8186        cx: &mut Context<Self>,
 8187    ) {
 8188        self.duplicate(true, true, window, cx);
 8189    }
 8190
 8191    pub fn duplicate_line_down(
 8192        &mut self,
 8193        _: &DuplicateLineDown,
 8194        window: &mut Window,
 8195        cx: &mut Context<Self>,
 8196    ) {
 8197        self.duplicate(false, true, window, cx);
 8198    }
 8199
 8200    pub fn duplicate_selection(
 8201        &mut self,
 8202        _: &DuplicateSelection,
 8203        window: &mut Window,
 8204        cx: &mut Context<Self>,
 8205    ) {
 8206        self.duplicate(false, false, window, cx);
 8207    }
 8208
 8209    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8210        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8211        let buffer = self.buffer.read(cx).snapshot(cx);
 8212
 8213        let mut edits = Vec::new();
 8214        let mut unfold_ranges = Vec::new();
 8215        let mut refold_creases = Vec::new();
 8216
 8217        let selections = self.selections.all::<Point>(cx);
 8218        let mut selections = selections.iter().peekable();
 8219        let mut contiguous_row_selections = Vec::new();
 8220        let mut new_selections = Vec::new();
 8221
 8222        while let Some(selection) = selections.next() {
 8223            // Find all the selections that span a contiguous row range
 8224            let (start_row, end_row) = consume_contiguous_rows(
 8225                &mut contiguous_row_selections,
 8226                selection,
 8227                &display_map,
 8228                &mut selections,
 8229            );
 8230
 8231            // Move the text spanned by the row range to be before the line preceding the row range
 8232            if start_row.0 > 0 {
 8233                let range_to_move = Point::new(
 8234                    start_row.previous_row().0,
 8235                    buffer.line_len(start_row.previous_row()),
 8236                )
 8237                    ..Point::new(
 8238                        end_row.previous_row().0,
 8239                        buffer.line_len(end_row.previous_row()),
 8240                    );
 8241                let insertion_point = display_map
 8242                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8243                    .0;
 8244
 8245                // Don't move lines across excerpts
 8246                if buffer
 8247                    .excerpt_containing(insertion_point..range_to_move.end)
 8248                    .is_some()
 8249                {
 8250                    let text = buffer
 8251                        .text_for_range(range_to_move.clone())
 8252                        .flat_map(|s| s.chars())
 8253                        .skip(1)
 8254                        .chain(['\n'])
 8255                        .collect::<String>();
 8256
 8257                    edits.push((
 8258                        buffer.anchor_after(range_to_move.start)
 8259                            ..buffer.anchor_before(range_to_move.end),
 8260                        String::new(),
 8261                    ));
 8262                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8263                    edits.push((insertion_anchor..insertion_anchor, text));
 8264
 8265                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8266
 8267                    // Move selections up
 8268                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8269                        |mut selection| {
 8270                            selection.start.row -= row_delta;
 8271                            selection.end.row -= row_delta;
 8272                            selection
 8273                        },
 8274                    ));
 8275
 8276                    // Move folds up
 8277                    unfold_ranges.push(range_to_move.clone());
 8278                    for fold in display_map.folds_in_range(
 8279                        buffer.anchor_before(range_to_move.start)
 8280                            ..buffer.anchor_after(range_to_move.end),
 8281                    ) {
 8282                        let mut start = fold.range.start.to_point(&buffer);
 8283                        let mut end = fold.range.end.to_point(&buffer);
 8284                        start.row -= row_delta;
 8285                        end.row -= row_delta;
 8286                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8287                    }
 8288                }
 8289            }
 8290
 8291            // If we didn't move line(s), preserve the existing selections
 8292            new_selections.append(&mut contiguous_row_selections);
 8293        }
 8294
 8295        self.transact(window, cx, |this, window, cx| {
 8296            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8297            this.buffer.update(cx, |buffer, cx| {
 8298                for (range, text) in edits {
 8299                    buffer.edit([(range, text)], None, cx);
 8300                }
 8301            });
 8302            this.fold_creases(refold_creases, true, window, cx);
 8303            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8304                s.select(new_selections);
 8305            })
 8306        });
 8307    }
 8308
 8309    pub fn move_line_down(
 8310        &mut self,
 8311        _: &MoveLineDown,
 8312        window: &mut Window,
 8313        cx: &mut Context<Self>,
 8314    ) {
 8315        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8316        let buffer = self.buffer.read(cx).snapshot(cx);
 8317
 8318        let mut edits = Vec::new();
 8319        let mut unfold_ranges = Vec::new();
 8320        let mut refold_creases = Vec::new();
 8321
 8322        let selections = self.selections.all::<Point>(cx);
 8323        let mut selections = selections.iter().peekable();
 8324        let mut contiguous_row_selections = Vec::new();
 8325        let mut new_selections = Vec::new();
 8326
 8327        while let Some(selection) = selections.next() {
 8328            // Find all the selections that span a contiguous row range
 8329            let (start_row, end_row) = consume_contiguous_rows(
 8330                &mut contiguous_row_selections,
 8331                selection,
 8332                &display_map,
 8333                &mut selections,
 8334            );
 8335
 8336            // Move the text spanned by the row range to be after the last line of the row range
 8337            if end_row.0 <= buffer.max_point().row {
 8338                let range_to_move =
 8339                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8340                let insertion_point = display_map
 8341                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8342                    .0;
 8343
 8344                // Don't move lines across excerpt boundaries
 8345                if buffer
 8346                    .excerpt_containing(range_to_move.start..insertion_point)
 8347                    .is_some()
 8348                {
 8349                    let mut text = String::from("\n");
 8350                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8351                    text.pop(); // Drop trailing newline
 8352                    edits.push((
 8353                        buffer.anchor_after(range_to_move.start)
 8354                            ..buffer.anchor_before(range_to_move.end),
 8355                        String::new(),
 8356                    ));
 8357                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8358                    edits.push((insertion_anchor..insertion_anchor, text));
 8359
 8360                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8361
 8362                    // Move selections down
 8363                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8364                        |mut selection| {
 8365                            selection.start.row += row_delta;
 8366                            selection.end.row += row_delta;
 8367                            selection
 8368                        },
 8369                    ));
 8370
 8371                    // Move folds down
 8372                    unfold_ranges.push(range_to_move.clone());
 8373                    for fold in display_map.folds_in_range(
 8374                        buffer.anchor_before(range_to_move.start)
 8375                            ..buffer.anchor_after(range_to_move.end),
 8376                    ) {
 8377                        let mut start = fold.range.start.to_point(&buffer);
 8378                        let mut end = fold.range.end.to_point(&buffer);
 8379                        start.row += row_delta;
 8380                        end.row += row_delta;
 8381                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8382                    }
 8383                }
 8384            }
 8385
 8386            // If we didn't move line(s), preserve the existing selections
 8387            new_selections.append(&mut contiguous_row_selections);
 8388        }
 8389
 8390        self.transact(window, cx, |this, window, cx| {
 8391            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8392            this.buffer.update(cx, |buffer, cx| {
 8393                for (range, text) in edits {
 8394                    buffer.edit([(range, text)], None, cx);
 8395                }
 8396            });
 8397            this.fold_creases(refold_creases, true, window, cx);
 8398            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8399                s.select(new_selections)
 8400            });
 8401        });
 8402    }
 8403
 8404    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8405        let text_layout_details = &self.text_layout_details(window);
 8406        self.transact(window, cx, |this, window, cx| {
 8407            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8408                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8409                let line_mode = s.line_mode;
 8410                s.move_with(|display_map, selection| {
 8411                    if !selection.is_empty() || line_mode {
 8412                        return;
 8413                    }
 8414
 8415                    let mut head = selection.head();
 8416                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8417                    if head.column() == display_map.line_len(head.row()) {
 8418                        transpose_offset = display_map
 8419                            .buffer_snapshot
 8420                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8421                    }
 8422
 8423                    if transpose_offset == 0 {
 8424                        return;
 8425                    }
 8426
 8427                    *head.column_mut() += 1;
 8428                    head = display_map.clip_point(head, Bias::Right);
 8429                    let goal = SelectionGoal::HorizontalPosition(
 8430                        display_map
 8431                            .x_for_display_point(head, text_layout_details)
 8432                            .into(),
 8433                    );
 8434                    selection.collapse_to(head, goal);
 8435
 8436                    let transpose_start = display_map
 8437                        .buffer_snapshot
 8438                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8439                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8440                        let transpose_end = display_map
 8441                            .buffer_snapshot
 8442                            .clip_offset(transpose_offset + 1, Bias::Right);
 8443                        if let Some(ch) =
 8444                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8445                        {
 8446                            edits.push((transpose_start..transpose_offset, String::new()));
 8447                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8448                        }
 8449                    }
 8450                });
 8451                edits
 8452            });
 8453            this.buffer
 8454                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8455            let selections = this.selections.all::<usize>(cx);
 8456            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8457                s.select(selections);
 8458            });
 8459        });
 8460    }
 8461
 8462    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8463        self.rewrap_impl(IsVimMode::No, cx)
 8464    }
 8465
 8466    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8467        let buffer = self.buffer.read(cx).snapshot(cx);
 8468        let selections = self.selections.all::<Point>(cx);
 8469        let mut selections = selections.iter().peekable();
 8470
 8471        let mut edits = Vec::new();
 8472        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8473
 8474        while let Some(selection) = selections.next() {
 8475            let mut start_row = selection.start.row;
 8476            let mut end_row = selection.end.row;
 8477
 8478            // Skip selections that overlap with a range that has already been rewrapped.
 8479            let selection_range = start_row..end_row;
 8480            if rewrapped_row_ranges
 8481                .iter()
 8482                .any(|range| range.overlaps(&selection_range))
 8483            {
 8484                continue;
 8485            }
 8486
 8487            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8488
 8489            // Since not all lines in the selection may be at the same indent
 8490            // level, choose the indent size that is the most common between all
 8491            // of the lines.
 8492            //
 8493            // If there is a tie, we use the deepest indent.
 8494            let (indent_size, indent_end) = {
 8495                let mut indent_size_occurrences = HashMap::default();
 8496                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8497
 8498                for row in start_row..=end_row {
 8499                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8500                    rows_by_indent_size.entry(indent).or_default().push(row);
 8501                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8502                }
 8503
 8504                let indent_size = indent_size_occurrences
 8505                    .into_iter()
 8506                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8507                    .map(|(indent, _)| indent)
 8508                    .unwrap_or_default();
 8509                let row = rows_by_indent_size[&indent_size][0];
 8510                let indent_end = Point::new(row, indent_size.len);
 8511
 8512                (indent_size, indent_end)
 8513            };
 8514
 8515            let mut line_prefix = indent_size.chars().collect::<String>();
 8516
 8517            let mut inside_comment = false;
 8518            if let Some(comment_prefix) =
 8519                buffer
 8520                    .language_scope_at(selection.head())
 8521                    .and_then(|language| {
 8522                        language
 8523                            .line_comment_prefixes()
 8524                            .iter()
 8525                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8526                            .cloned()
 8527                    })
 8528            {
 8529                line_prefix.push_str(&comment_prefix);
 8530                inside_comment = true;
 8531            }
 8532
 8533            let language_settings = buffer.settings_at(selection.head(), cx);
 8534            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8535                RewrapBehavior::InComments => inside_comment,
 8536                RewrapBehavior::InSelections => !selection.is_empty(),
 8537                RewrapBehavior::Anywhere => true,
 8538            };
 8539
 8540            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8541            if !should_rewrap {
 8542                continue;
 8543            }
 8544
 8545            if selection.is_empty() {
 8546                'expand_upwards: while start_row > 0 {
 8547                    let prev_row = start_row - 1;
 8548                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8549                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8550                    {
 8551                        start_row = prev_row;
 8552                    } else {
 8553                        break 'expand_upwards;
 8554                    }
 8555                }
 8556
 8557                'expand_downwards: while end_row < buffer.max_point().row {
 8558                    let next_row = end_row + 1;
 8559                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8560                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8561                    {
 8562                        end_row = next_row;
 8563                    } else {
 8564                        break 'expand_downwards;
 8565                    }
 8566                }
 8567            }
 8568
 8569            let start = Point::new(start_row, 0);
 8570            let start_offset = start.to_offset(&buffer);
 8571            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8572            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8573            let Some(lines_without_prefixes) = selection_text
 8574                .lines()
 8575                .map(|line| {
 8576                    line.strip_prefix(&line_prefix)
 8577                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8578                        .ok_or_else(|| {
 8579                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8580                        })
 8581                })
 8582                .collect::<Result<Vec<_>, _>>()
 8583                .log_err()
 8584            else {
 8585                continue;
 8586            };
 8587
 8588            let wrap_column = buffer
 8589                .settings_at(Point::new(start_row, 0), cx)
 8590                .preferred_line_length as usize;
 8591            let wrapped_text = wrap_with_prefix(
 8592                line_prefix,
 8593                lines_without_prefixes.join(" "),
 8594                wrap_column,
 8595                tab_size,
 8596            );
 8597
 8598            // TODO: should always use char-based diff while still supporting cursor behavior that
 8599            // matches vim.
 8600            let mut diff_options = DiffOptions::default();
 8601            if is_vim_mode == IsVimMode::Yes {
 8602                diff_options.max_word_diff_len = 0;
 8603                diff_options.max_word_diff_line_count = 0;
 8604            } else {
 8605                diff_options.max_word_diff_len = usize::MAX;
 8606                diff_options.max_word_diff_line_count = usize::MAX;
 8607            }
 8608
 8609            for (old_range, new_text) in
 8610                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8611            {
 8612                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8613                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8614                edits.push((edit_start..edit_end, new_text));
 8615            }
 8616
 8617            rewrapped_row_ranges.push(start_row..=end_row);
 8618        }
 8619
 8620        self.buffer
 8621            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8622    }
 8623
 8624    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8625        let mut text = String::new();
 8626        let buffer = self.buffer.read(cx).snapshot(cx);
 8627        let mut selections = self.selections.all::<Point>(cx);
 8628        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8629        {
 8630            let max_point = buffer.max_point();
 8631            let mut is_first = true;
 8632            for selection in &mut selections {
 8633                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8634                if is_entire_line {
 8635                    selection.start = Point::new(selection.start.row, 0);
 8636                    if !selection.is_empty() && selection.end.column == 0 {
 8637                        selection.end = cmp::min(max_point, selection.end);
 8638                    } else {
 8639                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8640                    }
 8641                    selection.goal = SelectionGoal::None;
 8642                }
 8643                if is_first {
 8644                    is_first = false;
 8645                } else {
 8646                    text += "\n";
 8647                }
 8648                let mut len = 0;
 8649                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8650                    text.push_str(chunk);
 8651                    len += chunk.len();
 8652                }
 8653                clipboard_selections.push(ClipboardSelection {
 8654                    len,
 8655                    is_entire_line,
 8656                    start_column: selection.start.column,
 8657                });
 8658            }
 8659        }
 8660
 8661        self.transact(window, cx, |this, window, cx| {
 8662            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8663                s.select(selections);
 8664            });
 8665            this.insert("", window, cx);
 8666        });
 8667        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8668    }
 8669
 8670    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8671        let item = self.cut_common(window, cx);
 8672        cx.write_to_clipboard(item);
 8673    }
 8674
 8675    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8676        self.change_selections(None, window, cx, |s| {
 8677            s.move_with(|snapshot, sel| {
 8678                if sel.is_empty() {
 8679                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8680                }
 8681            });
 8682        });
 8683        let item = self.cut_common(window, cx);
 8684        cx.set_global(KillRing(item))
 8685    }
 8686
 8687    pub fn kill_ring_yank(
 8688        &mut self,
 8689        _: &KillRingYank,
 8690        window: &mut Window,
 8691        cx: &mut Context<Self>,
 8692    ) {
 8693        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8694            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8695                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8696            } else {
 8697                return;
 8698            }
 8699        } else {
 8700            return;
 8701        };
 8702        self.do_paste(&text, metadata, false, window, cx);
 8703    }
 8704
 8705    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8706        let selections = self.selections.all::<Point>(cx);
 8707        let buffer = self.buffer.read(cx).read(cx);
 8708        let mut text = String::new();
 8709
 8710        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8711        {
 8712            let max_point = buffer.max_point();
 8713            let mut is_first = true;
 8714            for selection in selections.iter() {
 8715                let mut start = selection.start;
 8716                let mut end = selection.end;
 8717                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8718                if is_entire_line {
 8719                    start = Point::new(start.row, 0);
 8720                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8721                }
 8722                if is_first {
 8723                    is_first = false;
 8724                } else {
 8725                    text += "\n";
 8726                }
 8727                let mut len = 0;
 8728                for chunk in buffer.text_for_range(start..end) {
 8729                    text.push_str(chunk);
 8730                    len += chunk.len();
 8731                }
 8732                clipboard_selections.push(ClipboardSelection {
 8733                    len,
 8734                    is_entire_line,
 8735                    start_column: start.column,
 8736                });
 8737            }
 8738        }
 8739
 8740        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8741            text,
 8742            clipboard_selections,
 8743        ));
 8744    }
 8745
 8746    pub fn do_paste(
 8747        &mut self,
 8748        text: &String,
 8749        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8750        handle_entire_lines: bool,
 8751        window: &mut Window,
 8752        cx: &mut Context<Self>,
 8753    ) {
 8754        if self.read_only(cx) {
 8755            return;
 8756        }
 8757
 8758        let clipboard_text = Cow::Borrowed(text);
 8759
 8760        self.transact(window, cx, |this, window, cx| {
 8761            if let Some(mut clipboard_selections) = clipboard_selections {
 8762                let old_selections = this.selections.all::<usize>(cx);
 8763                let all_selections_were_entire_line =
 8764                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8765                let first_selection_start_column =
 8766                    clipboard_selections.first().map(|s| s.start_column);
 8767                if clipboard_selections.len() != old_selections.len() {
 8768                    clipboard_selections.drain(..);
 8769                }
 8770                let cursor_offset = this.selections.last::<usize>(cx).head();
 8771                let mut auto_indent_on_paste = true;
 8772
 8773                this.buffer.update(cx, |buffer, cx| {
 8774                    let snapshot = buffer.read(cx);
 8775                    auto_indent_on_paste =
 8776                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8777
 8778                    let mut start_offset = 0;
 8779                    let mut edits = Vec::new();
 8780                    let mut original_start_columns = Vec::new();
 8781                    for (ix, selection) in old_selections.iter().enumerate() {
 8782                        let to_insert;
 8783                        let entire_line;
 8784                        let original_start_column;
 8785                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8786                            let end_offset = start_offset + clipboard_selection.len;
 8787                            to_insert = &clipboard_text[start_offset..end_offset];
 8788                            entire_line = clipboard_selection.is_entire_line;
 8789                            start_offset = end_offset + 1;
 8790                            original_start_column = Some(clipboard_selection.start_column);
 8791                        } else {
 8792                            to_insert = clipboard_text.as_str();
 8793                            entire_line = all_selections_were_entire_line;
 8794                            original_start_column = first_selection_start_column
 8795                        }
 8796
 8797                        // If the corresponding selection was empty when this slice of the
 8798                        // clipboard text was written, then the entire line containing the
 8799                        // selection was copied. If this selection is also currently empty,
 8800                        // then paste the line before the current line of the buffer.
 8801                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8802                            let column = selection.start.to_point(&snapshot).column as usize;
 8803                            let line_start = selection.start - column;
 8804                            line_start..line_start
 8805                        } else {
 8806                            selection.range()
 8807                        };
 8808
 8809                        edits.push((range, to_insert));
 8810                        original_start_columns.extend(original_start_column);
 8811                    }
 8812                    drop(snapshot);
 8813
 8814                    buffer.edit(
 8815                        edits,
 8816                        if auto_indent_on_paste {
 8817                            Some(AutoindentMode::Block {
 8818                                original_start_columns,
 8819                            })
 8820                        } else {
 8821                            None
 8822                        },
 8823                        cx,
 8824                    );
 8825                });
 8826
 8827                let selections = this.selections.all::<usize>(cx);
 8828                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8829                    s.select(selections)
 8830                });
 8831            } else {
 8832                this.insert(&clipboard_text, window, cx);
 8833            }
 8834        });
 8835    }
 8836
 8837    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8838        if let Some(item) = cx.read_from_clipboard() {
 8839            let entries = item.entries();
 8840
 8841            match entries.first() {
 8842                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8843                // of all the pasted entries.
 8844                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8845                    .do_paste(
 8846                        clipboard_string.text(),
 8847                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8848                        true,
 8849                        window,
 8850                        cx,
 8851                    ),
 8852                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8853            }
 8854        }
 8855    }
 8856
 8857    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8858        if self.read_only(cx) {
 8859            return;
 8860        }
 8861
 8862        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8863            if let Some((selections, _)) =
 8864                self.selection_history.transaction(transaction_id).cloned()
 8865            {
 8866                self.change_selections(None, window, cx, |s| {
 8867                    s.select_anchors(selections.to_vec());
 8868                });
 8869            } else {
 8870                log::error!(
 8871                    "No entry in selection_history found for undo. \
 8872                     This may correspond to a bug where undo does not update the selection. \
 8873                     If this is occurring, please add details to \
 8874                     https://github.com/zed-industries/zed/issues/22692"
 8875                );
 8876            }
 8877            self.request_autoscroll(Autoscroll::fit(), cx);
 8878            self.unmark_text(window, cx);
 8879            self.refresh_inline_completion(true, false, window, cx);
 8880            cx.emit(EditorEvent::Edited { transaction_id });
 8881            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8882        }
 8883    }
 8884
 8885    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8886        if self.read_only(cx) {
 8887            return;
 8888        }
 8889
 8890        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8891            if let Some((_, Some(selections))) =
 8892                self.selection_history.transaction(transaction_id).cloned()
 8893            {
 8894                self.change_selections(None, window, cx, |s| {
 8895                    s.select_anchors(selections.to_vec());
 8896                });
 8897            } else {
 8898                log::error!(
 8899                    "No entry in selection_history found for redo. \
 8900                     This may correspond to a bug where undo does not update the selection. \
 8901                     If this is occurring, please add details to \
 8902                     https://github.com/zed-industries/zed/issues/22692"
 8903                );
 8904            }
 8905            self.request_autoscroll(Autoscroll::fit(), cx);
 8906            self.unmark_text(window, cx);
 8907            self.refresh_inline_completion(true, false, window, cx);
 8908            cx.emit(EditorEvent::Edited { transaction_id });
 8909        }
 8910    }
 8911
 8912    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8913        self.buffer
 8914            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8915    }
 8916
 8917    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8918        self.buffer
 8919            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8920    }
 8921
 8922    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8923        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8924            let line_mode = s.line_mode;
 8925            s.move_with(|map, selection| {
 8926                let cursor = if selection.is_empty() && !line_mode {
 8927                    movement::left(map, selection.start)
 8928                } else {
 8929                    selection.start
 8930                };
 8931                selection.collapse_to(cursor, SelectionGoal::None);
 8932            });
 8933        })
 8934    }
 8935
 8936    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8937        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8938            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8939        })
 8940    }
 8941
 8942    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8943        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8944            let line_mode = s.line_mode;
 8945            s.move_with(|map, selection| {
 8946                let cursor = if selection.is_empty() && !line_mode {
 8947                    movement::right(map, selection.end)
 8948                } else {
 8949                    selection.end
 8950                };
 8951                selection.collapse_to(cursor, SelectionGoal::None)
 8952            });
 8953        })
 8954    }
 8955
 8956    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8957        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8958            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8959        })
 8960    }
 8961
 8962    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8963        if self.take_rename(true, window, cx).is_some() {
 8964            return;
 8965        }
 8966
 8967        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8968            cx.propagate();
 8969            return;
 8970        }
 8971
 8972        let text_layout_details = &self.text_layout_details(window);
 8973        let selection_count = self.selections.count();
 8974        let first_selection = self.selections.first_anchor();
 8975
 8976        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8977            let line_mode = s.line_mode;
 8978            s.move_with(|map, selection| {
 8979                if !selection.is_empty() && !line_mode {
 8980                    selection.goal = SelectionGoal::None;
 8981                }
 8982                let (cursor, goal) = movement::up(
 8983                    map,
 8984                    selection.start,
 8985                    selection.goal,
 8986                    false,
 8987                    text_layout_details,
 8988                );
 8989                selection.collapse_to(cursor, goal);
 8990            });
 8991        });
 8992
 8993        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8994        {
 8995            cx.propagate();
 8996        }
 8997    }
 8998
 8999    pub fn move_up_by_lines(
 9000        &mut self,
 9001        action: &MoveUpByLines,
 9002        window: &mut Window,
 9003        cx: &mut Context<Self>,
 9004    ) {
 9005        if self.take_rename(true, window, cx).is_some() {
 9006            return;
 9007        }
 9008
 9009        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9010            cx.propagate();
 9011            return;
 9012        }
 9013
 9014        let text_layout_details = &self.text_layout_details(window);
 9015
 9016        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9017            let line_mode = s.line_mode;
 9018            s.move_with(|map, selection| {
 9019                if !selection.is_empty() && !line_mode {
 9020                    selection.goal = SelectionGoal::None;
 9021                }
 9022                let (cursor, goal) = movement::up_by_rows(
 9023                    map,
 9024                    selection.start,
 9025                    action.lines,
 9026                    selection.goal,
 9027                    false,
 9028                    text_layout_details,
 9029                );
 9030                selection.collapse_to(cursor, goal);
 9031            });
 9032        })
 9033    }
 9034
 9035    pub fn move_down_by_lines(
 9036        &mut self,
 9037        action: &MoveDownByLines,
 9038        window: &mut Window,
 9039        cx: &mut Context<Self>,
 9040    ) {
 9041        if self.take_rename(true, window, cx).is_some() {
 9042            return;
 9043        }
 9044
 9045        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9046            cx.propagate();
 9047            return;
 9048        }
 9049
 9050        let text_layout_details = &self.text_layout_details(window);
 9051
 9052        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9053            let line_mode = s.line_mode;
 9054            s.move_with(|map, selection| {
 9055                if !selection.is_empty() && !line_mode {
 9056                    selection.goal = SelectionGoal::None;
 9057                }
 9058                let (cursor, goal) = movement::down_by_rows(
 9059                    map,
 9060                    selection.start,
 9061                    action.lines,
 9062                    selection.goal,
 9063                    false,
 9064                    text_layout_details,
 9065                );
 9066                selection.collapse_to(cursor, goal);
 9067            });
 9068        })
 9069    }
 9070
 9071    pub fn select_down_by_lines(
 9072        &mut self,
 9073        action: &SelectDownByLines,
 9074        window: &mut Window,
 9075        cx: &mut Context<Self>,
 9076    ) {
 9077        let text_layout_details = &self.text_layout_details(window);
 9078        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9079            s.move_heads_with(|map, head, goal| {
 9080                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9081            })
 9082        })
 9083    }
 9084
 9085    pub fn select_up_by_lines(
 9086        &mut self,
 9087        action: &SelectUpByLines,
 9088        window: &mut Window,
 9089        cx: &mut Context<Self>,
 9090    ) {
 9091        let text_layout_details = &self.text_layout_details(window);
 9092        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9093            s.move_heads_with(|map, head, goal| {
 9094                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9095            })
 9096        })
 9097    }
 9098
 9099    pub fn select_page_up(
 9100        &mut self,
 9101        _: &SelectPageUp,
 9102        window: &mut Window,
 9103        cx: &mut Context<Self>,
 9104    ) {
 9105        let Some(row_count) = self.visible_row_count() else {
 9106            return;
 9107        };
 9108
 9109        let text_layout_details = &self.text_layout_details(window);
 9110
 9111        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9112            s.move_heads_with(|map, head, goal| {
 9113                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9114            })
 9115        })
 9116    }
 9117
 9118    pub fn move_page_up(
 9119        &mut self,
 9120        action: &MovePageUp,
 9121        window: &mut Window,
 9122        cx: &mut Context<Self>,
 9123    ) {
 9124        if self.take_rename(true, window, cx).is_some() {
 9125            return;
 9126        }
 9127
 9128        if self
 9129            .context_menu
 9130            .borrow_mut()
 9131            .as_mut()
 9132            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9133            .unwrap_or(false)
 9134        {
 9135            return;
 9136        }
 9137
 9138        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9139            cx.propagate();
 9140            return;
 9141        }
 9142
 9143        let Some(row_count) = self.visible_row_count() else {
 9144            return;
 9145        };
 9146
 9147        let autoscroll = if action.center_cursor {
 9148            Autoscroll::center()
 9149        } else {
 9150            Autoscroll::fit()
 9151        };
 9152
 9153        let text_layout_details = &self.text_layout_details(window);
 9154
 9155        self.change_selections(Some(autoscroll), window, cx, |s| {
 9156            let line_mode = s.line_mode;
 9157            s.move_with(|map, selection| {
 9158                if !selection.is_empty() && !line_mode {
 9159                    selection.goal = SelectionGoal::None;
 9160                }
 9161                let (cursor, goal) = movement::up_by_rows(
 9162                    map,
 9163                    selection.end,
 9164                    row_count,
 9165                    selection.goal,
 9166                    false,
 9167                    text_layout_details,
 9168                );
 9169                selection.collapse_to(cursor, goal);
 9170            });
 9171        });
 9172    }
 9173
 9174    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9175        let text_layout_details = &self.text_layout_details(window);
 9176        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9177            s.move_heads_with(|map, head, goal| {
 9178                movement::up(map, head, goal, false, text_layout_details)
 9179            })
 9180        })
 9181    }
 9182
 9183    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9184        self.take_rename(true, window, cx);
 9185
 9186        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9187            cx.propagate();
 9188            return;
 9189        }
 9190
 9191        let text_layout_details = &self.text_layout_details(window);
 9192        let selection_count = self.selections.count();
 9193        let first_selection = self.selections.first_anchor();
 9194
 9195        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9196            let line_mode = s.line_mode;
 9197            s.move_with(|map, selection| {
 9198                if !selection.is_empty() && !line_mode {
 9199                    selection.goal = SelectionGoal::None;
 9200                }
 9201                let (cursor, goal) = movement::down(
 9202                    map,
 9203                    selection.end,
 9204                    selection.goal,
 9205                    false,
 9206                    text_layout_details,
 9207                );
 9208                selection.collapse_to(cursor, goal);
 9209            });
 9210        });
 9211
 9212        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9213        {
 9214            cx.propagate();
 9215        }
 9216    }
 9217
 9218    pub fn select_page_down(
 9219        &mut self,
 9220        _: &SelectPageDown,
 9221        window: &mut Window,
 9222        cx: &mut Context<Self>,
 9223    ) {
 9224        let Some(row_count) = self.visible_row_count() else {
 9225            return;
 9226        };
 9227
 9228        let text_layout_details = &self.text_layout_details(window);
 9229
 9230        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9231            s.move_heads_with(|map, head, goal| {
 9232                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9233            })
 9234        })
 9235    }
 9236
 9237    pub fn move_page_down(
 9238        &mut self,
 9239        action: &MovePageDown,
 9240        window: &mut Window,
 9241        cx: &mut Context<Self>,
 9242    ) {
 9243        if self.take_rename(true, window, cx).is_some() {
 9244            return;
 9245        }
 9246
 9247        if self
 9248            .context_menu
 9249            .borrow_mut()
 9250            .as_mut()
 9251            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9252            .unwrap_or(false)
 9253        {
 9254            return;
 9255        }
 9256
 9257        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9258            cx.propagate();
 9259            return;
 9260        }
 9261
 9262        let Some(row_count) = self.visible_row_count() else {
 9263            return;
 9264        };
 9265
 9266        let autoscroll = if action.center_cursor {
 9267            Autoscroll::center()
 9268        } else {
 9269            Autoscroll::fit()
 9270        };
 9271
 9272        let text_layout_details = &self.text_layout_details(window);
 9273        self.change_selections(Some(autoscroll), window, cx, |s| {
 9274            let line_mode = s.line_mode;
 9275            s.move_with(|map, selection| {
 9276                if !selection.is_empty() && !line_mode {
 9277                    selection.goal = SelectionGoal::None;
 9278                }
 9279                let (cursor, goal) = movement::down_by_rows(
 9280                    map,
 9281                    selection.end,
 9282                    row_count,
 9283                    selection.goal,
 9284                    false,
 9285                    text_layout_details,
 9286                );
 9287                selection.collapse_to(cursor, goal);
 9288            });
 9289        });
 9290    }
 9291
 9292    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9293        let text_layout_details = &self.text_layout_details(window);
 9294        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9295            s.move_heads_with(|map, head, goal| {
 9296                movement::down(map, head, goal, false, text_layout_details)
 9297            })
 9298        });
 9299    }
 9300
 9301    pub fn context_menu_first(
 9302        &mut self,
 9303        _: &ContextMenuFirst,
 9304        _window: &mut Window,
 9305        cx: &mut Context<Self>,
 9306    ) {
 9307        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9308            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9309        }
 9310    }
 9311
 9312    pub fn context_menu_prev(
 9313        &mut self,
 9314        _: &ContextMenuPrevious,
 9315        _window: &mut Window,
 9316        cx: &mut Context<Self>,
 9317    ) {
 9318        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9319            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9320        }
 9321    }
 9322
 9323    pub fn context_menu_next(
 9324        &mut self,
 9325        _: &ContextMenuNext,
 9326        _window: &mut Window,
 9327        cx: &mut Context<Self>,
 9328    ) {
 9329        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9330            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9331        }
 9332    }
 9333
 9334    pub fn context_menu_last(
 9335        &mut self,
 9336        _: &ContextMenuLast,
 9337        _window: &mut Window,
 9338        cx: &mut Context<Self>,
 9339    ) {
 9340        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9341            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9342        }
 9343    }
 9344
 9345    pub fn move_to_previous_word_start(
 9346        &mut self,
 9347        _: &MoveToPreviousWordStart,
 9348        window: &mut Window,
 9349        cx: &mut Context<Self>,
 9350    ) {
 9351        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9352            s.move_cursors_with(|map, head, _| {
 9353                (
 9354                    movement::previous_word_start(map, head),
 9355                    SelectionGoal::None,
 9356                )
 9357            });
 9358        })
 9359    }
 9360
 9361    pub fn move_to_previous_subword_start(
 9362        &mut self,
 9363        _: &MoveToPreviousSubwordStart,
 9364        window: &mut Window,
 9365        cx: &mut Context<Self>,
 9366    ) {
 9367        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9368            s.move_cursors_with(|map, head, _| {
 9369                (
 9370                    movement::previous_subword_start(map, head),
 9371                    SelectionGoal::None,
 9372                )
 9373            });
 9374        })
 9375    }
 9376
 9377    pub fn select_to_previous_word_start(
 9378        &mut self,
 9379        _: &SelectToPreviousWordStart,
 9380        window: &mut Window,
 9381        cx: &mut Context<Self>,
 9382    ) {
 9383        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9384            s.move_heads_with(|map, head, _| {
 9385                (
 9386                    movement::previous_word_start(map, head),
 9387                    SelectionGoal::None,
 9388                )
 9389            });
 9390        })
 9391    }
 9392
 9393    pub fn select_to_previous_subword_start(
 9394        &mut self,
 9395        _: &SelectToPreviousSubwordStart,
 9396        window: &mut Window,
 9397        cx: &mut Context<Self>,
 9398    ) {
 9399        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9400            s.move_heads_with(|map, head, _| {
 9401                (
 9402                    movement::previous_subword_start(map, head),
 9403                    SelectionGoal::None,
 9404                )
 9405            });
 9406        })
 9407    }
 9408
 9409    pub fn delete_to_previous_word_start(
 9410        &mut self,
 9411        action: &DeleteToPreviousWordStart,
 9412        window: &mut Window,
 9413        cx: &mut Context<Self>,
 9414    ) {
 9415        self.transact(window, cx, |this, window, cx| {
 9416            this.select_autoclose_pair(window, cx);
 9417            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9418                let line_mode = s.line_mode;
 9419                s.move_with(|map, selection| {
 9420                    if selection.is_empty() && !line_mode {
 9421                        let cursor = if action.ignore_newlines {
 9422                            movement::previous_word_start(map, selection.head())
 9423                        } else {
 9424                            movement::previous_word_start_or_newline(map, selection.head())
 9425                        };
 9426                        selection.set_head(cursor, SelectionGoal::None);
 9427                    }
 9428                });
 9429            });
 9430            this.insert("", window, cx);
 9431        });
 9432    }
 9433
 9434    pub fn delete_to_previous_subword_start(
 9435        &mut self,
 9436        _: &DeleteToPreviousSubwordStart,
 9437        window: &mut Window,
 9438        cx: &mut Context<Self>,
 9439    ) {
 9440        self.transact(window, cx, |this, window, cx| {
 9441            this.select_autoclose_pair(window, cx);
 9442            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9443                let line_mode = s.line_mode;
 9444                s.move_with(|map, selection| {
 9445                    if selection.is_empty() && !line_mode {
 9446                        let cursor = movement::previous_subword_start(map, selection.head());
 9447                        selection.set_head(cursor, SelectionGoal::None);
 9448                    }
 9449                });
 9450            });
 9451            this.insert("", window, cx);
 9452        });
 9453    }
 9454
 9455    pub fn move_to_next_word_end(
 9456        &mut self,
 9457        _: &MoveToNextWordEnd,
 9458        window: &mut Window,
 9459        cx: &mut Context<Self>,
 9460    ) {
 9461        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9462            s.move_cursors_with(|map, head, _| {
 9463                (movement::next_word_end(map, head), SelectionGoal::None)
 9464            });
 9465        })
 9466    }
 9467
 9468    pub fn move_to_next_subword_end(
 9469        &mut self,
 9470        _: &MoveToNextSubwordEnd,
 9471        window: &mut Window,
 9472        cx: &mut Context<Self>,
 9473    ) {
 9474        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9475            s.move_cursors_with(|map, head, _| {
 9476                (movement::next_subword_end(map, head), SelectionGoal::None)
 9477            });
 9478        })
 9479    }
 9480
 9481    pub fn select_to_next_word_end(
 9482        &mut self,
 9483        _: &SelectToNextWordEnd,
 9484        window: &mut Window,
 9485        cx: &mut Context<Self>,
 9486    ) {
 9487        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9488            s.move_heads_with(|map, head, _| {
 9489                (movement::next_word_end(map, head), SelectionGoal::None)
 9490            });
 9491        })
 9492    }
 9493
 9494    pub fn select_to_next_subword_end(
 9495        &mut self,
 9496        _: &SelectToNextSubwordEnd,
 9497        window: &mut Window,
 9498        cx: &mut Context<Self>,
 9499    ) {
 9500        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9501            s.move_heads_with(|map, head, _| {
 9502                (movement::next_subword_end(map, head), SelectionGoal::None)
 9503            });
 9504        })
 9505    }
 9506
 9507    pub fn delete_to_next_word_end(
 9508        &mut self,
 9509        action: &DeleteToNextWordEnd,
 9510        window: &mut Window,
 9511        cx: &mut Context<Self>,
 9512    ) {
 9513        self.transact(window, cx, |this, window, cx| {
 9514            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9515                let line_mode = s.line_mode;
 9516                s.move_with(|map, selection| {
 9517                    if selection.is_empty() && !line_mode {
 9518                        let cursor = if action.ignore_newlines {
 9519                            movement::next_word_end(map, selection.head())
 9520                        } else {
 9521                            movement::next_word_end_or_newline(map, selection.head())
 9522                        };
 9523                        selection.set_head(cursor, SelectionGoal::None);
 9524                    }
 9525                });
 9526            });
 9527            this.insert("", window, cx);
 9528        });
 9529    }
 9530
 9531    pub fn delete_to_next_subword_end(
 9532        &mut self,
 9533        _: &DeleteToNextSubwordEnd,
 9534        window: &mut Window,
 9535        cx: &mut Context<Self>,
 9536    ) {
 9537        self.transact(window, cx, |this, window, cx| {
 9538            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9539                s.move_with(|map, selection| {
 9540                    if selection.is_empty() {
 9541                        let cursor = movement::next_subword_end(map, selection.head());
 9542                        selection.set_head(cursor, SelectionGoal::None);
 9543                    }
 9544                });
 9545            });
 9546            this.insert("", window, cx);
 9547        });
 9548    }
 9549
 9550    pub fn move_to_beginning_of_line(
 9551        &mut self,
 9552        action: &MoveToBeginningOfLine,
 9553        window: &mut Window,
 9554        cx: &mut Context<Self>,
 9555    ) {
 9556        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9557            s.move_cursors_with(|map, head, _| {
 9558                (
 9559                    movement::indented_line_beginning(
 9560                        map,
 9561                        head,
 9562                        action.stop_at_soft_wraps,
 9563                        action.stop_at_indent,
 9564                    ),
 9565                    SelectionGoal::None,
 9566                )
 9567            });
 9568        })
 9569    }
 9570
 9571    pub fn select_to_beginning_of_line(
 9572        &mut self,
 9573        action: &SelectToBeginningOfLine,
 9574        window: &mut Window,
 9575        cx: &mut Context<Self>,
 9576    ) {
 9577        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9578            s.move_heads_with(|map, head, _| {
 9579                (
 9580                    movement::indented_line_beginning(
 9581                        map,
 9582                        head,
 9583                        action.stop_at_soft_wraps,
 9584                        action.stop_at_indent,
 9585                    ),
 9586                    SelectionGoal::None,
 9587                )
 9588            });
 9589        });
 9590    }
 9591
 9592    pub fn delete_to_beginning_of_line(
 9593        &mut self,
 9594        action: &DeleteToBeginningOfLine,
 9595        window: &mut Window,
 9596        cx: &mut Context<Self>,
 9597    ) {
 9598        self.transact(window, cx, |this, window, cx| {
 9599            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9600                s.move_with(|_, selection| {
 9601                    selection.reversed = true;
 9602                });
 9603            });
 9604
 9605            this.select_to_beginning_of_line(
 9606                &SelectToBeginningOfLine {
 9607                    stop_at_soft_wraps: false,
 9608                    stop_at_indent: action.stop_at_indent,
 9609                },
 9610                window,
 9611                cx,
 9612            );
 9613            this.backspace(&Backspace, window, cx);
 9614        });
 9615    }
 9616
 9617    pub fn move_to_end_of_line(
 9618        &mut self,
 9619        action: &MoveToEndOfLine,
 9620        window: &mut Window,
 9621        cx: &mut Context<Self>,
 9622    ) {
 9623        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9624            s.move_cursors_with(|map, head, _| {
 9625                (
 9626                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9627                    SelectionGoal::None,
 9628                )
 9629            });
 9630        })
 9631    }
 9632
 9633    pub fn select_to_end_of_line(
 9634        &mut self,
 9635        action: &SelectToEndOfLine,
 9636        window: &mut Window,
 9637        cx: &mut Context<Self>,
 9638    ) {
 9639        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9640            s.move_heads_with(|map, head, _| {
 9641                (
 9642                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9643                    SelectionGoal::None,
 9644                )
 9645            });
 9646        })
 9647    }
 9648
 9649    pub fn delete_to_end_of_line(
 9650        &mut self,
 9651        _: &DeleteToEndOfLine,
 9652        window: &mut Window,
 9653        cx: &mut Context<Self>,
 9654    ) {
 9655        self.transact(window, cx, |this, window, cx| {
 9656            this.select_to_end_of_line(
 9657                &SelectToEndOfLine {
 9658                    stop_at_soft_wraps: false,
 9659                },
 9660                window,
 9661                cx,
 9662            );
 9663            this.delete(&Delete, window, cx);
 9664        });
 9665    }
 9666
 9667    pub fn cut_to_end_of_line(
 9668        &mut self,
 9669        _: &CutToEndOfLine,
 9670        window: &mut Window,
 9671        cx: &mut Context<Self>,
 9672    ) {
 9673        self.transact(window, cx, |this, window, cx| {
 9674            this.select_to_end_of_line(
 9675                &SelectToEndOfLine {
 9676                    stop_at_soft_wraps: false,
 9677                },
 9678                window,
 9679                cx,
 9680            );
 9681            this.cut(&Cut, window, cx);
 9682        });
 9683    }
 9684
 9685    pub fn move_to_start_of_paragraph(
 9686        &mut self,
 9687        _: &MoveToStartOfParagraph,
 9688        window: &mut Window,
 9689        cx: &mut Context<Self>,
 9690    ) {
 9691        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9692            cx.propagate();
 9693            return;
 9694        }
 9695
 9696        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9697            s.move_with(|map, selection| {
 9698                selection.collapse_to(
 9699                    movement::start_of_paragraph(map, selection.head(), 1),
 9700                    SelectionGoal::None,
 9701                )
 9702            });
 9703        })
 9704    }
 9705
 9706    pub fn move_to_end_of_paragraph(
 9707        &mut self,
 9708        _: &MoveToEndOfParagraph,
 9709        window: &mut Window,
 9710        cx: &mut Context<Self>,
 9711    ) {
 9712        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9713            cx.propagate();
 9714            return;
 9715        }
 9716
 9717        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9718            s.move_with(|map, selection| {
 9719                selection.collapse_to(
 9720                    movement::end_of_paragraph(map, selection.head(), 1),
 9721                    SelectionGoal::None,
 9722                )
 9723            });
 9724        })
 9725    }
 9726
 9727    pub fn select_to_start_of_paragraph(
 9728        &mut self,
 9729        _: &SelectToStartOfParagraph,
 9730        window: &mut Window,
 9731        cx: &mut Context<Self>,
 9732    ) {
 9733        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9734            cx.propagate();
 9735            return;
 9736        }
 9737
 9738        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9739            s.move_heads_with(|map, head, _| {
 9740                (
 9741                    movement::start_of_paragraph(map, head, 1),
 9742                    SelectionGoal::None,
 9743                )
 9744            });
 9745        })
 9746    }
 9747
 9748    pub fn select_to_end_of_paragraph(
 9749        &mut self,
 9750        _: &SelectToEndOfParagraph,
 9751        window: &mut Window,
 9752        cx: &mut Context<Self>,
 9753    ) {
 9754        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9755            cx.propagate();
 9756            return;
 9757        }
 9758
 9759        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9760            s.move_heads_with(|map, head, _| {
 9761                (
 9762                    movement::end_of_paragraph(map, head, 1),
 9763                    SelectionGoal::None,
 9764                )
 9765            });
 9766        })
 9767    }
 9768
 9769    pub fn move_to_start_of_excerpt(
 9770        &mut self,
 9771        _: &MoveToStartOfExcerpt,
 9772        window: &mut Window,
 9773        cx: &mut Context<Self>,
 9774    ) {
 9775        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9776            cx.propagate();
 9777            return;
 9778        }
 9779
 9780        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9781            s.move_with(|map, selection| {
 9782                selection.collapse_to(
 9783                    movement::start_of_excerpt(
 9784                        map,
 9785                        selection.head(),
 9786                        workspace::searchable::Direction::Prev,
 9787                    ),
 9788                    SelectionGoal::None,
 9789                )
 9790            });
 9791        })
 9792    }
 9793
 9794    pub fn move_to_end_of_excerpt(
 9795        &mut self,
 9796        _: &MoveToEndOfExcerpt,
 9797        window: &mut Window,
 9798        cx: &mut Context<Self>,
 9799    ) {
 9800        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9801            cx.propagate();
 9802            return;
 9803        }
 9804
 9805        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9806            s.move_with(|map, selection| {
 9807                selection.collapse_to(
 9808                    movement::end_of_excerpt(
 9809                        map,
 9810                        selection.head(),
 9811                        workspace::searchable::Direction::Next,
 9812                    ),
 9813                    SelectionGoal::None,
 9814                )
 9815            });
 9816        })
 9817    }
 9818
 9819    pub fn select_to_start_of_excerpt(
 9820        &mut self,
 9821        _: &SelectToStartOfExcerpt,
 9822        window: &mut Window,
 9823        cx: &mut Context<Self>,
 9824    ) {
 9825        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9826            cx.propagate();
 9827            return;
 9828        }
 9829
 9830        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9831            s.move_heads_with(|map, head, _| {
 9832                (
 9833                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9834                    SelectionGoal::None,
 9835                )
 9836            });
 9837        })
 9838    }
 9839
 9840    pub fn select_to_end_of_excerpt(
 9841        &mut self,
 9842        _: &SelectToEndOfExcerpt,
 9843        window: &mut Window,
 9844        cx: &mut Context<Self>,
 9845    ) {
 9846        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9847            cx.propagate();
 9848            return;
 9849        }
 9850
 9851        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9852            s.move_heads_with(|map, head, _| {
 9853                (
 9854                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9855                    SelectionGoal::None,
 9856                )
 9857            });
 9858        })
 9859    }
 9860
 9861    pub fn move_to_beginning(
 9862        &mut self,
 9863        _: &MoveToBeginning,
 9864        window: &mut Window,
 9865        cx: &mut Context<Self>,
 9866    ) {
 9867        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9868            cx.propagate();
 9869            return;
 9870        }
 9871
 9872        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9873            s.select_ranges(vec![0..0]);
 9874        });
 9875    }
 9876
 9877    pub fn select_to_beginning(
 9878        &mut self,
 9879        _: &SelectToBeginning,
 9880        window: &mut Window,
 9881        cx: &mut Context<Self>,
 9882    ) {
 9883        let mut selection = self.selections.last::<Point>(cx);
 9884        selection.set_head(Point::zero(), SelectionGoal::None);
 9885
 9886        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9887            s.select(vec![selection]);
 9888        });
 9889    }
 9890
 9891    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9892        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9893            cx.propagate();
 9894            return;
 9895        }
 9896
 9897        let cursor = self.buffer.read(cx).read(cx).len();
 9898        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9899            s.select_ranges(vec![cursor..cursor])
 9900        });
 9901    }
 9902
 9903    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9904        self.nav_history = nav_history;
 9905    }
 9906
 9907    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9908        self.nav_history.as_ref()
 9909    }
 9910
 9911    fn push_to_nav_history(
 9912        &mut self,
 9913        cursor_anchor: Anchor,
 9914        new_position: Option<Point>,
 9915        cx: &mut Context<Self>,
 9916    ) {
 9917        if let Some(nav_history) = self.nav_history.as_mut() {
 9918            let buffer = self.buffer.read(cx).read(cx);
 9919            let cursor_position = cursor_anchor.to_point(&buffer);
 9920            let scroll_state = self.scroll_manager.anchor();
 9921            let scroll_top_row = scroll_state.top_row(&buffer);
 9922            drop(buffer);
 9923
 9924            if let Some(new_position) = new_position {
 9925                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9926                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9927                    return;
 9928                }
 9929            }
 9930
 9931            nav_history.push(
 9932                Some(NavigationData {
 9933                    cursor_anchor,
 9934                    cursor_position,
 9935                    scroll_anchor: scroll_state,
 9936                    scroll_top_row,
 9937                }),
 9938                cx,
 9939            );
 9940        }
 9941    }
 9942
 9943    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9944        let buffer = self.buffer.read(cx).snapshot(cx);
 9945        let mut selection = self.selections.first::<usize>(cx);
 9946        selection.set_head(buffer.len(), SelectionGoal::None);
 9947        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9948            s.select(vec![selection]);
 9949        });
 9950    }
 9951
 9952    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9953        let end = self.buffer.read(cx).read(cx).len();
 9954        self.change_selections(None, window, cx, |s| {
 9955            s.select_ranges(vec![0..end]);
 9956        });
 9957    }
 9958
 9959    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9960        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9961        let mut selections = self.selections.all::<Point>(cx);
 9962        let max_point = display_map.buffer_snapshot.max_point();
 9963        for selection in &mut selections {
 9964            let rows = selection.spanned_rows(true, &display_map);
 9965            selection.start = Point::new(rows.start.0, 0);
 9966            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9967            selection.reversed = false;
 9968        }
 9969        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9970            s.select(selections);
 9971        });
 9972    }
 9973
 9974    pub fn split_selection_into_lines(
 9975        &mut self,
 9976        _: &SplitSelectionIntoLines,
 9977        window: &mut Window,
 9978        cx: &mut Context<Self>,
 9979    ) {
 9980        let selections = self
 9981            .selections
 9982            .all::<Point>(cx)
 9983            .into_iter()
 9984            .map(|selection| selection.start..selection.end)
 9985            .collect::<Vec<_>>();
 9986        self.unfold_ranges(&selections, true, true, cx);
 9987
 9988        let mut new_selection_ranges = Vec::new();
 9989        {
 9990            let buffer = self.buffer.read(cx).read(cx);
 9991            for selection in selections {
 9992                for row in selection.start.row..selection.end.row {
 9993                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9994                    new_selection_ranges.push(cursor..cursor);
 9995                }
 9996
 9997                let is_multiline_selection = selection.start.row != selection.end.row;
 9998                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9999                // so this action feels more ergonomic when paired with other selection operations
10000                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10001                if !should_skip_last {
10002                    new_selection_ranges.push(selection.end..selection.end);
10003                }
10004            }
10005        }
10006        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10007            s.select_ranges(new_selection_ranges);
10008        });
10009    }
10010
10011    pub fn add_selection_above(
10012        &mut self,
10013        _: &AddSelectionAbove,
10014        window: &mut Window,
10015        cx: &mut Context<Self>,
10016    ) {
10017        self.add_selection(true, window, cx);
10018    }
10019
10020    pub fn add_selection_below(
10021        &mut self,
10022        _: &AddSelectionBelow,
10023        window: &mut Window,
10024        cx: &mut Context<Self>,
10025    ) {
10026        self.add_selection(false, window, cx);
10027    }
10028
10029    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10030        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10031        let mut selections = self.selections.all::<Point>(cx);
10032        let text_layout_details = self.text_layout_details(window);
10033        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10034            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10035            let range = oldest_selection.display_range(&display_map).sorted();
10036
10037            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10038            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10039            let positions = start_x.min(end_x)..start_x.max(end_x);
10040
10041            selections.clear();
10042            let mut stack = Vec::new();
10043            for row in range.start.row().0..=range.end.row().0 {
10044                if let Some(selection) = self.selections.build_columnar_selection(
10045                    &display_map,
10046                    DisplayRow(row),
10047                    &positions,
10048                    oldest_selection.reversed,
10049                    &text_layout_details,
10050                ) {
10051                    stack.push(selection.id);
10052                    selections.push(selection);
10053                }
10054            }
10055
10056            if above {
10057                stack.reverse();
10058            }
10059
10060            AddSelectionsState { above, stack }
10061        });
10062
10063        let last_added_selection = *state.stack.last().unwrap();
10064        let mut new_selections = Vec::new();
10065        if above == state.above {
10066            let end_row = if above {
10067                DisplayRow(0)
10068            } else {
10069                display_map.max_point().row()
10070            };
10071
10072            'outer: for selection in selections {
10073                if selection.id == last_added_selection {
10074                    let range = selection.display_range(&display_map).sorted();
10075                    debug_assert_eq!(range.start.row(), range.end.row());
10076                    let mut row = range.start.row();
10077                    let positions =
10078                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10079                            px(start)..px(end)
10080                        } else {
10081                            let start_x =
10082                                display_map.x_for_display_point(range.start, &text_layout_details);
10083                            let end_x =
10084                                display_map.x_for_display_point(range.end, &text_layout_details);
10085                            start_x.min(end_x)..start_x.max(end_x)
10086                        };
10087
10088                    while row != end_row {
10089                        if above {
10090                            row.0 -= 1;
10091                        } else {
10092                            row.0 += 1;
10093                        }
10094
10095                        if let Some(new_selection) = self.selections.build_columnar_selection(
10096                            &display_map,
10097                            row,
10098                            &positions,
10099                            selection.reversed,
10100                            &text_layout_details,
10101                        ) {
10102                            state.stack.push(new_selection.id);
10103                            if above {
10104                                new_selections.push(new_selection);
10105                                new_selections.push(selection);
10106                            } else {
10107                                new_selections.push(selection);
10108                                new_selections.push(new_selection);
10109                            }
10110
10111                            continue 'outer;
10112                        }
10113                    }
10114                }
10115
10116                new_selections.push(selection);
10117            }
10118        } else {
10119            new_selections = selections;
10120            new_selections.retain(|s| s.id != last_added_selection);
10121            state.stack.pop();
10122        }
10123
10124        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10125            s.select(new_selections);
10126        });
10127        if state.stack.len() > 1 {
10128            self.add_selections_state = Some(state);
10129        }
10130    }
10131
10132    pub fn select_next_match_internal(
10133        &mut self,
10134        display_map: &DisplaySnapshot,
10135        replace_newest: bool,
10136        autoscroll: Option<Autoscroll>,
10137        window: &mut Window,
10138        cx: &mut Context<Self>,
10139    ) -> Result<()> {
10140        fn select_next_match_ranges(
10141            this: &mut Editor,
10142            range: Range<usize>,
10143            replace_newest: bool,
10144            auto_scroll: Option<Autoscroll>,
10145            window: &mut Window,
10146            cx: &mut Context<Editor>,
10147        ) {
10148            this.unfold_ranges(&[range.clone()], false, true, cx);
10149            this.change_selections(auto_scroll, window, cx, |s| {
10150                if replace_newest {
10151                    s.delete(s.newest_anchor().id);
10152                }
10153                s.insert_range(range.clone());
10154            });
10155        }
10156
10157        let buffer = &display_map.buffer_snapshot;
10158        let mut selections = self.selections.all::<usize>(cx);
10159        if let Some(mut select_next_state) = self.select_next_state.take() {
10160            let query = &select_next_state.query;
10161            if !select_next_state.done {
10162                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10163                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10164                let mut next_selected_range = None;
10165
10166                let bytes_after_last_selection =
10167                    buffer.bytes_in_range(last_selection.end..buffer.len());
10168                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10169                let query_matches = query
10170                    .stream_find_iter(bytes_after_last_selection)
10171                    .map(|result| (last_selection.end, result))
10172                    .chain(
10173                        query
10174                            .stream_find_iter(bytes_before_first_selection)
10175                            .map(|result| (0, result)),
10176                    );
10177
10178                for (start_offset, query_match) in query_matches {
10179                    let query_match = query_match.unwrap(); // can only fail due to I/O
10180                    let offset_range =
10181                        start_offset + query_match.start()..start_offset + query_match.end();
10182                    let display_range = offset_range.start.to_display_point(display_map)
10183                        ..offset_range.end.to_display_point(display_map);
10184
10185                    if !select_next_state.wordwise
10186                        || (!movement::is_inside_word(display_map, display_range.start)
10187                            && !movement::is_inside_word(display_map, display_range.end))
10188                    {
10189                        // TODO: This is n^2, because we might check all the selections
10190                        if !selections
10191                            .iter()
10192                            .any(|selection| selection.range().overlaps(&offset_range))
10193                        {
10194                            next_selected_range = Some(offset_range);
10195                            break;
10196                        }
10197                    }
10198                }
10199
10200                if let Some(next_selected_range) = next_selected_range {
10201                    select_next_match_ranges(
10202                        self,
10203                        next_selected_range,
10204                        replace_newest,
10205                        autoscroll,
10206                        window,
10207                        cx,
10208                    );
10209                } else {
10210                    select_next_state.done = true;
10211                }
10212            }
10213
10214            self.select_next_state = Some(select_next_state);
10215        } else {
10216            let mut only_carets = true;
10217            let mut same_text_selected = true;
10218            let mut selected_text = None;
10219
10220            let mut selections_iter = selections.iter().peekable();
10221            while let Some(selection) = selections_iter.next() {
10222                if selection.start != selection.end {
10223                    only_carets = false;
10224                }
10225
10226                if same_text_selected {
10227                    if selected_text.is_none() {
10228                        selected_text =
10229                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10230                    }
10231
10232                    if let Some(next_selection) = selections_iter.peek() {
10233                        if next_selection.range().len() == selection.range().len() {
10234                            let next_selected_text = buffer
10235                                .text_for_range(next_selection.range())
10236                                .collect::<String>();
10237                            if Some(next_selected_text) != selected_text {
10238                                same_text_selected = false;
10239                                selected_text = None;
10240                            }
10241                        } else {
10242                            same_text_selected = false;
10243                            selected_text = None;
10244                        }
10245                    }
10246                }
10247            }
10248
10249            if only_carets {
10250                for selection in &mut selections {
10251                    let word_range = movement::surrounding_word(
10252                        display_map,
10253                        selection.start.to_display_point(display_map),
10254                    );
10255                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10256                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10257                    selection.goal = SelectionGoal::None;
10258                    selection.reversed = false;
10259                    select_next_match_ranges(
10260                        self,
10261                        selection.start..selection.end,
10262                        replace_newest,
10263                        autoscroll,
10264                        window,
10265                        cx,
10266                    );
10267                }
10268
10269                if selections.len() == 1 {
10270                    let selection = selections
10271                        .last()
10272                        .expect("ensured that there's only one selection");
10273                    let query = buffer
10274                        .text_for_range(selection.start..selection.end)
10275                        .collect::<String>();
10276                    let is_empty = query.is_empty();
10277                    let select_state = SelectNextState {
10278                        query: AhoCorasick::new(&[query])?,
10279                        wordwise: true,
10280                        done: is_empty,
10281                    };
10282                    self.select_next_state = Some(select_state);
10283                } else {
10284                    self.select_next_state = None;
10285                }
10286            } else if let Some(selected_text) = selected_text {
10287                self.select_next_state = Some(SelectNextState {
10288                    query: AhoCorasick::new(&[selected_text])?,
10289                    wordwise: false,
10290                    done: false,
10291                });
10292                self.select_next_match_internal(
10293                    display_map,
10294                    replace_newest,
10295                    autoscroll,
10296                    window,
10297                    cx,
10298                )?;
10299            }
10300        }
10301        Ok(())
10302    }
10303
10304    pub fn select_all_matches(
10305        &mut self,
10306        _action: &SelectAllMatches,
10307        window: &mut Window,
10308        cx: &mut Context<Self>,
10309    ) -> Result<()> {
10310        self.push_to_selection_history();
10311        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10312
10313        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10314        let Some(select_next_state) = self.select_next_state.as_mut() else {
10315            return Ok(());
10316        };
10317        if select_next_state.done {
10318            return Ok(());
10319        }
10320
10321        let mut new_selections = self.selections.all::<usize>(cx);
10322
10323        let buffer = &display_map.buffer_snapshot;
10324        let query_matches = select_next_state
10325            .query
10326            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10327
10328        for query_match in query_matches {
10329            let query_match = query_match.unwrap(); // can only fail due to I/O
10330            let offset_range = query_match.start()..query_match.end();
10331            let display_range = offset_range.start.to_display_point(&display_map)
10332                ..offset_range.end.to_display_point(&display_map);
10333
10334            if !select_next_state.wordwise
10335                || (!movement::is_inside_word(&display_map, display_range.start)
10336                    && !movement::is_inside_word(&display_map, display_range.end))
10337            {
10338                self.selections.change_with(cx, |selections| {
10339                    new_selections.push(Selection {
10340                        id: selections.new_selection_id(),
10341                        start: offset_range.start,
10342                        end: offset_range.end,
10343                        reversed: false,
10344                        goal: SelectionGoal::None,
10345                    });
10346                });
10347            }
10348        }
10349
10350        new_selections.sort_by_key(|selection| selection.start);
10351        let mut ix = 0;
10352        while ix + 1 < new_selections.len() {
10353            let current_selection = &new_selections[ix];
10354            let next_selection = &new_selections[ix + 1];
10355            if current_selection.range().overlaps(&next_selection.range()) {
10356                if current_selection.id < next_selection.id {
10357                    new_selections.remove(ix + 1);
10358                } else {
10359                    new_selections.remove(ix);
10360                }
10361            } else {
10362                ix += 1;
10363            }
10364        }
10365
10366        let reversed = self.selections.oldest::<usize>(cx).reversed;
10367
10368        for selection in new_selections.iter_mut() {
10369            selection.reversed = reversed;
10370        }
10371
10372        select_next_state.done = true;
10373        self.unfold_ranges(
10374            &new_selections
10375                .iter()
10376                .map(|selection| selection.range())
10377                .collect::<Vec<_>>(),
10378            false,
10379            false,
10380            cx,
10381        );
10382        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10383            selections.select(new_selections)
10384        });
10385
10386        Ok(())
10387    }
10388
10389    pub fn select_next(
10390        &mut self,
10391        action: &SelectNext,
10392        window: &mut Window,
10393        cx: &mut Context<Self>,
10394    ) -> Result<()> {
10395        self.push_to_selection_history();
10396        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10397        self.select_next_match_internal(
10398            &display_map,
10399            action.replace_newest,
10400            Some(Autoscroll::newest()),
10401            window,
10402            cx,
10403        )?;
10404        Ok(())
10405    }
10406
10407    pub fn select_previous(
10408        &mut self,
10409        action: &SelectPrevious,
10410        window: &mut Window,
10411        cx: &mut Context<Self>,
10412    ) -> Result<()> {
10413        self.push_to_selection_history();
10414        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10415        let buffer = &display_map.buffer_snapshot;
10416        let mut selections = self.selections.all::<usize>(cx);
10417        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10418            let query = &select_prev_state.query;
10419            if !select_prev_state.done {
10420                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10421                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10422                let mut next_selected_range = None;
10423                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10424                let bytes_before_last_selection =
10425                    buffer.reversed_bytes_in_range(0..last_selection.start);
10426                let bytes_after_first_selection =
10427                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10428                let query_matches = query
10429                    .stream_find_iter(bytes_before_last_selection)
10430                    .map(|result| (last_selection.start, result))
10431                    .chain(
10432                        query
10433                            .stream_find_iter(bytes_after_first_selection)
10434                            .map(|result| (buffer.len(), result)),
10435                    );
10436                for (end_offset, query_match) in query_matches {
10437                    let query_match = query_match.unwrap(); // can only fail due to I/O
10438                    let offset_range =
10439                        end_offset - query_match.end()..end_offset - query_match.start();
10440                    let display_range = offset_range.start.to_display_point(&display_map)
10441                        ..offset_range.end.to_display_point(&display_map);
10442
10443                    if !select_prev_state.wordwise
10444                        || (!movement::is_inside_word(&display_map, display_range.start)
10445                            && !movement::is_inside_word(&display_map, display_range.end))
10446                    {
10447                        next_selected_range = Some(offset_range);
10448                        break;
10449                    }
10450                }
10451
10452                if let Some(next_selected_range) = next_selected_range {
10453                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10454                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10455                        if action.replace_newest {
10456                            s.delete(s.newest_anchor().id);
10457                        }
10458                        s.insert_range(next_selected_range);
10459                    });
10460                } else {
10461                    select_prev_state.done = true;
10462                }
10463            }
10464
10465            self.select_prev_state = Some(select_prev_state);
10466        } else {
10467            let mut only_carets = true;
10468            let mut same_text_selected = true;
10469            let mut selected_text = None;
10470
10471            let mut selections_iter = selections.iter().peekable();
10472            while let Some(selection) = selections_iter.next() {
10473                if selection.start != selection.end {
10474                    only_carets = false;
10475                }
10476
10477                if same_text_selected {
10478                    if selected_text.is_none() {
10479                        selected_text =
10480                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10481                    }
10482
10483                    if let Some(next_selection) = selections_iter.peek() {
10484                        if next_selection.range().len() == selection.range().len() {
10485                            let next_selected_text = buffer
10486                                .text_for_range(next_selection.range())
10487                                .collect::<String>();
10488                            if Some(next_selected_text) != selected_text {
10489                                same_text_selected = false;
10490                                selected_text = None;
10491                            }
10492                        } else {
10493                            same_text_selected = false;
10494                            selected_text = None;
10495                        }
10496                    }
10497                }
10498            }
10499
10500            if only_carets {
10501                for selection in &mut selections {
10502                    let word_range = movement::surrounding_word(
10503                        &display_map,
10504                        selection.start.to_display_point(&display_map),
10505                    );
10506                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10507                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10508                    selection.goal = SelectionGoal::None;
10509                    selection.reversed = false;
10510                }
10511                if selections.len() == 1 {
10512                    let selection = selections
10513                        .last()
10514                        .expect("ensured that there's only one selection");
10515                    let query = buffer
10516                        .text_for_range(selection.start..selection.end)
10517                        .collect::<String>();
10518                    let is_empty = query.is_empty();
10519                    let select_state = SelectNextState {
10520                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10521                        wordwise: true,
10522                        done: is_empty,
10523                    };
10524                    self.select_prev_state = Some(select_state);
10525                } else {
10526                    self.select_prev_state = None;
10527                }
10528
10529                self.unfold_ranges(
10530                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10531                    false,
10532                    true,
10533                    cx,
10534                );
10535                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10536                    s.select(selections);
10537                });
10538            } else if let Some(selected_text) = selected_text {
10539                self.select_prev_state = Some(SelectNextState {
10540                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10541                    wordwise: false,
10542                    done: false,
10543                });
10544                self.select_previous(action, window, cx)?;
10545            }
10546        }
10547        Ok(())
10548    }
10549
10550    pub fn toggle_comments(
10551        &mut self,
10552        action: &ToggleComments,
10553        window: &mut Window,
10554        cx: &mut Context<Self>,
10555    ) {
10556        if self.read_only(cx) {
10557            return;
10558        }
10559        let text_layout_details = &self.text_layout_details(window);
10560        self.transact(window, cx, |this, window, cx| {
10561            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10562            let mut edits = Vec::new();
10563            let mut selection_edit_ranges = Vec::new();
10564            let mut last_toggled_row = None;
10565            let snapshot = this.buffer.read(cx).read(cx);
10566            let empty_str: Arc<str> = Arc::default();
10567            let mut suffixes_inserted = Vec::new();
10568            let ignore_indent = action.ignore_indent;
10569
10570            fn comment_prefix_range(
10571                snapshot: &MultiBufferSnapshot,
10572                row: MultiBufferRow,
10573                comment_prefix: &str,
10574                comment_prefix_whitespace: &str,
10575                ignore_indent: bool,
10576            ) -> Range<Point> {
10577                let indent_size = if ignore_indent {
10578                    0
10579                } else {
10580                    snapshot.indent_size_for_line(row).len
10581                };
10582
10583                let start = Point::new(row.0, indent_size);
10584
10585                let mut line_bytes = snapshot
10586                    .bytes_in_range(start..snapshot.max_point())
10587                    .flatten()
10588                    .copied();
10589
10590                // If this line currently begins with the line comment prefix, then record
10591                // the range containing the prefix.
10592                if line_bytes
10593                    .by_ref()
10594                    .take(comment_prefix.len())
10595                    .eq(comment_prefix.bytes())
10596                {
10597                    // Include any whitespace that matches the comment prefix.
10598                    let matching_whitespace_len = line_bytes
10599                        .zip(comment_prefix_whitespace.bytes())
10600                        .take_while(|(a, b)| a == b)
10601                        .count() as u32;
10602                    let end = Point::new(
10603                        start.row,
10604                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10605                    );
10606                    start..end
10607                } else {
10608                    start..start
10609                }
10610            }
10611
10612            fn comment_suffix_range(
10613                snapshot: &MultiBufferSnapshot,
10614                row: MultiBufferRow,
10615                comment_suffix: &str,
10616                comment_suffix_has_leading_space: bool,
10617            ) -> Range<Point> {
10618                let end = Point::new(row.0, snapshot.line_len(row));
10619                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10620
10621                let mut line_end_bytes = snapshot
10622                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10623                    .flatten()
10624                    .copied();
10625
10626                let leading_space_len = if suffix_start_column > 0
10627                    && line_end_bytes.next() == Some(b' ')
10628                    && comment_suffix_has_leading_space
10629                {
10630                    1
10631                } else {
10632                    0
10633                };
10634
10635                // If this line currently begins with the line comment prefix, then record
10636                // the range containing the prefix.
10637                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10638                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10639                    start..end
10640                } else {
10641                    end..end
10642                }
10643            }
10644
10645            // TODO: Handle selections that cross excerpts
10646            for selection in &mut selections {
10647                let start_column = snapshot
10648                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10649                    .len;
10650                let language = if let Some(language) =
10651                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10652                {
10653                    language
10654                } else {
10655                    continue;
10656                };
10657
10658                selection_edit_ranges.clear();
10659
10660                // If multiple selections contain a given row, avoid processing that
10661                // row more than once.
10662                let mut start_row = MultiBufferRow(selection.start.row);
10663                if last_toggled_row == Some(start_row) {
10664                    start_row = start_row.next_row();
10665                }
10666                let end_row =
10667                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10668                        MultiBufferRow(selection.end.row - 1)
10669                    } else {
10670                        MultiBufferRow(selection.end.row)
10671                    };
10672                last_toggled_row = Some(end_row);
10673
10674                if start_row > end_row {
10675                    continue;
10676                }
10677
10678                // If the language has line comments, toggle those.
10679                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10680
10681                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10682                if ignore_indent {
10683                    full_comment_prefixes = full_comment_prefixes
10684                        .into_iter()
10685                        .map(|s| Arc::from(s.trim_end()))
10686                        .collect();
10687                }
10688
10689                if !full_comment_prefixes.is_empty() {
10690                    let first_prefix = full_comment_prefixes
10691                        .first()
10692                        .expect("prefixes is non-empty");
10693                    let prefix_trimmed_lengths = full_comment_prefixes
10694                        .iter()
10695                        .map(|p| p.trim_end_matches(' ').len())
10696                        .collect::<SmallVec<[usize; 4]>>();
10697
10698                    let mut all_selection_lines_are_comments = true;
10699
10700                    for row in start_row.0..=end_row.0 {
10701                        let row = MultiBufferRow(row);
10702                        if start_row < end_row && snapshot.is_line_blank(row) {
10703                            continue;
10704                        }
10705
10706                        let prefix_range = full_comment_prefixes
10707                            .iter()
10708                            .zip(prefix_trimmed_lengths.iter().copied())
10709                            .map(|(prefix, trimmed_prefix_len)| {
10710                                comment_prefix_range(
10711                                    snapshot.deref(),
10712                                    row,
10713                                    &prefix[..trimmed_prefix_len],
10714                                    &prefix[trimmed_prefix_len..],
10715                                    ignore_indent,
10716                                )
10717                            })
10718                            .max_by_key(|range| range.end.column - range.start.column)
10719                            .expect("prefixes is non-empty");
10720
10721                        if prefix_range.is_empty() {
10722                            all_selection_lines_are_comments = false;
10723                        }
10724
10725                        selection_edit_ranges.push(prefix_range);
10726                    }
10727
10728                    if all_selection_lines_are_comments {
10729                        edits.extend(
10730                            selection_edit_ranges
10731                                .iter()
10732                                .cloned()
10733                                .map(|range| (range, empty_str.clone())),
10734                        );
10735                    } else {
10736                        let min_column = selection_edit_ranges
10737                            .iter()
10738                            .map(|range| range.start.column)
10739                            .min()
10740                            .unwrap_or(0);
10741                        edits.extend(selection_edit_ranges.iter().map(|range| {
10742                            let position = Point::new(range.start.row, min_column);
10743                            (position..position, first_prefix.clone())
10744                        }));
10745                    }
10746                } else if let Some((full_comment_prefix, comment_suffix)) =
10747                    language.block_comment_delimiters()
10748                {
10749                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10750                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10751                    let prefix_range = comment_prefix_range(
10752                        snapshot.deref(),
10753                        start_row,
10754                        comment_prefix,
10755                        comment_prefix_whitespace,
10756                        ignore_indent,
10757                    );
10758                    let suffix_range = comment_suffix_range(
10759                        snapshot.deref(),
10760                        end_row,
10761                        comment_suffix.trim_start_matches(' '),
10762                        comment_suffix.starts_with(' '),
10763                    );
10764
10765                    if prefix_range.is_empty() || suffix_range.is_empty() {
10766                        edits.push((
10767                            prefix_range.start..prefix_range.start,
10768                            full_comment_prefix.clone(),
10769                        ));
10770                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10771                        suffixes_inserted.push((end_row, comment_suffix.len()));
10772                    } else {
10773                        edits.push((prefix_range, empty_str.clone()));
10774                        edits.push((suffix_range, empty_str.clone()));
10775                    }
10776                } else {
10777                    continue;
10778                }
10779            }
10780
10781            drop(snapshot);
10782            this.buffer.update(cx, |buffer, cx| {
10783                buffer.edit(edits, None, cx);
10784            });
10785
10786            // Adjust selections so that they end before any comment suffixes that
10787            // were inserted.
10788            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10789            let mut selections = this.selections.all::<Point>(cx);
10790            let snapshot = this.buffer.read(cx).read(cx);
10791            for selection in &mut selections {
10792                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10793                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10794                        Ordering::Less => {
10795                            suffixes_inserted.next();
10796                            continue;
10797                        }
10798                        Ordering::Greater => break,
10799                        Ordering::Equal => {
10800                            if selection.end.column == snapshot.line_len(row) {
10801                                if selection.is_empty() {
10802                                    selection.start.column -= suffix_len as u32;
10803                                }
10804                                selection.end.column -= suffix_len as u32;
10805                            }
10806                            break;
10807                        }
10808                    }
10809                }
10810            }
10811
10812            drop(snapshot);
10813            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10814                s.select(selections)
10815            });
10816
10817            let selections = this.selections.all::<Point>(cx);
10818            let selections_on_single_row = selections.windows(2).all(|selections| {
10819                selections[0].start.row == selections[1].start.row
10820                    && selections[0].end.row == selections[1].end.row
10821                    && selections[0].start.row == selections[0].end.row
10822            });
10823            let selections_selecting = selections
10824                .iter()
10825                .any(|selection| selection.start != selection.end);
10826            let advance_downwards = action.advance_downwards
10827                && selections_on_single_row
10828                && !selections_selecting
10829                && !matches!(this.mode, EditorMode::SingleLine { .. });
10830
10831            if advance_downwards {
10832                let snapshot = this.buffer.read(cx).snapshot(cx);
10833
10834                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10835                    s.move_cursors_with(|display_snapshot, display_point, _| {
10836                        let mut point = display_point.to_point(display_snapshot);
10837                        point.row += 1;
10838                        point = snapshot.clip_point(point, Bias::Left);
10839                        let display_point = point.to_display_point(display_snapshot);
10840                        let goal = SelectionGoal::HorizontalPosition(
10841                            display_snapshot
10842                                .x_for_display_point(display_point, text_layout_details)
10843                                .into(),
10844                        );
10845                        (display_point, goal)
10846                    })
10847                });
10848            }
10849        });
10850    }
10851
10852    pub fn select_enclosing_symbol(
10853        &mut self,
10854        _: &SelectEnclosingSymbol,
10855        window: &mut Window,
10856        cx: &mut Context<Self>,
10857    ) {
10858        let buffer = self.buffer.read(cx).snapshot(cx);
10859        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10860
10861        fn update_selection(
10862            selection: &Selection<usize>,
10863            buffer_snap: &MultiBufferSnapshot,
10864        ) -> Option<Selection<usize>> {
10865            let cursor = selection.head();
10866            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10867            for symbol in symbols.iter().rev() {
10868                let start = symbol.range.start.to_offset(buffer_snap);
10869                let end = symbol.range.end.to_offset(buffer_snap);
10870                let new_range = start..end;
10871                if start < selection.start || end > selection.end {
10872                    return Some(Selection {
10873                        id: selection.id,
10874                        start: new_range.start,
10875                        end: new_range.end,
10876                        goal: SelectionGoal::None,
10877                        reversed: selection.reversed,
10878                    });
10879                }
10880            }
10881            None
10882        }
10883
10884        let mut selected_larger_symbol = false;
10885        let new_selections = old_selections
10886            .iter()
10887            .map(|selection| match update_selection(selection, &buffer) {
10888                Some(new_selection) => {
10889                    if new_selection.range() != selection.range() {
10890                        selected_larger_symbol = true;
10891                    }
10892                    new_selection
10893                }
10894                None => selection.clone(),
10895            })
10896            .collect::<Vec<_>>();
10897
10898        if selected_larger_symbol {
10899            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10900                s.select(new_selections);
10901            });
10902        }
10903    }
10904
10905    pub fn select_larger_syntax_node(
10906        &mut self,
10907        _: &SelectLargerSyntaxNode,
10908        window: &mut Window,
10909        cx: &mut Context<Self>,
10910    ) {
10911        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10912        let buffer = self.buffer.read(cx).snapshot(cx);
10913        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10914
10915        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10916        let mut selected_larger_node = false;
10917        let new_selections = old_selections
10918            .iter()
10919            .map(|selection| {
10920                let old_range = selection.start..selection.end;
10921                let mut new_range = old_range.clone();
10922                let mut new_node = None;
10923                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10924                {
10925                    new_node = Some(node);
10926                    new_range = match containing_range {
10927                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10928                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10929                    };
10930                    if !display_map.intersects_fold(new_range.start)
10931                        && !display_map.intersects_fold(new_range.end)
10932                    {
10933                        break;
10934                    }
10935                }
10936
10937                if let Some(node) = new_node {
10938                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10939                    // nodes. Parent and grandparent are also logged because this operation will not
10940                    // visit nodes that have the same range as their parent.
10941                    log::info!("Node: {node:?}");
10942                    let parent = node.parent();
10943                    log::info!("Parent: {parent:?}");
10944                    let grandparent = parent.and_then(|x| x.parent());
10945                    log::info!("Grandparent: {grandparent:?}");
10946                }
10947
10948                selected_larger_node |= new_range != old_range;
10949                Selection {
10950                    id: selection.id,
10951                    start: new_range.start,
10952                    end: new_range.end,
10953                    goal: SelectionGoal::None,
10954                    reversed: selection.reversed,
10955                }
10956            })
10957            .collect::<Vec<_>>();
10958
10959        if selected_larger_node {
10960            stack.push(old_selections);
10961            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10962                s.select(new_selections);
10963            });
10964        }
10965        self.select_larger_syntax_node_stack = stack;
10966    }
10967
10968    pub fn select_smaller_syntax_node(
10969        &mut self,
10970        _: &SelectSmallerSyntaxNode,
10971        window: &mut Window,
10972        cx: &mut Context<Self>,
10973    ) {
10974        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10975        if let Some(selections) = stack.pop() {
10976            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10977                s.select(selections.to_vec());
10978            });
10979        }
10980        self.select_larger_syntax_node_stack = stack;
10981    }
10982
10983    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10984        if !EditorSettings::get_global(cx).gutter.runnables {
10985            self.clear_tasks();
10986            return Task::ready(());
10987        }
10988        let project = self.project.as_ref().map(Entity::downgrade);
10989        cx.spawn_in(window, |this, mut cx| async move {
10990            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10991            let Some(project) = project.and_then(|p| p.upgrade()) else {
10992                return;
10993            };
10994            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10995                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10996            }) else {
10997                return;
10998            };
10999
11000            let hide_runnables = project
11001                .update(&mut cx, |project, cx| {
11002                    // Do not display any test indicators in non-dev server remote projects.
11003                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11004                })
11005                .unwrap_or(true);
11006            if hide_runnables {
11007                return;
11008            }
11009            let new_rows =
11010                cx.background_spawn({
11011                    let snapshot = display_snapshot.clone();
11012                    async move {
11013                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11014                    }
11015                })
11016                    .await;
11017
11018            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11019            this.update(&mut cx, |this, _| {
11020                this.clear_tasks();
11021                for (key, value) in rows {
11022                    this.insert_tasks(key, value);
11023                }
11024            })
11025            .ok();
11026        })
11027    }
11028    fn fetch_runnable_ranges(
11029        snapshot: &DisplaySnapshot,
11030        range: Range<Anchor>,
11031    ) -> Vec<language::RunnableRange> {
11032        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11033    }
11034
11035    fn runnable_rows(
11036        project: Entity<Project>,
11037        snapshot: DisplaySnapshot,
11038        runnable_ranges: Vec<RunnableRange>,
11039        mut cx: AsyncWindowContext,
11040    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11041        runnable_ranges
11042            .into_iter()
11043            .filter_map(|mut runnable| {
11044                let tasks = cx
11045                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11046                    .ok()?;
11047                if tasks.is_empty() {
11048                    return None;
11049                }
11050
11051                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11052
11053                let row = snapshot
11054                    .buffer_snapshot
11055                    .buffer_line_for_row(MultiBufferRow(point.row))?
11056                    .1
11057                    .start
11058                    .row;
11059
11060                let context_range =
11061                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11062                Some((
11063                    (runnable.buffer_id, row),
11064                    RunnableTasks {
11065                        templates: tasks,
11066                        offset: snapshot
11067                            .buffer_snapshot
11068                            .anchor_before(runnable.run_range.start),
11069                        context_range,
11070                        column: point.column,
11071                        extra_variables: runnable.extra_captures,
11072                    },
11073                ))
11074            })
11075            .collect()
11076    }
11077
11078    fn templates_with_tags(
11079        project: &Entity<Project>,
11080        runnable: &mut Runnable,
11081        cx: &mut App,
11082    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11083        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11084            let (worktree_id, file) = project
11085                .buffer_for_id(runnable.buffer, cx)
11086                .and_then(|buffer| buffer.read(cx).file())
11087                .map(|file| (file.worktree_id(cx), file.clone()))
11088                .unzip();
11089
11090            (
11091                project.task_store().read(cx).task_inventory().cloned(),
11092                worktree_id,
11093                file,
11094            )
11095        });
11096
11097        let tags = mem::take(&mut runnable.tags);
11098        let mut tags: Vec<_> = tags
11099            .into_iter()
11100            .flat_map(|tag| {
11101                let tag = tag.0.clone();
11102                inventory
11103                    .as_ref()
11104                    .into_iter()
11105                    .flat_map(|inventory| {
11106                        inventory.read(cx).list_tasks(
11107                            file.clone(),
11108                            Some(runnable.language.clone()),
11109                            worktree_id,
11110                            cx,
11111                        )
11112                    })
11113                    .filter(move |(_, template)| {
11114                        template.tags.iter().any(|source_tag| source_tag == &tag)
11115                    })
11116            })
11117            .sorted_by_key(|(kind, _)| kind.to_owned())
11118            .collect();
11119        if let Some((leading_tag_source, _)) = tags.first() {
11120            // Strongest source wins; if we have worktree tag binding, prefer that to
11121            // global and language bindings;
11122            // if we have a global binding, prefer that to language binding.
11123            let first_mismatch = tags
11124                .iter()
11125                .position(|(tag_source, _)| tag_source != leading_tag_source);
11126            if let Some(index) = first_mismatch {
11127                tags.truncate(index);
11128            }
11129        }
11130
11131        tags
11132    }
11133
11134    pub fn move_to_enclosing_bracket(
11135        &mut self,
11136        _: &MoveToEnclosingBracket,
11137        window: &mut Window,
11138        cx: &mut Context<Self>,
11139    ) {
11140        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11141            s.move_offsets_with(|snapshot, selection| {
11142                let Some(enclosing_bracket_ranges) =
11143                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11144                else {
11145                    return;
11146                };
11147
11148                let mut best_length = usize::MAX;
11149                let mut best_inside = false;
11150                let mut best_in_bracket_range = false;
11151                let mut best_destination = None;
11152                for (open, close) in enclosing_bracket_ranges {
11153                    let close = close.to_inclusive();
11154                    let length = close.end() - open.start;
11155                    let inside = selection.start >= open.end && selection.end <= *close.start();
11156                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11157                        || close.contains(&selection.head());
11158
11159                    // If best is next to a bracket and current isn't, skip
11160                    if !in_bracket_range && best_in_bracket_range {
11161                        continue;
11162                    }
11163
11164                    // Prefer smaller lengths unless best is inside and current isn't
11165                    if length > best_length && (best_inside || !inside) {
11166                        continue;
11167                    }
11168
11169                    best_length = length;
11170                    best_inside = inside;
11171                    best_in_bracket_range = in_bracket_range;
11172                    best_destination = Some(
11173                        if close.contains(&selection.start) && close.contains(&selection.end) {
11174                            if inside {
11175                                open.end
11176                            } else {
11177                                open.start
11178                            }
11179                        } else if inside {
11180                            *close.start()
11181                        } else {
11182                            *close.end()
11183                        },
11184                    );
11185                }
11186
11187                if let Some(destination) = best_destination {
11188                    selection.collapse_to(destination, SelectionGoal::None);
11189                }
11190            })
11191        });
11192    }
11193
11194    pub fn undo_selection(
11195        &mut self,
11196        _: &UndoSelection,
11197        window: &mut Window,
11198        cx: &mut Context<Self>,
11199    ) {
11200        self.end_selection(window, cx);
11201        self.selection_history.mode = SelectionHistoryMode::Undoing;
11202        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11203            self.change_selections(None, window, cx, |s| {
11204                s.select_anchors(entry.selections.to_vec())
11205            });
11206            self.select_next_state = entry.select_next_state;
11207            self.select_prev_state = entry.select_prev_state;
11208            self.add_selections_state = entry.add_selections_state;
11209            self.request_autoscroll(Autoscroll::newest(), cx);
11210        }
11211        self.selection_history.mode = SelectionHistoryMode::Normal;
11212    }
11213
11214    pub fn redo_selection(
11215        &mut self,
11216        _: &RedoSelection,
11217        window: &mut Window,
11218        cx: &mut Context<Self>,
11219    ) {
11220        self.end_selection(window, cx);
11221        self.selection_history.mode = SelectionHistoryMode::Redoing;
11222        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11223            self.change_selections(None, window, cx, |s| {
11224                s.select_anchors(entry.selections.to_vec())
11225            });
11226            self.select_next_state = entry.select_next_state;
11227            self.select_prev_state = entry.select_prev_state;
11228            self.add_selections_state = entry.add_selections_state;
11229            self.request_autoscroll(Autoscroll::newest(), cx);
11230        }
11231        self.selection_history.mode = SelectionHistoryMode::Normal;
11232    }
11233
11234    pub fn expand_excerpts(
11235        &mut self,
11236        action: &ExpandExcerpts,
11237        _: &mut Window,
11238        cx: &mut Context<Self>,
11239    ) {
11240        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11241    }
11242
11243    pub fn expand_excerpts_down(
11244        &mut self,
11245        action: &ExpandExcerptsDown,
11246        _: &mut Window,
11247        cx: &mut Context<Self>,
11248    ) {
11249        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11250    }
11251
11252    pub fn expand_excerpts_up(
11253        &mut self,
11254        action: &ExpandExcerptsUp,
11255        _: &mut Window,
11256        cx: &mut Context<Self>,
11257    ) {
11258        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11259    }
11260
11261    pub fn expand_excerpts_for_direction(
11262        &mut self,
11263        lines: u32,
11264        direction: ExpandExcerptDirection,
11265
11266        cx: &mut Context<Self>,
11267    ) {
11268        let selections = self.selections.disjoint_anchors();
11269
11270        let lines = if lines == 0 {
11271            EditorSettings::get_global(cx).expand_excerpt_lines
11272        } else {
11273            lines
11274        };
11275
11276        self.buffer.update(cx, |buffer, cx| {
11277            let snapshot = buffer.snapshot(cx);
11278            let mut excerpt_ids = selections
11279                .iter()
11280                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11281                .collect::<Vec<_>>();
11282            excerpt_ids.sort();
11283            excerpt_ids.dedup();
11284            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11285        })
11286    }
11287
11288    pub fn expand_excerpt(
11289        &mut self,
11290        excerpt: ExcerptId,
11291        direction: ExpandExcerptDirection,
11292        cx: &mut Context<Self>,
11293    ) {
11294        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11295        self.buffer.update(cx, |buffer, cx| {
11296            buffer.expand_excerpts([excerpt], lines, direction, cx)
11297        })
11298    }
11299
11300    pub fn go_to_singleton_buffer_point(
11301        &mut self,
11302        point: Point,
11303        window: &mut Window,
11304        cx: &mut Context<Self>,
11305    ) {
11306        self.go_to_singleton_buffer_range(point..point, window, cx);
11307    }
11308
11309    pub fn go_to_singleton_buffer_range(
11310        &mut self,
11311        range: Range<Point>,
11312        window: &mut Window,
11313        cx: &mut Context<Self>,
11314    ) {
11315        let multibuffer = self.buffer().read(cx);
11316        let Some(buffer) = multibuffer.as_singleton() else {
11317            return;
11318        };
11319        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11320            return;
11321        };
11322        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11323            return;
11324        };
11325        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11326            s.select_anchor_ranges([start..end])
11327        });
11328    }
11329
11330    fn go_to_diagnostic(
11331        &mut self,
11332        _: &GoToDiagnostic,
11333        window: &mut Window,
11334        cx: &mut Context<Self>,
11335    ) {
11336        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11337    }
11338
11339    fn go_to_prev_diagnostic(
11340        &mut self,
11341        _: &GoToPreviousDiagnostic,
11342        window: &mut Window,
11343        cx: &mut Context<Self>,
11344    ) {
11345        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11346    }
11347
11348    pub fn go_to_diagnostic_impl(
11349        &mut self,
11350        direction: Direction,
11351        window: &mut Window,
11352        cx: &mut Context<Self>,
11353    ) {
11354        let buffer = self.buffer.read(cx).snapshot(cx);
11355        let selection = self.selections.newest::<usize>(cx);
11356
11357        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11358        if direction == Direction::Next {
11359            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11360                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11361                    return;
11362                };
11363                self.activate_diagnostics(
11364                    buffer_id,
11365                    popover.local_diagnostic.diagnostic.group_id,
11366                    window,
11367                    cx,
11368                );
11369                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11370                    let primary_range_start = active_diagnostics.primary_range.start;
11371                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11372                        let mut new_selection = s.newest_anchor().clone();
11373                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11374                        s.select_anchors(vec![new_selection.clone()]);
11375                    });
11376                    self.refresh_inline_completion(false, true, window, cx);
11377                }
11378                return;
11379            }
11380        }
11381
11382        let active_group_id = self
11383            .active_diagnostics
11384            .as_ref()
11385            .map(|active_group| active_group.group_id);
11386        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11387            active_diagnostics
11388                .primary_range
11389                .to_offset(&buffer)
11390                .to_inclusive()
11391        });
11392        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11393            if active_primary_range.contains(&selection.head()) {
11394                *active_primary_range.start()
11395            } else {
11396                selection.head()
11397            }
11398        } else {
11399            selection.head()
11400        };
11401
11402        let snapshot = self.snapshot(window, cx);
11403        let primary_diagnostics_before = buffer
11404            .diagnostics_in_range::<usize>(0..search_start)
11405            .filter(|entry| entry.diagnostic.is_primary)
11406            .filter(|entry| entry.range.start != entry.range.end)
11407            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11408            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11409            .collect::<Vec<_>>();
11410        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11411            primary_diagnostics_before
11412                .iter()
11413                .position(|entry| entry.diagnostic.group_id == active_group_id)
11414        });
11415
11416        let primary_diagnostics_after = buffer
11417            .diagnostics_in_range::<usize>(search_start..buffer.len())
11418            .filter(|entry| entry.diagnostic.is_primary)
11419            .filter(|entry| entry.range.start != entry.range.end)
11420            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11421            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11422            .collect::<Vec<_>>();
11423        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11424            primary_diagnostics_after
11425                .iter()
11426                .enumerate()
11427                .rev()
11428                .find_map(|(i, entry)| {
11429                    if entry.diagnostic.group_id == active_group_id {
11430                        Some(i)
11431                    } else {
11432                        None
11433                    }
11434                })
11435        });
11436
11437        let next_primary_diagnostic = match direction {
11438            Direction::Prev => primary_diagnostics_before
11439                .iter()
11440                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11441                .rev()
11442                .next(),
11443            Direction::Next => primary_diagnostics_after
11444                .iter()
11445                .skip(
11446                    last_same_group_diagnostic_after
11447                        .map(|index| index + 1)
11448                        .unwrap_or(0),
11449                )
11450                .next(),
11451        };
11452
11453        // Cycle around to the start of the buffer, potentially moving back to the start of
11454        // the currently active diagnostic.
11455        let cycle_around = || match direction {
11456            Direction::Prev => primary_diagnostics_after
11457                .iter()
11458                .rev()
11459                .chain(primary_diagnostics_before.iter().rev())
11460                .next(),
11461            Direction::Next => primary_diagnostics_before
11462                .iter()
11463                .chain(primary_diagnostics_after.iter())
11464                .next(),
11465        };
11466
11467        if let Some((primary_range, group_id)) = next_primary_diagnostic
11468            .or_else(cycle_around)
11469            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11470        {
11471            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11472                return;
11473            };
11474            self.activate_diagnostics(buffer_id, group_id, window, cx);
11475            if self.active_diagnostics.is_some() {
11476                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11477                    s.select(vec![Selection {
11478                        id: selection.id,
11479                        start: primary_range.start,
11480                        end: primary_range.start,
11481                        reversed: false,
11482                        goal: SelectionGoal::None,
11483                    }]);
11484                });
11485                self.refresh_inline_completion(false, true, window, cx);
11486            }
11487        }
11488    }
11489
11490    fn go_to_next_hunk(&mut self, action: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11491        let snapshot = self.snapshot(window, cx);
11492        let selection = self.selections.newest::<Point>(cx);
11493        self.go_to_hunk_after_or_before_position(
11494            &snapshot,
11495            selection.head(),
11496            true,
11497            action.center_cursor,
11498            window,
11499            cx,
11500        );
11501    }
11502
11503    fn go_to_hunk_after_or_before_position(
11504        &mut self,
11505        snapshot: &EditorSnapshot,
11506        position: Point,
11507        after: bool,
11508        scroll_center: bool,
11509        window: &mut Window,
11510        cx: &mut Context<Editor>,
11511    ) -> Option<MultiBufferDiffHunk> {
11512        let hunk = if after {
11513            self.hunk_after_position(snapshot, position)
11514        } else {
11515            self.hunk_before_position(snapshot, position)
11516        };
11517
11518        if let Some(hunk) = &hunk {
11519            let destination = Point::new(hunk.row_range.start.0, 0);
11520            let autoscroll = if scroll_center {
11521                Autoscroll::center()
11522            } else {
11523                Autoscroll::fit()
11524            };
11525
11526            self.unfold_ranges(&[destination..destination], false, false, cx);
11527            self.change_selections(Some(autoscroll), window, cx, |s| {
11528                s.select_ranges([destination..destination]);
11529            });
11530        }
11531
11532        hunk
11533    }
11534
11535    fn hunk_after_position(
11536        &mut self,
11537        snapshot: &EditorSnapshot,
11538        position: Point,
11539    ) -> Option<MultiBufferDiffHunk> {
11540        snapshot
11541            .buffer_snapshot
11542            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11543            .find(|hunk| hunk.row_range.start.0 > position.row)
11544            .or_else(|| {
11545                snapshot
11546                    .buffer_snapshot
11547                    .diff_hunks_in_range(Point::zero()..position)
11548                    .find(|hunk| hunk.row_range.end.0 < position.row)
11549            })
11550    }
11551
11552    fn go_to_prev_hunk(
11553        &mut self,
11554        action: &GoToPreviousHunk,
11555        window: &mut Window,
11556        cx: &mut Context<Self>,
11557    ) {
11558        let snapshot = self.snapshot(window, cx);
11559        let selection = self.selections.newest::<Point>(cx);
11560        self.go_to_hunk_after_or_before_position(
11561            &snapshot,
11562            selection.head(),
11563            false,
11564            action.center_cursor,
11565            window,
11566            cx,
11567        );
11568    }
11569
11570    fn hunk_before_position(
11571        &mut self,
11572        snapshot: &EditorSnapshot,
11573        position: Point,
11574    ) -> Option<MultiBufferDiffHunk> {
11575        snapshot
11576            .buffer_snapshot
11577            .diff_hunk_before(position)
11578            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11579    }
11580
11581    pub fn go_to_definition(
11582        &mut self,
11583        _: &GoToDefinition,
11584        window: &mut Window,
11585        cx: &mut Context<Self>,
11586    ) -> Task<Result<Navigated>> {
11587        let definition =
11588            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11589        cx.spawn_in(window, |editor, mut cx| async move {
11590            if definition.await? == Navigated::Yes {
11591                return Ok(Navigated::Yes);
11592            }
11593            match editor.update_in(&mut cx, |editor, window, cx| {
11594                editor.find_all_references(&FindAllReferences, window, cx)
11595            })? {
11596                Some(references) => references.await,
11597                None => Ok(Navigated::No),
11598            }
11599        })
11600    }
11601
11602    pub fn go_to_declaration(
11603        &mut self,
11604        _: &GoToDeclaration,
11605        window: &mut Window,
11606        cx: &mut Context<Self>,
11607    ) -> Task<Result<Navigated>> {
11608        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11609    }
11610
11611    pub fn go_to_declaration_split(
11612        &mut self,
11613        _: &GoToDeclaration,
11614        window: &mut Window,
11615        cx: &mut Context<Self>,
11616    ) -> Task<Result<Navigated>> {
11617        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11618    }
11619
11620    pub fn go_to_implementation(
11621        &mut self,
11622        _: &GoToImplementation,
11623        window: &mut Window,
11624        cx: &mut Context<Self>,
11625    ) -> Task<Result<Navigated>> {
11626        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11627    }
11628
11629    pub fn go_to_implementation_split(
11630        &mut self,
11631        _: &GoToImplementationSplit,
11632        window: &mut Window,
11633        cx: &mut Context<Self>,
11634    ) -> Task<Result<Navigated>> {
11635        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11636    }
11637
11638    pub fn go_to_type_definition(
11639        &mut self,
11640        _: &GoToTypeDefinition,
11641        window: &mut Window,
11642        cx: &mut Context<Self>,
11643    ) -> Task<Result<Navigated>> {
11644        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11645    }
11646
11647    pub fn go_to_definition_split(
11648        &mut self,
11649        _: &GoToDefinitionSplit,
11650        window: &mut Window,
11651        cx: &mut Context<Self>,
11652    ) -> Task<Result<Navigated>> {
11653        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11654    }
11655
11656    pub fn go_to_type_definition_split(
11657        &mut self,
11658        _: &GoToTypeDefinitionSplit,
11659        window: &mut Window,
11660        cx: &mut Context<Self>,
11661    ) -> Task<Result<Navigated>> {
11662        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11663    }
11664
11665    fn go_to_definition_of_kind(
11666        &mut self,
11667        kind: GotoDefinitionKind,
11668        split: bool,
11669        window: &mut Window,
11670        cx: &mut Context<Self>,
11671    ) -> Task<Result<Navigated>> {
11672        let Some(provider) = self.semantics_provider.clone() else {
11673            return Task::ready(Ok(Navigated::No));
11674        };
11675        let head = self.selections.newest::<usize>(cx).head();
11676        let buffer = self.buffer.read(cx);
11677        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11678            text_anchor
11679        } else {
11680            return Task::ready(Ok(Navigated::No));
11681        };
11682
11683        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11684            return Task::ready(Ok(Navigated::No));
11685        };
11686
11687        cx.spawn_in(window, |editor, mut cx| async move {
11688            let definitions = definitions.await?;
11689            let navigated = editor
11690                .update_in(&mut cx, |editor, window, cx| {
11691                    editor.navigate_to_hover_links(
11692                        Some(kind),
11693                        definitions
11694                            .into_iter()
11695                            .filter(|location| {
11696                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11697                            })
11698                            .map(HoverLink::Text)
11699                            .collect::<Vec<_>>(),
11700                        split,
11701                        window,
11702                        cx,
11703                    )
11704                })?
11705                .await?;
11706            anyhow::Ok(navigated)
11707        })
11708    }
11709
11710    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11711        let selection = self.selections.newest_anchor();
11712        let head = selection.head();
11713        let tail = selection.tail();
11714
11715        let Some((buffer, start_position)) =
11716            self.buffer.read(cx).text_anchor_for_position(head, cx)
11717        else {
11718            return;
11719        };
11720
11721        let end_position = if head != tail {
11722            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11723                return;
11724            };
11725            Some(pos)
11726        } else {
11727            None
11728        };
11729
11730        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11731            let url = if let Some(end_pos) = end_position {
11732                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11733            } else {
11734                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11735            };
11736
11737            if let Some(url) = url {
11738                editor.update(&mut cx, |_, cx| {
11739                    cx.open_url(&url);
11740                })
11741            } else {
11742                Ok(())
11743            }
11744        });
11745
11746        url_finder.detach();
11747    }
11748
11749    pub fn open_selected_filename(
11750        &mut self,
11751        _: &OpenSelectedFilename,
11752        window: &mut Window,
11753        cx: &mut Context<Self>,
11754    ) {
11755        let Some(workspace) = self.workspace() else {
11756            return;
11757        };
11758
11759        let position = self.selections.newest_anchor().head();
11760
11761        let Some((buffer, buffer_position)) =
11762            self.buffer.read(cx).text_anchor_for_position(position, cx)
11763        else {
11764            return;
11765        };
11766
11767        let project = self.project.clone();
11768
11769        cx.spawn_in(window, |_, mut cx| async move {
11770            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11771
11772            if let Some((_, path)) = result {
11773                workspace
11774                    .update_in(&mut cx, |workspace, window, cx| {
11775                        workspace.open_resolved_path(path, window, cx)
11776                    })?
11777                    .await?;
11778            }
11779            anyhow::Ok(())
11780        })
11781        .detach();
11782    }
11783
11784    pub(crate) fn navigate_to_hover_links(
11785        &mut self,
11786        kind: Option<GotoDefinitionKind>,
11787        mut definitions: Vec<HoverLink>,
11788        split: bool,
11789        window: &mut Window,
11790        cx: &mut Context<Editor>,
11791    ) -> Task<Result<Navigated>> {
11792        // If there is one definition, just open it directly
11793        if definitions.len() == 1 {
11794            let definition = definitions.pop().unwrap();
11795
11796            enum TargetTaskResult {
11797                Location(Option<Location>),
11798                AlreadyNavigated,
11799            }
11800
11801            let target_task = match definition {
11802                HoverLink::Text(link) => {
11803                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11804                }
11805                HoverLink::InlayHint(lsp_location, server_id) => {
11806                    let computation =
11807                        self.compute_target_location(lsp_location, server_id, window, cx);
11808                    cx.background_spawn(async move {
11809                        let location = computation.await?;
11810                        Ok(TargetTaskResult::Location(location))
11811                    })
11812                }
11813                HoverLink::Url(url) => {
11814                    cx.open_url(&url);
11815                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11816                }
11817                HoverLink::File(path) => {
11818                    if let Some(workspace) = self.workspace() {
11819                        cx.spawn_in(window, |_, mut cx| async move {
11820                            workspace
11821                                .update_in(&mut cx, |workspace, window, cx| {
11822                                    workspace.open_resolved_path(path, window, cx)
11823                                })?
11824                                .await
11825                                .map(|_| TargetTaskResult::AlreadyNavigated)
11826                        })
11827                    } else {
11828                        Task::ready(Ok(TargetTaskResult::Location(None)))
11829                    }
11830                }
11831            };
11832            cx.spawn_in(window, |editor, mut cx| async move {
11833                let target = match target_task.await.context("target resolution task")? {
11834                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11835                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11836                    TargetTaskResult::Location(Some(target)) => target,
11837                };
11838
11839                editor.update_in(&mut cx, |editor, window, cx| {
11840                    let Some(workspace) = editor.workspace() else {
11841                        return Navigated::No;
11842                    };
11843                    let pane = workspace.read(cx).active_pane().clone();
11844
11845                    let range = target.range.to_point(target.buffer.read(cx));
11846                    let range = editor.range_for_match(&range);
11847                    let range = collapse_multiline_range(range);
11848
11849                    if !split
11850                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11851                    {
11852                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11853                    } else {
11854                        window.defer(cx, move |window, cx| {
11855                            let target_editor: Entity<Self> =
11856                                workspace.update(cx, |workspace, cx| {
11857                                    let pane = if split {
11858                                        workspace.adjacent_pane(window, cx)
11859                                    } else {
11860                                        workspace.active_pane().clone()
11861                                    };
11862
11863                                    workspace.open_project_item(
11864                                        pane,
11865                                        target.buffer.clone(),
11866                                        true,
11867                                        true,
11868                                        window,
11869                                        cx,
11870                                    )
11871                                });
11872                            target_editor.update(cx, |target_editor, cx| {
11873                                // When selecting a definition in a different buffer, disable the nav history
11874                                // to avoid creating a history entry at the previous cursor location.
11875                                pane.update(cx, |pane, _| pane.disable_history());
11876                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11877                                pane.update(cx, |pane, _| pane.enable_history());
11878                            });
11879                        });
11880                    }
11881                    Navigated::Yes
11882                })
11883            })
11884        } else if !definitions.is_empty() {
11885            cx.spawn_in(window, |editor, mut cx| async move {
11886                let (title, location_tasks, workspace) = editor
11887                    .update_in(&mut cx, |editor, window, cx| {
11888                        let tab_kind = match kind {
11889                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11890                            _ => "Definitions",
11891                        };
11892                        let title = definitions
11893                            .iter()
11894                            .find_map(|definition| match definition {
11895                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11896                                    let buffer = origin.buffer.read(cx);
11897                                    format!(
11898                                        "{} for {}",
11899                                        tab_kind,
11900                                        buffer
11901                                            .text_for_range(origin.range.clone())
11902                                            .collect::<String>()
11903                                    )
11904                                }),
11905                                HoverLink::InlayHint(_, _) => None,
11906                                HoverLink::Url(_) => None,
11907                                HoverLink::File(_) => None,
11908                            })
11909                            .unwrap_or(tab_kind.to_string());
11910                        let location_tasks = definitions
11911                            .into_iter()
11912                            .map(|definition| match definition {
11913                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11914                                HoverLink::InlayHint(lsp_location, server_id) => editor
11915                                    .compute_target_location(lsp_location, server_id, window, cx),
11916                                HoverLink::Url(_) => Task::ready(Ok(None)),
11917                                HoverLink::File(_) => Task::ready(Ok(None)),
11918                            })
11919                            .collect::<Vec<_>>();
11920                        (title, location_tasks, editor.workspace().clone())
11921                    })
11922                    .context("location tasks preparation")?;
11923
11924                let locations = future::join_all(location_tasks)
11925                    .await
11926                    .into_iter()
11927                    .filter_map(|location| location.transpose())
11928                    .collect::<Result<_>>()
11929                    .context("location tasks")?;
11930
11931                let Some(workspace) = workspace else {
11932                    return Ok(Navigated::No);
11933                };
11934                let opened = workspace
11935                    .update_in(&mut cx, |workspace, window, cx| {
11936                        Self::open_locations_in_multibuffer(
11937                            workspace,
11938                            locations,
11939                            title,
11940                            split,
11941                            MultibufferSelectionMode::First,
11942                            window,
11943                            cx,
11944                        )
11945                    })
11946                    .ok();
11947
11948                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11949            })
11950        } else {
11951            Task::ready(Ok(Navigated::No))
11952        }
11953    }
11954
11955    fn compute_target_location(
11956        &self,
11957        lsp_location: lsp::Location,
11958        server_id: LanguageServerId,
11959        window: &mut Window,
11960        cx: &mut Context<Self>,
11961    ) -> Task<anyhow::Result<Option<Location>>> {
11962        let Some(project) = self.project.clone() else {
11963            return Task::ready(Ok(None));
11964        };
11965
11966        cx.spawn_in(window, move |editor, mut cx| async move {
11967            let location_task = editor.update(&mut cx, |_, cx| {
11968                project.update(cx, |project, cx| {
11969                    let language_server_name = project
11970                        .language_server_statuses(cx)
11971                        .find(|(id, _)| server_id == *id)
11972                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11973                    language_server_name.map(|language_server_name| {
11974                        project.open_local_buffer_via_lsp(
11975                            lsp_location.uri.clone(),
11976                            server_id,
11977                            language_server_name,
11978                            cx,
11979                        )
11980                    })
11981                })
11982            })?;
11983            let location = match location_task {
11984                Some(task) => Some({
11985                    let target_buffer_handle = task.await.context("open local buffer")?;
11986                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11987                        let target_start = target_buffer
11988                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11989                        let target_end = target_buffer
11990                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11991                        target_buffer.anchor_after(target_start)
11992                            ..target_buffer.anchor_before(target_end)
11993                    })?;
11994                    Location {
11995                        buffer: target_buffer_handle,
11996                        range,
11997                    }
11998                }),
11999                None => None,
12000            };
12001            Ok(location)
12002        })
12003    }
12004
12005    pub fn find_all_references(
12006        &mut self,
12007        _: &FindAllReferences,
12008        window: &mut Window,
12009        cx: &mut Context<Self>,
12010    ) -> Option<Task<Result<Navigated>>> {
12011        let selection = self.selections.newest::<usize>(cx);
12012        let multi_buffer = self.buffer.read(cx);
12013        let head = selection.head();
12014
12015        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12016        let head_anchor = multi_buffer_snapshot.anchor_at(
12017            head,
12018            if head < selection.tail() {
12019                Bias::Right
12020            } else {
12021                Bias::Left
12022            },
12023        );
12024
12025        match self
12026            .find_all_references_task_sources
12027            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12028        {
12029            Ok(_) => {
12030                log::info!(
12031                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12032                );
12033                return None;
12034            }
12035            Err(i) => {
12036                self.find_all_references_task_sources.insert(i, head_anchor);
12037            }
12038        }
12039
12040        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12041        let workspace = self.workspace()?;
12042        let project = workspace.read(cx).project().clone();
12043        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12044        Some(cx.spawn_in(window, |editor, mut cx| async move {
12045            let _cleanup = defer({
12046                let mut cx = cx.clone();
12047                move || {
12048                    let _ = editor.update(&mut cx, |editor, _| {
12049                        if let Ok(i) =
12050                            editor
12051                                .find_all_references_task_sources
12052                                .binary_search_by(|anchor| {
12053                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12054                                })
12055                        {
12056                            editor.find_all_references_task_sources.remove(i);
12057                        }
12058                    });
12059                }
12060            });
12061
12062            let locations = references.await?;
12063            if locations.is_empty() {
12064                return anyhow::Ok(Navigated::No);
12065            }
12066
12067            workspace.update_in(&mut cx, |workspace, window, cx| {
12068                let title = locations
12069                    .first()
12070                    .as_ref()
12071                    .map(|location| {
12072                        let buffer = location.buffer.read(cx);
12073                        format!(
12074                            "References to `{}`",
12075                            buffer
12076                                .text_for_range(location.range.clone())
12077                                .collect::<String>()
12078                        )
12079                    })
12080                    .unwrap();
12081                Self::open_locations_in_multibuffer(
12082                    workspace,
12083                    locations,
12084                    title,
12085                    false,
12086                    MultibufferSelectionMode::First,
12087                    window,
12088                    cx,
12089                );
12090                Navigated::Yes
12091            })
12092        }))
12093    }
12094
12095    /// Opens a multibuffer with the given project locations in it
12096    pub fn open_locations_in_multibuffer(
12097        workspace: &mut Workspace,
12098        mut locations: Vec<Location>,
12099        title: String,
12100        split: bool,
12101        multibuffer_selection_mode: MultibufferSelectionMode,
12102        window: &mut Window,
12103        cx: &mut Context<Workspace>,
12104    ) {
12105        // If there are multiple definitions, open them in a multibuffer
12106        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12107        let mut locations = locations.into_iter().peekable();
12108        let mut ranges = Vec::new();
12109        let capability = workspace.project().read(cx).capability();
12110
12111        let excerpt_buffer = cx.new(|cx| {
12112            let mut multibuffer = MultiBuffer::new(capability);
12113            while let Some(location) = locations.next() {
12114                let buffer = location.buffer.read(cx);
12115                let mut ranges_for_buffer = Vec::new();
12116                let range = location.range.to_offset(buffer);
12117                ranges_for_buffer.push(range.clone());
12118
12119                while let Some(next_location) = locations.peek() {
12120                    if next_location.buffer == location.buffer {
12121                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12122                        locations.next();
12123                    } else {
12124                        break;
12125                    }
12126                }
12127
12128                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12129                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12130                    location.buffer.clone(),
12131                    ranges_for_buffer,
12132                    DEFAULT_MULTIBUFFER_CONTEXT,
12133                    cx,
12134                ))
12135            }
12136
12137            multibuffer.with_title(title)
12138        });
12139
12140        let editor = cx.new(|cx| {
12141            Editor::for_multibuffer(
12142                excerpt_buffer,
12143                Some(workspace.project().clone()),
12144                true,
12145                window,
12146                cx,
12147            )
12148        });
12149        editor.update(cx, |editor, cx| {
12150            match multibuffer_selection_mode {
12151                MultibufferSelectionMode::First => {
12152                    if let Some(first_range) = ranges.first() {
12153                        editor.change_selections(None, window, cx, |selections| {
12154                            selections.clear_disjoint();
12155                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12156                        });
12157                    }
12158                    editor.highlight_background::<Self>(
12159                        &ranges,
12160                        |theme| theme.editor_highlighted_line_background,
12161                        cx,
12162                    );
12163                }
12164                MultibufferSelectionMode::All => {
12165                    editor.change_selections(None, window, cx, |selections| {
12166                        selections.clear_disjoint();
12167                        selections.select_anchor_ranges(ranges);
12168                    });
12169                }
12170            }
12171            editor.register_buffers_with_language_servers(cx);
12172        });
12173
12174        let item = Box::new(editor);
12175        let item_id = item.item_id();
12176
12177        if split {
12178            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12179        } else {
12180            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12181                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12182                    pane.close_current_preview_item(window, cx)
12183                } else {
12184                    None
12185                }
12186            });
12187            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12188        }
12189        workspace.active_pane().update(cx, |pane, cx| {
12190            pane.set_preview_item_id(Some(item_id), cx);
12191        });
12192    }
12193
12194    pub fn rename(
12195        &mut self,
12196        _: &Rename,
12197        window: &mut Window,
12198        cx: &mut Context<Self>,
12199    ) -> Option<Task<Result<()>>> {
12200        use language::ToOffset as _;
12201
12202        let provider = self.semantics_provider.clone()?;
12203        let selection = self.selections.newest_anchor().clone();
12204        let (cursor_buffer, cursor_buffer_position) = self
12205            .buffer
12206            .read(cx)
12207            .text_anchor_for_position(selection.head(), cx)?;
12208        let (tail_buffer, cursor_buffer_position_end) = self
12209            .buffer
12210            .read(cx)
12211            .text_anchor_for_position(selection.tail(), cx)?;
12212        if tail_buffer != cursor_buffer {
12213            return None;
12214        }
12215
12216        let snapshot = cursor_buffer.read(cx).snapshot();
12217        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12218        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12219        let prepare_rename = provider
12220            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12221            .unwrap_or_else(|| Task::ready(Ok(None)));
12222        drop(snapshot);
12223
12224        Some(cx.spawn_in(window, |this, mut cx| async move {
12225            let rename_range = if let Some(range) = prepare_rename.await? {
12226                Some(range)
12227            } else {
12228                this.update(&mut cx, |this, cx| {
12229                    let buffer = this.buffer.read(cx).snapshot(cx);
12230                    let mut buffer_highlights = this
12231                        .document_highlights_for_position(selection.head(), &buffer)
12232                        .filter(|highlight| {
12233                            highlight.start.excerpt_id == selection.head().excerpt_id
12234                                && highlight.end.excerpt_id == selection.head().excerpt_id
12235                        });
12236                    buffer_highlights
12237                        .next()
12238                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12239                })?
12240            };
12241            if let Some(rename_range) = rename_range {
12242                this.update_in(&mut cx, |this, window, cx| {
12243                    let snapshot = cursor_buffer.read(cx).snapshot();
12244                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12245                    let cursor_offset_in_rename_range =
12246                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12247                    let cursor_offset_in_rename_range_end =
12248                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12249
12250                    this.take_rename(false, window, cx);
12251                    let buffer = this.buffer.read(cx).read(cx);
12252                    let cursor_offset = selection.head().to_offset(&buffer);
12253                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12254                    let rename_end = rename_start + rename_buffer_range.len();
12255                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12256                    let mut old_highlight_id = None;
12257                    let old_name: Arc<str> = buffer
12258                        .chunks(rename_start..rename_end, true)
12259                        .map(|chunk| {
12260                            if old_highlight_id.is_none() {
12261                                old_highlight_id = chunk.syntax_highlight_id;
12262                            }
12263                            chunk.text
12264                        })
12265                        .collect::<String>()
12266                        .into();
12267
12268                    drop(buffer);
12269
12270                    // Position the selection in the rename editor so that it matches the current selection.
12271                    this.show_local_selections = false;
12272                    let rename_editor = cx.new(|cx| {
12273                        let mut editor = Editor::single_line(window, cx);
12274                        editor.buffer.update(cx, |buffer, cx| {
12275                            buffer.edit([(0..0, old_name.clone())], None, cx)
12276                        });
12277                        let rename_selection_range = match cursor_offset_in_rename_range
12278                            .cmp(&cursor_offset_in_rename_range_end)
12279                        {
12280                            Ordering::Equal => {
12281                                editor.select_all(&SelectAll, window, cx);
12282                                return editor;
12283                            }
12284                            Ordering::Less => {
12285                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12286                            }
12287                            Ordering::Greater => {
12288                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12289                            }
12290                        };
12291                        if rename_selection_range.end > old_name.len() {
12292                            editor.select_all(&SelectAll, window, cx);
12293                        } else {
12294                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12295                                s.select_ranges([rename_selection_range]);
12296                            });
12297                        }
12298                        editor
12299                    });
12300                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12301                        if e == &EditorEvent::Focused {
12302                            cx.emit(EditorEvent::FocusedIn)
12303                        }
12304                    })
12305                    .detach();
12306
12307                    let write_highlights =
12308                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12309                    let read_highlights =
12310                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12311                    let ranges = write_highlights
12312                        .iter()
12313                        .flat_map(|(_, ranges)| ranges.iter())
12314                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12315                        .cloned()
12316                        .collect();
12317
12318                    this.highlight_text::<Rename>(
12319                        ranges,
12320                        HighlightStyle {
12321                            fade_out: Some(0.6),
12322                            ..Default::default()
12323                        },
12324                        cx,
12325                    );
12326                    let rename_focus_handle = rename_editor.focus_handle(cx);
12327                    window.focus(&rename_focus_handle);
12328                    let block_id = this.insert_blocks(
12329                        [BlockProperties {
12330                            style: BlockStyle::Flex,
12331                            placement: BlockPlacement::Below(range.start),
12332                            height: 1,
12333                            render: Arc::new({
12334                                let rename_editor = rename_editor.clone();
12335                                move |cx: &mut BlockContext| {
12336                                    let mut text_style = cx.editor_style.text.clone();
12337                                    if let Some(highlight_style) = old_highlight_id
12338                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12339                                    {
12340                                        text_style = text_style.highlight(highlight_style);
12341                                    }
12342                                    div()
12343                                        .block_mouse_down()
12344                                        .pl(cx.anchor_x)
12345                                        .child(EditorElement::new(
12346                                            &rename_editor,
12347                                            EditorStyle {
12348                                                background: cx.theme().system().transparent,
12349                                                local_player: cx.editor_style.local_player,
12350                                                text: text_style,
12351                                                scrollbar_width: cx.editor_style.scrollbar_width,
12352                                                syntax: cx.editor_style.syntax.clone(),
12353                                                status: cx.editor_style.status.clone(),
12354                                                inlay_hints_style: HighlightStyle {
12355                                                    font_weight: Some(FontWeight::BOLD),
12356                                                    ..make_inlay_hints_style(cx.app)
12357                                                },
12358                                                inline_completion_styles: make_suggestion_styles(
12359                                                    cx.app,
12360                                                ),
12361                                                ..EditorStyle::default()
12362                                            },
12363                                        ))
12364                                        .into_any_element()
12365                                }
12366                            }),
12367                            priority: 0,
12368                        }],
12369                        Some(Autoscroll::fit()),
12370                        cx,
12371                    )[0];
12372                    this.pending_rename = Some(RenameState {
12373                        range,
12374                        old_name,
12375                        editor: rename_editor,
12376                        block_id,
12377                    });
12378                })?;
12379            }
12380
12381            Ok(())
12382        }))
12383    }
12384
12385    pub fn confirm_rename(
12386        &mut self,
12387        _: &ConfirmRename,
12388        window: &mut Window,
12389        cx: &mut Context<Self>,
12390    ) -> Option<Task<Result<()>>> {
12391        let rename = self.take_rename(false, window, cx)?;
12392        let workspace = self.workspace()?.downgrade();
12393        let (buffer, start) = self
12394            .buffer
12395            .read(cx)
12396            .text_anchor_for_position(rename.range.start, cx)?;
12397        let (end_buffer, _) = self
12398            .buffer
12399            .read(cx)
12400            .text_anchor_for_position(rename.range.end, cx)?;
12401        if buffer != end_buffer {
12402            return None;
12403        }
12404
12405        let old_name = rename.old_name;
12406        let new_name = rename.editor.read(cx).text(cx);
12407
12408        let rename = self.semantics_provider.as_ref()?.perform_rename(
12409            &buffer,
12410            start,
12411            new_name.clone(),
12412            cx,
12413        )?;
12414
12415        Some(cx.spawn_in(window, |editor, mut cx| async move {
12416            let project_transaction = rename.await?;
12417            Self::open_project_transaction(
12418                &editor,
12419                workspace,
12420                project_transaction,
12421                format!("Rename: {}{}", old_name, new_name),
12422                cx.clone(),
12423            )
12424            .await?;
12425
12426            editor.update(&mut cx, |editor, cx| {
12427                editor.refresh_document_highlights(cx);
12428            })?;
12429            Ok(())
12430        }))
12431    }
12432
12433    fn take_rename(
12434        &mut self,
12435        moving_cursor: bool,
12436        window: &mut Window,
12437        cx: &mut Context<Self>,
12438    ) -> Option<RenameState> {
12439        let rename = self.pending_rename.take()?;
12440        if rename.editor.focus_handle(cx).is_focused(window) {
12441            window.focus(&self.focus_handle);
12442        }
12443
12444        self.remove_blocks(
12445            [rename.block_id].into_iter().collect(),
12446            Some(Autoscroll::fit()),
12447            cx,
12448        );
12449        self.clear_highlights::<Rename>(cx);
12450        self.show_local_selections = true;
12451
12452        if moving_cursor {
12453            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12454                editor.selections.newest::<usize>(cx).head()
12455            });
12456
12457            // Update the selection to match the position of the selection inside
12458            // the rename editor.
12459            let snapshot = self.buffer.read(cx).read(cx);
12460            let rename_range = rename.range.to_offset(&snapshot);
12461            let cursor_in_editor = snapshot
12462                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12463                .min(rename_range.end);
12464            drop(snapshot);
12465
12466            self.change_selections(None, window, cx, |s| {
12467                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12468            });
12469        } else {
12470            self.refresh_document_highlights(cx);
12471        }
12472
12473        Some(rename)
12474    }
12475
12476    pub fn pending_rename(&self) -> Option<&RenameState> {
12477        self.pending_rename.as_ref()
12478    }
12479
12480    fn format(
12481        &mut self,
12482        _: &Format,
12483        window: &mut Window,
12484        cx: &mut Context<Self>,
12485    ) -> Option<Task<Result<()>>> {
12486        let project = match &self.project {
12487            Some(project) => project.clone(),
12488            None => return None,
12489        };
12490
12491        Some(self.perform_format(
12492            project,
12493            FormatTrigger::Manual,
12494            FormatTarget::Buffers,
12495            window,
12496            cx,
12497        ))
12498    }
12499
12500    fn format_selections(
12501        &mut self,
12502        _: &FormatSelections,
12503        window: &mut Window,
12504        cx: &mut Context<Self>,
12505    ) -> Option<Task<Result<()>>> {
12506        let project = match &self.project {
12507            Some(project) => project.clone(),
12508            None => return None,
12509        };
12510
12511        let ranges = self
12512            .selections
12513            .all_adjusted(cx)
12514            .into_iter()
12515            .map(|selection| selection.range())
12516            .collect_vec();
12517
12518        Some(self.perform_format(
12519            project,
12520            FormatTrigger::Manual,
12521            FormatTarget::Ranges(ranges),
12522            window,
12523            cx,
12524        ))
12525    }
12526
12527    fn perform_format(
12528        &mut self,
12529        project: Entity<Project>,
12530        trigger: FormatTrigger,
12531        target: FormatTarget,
12532        window: &mut Window,
12533        cx: &mut Context<Self>,
12534    ) -> Task<Result<()>> {
12535        let buffer = self.buffer.clone();
12536        let (buffers, target) = match target {
12537            FormatTarget::Buffers => {
12538                let mut buffers = buffer.read(cx).all_buffers();
12539                if trigger == FormatTrigger::Save {
12540                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12541                }
12542                (buffers, LspFormatTarget::Buffers)
12543            }
12544            FormatTarget::Ranges(selection_ranges) => {
12545                let multi_buffer = buffer.read(cx);
12546                let snapshot = multi_buffer.read(cx);
12547                let mut buffers = HashSet::default();
12548                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12549                    BTreeMap::new();
12550                for selection_range in selection_ranges {
12551                    for (buffer, buffer_range, _) in
12552                        snapshot.range_to_buffer_ranges(selection_range)
12553                    {
12554                        let buffer_id = buffer.remote_id();
12555                        let start = buffer.anchor_before(buffer_range.start);
12556                        let end = buffer.anchor_after(buffer_range.end);
12557                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12558                        buffer_id_to_ranges
12559                            .entry(buffer_id)
12560                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12561                            .or_insert_with(|| vec![start..end]);
12562                    }
12563                }
12564                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12565            }
12566        };
12567
12568        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12569        let format = project.update(cx, |project, cx| {
12570            project.format(buffers, target, true, trigger, cx)
12571        });
12572
12573        cx.spawn_in(window, |_, mut cx| async move {
12574            let transaction = futures::select_biased! {
12575                () = timeout => {
12576                    log::warn!("timed out waiting for formatting");
12577                    None
12578                }
12579                transaction = format.log_err().fuse() => transaction,
12580            };
12581
12582            buffer
12583                .update(&mut cx, |buffer, cx| {
12584                    if let Some(transaction) = transaction {
12585                        if !buffer.is_singleton() {
12586                            buffer.push_transaction(&transaction.0, cx);
12587                        }
12588                    }
12589                    cx.notify();
12590                })
12591                .ok();
12592
12593            Ok(())
12594        })
12595    }
12596
12597    fn organize_imports(
12598        &mut self,
12599        _: &OrganizeImports,
12600        window: &mut Window,
12601        cx: &mut Context<Self>,
12602    ) -> Option<Task<Result<()>>> {
12603        let project = match &self.project {
12604            Some(project) => project.clone(),
12605            None => return None,
12606        };
12607        Some(self.perform_code_action_kind(
12608            project,
12609            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12610            window,
12611            cx,
12612        ))
12613    }
12614
12615    fn perform_code_action_kind(
12616        &mut self,
12617        project: Entity<Project>,
12618        kind: CodeActionKind,
12619        window: &mut Window,
12620        cx: &mut Context<Self>,
12621    ) -> Task<Result<()>> {
12622        let buffer = self.buffer.clone();
12623        let buffers = buffer.read(cx).all_buffers();
12624        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12625        let apply_action = project.update(cx, |project, cx| {
12626            project.apply_code_action_kind(buffers, kind, true, cx)
12627        });
12628        cx.spawn_in(window, |_, mut cx| async move {
12629            let transaction = futures::select_biased! {
12630                () = timeout => {
12631                    log::warn!("timed out waiting for executing code action");
12632                    None
12633                }
12634                transaction = apply_action.log_err().fuse() => transaction,
12635            };
12636            buffer
12637                .update(&mut cx, |buffer, cx| {
12638                    // check if we need this
12639                    if let Some(transaction) = transaction {
12640                        if !buffer.is_singleton() {
12641                            buffer.push_transaction(&transaction.0, cx);
12642                        }
12643                    }
12644                    cx.notify();
12645                })
12646                .ok();
12647            Ok(())
12648        })
12649    }
12650
12651    fn restart_language_server(
12652        &mut self,
12653        _: &RestartLanguageServer,
12654        _: &mut Window,
12655        cx: &mut Context<Self>,
12656    ) {
12657        if let Some(project) = self.project.clone() {
12658            self.buffer.update(cx, |multi_buffer, cx| {
12659                project.update(cx, |project, cx| {
12660                    project.restart_language_servers_for_buffers(
12661                        multi_buffer.all_buffers().into_iter().collect(),
12662                        cx,
12663                    );
12664                });
12665            })
12666        }
12667    }
12668
12669    fn cancel_language_server_work(
12670        workspace: &mut Workspace,
12671        _: &actions::CancelLanguageServerWork,
12672        _: &mut Window,
12673        cx: &mut Context<Workspace>,
12674    ) {
12675        let project = workspace.project();
12676        let buffers = workspace
12677            .active_item(cx)
12678            .and_then(|item| item.act_as::<Editor>(cx))
12679            .map_or(HashSet::default(), |editor| {
12680                editor.read(cx).buffer.read(cx).all_buffers()
12681            });
12682        project.update(cx, |project, cx| {
12683            project.cancel_language_server_work_for_buffers(buffers, cx);
12684        });
12685    }
12686
12687    fn show_character_palette(
12688        &mut self,
12689        _: &ShowCharacterPalette,
12690        window: &mut Window,
12691        _: &mut Context<Self>,
12692    ) {
12693        window.show_character_palette();
12694    }
12695
12696    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12697        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12698            let buffer = self.buffer.read(cx).snapshot(cx);
12699            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12700            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12701            let is_valid = buffer
12702                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12703                .any(|entry| {
12704                    entry.diagnostic.is_primary
12705                        && !entry.range.is_empty()
12706                        && entry.range.start == primary_range_start
12707                        && entry.diagnostic.message == active_diagnostics.primary_message
12708                });
12709
12710            if is_valid != active_diagnostics.is_valid {
12711                active_diagnostics.is_valid = is_valid;
12712                if is_valid {
12713                    let mut new_styles = HashMap::default();
12714                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12715                        new_styles.insert(
12716                            *block_id,
12717                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12718                        );
12719                    }
12720                    self.display_map.update(cx, |display_map, _cx| {
12721                        display_map.replace_blocks(new_styles);
12722                    });
12723                } else {
12724                    self.dismiss_diagnostics(cx);
12725                }
12726            }
12727        }
12728    }
12729
12730    fn activate_diagnostics(
12731        &mut self,
12732        buffer_id: BufferId,
12733        group_id: usize,
12734        window: &mut Window,
12735        cx: &mut Context<Self>,
12736    ) {
12737        self.dismiss_diagnostics(cx);
12738        let snapshot = self.snapshot(window, cx);
12739        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12740            let buffer = self.buffer.read(cx).snapshot(cx);
12741
12742            let mut primary_range = None;
12743            let mut primary_message = None;
12744            let diagnostic_group = buffer
12745                .diagnostic_group(buffer_id, group_id)
12746                .filter_map(|entry| {
12747                    let start = entry.range.start;
12748                    let end = entry.range.end;
12749                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12750                        && (start.row == end.row
12751                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12752                    {
12753                        return None;
12754                    }
12755                    if entry.diagnostic.is_primary {
12756                        primary_range = Some(entry.range.clone());
12757                        primary_message = Some(entry.diagnostic.message.clone());
12758                    }
12759                    Some(entry)
12760                })
12761                .collect::<Vec<_>>();
12762            let primary_range = primary_range?;
12763            let primary_message = primary_message?;
12764
12765            let blocks = display_map
12766                .insert_blocks(
12767                    diagnostic_group.iter().map(|entry| {
12768                        let diagnostic = entry.diagnostic.clone();
12769                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12770                        BlockProperties {
12771                            style: BlockStyle::Fixed,
12772                            placement: BlockPlacement::Below(
12773                                buffer.anchor_after(entry.range.start),
12774                            ),
12775                            height: message_height,
12776                            render: diagnostic_block_renderer(diagnostic, None, true),
12777                            priority: 0,
12778                        }
12779                    }),
12780                    cx,
12781                )
12782                .into_iter()
12783                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12784                .collect();
12785
12786            Some(ActiveDiagnosticGroup {
12787                primary_range: buffer.anchor_before(primary_range.start)
12788                    ..buffer.anchor_after(primary_range.end),
12789                primary_message,
12790                group_id,
12791                blocks,
12792                is_valid: true,
12793            })
12794        });
12795    }
12796
12797    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12798        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12799            self.display_map.update(cx, |display_map, cx| {
12800                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12801            });
12802            cx.notify();
12803        }
12804    }
12805
12806    /// Disable inline diagnostics rendering for this editor.
12807    pub fn disable_inline_diagnostics(&mut self) {
12808        self.inline_diagnostics_enabled = false;
12809        self.inline_diagnostics_update = Task::ready(());
12810        self.inline_diagnostics.clear();
12811    }
12812
12813    pub fn inline_diagnostics_enabled(&self) -> bool {
12814        self.inline_diagnostics_enabled
12815    }
12816
12817    pub fn show_inline_diagnostics(&self) -> bool {
12818        self.show_inline_diagnostics
12819    }
12820
12821    pub fn toggle_inline_diagnostics(
12822        &mut self,
12823        _: &ToggleInlineDiagnostics,
12824        window: &mut Window,
12825        cx: &mut Context<'_, Editor>,
12826    ) {
12827        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12828        self.refresh_inline_diagnostics(false, window, cx);
12829    }
12830
12831    fn refresh_inline_diagnostics(
12832        &mut self,
12833        debounce: bool,
12834        window: &mut Window,
12835        cx: &mut Context<Self>,
12836    ) {
12837        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12838            self.inline_diagnostics_update = Task::ready(());
12839            self.inline_diagnostics.clear();
12840            return;
12841        }
12842
12843        let debounce_ms = ProjectSettings::get_global(cx)
12844            .diagnostics
12845            .inline
12846            .update_debounce_ms;
12847        let debounce = if debounce && debounce_ms > 0 {
12848            Some(Duration::from_millis(debounce_ms))
12849        } else {
12850            None
12851        };
12852        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12853            if let Some(debounce) = debounce {
12854                cx.background_executor().timer(debounce).await;
12855            }
12856            let Some(snapshot) = editor
12857                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12858                .ok()
12859            else {
12860                return;
12861            };
12862
12863            let new_inline_diagnostics = cx
12864                .background_spawn(async move {
12865                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12866                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12867                        let message = diagnostic_entry
12868                            .diagnostic
12869                            .message
12870                            .split_once('\n')
12871                            .map(|(line, _)| line)
12872                            .map(SharedString::new)
12873                            .unwrap_or_else(|| {
12874                                SharedString::from(diagnostic_entry.diagnostic.message)
12875                            });
12876                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12877                        let (Ok(i) | Err(i)) = inline_diagnostics
12878                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12879                        inline_diagnostics.insert(
12880                            i,
12881                            (
12882                                start_anchor,
12883                                InlineDiagnostic {
12884                                    message,
12885                                    group_id: diagnostic_entry.diagnostic.group_id,
12886                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12887                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12888                                    severity: diagnostic_entry.diagnostic.severity,
12889                                },
12890                            ),
12891                        );
12892                    }
12893                    inline_diagnostics
12894                })
12895                .await;
12896
12897            editor
12898                .update(&mut cx, |editor, cx| {
12899                    editor.inline_diagnostics = new_inline_diagnostics;
12900                    cx.notify();
12901                })
12902                .ok();
12903        });
12904    }
12905
12906    pub fn set_selections_from_remote(
12907        &mut self,
12908        selections: Vec<Selection<Anchor>>,
12909        pending_selection: Option<Selection<Anchor>>,
12910        window: &mut Window,
12911        cx: &mut Context<Self>,
12912    ) {
12913        let old_cursor_position = self.selections.newest_anchor().head();
12914        self.selections.change_with(cx, |s| {
12915            s.select_anchors(selections);
12916            if let Some(pending_selection) = pending_selection {
12917                s.set_pending(pending_selection, SelectMode::Character);
12918            } else {
12919                s.clear_pending();
12920            }
12921        });
12922        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12923    }
12924
12925    fn push_to_selection_history(&mut self) {
12926        self.selection_history.push(SelectionHistoryEntry {
12927            selections: self.selections.disjoint_anchors(),
12928            select_next_state: self.select_next_state.clone(),
12929            select_prev_state: self.select_prev_state.clone(),
12930            add_selections_state: self.add_selections_state.clone(),
12931        });
12932    }
12933
12934    pub fn transact(
12935        &mut self,
12936        window: &mut Window,
12937        cx: &mut Context<Self>,
12938        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12939    ) -> Option<TransactionId> {
12940        self.start_transaction_at(Instant::now(), window, cx);
12941        update(self, window, cx);
12942        self.end_transaction_at(Instant::now(), cx)
12943    }
12944
12945    pub fn start_transaction_at(
12946        &mut self,
12947        now: Instant,
12948        window: &mut Window,
12949        cx: &mut Context<Self>,
12950    ) {
12951        self.end_selection(window, cx);
12952        if let Some(tx_id) = self
12953            .buffer
12954            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12955        {
12956            self.selection_history
12957                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12958            cx.emit(EditorEvent::TransactionBegun {
12959                transaction_id: tx_id,
12960            })
12961        }
12962    }
12963
12964    pub fn end_transaction_at(
12965        &mut self,
12966        now: Instant,
12967        cx: &mut Context<Self>,
12968    ) -> Option<TransactionId> {
12969        if let Some(transaction_id) = self
12970            .buffer
12971            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12972        {
12973            if let Some((_, end_selections)) =
12974                self.selection_history.transaction_mut(transaction_id)
12975            {
12976                *end_selections = Some(self.selections.disjoint_anchors());
12977            } else {
12978                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12979            }
12980
12981            cx.emit(EditorEvent::Edited { transaction_id });
12982            Some(transaction_id)
12983        } else {
12984            None
12985        }
12986    }
12987
12988    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12989        if self.selection_mark_mode {
12990            self.change_selections(None, window, cx, |s| {
12991                s.move_with(|_, sel| {
12992                    sel.collapse_to(sel.head(), SelectionGoal::None);
12993                });
12994            })
12995        }
12996        self.selection_mark_mode = true;
12997        cx.notify();
12998    }
12999
13000    pub fn swap_selection_ends(
13001        &mut self,
13002        _: &actions::SwapSelectionEnds,
13003        window: &mut Window,
13004        cx: &mut Context<Self>,
13005    ) {
13006        self.change_selections(None, window, cx, |s| {
13007            s.move_with(|_, sel| {
13008                if sel.start != sel.end {
13009                    sel.reversed = !sel.reversed
13010                }
13011            });
13012        });
13013        self.request_autoscroll(Autoscroll::newest(), cx);
13014        cx.notify();
13015    }
13016
13017    pub fn toggle_fold(
13018        &mut self,
13019        _: &actions::ToggleFold,
13020        window: &mut Window,
13021        cx: &mut Context<Self>,
13022    ) {
13023        if self.is_singleton(cx) {
13024            let selection = self.selections.newest::<Point>(cx);
13025
13026            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13027            let range = if selection.is_empty() {
13028                let point = selection.head().to_display_point(&display_map);
13029                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13030                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13031                    .to_point(&display_map);
13032                start..end
13033            } else {
13034                selection.range()
13035            };
13036            if display_map.folds_in_range(range).next().is_some() {
13037                self.unfold_lines(&Default::default(), window, cx)
13038            } else {
13039                self.fold(&Default::default(), window, cx)
13040            }
13041        } else {
13042            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13043            let buffer_ids: HashSet<_> = self
13044                .selections
13045                .disjoint_anchor_ranges()
13046                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13047                .collect();
13048
13049            let should_unfold = buffer_ids
13050                .iter()
13051                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13052
13053            for buffer_id in buffer_ids {
13054                if should_unfold {
13055                    self.unfold_buffer(buffer_id, cx);
13056                } else {
13057                    self.fold_buffer(buffer_id, cx);
13058                }
13059            }
13060        }
13061    }
13062
13063    pub fn toggle_fold_recursive(
13064        &mut self,
13065        _: &actions::ToggleFoldRecursive,
13066        window: &mut Window,
13067        cx: &mut Context<Self>,
13068    ) {
13069        let selection = self.selections.newest::<Point>(cx);
13070
13071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13072        let range = if selection.is_empty() {
13073            let point = selection.head().to_display_point(&display_map);
13074            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13075            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13076                .to_point(&display_map);
13077            start..end
13078        } else {
13079            selection.range()
13080        };
13081        if display_map.folds_in_range(range).next().is_some() {
13082            self.unfold_recursive(&Default::default(), window, cx)
13083        } else {
13084            self.fold_recursive(&Default::default(), window, cx)
13085        }
13086    }
13087
13088    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13089        if self.is_singleton(cx) {
13090            let mut to_fold = Vec::new();
13091            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13092            let selections = self.selections.all_adjusted(cx);
13093
13094            for selection in selections {
13095                let range = selection.range().sorted();
13096                let buffer_start_row = range.start.row;
13097
13098                if range.start.row != range.end.row {
13099                    let mut found = false;
13100                    let mut row = range.start.row;
13101                    while row <= range.end.row {
13102                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13103                        {
13104                            found = true;
13105                            row = crease.range().end.row + 1;
13106                            to_fold.push(crease);
13107                        } else {
13108                            row += 1
13109                        }
13110                    }
13111                    if found {
13112                        continue;
13113                    }
13114                }
13115
13116                for row in (0..=range.start.row).rev() {
13117                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13118                        if crease.range().end.row >= buffer_start_row {
13119                            to_fold.push(crease);
13120                            if row <= range.start.row {
13121                                break;
13122                            }
13123                        }
13124                    }
13125                }
13126            }
13127
13128            self.fold_creases(to_fold, true, window, cx);
13129        } else {
13130            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13131            let buffer_ids = self
13132                .selections
13133                .disjoint_anchor_ranges()
13134                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13135                .collect::<HashSet<_>>();
13136            for buffer_id in buffer_ids {
13137                self.fold_buffer(buffer_id, cx);
13138            }
13139        }
13140    }
13141
13142    fn fold_at_level(
13143        &mut self,
13144        fold_at: &FoldAtLevel,
13145        window: &mut Window,
13146        cx: &mut Context<Self>,
13147    ) {
13148        if !self.buffer.read(cx).is_singleton() {
13149            return;
13150        }
13151
13152        let fold_at_level = fold_at.0;
13153        let snapshot = self.buffer.read(cx).snapshot(cx);
13154        let mut to_fold = Vec::new();
13155        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13156
13157        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13158            while start_row < end_row {
13159                match self
13160                    .snapshot(window, cx)
13161                    .crease_for_buffer_row(MultiBufferRow(start_row))
13162                {
13163                    Some(crease) => {
13164                        let nested_start_row = crease.range().start.row + 1;
13165                        let nested_end_row = crease.range().end.row;
13166
13167                        if current_level < fold_at_level {
13168                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13169                        } else if current_level == fold_at_level {
13170                            to_fold.push(crease);
13171                        }
13172
13173                        start_row = nested_end_row + 1;
13174                    }
13175                    None => start_row += 1,
13176                }
13177            }
13178        }
13179
13180        self.fold_creases(to_fold, true, window, cx);
13181    }
13182
13183    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13184        if self.buffer.read(cx).is_singleton() {
13185            let mut fold_ranges = Vec::new();
13186            let snapshot = self.buffer.read(cx).snapshot(cx);
13187
13188            for row in 0..snapshot.max_row().0 {
13189                if let Some(foldable_range) = self
13190                    .snapshot(window, cx)
13191                    .crease_for_buffer_row(MultiBufferRow(row))
13192                {
13193                    fold_ranges.push(foldable_range);
13194                }
13195            }
13196
13197            self.fold_creases(fold_ranges, true, window, cx);
13198        } else {
13199            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13200                editor
13201                    .update_in(&mut cx, |editor, _, cx| {
13202                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13203                            editor.fold_buffer(buffer_id, cx);
13204                        }
13205                    })
13206                    .ok();
13207            });
13208        }
13209    }
13210
13211    pub fn fold_function_bodies(
13212        &mut self,
13213        _: &actions::FoldFunctionBodies,
13214        window: &mut Window,
13215        cx: &mut Context<Self>,
13216    ) {
13217        let snapshot = self.buffer.read(cx).snapshot(cx);
13218
13219        let ranges = snapshot
13220            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13221            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13222            .collect::<Vec<_>>();
13223
13224        let creases = ranges
13225            .into_iter()
13226            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13227            .collect();
13228
13229        self.fold_creases(creases, true, window, cx);
13230    }
13231
13232    pub fn fold_recursive(
13233        &mut self,
13234        _: &actions::FoldRecursive,
13235        window: &mut Window,
13236        cx: &mut Context<Self>,
13237    ) {
13238        let mut to_fold = Vec::new();
13239        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13240        let selections = self.selections.all_adjusted(cx);
13241
13242        for selection in selections {
13243            let range = selection.range().sorted();
13244            let buffer_start_row = range.start.row;
13245
13246            if range.start.row != range.end.row {
13247                let mut found = false;
13248                for row in range.start.row..=range.end.row {
13249                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13250                        found = true;
13251                        to_fold.push(crease);
13252                    }
13253                }
13254                if found {
13255                    continue;
13256                }
13257            }
13258
13259            for row in (0..=range.start.row).rev() {
13260                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13261                    if crease.range().end.row >= buffer_start_row {
13262                        to_fold.push(crease);
13263                    } else {
13264                        break;
13265                    }
13266                }
13267            }
13268        }
13269
13270        self.fold_creases(to_fold, true, window, cx);
13271    }
13272
13273    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13274        let buffer_row = fold_at.buffer_row;
13275        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13276
13277        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13278            let autoscroll = self
13279                .selections
13280                .all::<Point>(cx)
13281                .iter()
13282                .any(|selection| crease.range().overlaps(&selection.range()));
13283
13284            self.fold_creases(vec![crease], autoscroll, window, cx);
13285        }
13286    }
13287
13288    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13289        if self.is_singleton(cx) {
13290            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13291            let buffer = &display_map.buffer_snapshot;
13292            let selections = self.selections.all::<Point>(cx);
13293            let ranges = selections
13294                .iter()
13295                .map(|s| {
13296                    let range = s.display_range(&display_map).sorted();
13297                    let mut start = range.start.to_point(&display_map);
13298                    let mut end = range.end.to_point(&display_map);
13299                    start.column = 0;
13300                    end.column = buffer.line_len(MultiBufferRow(end.row));
13301                    start..end
13302                })
13303                .collect::<Vec<_>>();
13304
13305            self.unfold_ranges(&ranges, true, true, cx);
13306        } else {
13307            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13308            let buffer_ids = self
13309                .selections
13310                .disjoint_anchor_ranges()
13311                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13312                .collect::<HashSet<_>>();
13313            for buffer_id in buffer_ids {
13314                self.unfold_buffer(buffer_id, cx);
13315            }
13316        }
13317    }
13318
13319    pub fn unfold_recursive(
13320        &mut self,
13321        _: &UnfoldRecursive,
13322        _window: &mut Window,
13323        cx: &mut Context<Self>,
13324    ) {
13325        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13326        let selections = self.selections.all::<Point>(cx);
13327        let ranges = selections
13328            .iter()
13329            .map(|s| {
13330                let mut range = s.display_range(&display_map).sorted();
13331                *range.start.column_mut() = 0;
13332                *range.end.column_mut() = display_map.line_len(range.end.row());
13333                let start = range.start.to_point(&display_map);
13334                let end = range.end.to_point(&display_map);
13335                start..end
13336            })
13337            .collect::<Vec<_>>();
13338
13339        self.unfold_ranges(&ranges, true, true, cx);
13340    }
13341
13342    pub fn unfold_at(
13343        &mut self,
13344        unfold_at: &UnfoldAt,
13345        _window: &mut Window,
13346        cx: &mut Context<Self>,
13347    ) {
13348        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13349
13350        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13351            ..Point::new(
13352                unfold_at.buffer_row.0,
13353                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13354            );
13355
13356        let autoscroll = self
13357            .selections
13358            .all::<Point>(cx)
13359            .iter()
13360            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13361
13362        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13363    }
13364
13365    pub fn unfold_all(
13366        &mut self,
13367        _: &actions::UnfoldAll,
13368        _window: &mut Window,
13369        cx: &mut Context<Self>,
13370    ) {
13371        if self.buffer.read(cx).is_singleton() {
13372            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13373            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13374        } else {
13375            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13376                editor
13377                    .update(&mut cx, |editor, cx| {
13378                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13379                            editor.unfold_buffer(buffer_id, cx);
13380                        }
13381                    })
13382                    .ok();
13383            });
13384        }
13385    }
13386
13387    pub fn fold_selected_ranges(
13388        &mut self,
13389        _: &FoldSelectedRanges,
13390        window: &mut Window,
13391        cx: &mut Context<Self>,
13392    ) {
13393        let selections = self.selections.all::<Point>(cx);
13394        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13395        let line_mode = self.selections.line_mode;
13396        let ranges = selections
13397            .into_iter()
13398            .map(|s| {
13399                if line_mode {
13400                    let start = Point::new(s.start.row, 0);
13401                    let end = Point::new(
13402                        s.end.row,
13403                        display_map
13404                            .buffer_snapshot
13405                            .line_len(MultiBufferRow(s.end.row)),
13406                    );
13407                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13408                } else {
13409                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13410                }
13411            })
13412            .collect::<Vec<_>>();
13413        self.fold_creases(ranges, true, window, cx);
13414    }
13415
13416    pub fn fold_ranges<T: ToOffset + Clone>(
13417        &mut self,
13418        ranges: Vec<Range<T>>,
13419        auto_scroll: bool,
13420        window: &mut Window,
13421        cx: &mut Context<Self>,
13422    ) {
13423        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13424        let ranges = ranges
13425            .into_iter()
13426            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13427            .collect::<Vec<_>>();
13428        self.fold_creases(ranges, auto_scroll, window, cx);
13429    }
13430
13431    pub fn fold_creases<T: ToOffset + Clone>(
13432        &mut self,
13433        creases: Vec<Crease<T>>,
13434        auto_scroll: bool,
13435        window: &mut Window,
13436        cx: &mut Context<Self>,
13437    ) {
13438        if creases.is_empty() {
13439            return;
13440        }
13441
13442        let mut buffers_affected = HashSet::default();
13443        let multi_buffer = self.buffer().read(cx);
13444        for crease in &creases {
13445            if let Some((_, buffer, _)) =
13446                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13447            {
13448                buffers_affected.insert(buffer.read(cx).remote_id());
13449            };
13450        }
13451
13452        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13453
13454        if auto_scroll {
13455            self.request_autoscroll(Autoscroll::fit(), cx);
13456        }
13457
13458        cx.notify();
13459
13460        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13461            // Clear diagnostics block when folding a range that contains it.
13462            let snapshot = self.snapshot(window, cx);
13463            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13464                drop(snapshot);
13465                self.active_diagnostics = Some(active_diagnostics);
13466                self.dismiss_diagnostics(cx);
13467            } else {
13468                self.active_diagnostics = Some(active_diagnostics);
13469            }
13470        }
13471
13472        self.scrollbar_marker_state.dirty = true;
13473    }
13474
13475    /// Removes any folds whose ranges intersect any of the given ranges.
13476    pub fn unfold_ranges<T: ToOffset + Clone>(
13477        &mut self,
13478        ranges: &[Range<T>],
13479        inclusive: bool,
13480        auto_scroll: bool,
13481        cx: &mut Context<Self>,
13482    ) {
13483        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13484            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13485        });
13486    }
13487
13488    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13489        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13490            return;
13491        }
13492        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13493        self.display_map.update(cx, |display_map, cx| {
13494            display_map.fold_buffers([buffer_id], cx)
13495        });
13496        cx.emit(EditorEvent::BufferFoldToggled {
13497            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13498            folded: true,
13499        });
13500        cx.notify();
13501    }
13502
13503    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13504        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13505            return;
13506        }
13507        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13508        self.display_map.update(cx, |display_map, cx| {
13509            display_map.unfold_buffers([buffer_id], cx);
13510        });
13511        cx.emit(EditorEvent::BufferFoldToggled {
13512            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13513            folded: false,
13514        });
13515        cx.notify();
13516    }
13517
13518    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13519        self.display_map.read(cx).is_buffer_folded(buffer)
13520    }
13521
13522    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13523        self.display_map.read(cx).folded_buffers()
13524    }
13525
13526    /// Removes any folds with the given ranges.
13527    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13528        &mut self,
13529        ranges: &[Range<T>],
13530        type_id: TypeId,
13531        auto_scroll: bool,
13532        cx: &mut Context<Self>,
13533    ) {
13534        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13535            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13536        });
13537    }
13538
13539    fn remove_folds_with<T: ToOffset + Clone>(
13540        &mut self,
13541        ranges: &[Range<T>],
13542        auto_scroll: bool,
13543        cx: &mut Context<Self>,
13544        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13545    ) {
13546        if ranges.is_empty() {
13547            return;
13548        }
13549
13550        let mut buffers_affected = HashSet::default();
13551        let multi_buffer = self.buffer().read(cx);
13552        for range in ranges {
13553            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13554                buffers_affected.insert(buffer.read(cx).remote_id());
13555            };
13556        }
13557
13558        self.display_map.update(cx, update);
13559
13560        if auto_scroll {
13561            self.request_autoscroll(Autoscroll::fit(), cx);
13562        }
13563
13564        cx.notify();
13565        self.scrollbar_marker_state.dirty = true;
13566        self.active_indent_guides_state.dirty = true;
13567    }
13568
13569    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13570        self.display_map.read(cx).fold_placeholder.clone()
13571    }
13572
13573    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13574        self.buffer.update(cx, |buffer, cx| {
13575            buffer.set_all_diff_hunks_expanded(cx);
13576        });
13577    }
13578
13579    pub fn expand_all_diff_hunks(
13580        &mut self,
13581        _: &ExpandAllDiffHunks,
13582        _window: &mut Window,
13583        cx: &mut Context<Self>,
13584    ) {
13585        self.buffer.update(cx, |buffer, cx| {
13586            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13587        });
13588    }
13589
13590    pub fn toggle_selected_diff_hunks(
13591        &mut self,
13592        _: &ToggleSelectedDiffHunks,
13593        _window: &mut Window,
13594        cx: &mut Context<Self>,
13595    ) {
13596        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13597        self.toggle_diff_hunks_in_ranges(ranges, cx);
13598    }
13599
13600    pub fn diff_hunks_in_ranges<'a>(
13601        &'a self,
13602        ranges: &'a [Range<Anchor>],
13603        buffer: &'a MultiBufferSnapshot,
13604    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13605        ranges.iter().flat_map(move |range| {
13606            let end_excerpt_id = range.end.excerpt_id;
13607            let range = range.to_point(buffer);
13608            let mut peek_end = range.end;
13609            if range.end.row < buffer.max_row().0 {
13610                peek_end = Point::new(range.end.row + 1, 0);
13611            }
13612            buffer
13613                .diff_hunks_in_range(range.start..peek_end)
13614                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13615        })
13616    }
13617
13618    pub fn has_stageable_diff_hunks_in_ranges(
13619        &self,
13620        ranges: &[Range<Anchor>],
13621        snapshot: &MultiBufferSnapshot,
13622    ) -> bool {
13623        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13624        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13625    }
13626
13627    pub fn toggle_staged_selected_diff_hunks(
13628        &mut self,
13629        _: &::git::ToggleStaged,
13630        window: &mut Window,
13631        cx: &mut Context<Self>,
13632    ) {
13633        let snapshot = self.buffer.read(cx).snapshot(cx);
13634        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13635        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13636        self.stage_or_unstage_diff_hunks(stage, &ranges, window, cx);
13637    }
13638
13639    pub fn stage_and_next(
13640        &mut self,
13641        action: &::git::StageAndNext,
13642        window: &mut Window,
13643        cx: &mut Context<Self>,
13644    ) {
13645        self.do_stage_or_unstage_and_next(true, action.whole_excerpt, window, cx);
13646    }
13647
13648    pub fn unstage_and_next(
13649        &mut self,
13650        action: &::git::UnstageAndNext,
13651        window: &mut Window,
13652        cx: &mut Context<Self>,
13653    ) {
13654        self.do_stage_or_unstage_and_next(false, action.whole_excerpt, window, cx);
13655    }
13656
13657    pub fn stage_or_unstage_diff_hunks(
13658        &mut self,
13659        stage: bool,
13660        ranges: &[Range<Anchor>],
13661        window: &mut Window,
13662        cx: &mut Context<Self>,
13663    ) {
13664        let snapshot = self.buffer.read(cx).snapshot(cx);
13665        let chunk_by = self
13666            .diff_hunks_in_ranges(&ranges, &snapshot)
13667            .chunk_by(|hunk| hunk.buffer_id);
13668        for (buffer_id, hunks) in &chunk_by {
13669            self.do_stage_or_unstage(stage, buffer_id, hunks, window, cx);
13670        }
13671    }
13672
13673    fn do_stage_or_unstage_and_next(
13674        &mut self,
13675        stage: bool,
13676        whole_excerpt: bool,
13677        window: &mut Window,
13678        cx: &mut Context<Self>,
13679    ) {
13680        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13681
13682        if ranges.iter().any(|range| range.start != range.end) {
13683            self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13684            return;
13685        }
13686
13687        if !whole_excerpt {
13688            let snapshot = self.snapshot(window, cx);
13689            let newest_range = self.selections.newest::<Point>(cx).range();
13690
13691            let run_twice = snapshot
13692                .hunks_for_ranges([newest_range])
13693                .first()
13694                .is_some_and(|hunk| {
13695                    let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13696                    self.hunk_after_position(&snapshot, next_line)
13697                        .is_some_and(|other| other.row_range == hunk.row_range)
13698                });
13699
13700            if run_twice {
13701                self.go_to_next_hunk(
13702                    &GoToHunk {
13703                        center_cursor: true,
13704                    },
13705                    window,
13706                    cx,
13707                );
13708            }
13709        } else if !self.buffer().read(cx).is_singleton() {
13710            self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13711
13712            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13713                if buffer.read(cx).is_empty() {
13714                    let buffer = buffer.read(cx);
13715                    let Some(file) = buffer.file() else {
13716                        return;
13717                    };
13718                    let project_path = project::ProjectPath {
13719                        worktree_id: file.worktree_id(cx),
13720                        path: file.path().clone(),
13721                    };
13722                    let Some(project) = self.project.as_ref() else {
13723                        return;
13724                    };
13725
13726                    let Some(repo) = project.read(cx).git_store().read(cx).active_repository()
13727                    else {
13728                        return;
13729                    };
13730
13731                    repo.update(cx, |repo, cx| {
13732                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13733                            return;
13734                        };
13735                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13736                            return;
13737                        };
13738                        if stage && status.status == FileStatus::Untracked {
13739                            repo.stage_entries(vec![repo_path], cx)
13740                                .detach_and_log_err(cx);
13741                            return;
13742                        }
13743                    })
13744                }
13745                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13746                    excerpt_id,
13747                    buffer.read(cx).remote_id(),
13748                    range,
13749                )];
13750                self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13751                let snapshot = self.buffer().read(cx).snapshot(cx);
13752                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13753                if point.row < snapshot.max_row().0 {
13754                    point.row += 1;
13755                    point.column = 0;
13756                    point = snapshot.clip_point(point, Bias::Right);
13757                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13758                        s.select_ranges([point..point]);
13759                    });
13760                }
13761                return;
13762            }
13763        }
13764        self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13765        self.go_to_next_hunk(
13766            &GoToHunk {
13767                center_cursor: true,
13768            },
13769            window,
13770            cx,
13771        );
13772    }
13773
13774    fn do_stage_or_unstage(
13775        &self,
13776        stage: bool,
13777        buffer_id: BufferId,
13778        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13779        window: &mut Window,
13780        cx: &mut App,
13781    ) {
13782        let Some(project) = self.project.as_ref() else {
13783            return;
13784        };
13785        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13786            return;
13787        };
13788        let Some(diff) = self.buffer.read(cx).diff_for(buffer_id) else {
13789            return;
13790        };
13791        let buffer_snapshot = buffer.read(cx).snapshot();
13792        let file_exists = buffer_snapshot
13793            .file()
13794            .is_some_and(|file| file.disk_state().exists());
13795        let Some((repo, path)) = project
13796            .read(cx)
13797            .repository_and_path_for_buffer_id(buffer_id, cx)
13798        else {
13799            log::debug!("no git repo for buffer id");
13800            return;
13801        };
13802
13803        let new_index_text = diff.update(cx, |diff, cx| {
13804            diff.stage_or_unstage_hunks(
13805                stage,
13806                &hunks
13807                    .map(|hunk| buffer_diff::DiffHunk {
13808                        buffer_range: hunk.buffer_range,
13809                        diff_base_byte_range: hunk.diff_base_byte_range,
13810                        secondary_status: hunk.secondary_status,
13811                        range: Point::zero()..Point::zero(), // unused
13812                    })
13813                    .collect::<Vec<_>>(),
13814                &buffer_snapshot,
13815                file_exists,
13816                cx,
13817            )
13818        });
13819
13820        if file_exists {
13821            let buffer_store = project.read(cx).buffer_store().clone();
13822            buffer_store
13823                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13824                .detach_and_log_err(cx);
13825        }
13826
13827        let recv = repo
13828            .read(cx)
13829            .set_index_text(&path, new_index_text.map(|rope| rope.to_string()));
13830
13831        cx.background_spawn(async move { recv.await? })
13832            .detach_and_notify_err(window, cx);
13833    }
13834
13835    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13836        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13837        self.buffer
13838            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13839    }
13840
13841    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13842        self.buffer.update(cx, |buffer, cx| {
13843            let ranges = vec![Anchor::min()..Anchor::max()];
13844            if !buffer.all_diff_hunks_expanded()
13845                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13846            {
13847                buffer.collapse_diff_hunks(ranges, cx);
13848                true
13849            } else {
13850                false
13851            }
13852        })
13853    }
13854
13855    fn toggle_diff_hunks_in_ranges(
13856        &mut self,
13857        ranges: Vec<Range<Anchor>>,
13858        cx: &mut Context<'_, Editor>,
13859    ) {
13860        self.buffer.update(cx, |buffer, cx| {
13861            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13862            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13863        })
13864    }
13865
13866    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13867        self.buffer.update(cx, |buffer, cx| {
13868            let snapshot = buffer.snapshot(cx);
13869            let excerpt_id = range.end.excerpt_id;
13870            let point_range = range.to_point(&snapshot);
13871            let expand = !buffer.single_hunk_is_expanded(range, cx);
13872            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13873        })
13874    }
13875
13876    pub(crate) fn apply_all_diff_hunks(
13877        &mut self,
13878        _: &ApplyAllDiffHunks,
13879        window: &mut Window,
13880        cx: &mut Context<Self>,
13881    ) {
13882        let buffers = self.buffer.read(cx).all_buffers();
13883        for branch_buffer in buffers {
13884            branch_buffer.update(cx, |branch_buffer, cx| {
13885                branch_buffer.merge_into_base(Vec::new(), cx);
13886            });
13887        }
13888
13889        if let Some(project) = self.project.clone() {
13890            self.save(true, project, window, cx).detach_and_log_err(cx);
13891        }
13892    }
13893
13894    pub(crate) fn apply_selected_diff_hunks(
13895        &mut self,
13896        _: &ApplyDiffHunk,
13897        window: &mut Window,
13898        cx: &mut Context<Self>,
13899    ) {
13900        let snapshot = self.snapshot(window, cx);
13901        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13902        let mut ranges_by_buffer = HashMap::default();
13903        self.transact(window, cx, |editor, _window, cx| {
13904            for hunk in hunks {
13905                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13906                    ranges_by_buffer
13907                        .entry(buffer.clone())
13908                        .or_insert_with(Vec::new)
13909                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13910                }
13911            }
13912
13913            for (buffer, ranges) in ranges_by_buffer {
13914                buffer.update(cx, |buffer, cx| {
13915                    buffer.merge_into_base(ranges, cx);
13916                });
13917            }
13918        });
13919
13920        if let Some(project) = self.project.clone() {
13921            self.save(true, project, window, cx).detach_and_log_err(cx);
13922        }
13923    }
13924
13925    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13926        if hovered != self.gutter_hovered {
13927            self.gutter_hovered = hovered;
13928            cx.notify();
13929        }
13930    }
13931
13932    pub fn insert_blocks(
13933        &mut self,
13934        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13935        autoscroll: Option<Autoscroll>,
13936        cx: &mut Context<Self>,
13937    ) -> Vec<CustomBlockId> {
13938        let blocks = self
13939            .display_map
13940            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13941        if let Some(autoscroll) = autoscroll {
13942            self.request_autoscroll(autoscroll, cx);
13943        }
13944        cx.notify();
13945        blocks
13946    }
13947
13948    pub fn resize_blocks(
13949        &mut self,
13950        heights: HashMap<CustomBlockId, u32>,
13951        autoscroll: Option<Autoscroll>,
13952        cx: &mut Context<Self>,
13953    ) {
13954        self.display_map
13955            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13956        if let Some(autoscroll) = autoscroll {
13957            self.request_autoscroll(autoscroll, cx);
13958        }
13959        cx.notify();
13960    }
13961
13962    pub fn replace_blocks(
13963        &mut self,
13964        renderers: HashMap<CustomBlockId, RenderBlock>,
13965        autoscroll: Option<Autoscroll>,
13966        cx: &mut Context<Self>,
13967    ) {
13968        self.display_map
13969            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13970        if let Some(autoscroll) = autoscroll {
13971            self.request_autoscroll(autoscroll, cx);
13972        }
13973        cx.notify();
13974    }
13975
13976    pub fn remove_blocks(
13977        &mut self,
13978        block_ids: HashSet<CustomBlockId>,
13979        autoscroll: Option<Autoscroll>,
13980        cx: &mut Context<Self>,
13981    ) {
13982        self.display_map.update(cx, |display_map, cx| {
13983            display_map.remove_blocks(block_ids, cx)
13984        });
13985        if let Some(autoscroll) = autoscroll {
13986            self.request_autoscroll(autoscroll, cx);
13987        }
13988        cx.notify();
13989    }
13990
13991    pub fn row_for_block(
13992        &self,
13993        block_id: CustomBlockId,
13994        cx: &mut Context<Self>,
13995    ) -> Option<DisplayRow> {
13996        self.display_map
13997            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13998    }
13999
14000    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14001        self.focused_block = Some(focused_block);
14002    }
14003
14004    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14005        self.focused_block.take()
14006    }
14007
14008    pub fn insert_creases(
14009        &mut self,
14010        creases: impl IntoIterator<Item = Crease<Anchor>>,
14011        cx: &mut Context<Self>,
14012    ) -> Vec<CreaseId> {
14013        self.display_map
14014            .update(cx, |map, cx| map.insert_creases(creases, cx))
14015    }
14016
14017    pub fn remove_creases(
14018        &mut self,
14019        ids: impl IntoIterator<Item = CreaseId>,
14020        cx: &mut Context<Self>,
14021    ) {
14022        self.display_map
14023            .update(cx, |map, cx| map.remove_creases(ids, cx));
14024    }
14025
14026    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14027        self.display_map
14028            .update(cx, |map, cx| map.snapshot(cx))
14029            .longest_row()
14030    }
14031
14032    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14033        self.display_map
14034            .update(cx, |map, cx| map.snapshot(cx))
14035            .max_point()
14036    }
14037
14038    pub fn text(&self, cx: &App) -> String {
14039        self.buffer.read(cx).read(cx).text()
14040    }
14041
14042    pub fn is_empty(&self, cx: &App) -> bool {
14043        self.buffer.read(cx).read(cx).is_empty()
14044    }
14045
14046    pub fn text_option(&self, cx: &App) -> Option<String> {
14047        let text = self.text(cx);
14048        let text = text.trim();
14049
14050        if text.is_empty() {
14051            return None;
14052        }
14053
14054        Some(text.to_string())
14055    }
14056
14057    pub fn set_text(
14058        &mut self,
14059        text: impl Into<Arc<str>>,
14060        window: &mut Window,
14061        cx: &mut Context<Self>,
14062    ) {
14063        self.transact(window, cx, |this, _, cx| {
14064            this.buffer
14065                .read(cx)
14066                .as_singleton()
14067                .expect("you can only call set_text on editors for singleton buffers")
14068                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14069        });
14070    }
14071
14072    pub fn display_text(&self, cx: &mut App) -> String {
14073        self.display_map
14074            .update(cx, |map, cx| map.snapshot(cx))
14075            .text()
14076    }
14077
14078    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14079        let mut wrap_guides = smallvec::smallvec![];
14080
14081        if self.show_wrap_guides == Some(false) {
14082            return wrap_guides;
14083        }
14084
14085        let settings = self.buffer.read(cx).settings_at(0, cx);
14086        if settings.show_wrap_guides {
14087            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
14088                wrap_guides.push((soft_wrap as usize, true));
14089            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
14090                wrap_guides.push((soft_wrap as usize, true));
14091            }
14092            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14093        }
14094
14095        wrap_guides
14096    }
14097
14098    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14099        let settings = self.buffer.read(cx).settings_at(0, cx);
14100        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14101        match mode {
14102            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14103                SoftWrap::None
14104            }
14105            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14106            language_settings::SoftWrap::PreferredLineLength => {
14107                SoftWrap::Column(settings.preferred_line_length)
14108            }
14109            language_settings::SoftWrap::Bounded => {
14110                SoftWrap::Bounded(settings.preferred_line_length)
14111            }
14112        }
14113    }
14114
14115    pub fn set_soft_wrap_mode(
14116        &mut self,
14117        mode: language_settings::SoftWrap,
14118
14119        cx: &mut Context<Self>,
14120    ) {
14121        self.soft_wrap_mode_override = Some(mode);
14122        cx.notify();
14123    }
14124
14125    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14126        self.text_style_refinement = Some(style);
14127    }
14128
14129    /// called by the Element so we know what style we were most recently rendered with.
14130    pub(crate) fn set_style(
14131        &mut self,
14132        style: EditorStyle,
14133        window: &mut Window,
14134        cx: &mut Context<Self>,
14135    ) {
14136        let rem_size = window.rem_size();
14137        self.display_map.update(cx, |map, cx| {
14138            map.set_font(
14139                style.text.font(),
14140                style.text.font_size.to_pixels(rem_size),
14141                cx,
14142            )
14143        });
14144        self.style = Some(style);
14145    }
14146
14147    pub fn style(&self) -> Option<&EditorStyle> {
14148        self.style.as_ref()
14149    }
14150
14151    // Called by the element. This method is not designed to be called outside of the editor
14152    // element's layout code because it does not notify when rewrapping is computed synchronously.
14153    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14154        self.display_map
14155            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14156    }
14157
14158    pub fn set_soft_wrap(&mut self) {
14159        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14160    }
14161
14162    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14163        if self.soft_wrap_mode_override.is_some() {
14164            self.soft_wrap_mode_override.take();
14165        } else {
14166            let soft_wrap = match self.soft_wrap_mode(cx) {
14167                SoftWrap::GitDiff => return,
14168                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14169                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14170                    language_settings::SoftWrap::None
14171                }
14172            };
14173            self.soft_wrap_mode_override = Some(soft_wrap);
14174        }
14175        cx.notify();
14176    }
14177
14178    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14179        let Some(workspace) = self.workspace() else {
14180            return;
14181        };
14182        let fs = workspace.read(cx).app_state().fs.clone();
14183        let current_show = TabBarSettings::get_global(cx).show;
14184        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14185            setting.show = Some(!current_show);
14186        });
14187    }
14188
14189    pub fn toggle_indent_guides(
14190        &mut self,
14191        _: &ToggleIndentGuides,
14192        _: &mut Window,
14193        cx: &mut Context<Self>,
14194    ) {
14195        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14196            self.buffer
14197                .read(cx)
14198                .settings_at(0, cx)
14199                .indent_guides
14200                .enabled
14201        });
14202        self.show_indent_guides = Some(!currently_enabled);
14203        cx.notify();
14204    }
14205
14206    fn should_show_indent_guides(&self) -> Option<bool> {
14207        self.show_indent_guides
14208    }
14209
14210    pub fn toggle_line_numbers(
14211        &mut self,
14212        _: &ToggleLineNumbers,
14213        _: &mut Window,
14214        cx: &mut Context<Self>,
14215    ) {
14216        let mut editor_settings = EditorSettings::get_global(cx).clone();
14217        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14218        EditorSettings::override_global(editor_settings, cx);
14219    }
14220
14221    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14222        self.use_relative_line_numbers
14223            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14224    }
14225
14226    pub fn toggle_relative_line_numbers(
14227        &mut self,
14228        _: &ToggleRelativeLineNumbers,
14229        _: &mut Window,
14230        cx: &mut Context<Self>,
14231    ) {
14232        let is_relative = self.should_use_relative_line_numbers(cx);
14233        self.set_relative_line_number(Some(!is_relative), cx)
14234    }
14235
14236    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14237        self.use_relative_line_numbers = is_relative;
14238        cx.notify();
14239    }
14240
14241    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14242        self.show_gutter = show_gutter;
14243        cx.notify();
14244    }
14245
14246    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14247        self.show_scrollbars = show_scrollbars;
14248        cx.notify();
14249    }
14250
14251    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14252        self.show_line_numbers = Some(show_line_numbers);
14253        cx.notify();
14254    }
14255
14256    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14257        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14258        cx.notify();
14259    }
14260
14261    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14262        self.show_code_actions = Some(show_code_actions);
14263        cx.notify();
14264    }
14265
14266    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14267        self.show_runnables = Some(show_runnables);
14268        cx.notify();
14269    }
14270
14271    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14272        if self.display_map.read(cx).masked != masked {
14273            self.display_map.update(cx, |map, _| map.masked = masked);
14274        }
14275        cx.notify()
14276    }
14277
14278    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14279        self.show_wrap_guides = Some(show_wrap_guides);
14280        cx.notify();
14281    }
14282
14283    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14284        self.show_indent_guides = Some(show_indent_guides);
14285        cx.notify();
14286    }
14287
14288    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14289        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14290            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14291                if let Some(dir) = file.abs_path(cx).parent() {
14292                    return Some(dir.to_owned());
14293                }
14294            }
14295
14296            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14297                return Some(project_path.path.to_path_buf());
14298            }
14299        }
14300
14301        None
14302    }
14303
14304    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14305        self.active_excerpt(cx)?
14306            .1
14307            .read(cx)
14308            .file()
14309            .and_then(|f| f.as_local())
14310    }
14311
14312    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14313        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14314            let buffer = buffer.read(cx);
14315            if let Some(project_path) = buffer.project_path(cx) {
14316                let project = self.project.as_ref()?.read(cx);
14317                project.absolute_path(&project_path, cx)
14318            } else {
14319                buffer
14320                    .file()
14321                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14322            }
14323        })
14324    }
14325
14326    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14327        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14328            let project_path = buffer.read(cx).project_path(cx)?;
14329            let project = self.project.as_ref()?.read(cx);
14330            let entry = project.entry_for_path(&project_path, cx)?;
14331            let path = entry.path.to_path_buf();
14332            Some(path)
14333        })
14334    }
14335
14336    pub fn reveal_in_finder(
14337        &mut self,
14338        _: &RevealInFileManager,
14339        _window: &mut Window,
14340        cx: &mut Context<Self>,
14341    ) {
14342        if let Some(target) = self.target_file(cx) {
14343            cx.reveal_path(&target.abs_path(cx));
14344        }
14345    }
14346
14347    pub fn copy_path(
14348        &mut self,
14349        _: &zed_actions::workspace::CopyPath,
14350        _window: &mut Window,
14351        cx: &mut Context<Self>,
14352    ) {
14353        if let Some(path) = self.target_file_abs_path(cx) {
14354            if let Some(path) = path.to_str() {
14355                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14356            }
14357        }
14358    }
14359
14360    pub fn copy_relative_path(
14361        &mut self,
14362        _: &zed_actions::workspace::CopyRelativePath,
14363        _window: &mut Window,
14364        cx: &mut Context<Self>,
14365    ) {
14366        if let Some(path) = self.target_file_path(cx) {
14367            if let Some(path) = path.to_str() {
14368                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14369            }
14370        }
14371    }
14372
14373    pub fn copy_file_name_without_extension(
14374        &mut self,
14375        _: &CopyFileNameWithoutExtension,
14376        _: &mut Window,
14377        cx: &mut Context<Self>,
14378    ) {
14379        if let Some(file) = self.target_file(cx) {
14380            if let Some(file_stem) = file.path().file_stem() {
14381                if let Some(name) = file_stem.to_str() {
14382                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14383                }
14384            }
14385        }
14386    }
14387
14388    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14389        if let Some(file) = self.target_file(cx) {
14390            if let Some(file_name) = file.path().file_name() {
14391                if let Some(name) = file_name.to_str() {
14392                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14393                }
14394            }
14395        }
14396    }
14397
14398    pub fn toggle_git_blame(
14399        &mut self,
14400        _: &ToggleGitBlame,
14401        window: &mut Window,
14402        cx: &mut Context<Self>,
14403    ) {
14404        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14405
14406        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14407            self.start_git_blame(true, window, cx);
14408        }
14409
14410        cx.notify();
14411    }
14412
14413    pub fn toggle_git_blame_inline(
14414        &mut self,
14415        _: &ToggleGitBlameInline,
14416        window: &mut Window,
14417        cx: &mut Context<Self>,
14418    ) {
14419        self.toggle_git_blame_inline_internal(true, window, cx);
14420        cx.notify();
14421    }
14422
14423    pub fn git_blame_inline_enabled(&self) -> bool {
14424        self.git_blame_inline_enabled
14425    }
14426
14427    pub fn toggle_selection_menu(
14428        &mut self,
14429        _: &ToggleSelectionMenu,
14430        _: &mut Window,
14431        cx: &mut Context<Self>,
14432    ) {
14433        self.show_selection_menu = self
14434            .show_selection_menu
14435            .map(|show_selections_menu| !show_selections_menu)
14436            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14437
14438        cx.notify();
14439    }
14440
14441    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14442        self.show_selection_menu
14443            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14444    }
14445
14446    fn start_git_blame(
14447        &mut self,
14448        user_triggered: bool,
14449        window: &mut Window,
14450        cx: &mut Context<Self>,
14451    ) {
14452        if let Some(project) = self.project.as_ref() {
14453            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14454                return;
14455            };
14456
14457            if buffer.read(cx).file().is_none() {
14458                return;
14459            }
14460
14461            let focused = self.focus_handle(cx).contains_focused(window, cx);
14462
14463            let project = project.clone();
14464            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14465            self.blame_subscription =
14466                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14467            self.blame = Some(blame);
14468        }
14469    }
14470
14471    fn toggle_git_blame_inline_internal(
14472        &mut self,
14473        user_triggered: bool,
14474        window: &mut Window,
14475        cx: &mut Context<Self>,
14476    ) {
14477        if self.git_blame_inline_enabled {
14478            self.git_blame_inline_enabled = false;
14479            self.show_git_blame_inline = false;
14480            self.show_git_blame_inline_delay_task.take();
14481        } else {
14482            self.git_blame_inline_enabled = true;
14483            self.start_git_blame_inline(user_triggered, window, cx);
14484        }
14485
14486        cx.notify();
14487    }
14488
14489    fn start_git_blame_inline(
14490        &mut self,
14491        user_triggered: bool,
14492        window: &mut Window,
14493        cx: &mut Context<Self>,
14494    ) {
14495        self.start_git_blame(user_triggered, window, cx);
14496
14497        if ProjectSettings::get_global(cx)
14498            .git
14499            .inline_blame_delay()
14500            .is_some()
14501        {
14502            self.start_inline_blame_timer(window, cx);
14503        } else {
14504            self.show_git_blame_inline = true
14505        }
14506    }
14507
14508    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14509        self.blame.as_ref()
14510    }
14511
14512    pub fn show_git_blame_gutter(&self) -> bool {
14513        self.show_git_blame_gutter
14514    }
14515
14516    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14517        self.show_git_blame_gutter && self.has_blame_entries(cx)
14518    }
14519
14520    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14521        self.show_git_blame_inline
14522            && (self.focus_handle.is_focused(window)
14523                || self
14524                    .git_blame_inline_tooltip
14525                    .as_ref()
14526                    .and_then(|t| t.upgrade())
14527                    .is_some())
14528            && !self.newest_selection_head_on_empty_line(cx)
14529            && self.has_blame_entries(cx)
14530    }
14531
14532    fn has_blame_entries(&self, cx: &App) -> bool {
14533        self.blame()
14534            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14535    }
14536
14537    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14538        let cursor_anchor = self.selections.newest_anchor().head();
14539
14540        let snapshot = self.buffer.read(cx).snapshot(cx);
14541        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14542
14543        snapshot.line_len(buffer_row) == 0
14544    }
14545
14546    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14547        let buffer_and_selection = maybe!({
14548            let selection = self.selections.newest::<Point>(cx);
14549            let selection_range = selection.range();
14550
14551            let multi_buffer = self.buffer().read(cx);
14552            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14553            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14554
14555            let (buffer, range, _) = if selection.reversed {
14556                buffer_ranges.first()
14557            } else {
14558                buffer_ranges.last()
14559            }?;
14560
14561            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14562                ..text::ToPoint::to_point(&range.end, &buffer).row;
14563            Some((
14564                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14565                selection,
14566            ))
14567        });
14568
14569        let Some((buffer, selection)) = buffer_and_selection else {
14570            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14571        };
14572
14573        let Some(project) = self.project.as_ref() else {
14574            return Task::ready(Err(anyhow!("editor does not have project")));
14575        };
14576
14577        project.update(cx, |project, cx| {
14578            project.get_permalink_to_line(&buffer, selection, cx)
14579        })
14580    }
14581
14582    pub fn copy_permalink_to_line(
14583        &mut self,
14584        _: &CopyPermalinkToLine,
14585        window: &mut Window,
14586        cx: &mut Context<Self>,
14587    ) {
14588        let permalink_task = self.get_permalink_to_line(cx);
14589        let workspace = self.workspace();
14590
14591        cx.spawn_in(window, |_, mut cx| async move {
14592            match permalink_task.await {
14593                Ok(permalink) => {
14594                    cx.update(|_, cx| {
14595                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14596                    })
14597                    .ok();
14598                }
14599                Err(err) => {
14600                    let message = format!("Failed to copy permalink: {err}");
14601
14602                    Err::<(), anyhow::Error>(err).log_err();
14603
14604                    if let Some(workspace) = workspace {
14605                        workspace
14606                            .update_in(&mut cx, |workspace, _, cx| {
14607                                struct CopyPermalinkToLine;
14608
14609                                workspace.show_toast(
14610                                    Toast::new(
14611                                        NotificationId::unique::<CopyPermalinkToLine>(),
14612                                        message,
14613                                    ),
14614                                    cx,
14615                                )
14616                            })
14617                            .ok();
14618                    }
14619                }
14620            }
14621        })
14622        .detach();
14623    }
14624
14625    pub fn copy_file_location(
14626        &mut self,
14627        _: &CopyFileLocation,
14628        _: &mut Window,
14629        cx: &mut Context<Self>,
14630    ) {
14631        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14632        if let Some(file) = self.target_file(cx) {
14633            if let Some(path) = file.path().to_str() {
14634                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14635            }
14636        }
14637    }
14638
14639    pub fn open_permalink_to_line(
14640        &mut self,
14641        _: &OpenPermalinkToLine,
14642        window: &mut Window,
14643        cx: &mut Context<Self>,
14644    ) {
14645        let permalink_task = self.get_permalink_to_line(cx);
14646        let workspace = self.workspace();
14647
14648        cx.spawn_in(window, |_, mut cx| async move {
14649            match permalink_task.await {
14650                Ok(permalink) => {
14651                    cx.update(|_, cx| {
14652                        cx.open_url(permalink.as_ref());
14653                    })
14654                    .ok();
14655                }
14656                Err(err) => {
14657                    let message = format!("Failed to open permalink: {err}");
14658
14659                    Err::<(), anyhow::Error>(err).log_err();
14660
14661                    if let Some(workspace) = workspace {
14662                        workspace
14663                            .update(&mut cx, |workspace, cx| {
14664                                struct OpenPermalinkToLine;
14665
14666                                workspace.show_toast(
14667                                    Toast::new(
14668                                        NotificationId::unique::<OpenPermalinkToLine>(),
14669                                        message,
14670                                    ),
14671                                    cx,
14672                                )
14673                            })
14674                            .ok();
14675                    }
14676                }
14677            }
14678        })
14679        .detach();
14680    }
14681
14682    pub fn insert_uuid_v4(
14683        &mut self,
14684        _: &InsertUuidV4,
14685        window: &mut Window,
14686        cx: &mut Context<Self>,
14687    ) {
14688        self.insert_uuid(UuidVersion::V4, window, cx);
14689    }
14690
14691    pub fn insert_uuid_v7(
14692        &mut self,
14693        _: &InsertUuidV7,
14694        window: &mut Window,
14695        cx: &mut Context<Self>,
14696    ) {
14697        self.insert_uuid(UuidVersion::V7, window, cx);
14698    }
14699
14700    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14701        self.transact(window, cx, |this, window, cx| {
14702            let edits = this
14703                .selections
14704                .all::<Point>(cx)
14705                .into_iter()
14706                .map(|selection| {
14707                    let uuid = match version {
14708                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14709                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14710                    };
14711
14712                    (selection.range(), uuid.to_string())
14713                });
14714            this.edit(edits, cx);
14715            this.refresh_inline_completion(true, false, window, cx);
14716        });
14717    }
14718
14719    pub fn open_selections_in_multibuffer(
14720        &mut self,
14721        _: &OpenSelectionsInMultibuffer,
14722        window: &mut Window,
14723        cx: &mut Context<Self>,
14724    ) {
14725        let multibuffer = self.buffer.read(cx);
14726
14727        let Some(buffer) = multibuffer.as_singleton() else {
14728            return;
14729        };
14730
14731        let Some(workspace) = self.workspace() else {
14732            return;
14733        };
14734
14735        let locations = self
14736            .selections
14737            .disjoint_anchors()
14738            .iter()
14739            .map(|range| Location {
14740                buffer: buffer.clone(),
14741                range: range.start.text_anchor..range.end.text_anchor,
14742            })
14743            .collect::<Vec<_>>();
14744
14745        let title = multibuffer.title(cx).to_string();
14746
14747        cx.spawn_in(window, |_, mut cx| async move {
14748            workspace.update_in(&mut cx, |workspace, window, cx| {
14749                Self::open_locations_in_multibuffer(
14750                    workspace,
14751                    locations,
14752                    format!("Selections for '{title}'"),
14753                    false,
14754                    MultibufferSelectionMode::All,
14755                    window,
14756                    cx,
14757                );
14758            })
14759        })
14760        .detach();
14761    }
14762
14763    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14764    /// last highlight added will be used.
14765    ///
14766    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14767    pub fn highlight_rows<T: 'static>(
14768        &mut self,
14769        range: Range<Anchor>,
14770        color: Hsla,
14771        should_autoscroll: bool,
14772        cx: &mut Context<Self>,
14773    ) {
14774        let snapshot = self.buffer().read(cx).snapshot(cx);
14775        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14776        let ix = row_highlights.binary_search_by(|highlight| {
14777            Ordering::Equal
14778                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14779                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14780        });
14781
14782        if let Err(mut ix) = ix {
14783            let index = post_inc(&mut self.highlight_order);
14784
14785            // If this range intersects with the preceding highlight, then merge it with
14786            // the preceding highlight. Otherwise insert a new highlight.
14787            let mut merged = false;
14788            if ix > 0 {
14789                let prev_highlight = &mut row_highlights[ix - 1];
14790                if prev_highlight
14791                    .range
14792                    .end
14793                    .cmp(&range.start, &snapshot)
14794                    .is_ge()
14795                {
14796                    ix -= 1;
14797                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14798                        prev_highlight.range.end = range.end;
14799                    }
14800                    merged = true;
14801                    prev_highlight.index = index;
14802                    prev_highlight.color = color;
14803                    prev_highlight.should_autoscroll = should_autoscroll;
14804                }
14805            }
14806
14807            if !merged {
14808                row_highlights.insert(
14809                    ix,
14810                    RowHighlight {
14811                        range: range.clone(),
14812                        index,
14813                        color,
14814                        should_autoscroll,
14815                    },
14816                );
14817            }
14818
14819            // If any of the following highlights intersect with this one, merge them.
14820            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14821                let highlight = &row_highlights[ix];
14822                if next_highlight
14823                    .range
14824                    .start
14825                    .cmp(&highlight.range.end, &snapshot)
14826                    .is_le()
14827                {
14828                    if next_highlight
14829                        .range
14830                        .end
14831                        .cmp(&highlight.range.end, &snapshot)
14832                        .is_gt()
14833                    {
14834                        row_highlights[ix].range.end = next_highlight.range.end;
14835                    }
14836                    row_highlights.remove(ix + 1);
14837                } else {
14838                    break;
14839                }
14840            }
14841        }
14842    }
14843
14844    /// Remove any highlighted row ranges of the given type that intersect the
14845    /// given ranges.
14846    pub fn remove_highlighted_rows<T: 'static>(
14847        &mut self,
14848        ranges_to_remove: Vec<Range<Anchor>>,
14849        cx: &mut Context<Self>,
14850    ) {
14851        let snapshot = self.buffer().read(cx).snapshot(cx);
14852        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14853        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14854        row_highlights.retain(|highlight| {
14855            while let Some(range_to_remove) = ranges_to_remove.peek() {
14856                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14857                    Ordering::Less | Ordering::Equal => {
14858                        ranges_to_remove.next();
14859                    }
14860                    Ordering::Greater => {
14861                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14862                            Ordering::Less | Ordering::Equal => {
14863                                return false;
14864                            }
14865                            Ordering::Greater => break,
14866                        }
14867                    }
14868                }
14869            }
14870
14871            true
14872        })
14873    }
14874
14875    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14876    pub fn clear_row_highlights<T: 'static>(&mut self) {
14877        self.highlighted_rows.remove(&TypeId::of::<T>());
14878    }
14879
14880    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14881    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14882        self.highlighted_rows
14883            .get(&TypeId::of::<T>())
14884            .map_or(&[] as &[_], |vec| vec.as_slice())
14885            .iter()
14886            .map(|highlight| (highlight.range.clone(), highlight.color))
14887    }
14888
14889    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14890    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14891    /// Allows to ignore certain kinds of highlights.
14892    pub fn highlighted_display_rows(
14893        &self,
14894        window: &mut Window,
14895        cx: &mut App,
14896    ) -> BTreeMap<DisplayRow, Background> {
14897        let snapshot = self.snapshot(window, cx);
14898        let mut used_highlight_orders = HashMap::default();
14899        self.highlighted_rows
14900            .iter()
14901            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14902            .fold(
14903                BTreeMap::<DisplayRow, Background>::new(),
14904                |mut unique_rows, highlight| {
14905                    let start = highlight.range.start.to_display_point(&snapshot);
14906                    let end = highlight.range.end.to_display_point(&snapshot);
14907                    let start_row = start.row().0;
14908                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14909                        && end.column() == 0
14910                    {
14911                        end.row().0.saturating_sub(1)
14912                    } else {
14913                        end.row().0
14914                    };
14915                    for row in start_row..=end_row {
14916                        let used_index =
14917                            used_highlight_orders.entry(row).or_insert(highlight.index);
14918                        if highlight.index >= *used_index {
14919                            *used_index = highlight.index;
14920                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14921                        }
14922                    }
14923                    unique_rows
14924                },
14925            )
14926    }
14927
14928    pub fn highlighted_display_row_for_autoscroll(
14929        &self,
14930        snapshot: &DisplaySnapshot,
14931    ) -> Option<DisplayRow> {
14932        self.highlighted_rows
14933            .values()
14934            .flat_map(|highlighted_rows| highlighted_rows.iter())
14935            .filter_map(|highlight| {
14936                if highlight.should_autoscroll {
14937                    Some(highlight.range.start.to_display_point(snapshot).row())
14938                } else {
14939                    None
14940                }
14941            })
14942            .min()
14943    }
14944
14945    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14946        self.highlight_background::<SearchWithinRange>(
14947            ranges,
14948            |colors| colors.editor_document_highlight_read_background,
14949            cx,
14950        )
14951    }
14952
14953    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14954        self.breadcrumb_header = Some(new_header);
14955    }
14956
14957    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14958        self.clear_background_highlights::<SearchWithinRange>(cx);
14959    }
14960
14961    pub fn highlight_background<T: 'static>(
14962        &mut self,
14963        ranges: &[Range<Anchor>],
14964        color_fetcher: fn(&ThemeColors) -> Hsla,
14965        cx: &mut Context<Self>,
14966    ) {
14967        self.background_highlights
14968            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14969        self.scrollbar_marker_state.dirty = true;
14970        cx.notify();
14971    }
14972
14973    pub fn clear_background_highlights<T: 'static>(
14974        &mut self,
14975        cx: &mut Context<Self>,
14976    ) -> Option<BackgroundHighlight> {
14977        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14978        if !text_highlights.1.is_empty() {
14979            self.scrollbar_marker_state.dirty = true;
14980            cx.notify();
14981        }
14982        Some(text_highlights)
14983    }
14984
14985    pub fn highlight_gutter<T: 'static>(
14986        &mut self,
14987        ranges: &[Range<Anchor>],
14988        color_fetcher: fn(&App) -> Hsla,
14989        cx: &mut Context<Self>,
14990    ) {
14991        self.gutter_highlights
14992            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14993        cx.notify();
14994    }
14995
14996    pub fn clear_gutter_highlights<T: 'static>(
14997        &mut self,
14998        cx: &mut Context<Self>,
14999    ) -> Option<GutterHighlight> {
15000        cx.notify();
15001        self.gutter_highlights.remove(&TypeId::of::<T>())
15002    }
15003
15004    #[cfg(feature = "test-support")]
15005    pub fn all_text_background_highlights(
15006        &self,
15007        window: &mut Window,
15008        cx: &mut Context<Self>,
15009    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15010        let snapshot = self.snapshot(window, cx);
15011        let buffer = &snapshot.buffer_snapshot;
15012        let start = buffer.anchor_before(0);
15013        let end = buffer.anchor_after(buffer.len());
15014        let theme = cx.theme().colors();
15015        self.background_highlights_in_range(start..end, &snapshot, theme)
15016    }
15017
15018    #[cfg(feature = "test-support")]
15019    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15020        let snapshot = self.buffer().read(cx).snapshot(cx);
15021
15022        let highlights = self
15023            .background_highlights
15024            .get(&TypeId::of::<items::BufferSearchHighlights>());
15025
15026        if let Some((_color, ranges)) = highlights {
15027            ranges
15028                .iter()
15029                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15030                .collect_vec()
15031        } else {
15032            vec![]
15033        }
15034    }
15035
15036    fn document_highlights_for_position<'a>(
15037        &'a self,
15038        position: Anchor,
15039        buffer: &'a MultiBufferSnapshot,
15040    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15041        let read_highlights = self
15042            .background_highlights
15043            .get(&TypeId::of::<DocumentHighlightRead>())
15044            .map(|h| &h.1);
15045        let write_highlights = self
15046            .background_highlights
15047            .get(&TypeId::of::<DocumentHighlightWrite>())
15048            .map(|h| &h.1);
15049        let left_position = position.bias_left(buffer);
15050        let right_position = position.bias_right(buffer);
15051        read_highlights
15052            .into_iter()
15053            .chain(write_highlights)
15054            .flat_map(move |ranges| {
15055                let start_ix = match ranges.binary_search_by(|probe| {
15056                    let cmp = probe.end.cmp(&left_position, buffer);
15057                    if cmp.is_ge() {
15058                        Ordering::Greater
15059                    } else {
15060                        Ordering::Less
15061                    }
15062                }) {
15063                    Ok(i) | Err(i) => i,
15064                };
15065
15066                ranges[start_ix..]
15067                    .iter()
15068                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15069            })
15070    }
15071
15072    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15073        self.background_highlights
15074            .get(&TypeId::of::<T>())
15075            .map_or(false, |(_, highlights)| !highlights.is_empty())
15076    }
15077
15078    pub fn background_highlights_in_range(
15079        &self,
15080        search_range: Range<Anchor>,
15081        display_snapshot: &DisplaySnapshot,
15082        theme: &ThemeColors,
15083    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15084        let mut results = Vec::new();
15085        for (color_fetcher, ranges) in self.background_highlights.values() {
15086            let color = color_fetcher(theme);
15087            let start_ix = match ranges.binary_search_by(|probe| {
15088                let cmp = probe
15089                    .end
15090                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15091                if cmp.is_gt() {
15092                    Ordering::Greater
15093                } else {
15094                    Ordering::Less
15095                }
15096            }) {
15097                Ok(i) | Err(i) => i,
15098            };
15099            for range in &ranges[start_ix..] {
15100                if range
15101                    .start
15102                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15103                    .is_ge()
15104                {
15105                    break;
15106                }
15107
15108                let start = range.start.to_display_point(display_snapshot);
15109                let end = range.end.to_display_point(display_snapshot);
15110                results.push((start..end, color))
15111            }
15112        }
15113        results
15114    }
15115
15116    pub fn background_highlight_row_ranges<T: 'static>(
15117        &self,
15118        search_range: Range<Anchor>,
15119        display_snapshot: &DisplaySnapshot,
15120        count: usize,
15121    ) -> Vec<RangeInclusive<DisplayPoint>> {
15122        let mut results = Vec::new();
15123        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15124            return vec![];
15125        };
15126
15127        let start_ix = match ranges.binary_search_by(|probe| {
15128            let cmp = probe
15129                .end
15130                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15131            if cmp.is_gt() {
15132                Ordering::Greater
15133            } else {
15134                Ordering::Less
15135            }
15136        }) {
15137            Ok(i) | Err(i) => i,
15138        };
15139        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15140            if let (Some(start_display), Some(end_display)) = (start, end) {
15141                results.push(
15142                    start_display.to_display_point(display_snapshot)
15143                        ..=end_display.to_display_point(display_snapshot),
15144                );
15145            }
15146        };
15147        let mut start_row: Option<Point> = None;
15148        let mut end_row: Option<Point> = None;
15149        if ranges.len() > count {
15150            return Vec::new();
15151        }
15152        for range in &ranges[start_ix..] {
15153            if range
15154                .start
15155                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15156                .is_ge()
15157            {
15158                break;
15159            }
15160            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15161            if let Some(current_row) = &end_row {
15162                if end.row == current_row.row {
15163                    continue;
15164                }
15165            }
15166            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15167            if start_row.is_none() {
15168                assert_eq!(end_row, None);
15169                start_row = Some(start);
15170                end_row = Some(end);
15171                continue;
15172            }
15173            if let Some(current_end) = end_row.as_mut() {
15174                if start.row > current_end.row + 1 {
15175                    push_region(start_row, end_row);
15176                    start_row = Some(start);
15177                    end_row = Some(end);
15178                } else {
15179                    // Merge two hunks.
15180                    *current_end = end;
15181                }
15182            } else {
15183                unreachable!();
15184            }
15185        }
15186        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15187        push_region(start_row, end_row);
15188        results
15189    }
15190
15191    pub fn gutter_highlights_in_range(
15192        &self,
15193        search_range: Range<Anchor>,
15194        display_snapshot: &DisplaySnapshot,
15195        cx: &App,
15196    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15197        let mut results = Vec::new();
15198        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15199            let color = color_fetcher(cx);
15200            let start_ix = match ranges.binary_search_by(|probe| {
15201                let cmp = probe
15202                    .end
15203                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15204                if cmp.is_gt() {
15205                    Ordering::Greater
15206                } else {
15207                    Ordering::Less
15208                }
15209            }) {
15210                Ok(i) | Err(i) => i,
15211            };
15212            for range in &ranges[start_ix..] {
15213                if range
15214                    .start
15215                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15216                    .is_ge()
15217                {
15218                    break;
15219                }
15220
15221                let start = range.start.to_display_point(display_snapshot);
15222                let end = range.end.to_display_point(display_snapshot);
15223                results.push((start..end, color))
15224            }
15225        }
15226        results
15227    }
15228
15229    /// Get the text ranges corresponding to the redaction query
15230    pub fn redacted_ranges(
15231        &self,
15232        search_range: Range<Anchor>,
15233        display_snapshot: &DisplaySnapshot,
15234        cx: &App,
15235    ) -> Vec<Range<DisplayPoint>> {
15236        display_snapshot
15237            .buffer_snapshot
15238            .redacted_ranges(search_range, |file| {
15239                if let Some(file) = file {
15240                    file.is_private()
15241                        && EditorSettings::get(
15242                            Some(SettingsLocation {
15243                                worktree_id: file.worktree_id(cx),
15244                                path: file.path().as_ref(),
15245                            }),
15246                            cx,
15247                        )
15248                        .redact_private_values
15249                } else {
15250                    false
15251                }
15252            })
15253            .map(|range| {
15254                range.start.to_display_point(display_snapshot)
15255                    ..range.end.to_display_point(display_snapshot)
15256            })
15257            .collect()
15258    }
15259
15260    pub fn highlight_text<T: 'static>(
15261        &mut self,
15262        ranges: Vec<Range<Anchor>>,
15263        style: HighlightStyle,
15264        cx: &mut Context<Self>,
15265    ) {
15266        self.display_map.update(cx, |map, _| {
15267            map.highlight_text(TypeId::of::<T>(), ranges, style)
15268        });
15269        cx.notify();
15270    }
15271
15272    pub(crate) fn highlight_inlays<T: 'static>(
15273        &mut self,
15274        highlights: Vec<InlayHighlight>,
15275        style: HighlightStyle,
15276        cx: &mut Context<Self>,
15277    ) {
15278        self.display_map.update(cx, |map, _| {
15279            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15280        });
15281        cx.notify();
15282    }
15283
15284    pub fn text_highlights<'a, T: 'static>(
15285        &'a self,
15286        cx: &'a App,
15287    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15288        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15289    }
15290
15291    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15292        let cleared = self
15293            .display_map
15294            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15295        if cleared {
15296            cx.notify();
15297        }
15298    }
15299
15300    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15301        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15302            && self.focus_handle.is_focused(window)
15303    }
15304
15305    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15306        self.show_cursor_when_unfocused = is_enabled;
15307        cx.notify();
15308    }
15309
15310    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15311        cx.notify();
15312    }
15313
15314    fn on_buffer_event(
15315        &mut self,
15316        multibuffer: &Entity<MultiBuffer>,
15317        event: &multi_buffer::Event,
15318        window: &mut Window,
15319        cx: &mut Context<Self>,
15320    ) {
15321        match event {
15322            multi_buffer::Event::Edited {
15323                singleton_buffer_edited,
15324                edited_buffer: buffer_edited,
15325            } => {
15326                self.scrollbar_marker_state.dirty = true;
15327                self.active_indent_guides_state.dirty = true;
15328                self.refresh_active_diagnostics(cx);
15329                self.refresh_code_actions(window, cx);
15330                if self.has_active_inline_completion() {
15331                    self.update_visible_inline_completion(window, cx);
15332                }
15333                if let Some(buffer) = buffer_edited {
15334                    let buffer_id = buffer.read(cx).remote_id();
15335                    if !self.registered_buffers.contains_key(&buffer_id) {
15336                        if let Some(project) = self.project.as_ref() {
15337                            project.update(cx, |project, cx| {
15338                                self.registered_buffers.insert(
15339                                    buffer_id,
15340                                    project.register_buffer_with_language_servers(&buffer, cx),
15341                                );
15342                            })
15343                        }
15344                    }
15345                }
15346                cx.emit(EditorEvent::BufferEdited);
15347                cx.emit(SearchEvent::MatchesInvalidated);
15348                if *singleton_buffer_edited {
15349                    if let Some(project) = &self.project {
15350                        #[allow(clippy::mutable_key_type)]
15351                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15352                            multibuffer
15353                                .all_buffers()
15354                                .into_iter()
15355                                .filter_map(|buffer| {
15356                                    buffer.update(cx, |buffer, cx| {
15357                                        let language = buffer.language()?;
15358                                        let should_discard = project.update(cx, |project, cx| {
15359                                            project.is_local()
15360                                                && !project.has_language_servers_for(buffer, cx)
15361                                        });
15362                                        should_discard.not().then_some(language.clone())
15363                                    })
15364                                })
15365                                .collect::<HashSet<_>>()
15366                        });
15367                        if !languages_affected.is_empty() {
15368                            self.refresh_inlay_hints(
15369                                InlayHintRefreshReason::BufferEdited(languages_affected),
15370                                cx,
15371                            );
15372                        }
15373                    }
15374                }
15375
15376                let Some(project) = &self.project else { return };
15377                let (telemetry, is_via_ssh) = {
15378                    let project = project.read(cx);
15379                    let telemetry = project.client().telemetry().clone();
15380                    let is_via_ssh = project.is_via_ssh();
15381                    (telemetry, is_via_ssh)
15382                };
15383                refresh_linked_ranges(self, window, cx);
15384                telemetry.log_edit_event("editor", is_via_ssh);
15385            }
15386            multi_buffer::Event::ExcerptsAdded {
15387                buffer,
15388                predecessor,
15389                excerpts,
15390            } => {
15391                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15392                let buffer_id = buffer.read(cx).remote_id();
15393                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15394                    if let Some(project) = &self.project {
15395                        get_uncommitted_diff_for_buffer(
15396                            project,
15397                            [buffer.clone()],
15398                            self.buffer.clone(),
15399                            cx,
15400                        )
15401                        .detach();
15402                    }
15403                }
15404                cx.emit(EditorEvent::ExcerptsAdded {
15405                    buffer: buffer.clone(),
15406                    predecessor: *predecessor,
15407                    excerpts: excerpts.clone(),
15408                });
15409                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15410            }
15411            multi_buffer::Event::ExcerptsRemoved { ids } => {
15412                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15413                let buffer = self.buffer.read(cx);
15414                self.registered_buffers
15415                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15416                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15417            }
15418            multi_buffer::Event::ExcerptsEdited {
15419                excerpt_ids,
15420                buffer_ids,
15421            } => {
15422                self.display_map.update(cx, |map, cx| {
15423                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15424                });
15425                cx.emit(EditorEvent::ExcerptsEdited {
15426                    ids: excerpt_ids.clone(),
15427                })
15428            }
15429            multi_buffer::Event::ExcerptsExpanded { ids } => {
15430                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15431                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15432            }
15433            multi_buffer::Event::Reparsed(buffer_id) => {
15434                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15435
15436                cx.emit(EditorEvent::Reparsed(*buffer_id));
15437            }
15438            multi_buffer::Event::DiffHunksToggled => {
15439                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15440            }
15441            multi_buffer::Event::LanguageChanged(buffer_id) => {
15442                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15443                cx.emit(EditorEvent::Reparsed(*buffer_id));
15444                cx.notify();
15445            }
15446            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15447            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15448            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15449                cx.emit(EditorEvent::TitleChanged)
15450            }
15451            // multi_buffer::Event::DiffBaseChanged => {
15452            //     self.scrollbar_marker_state.dirty = true;
15453            //     cx.emit(EditorEvent::DiffBaseChanged);
15454            //     cx.notify();
15455            // }
15456            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15457            multi_buffer::Event::DiagnosticsUpdated => {
15458                self.refresh_active_diagnostics(cx);
15459                self.refresh_inline_diagnostics(true, window, cx);
15460                self.scrollbar_marker_state.dirty = true;
15461                cx.notify();
15462            }
15463            _ => {}
15464        };
15465    }
15466
15467    fn on_display_map_changed(
15468        &mut self,
15469        _: Entity<DisplayMap>,
15470        _: &mut Window,
15471        cx: &mut Context<Self>,
15472    ) {
15473        cx.notify();
15474    }
15475
15476    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15477        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15478        self.update_edit_prediction_settings(cx);
15479        self.refresh_inline_completion(true, false, window, cx);
15480        self.refresh_inlay_hints(
15481            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15482                self.selections.newest_anchor().head(),
15483                &self.buffer.read(cx).snapshot(cx),
15484                cx,
15485            )),
15486            cx,
15487        );
15488
15489        let old_cursor_shape = self.cursor_shape;
15490
15491        {
15492            let editor_settings = EditorSettings::get_global(cx);
15493            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15494            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15495            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15496        }
15497
15498        if old_cursor_shape != self.cursor_shape {
15499            cx.emit(EditorEvent::CursorShapeChanged);
15500        }
15501
15502        let project_settings = ProjectSettings::get_global(cx);
15503        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15504
15505        if self.mode == EditorMode::Full {
15506            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15507            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15508            if self.show_inline_diagnostics != show_inline_diagnostics {
15509                self.show_inline_diagnostics = show_inline_diagnostics;
15510                self.refresh_inline_diagnostics(false, window, cx);
15511            }
15512
15513            if self.git_blame_inline_enabled != inline_blame_enabled {
15514                self.toggle_git_blame_inline_internal(false, window, cx);
15515            }
15516        }
15517
15518        cx.notify();
15519    }
15520
15521    pub fn set_searchable(&mut self, searchable: bool) {
15522        self.searchable = searchable;
15523    }
15524
15525    pub fn searchable(&self) -> bool {
15526        self.searchable
15527    }
15528
15529    fn open_proposed_changes_editor(
15530        &mut self,
15531        _: &OpenProposedChangesEditor,
15532        window: &mut Window,
15533        cx: &mut Context<Self>,
15534    ) {
15535        let Some(workspace) = self.workspace() else {
15536            cx.propagate();
15537            return;
15538        };
15539
15540        let selections = self.selections.all::<usize>(cx);
15541        let multi_buffer = self.buffer.read(cx);
15542        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15543        let mut new_selections_by_buffer = HashMap::default();
15544        for selection in selections {
15545            for (buffer, range, _) in
15546                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15547            {
15548                let mut range = range.to_point(buffer);
15549                range.start.column = 0;
15550                range.end.column = buffer.line_len(range.end.row);
15551                new_selections_by_buffer
15552                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15553                    .or_insert(Vec::new())
15554                    .push(range)
15555            }
15556        }
15557
15558        let proposed_changes_buffers = new_selections_by_buffer
15559            .into_iter()
15560            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15561            .collect::<Vec<_>>();
15562        let proposed_changes_editor = cx.new(|cx| {
15563            ProposedChangesEditor::new(
15564                "Proposed changes",
15565                proposed_changes_buffers,
15566                self.project.clone(),
15567                window,
15568                cx,
15569            )
15570        });
15571
15572        window.defer(cx, move |window, cx| {
15573            workspace.update(cx, |workspace, cx| {
15574                workspace.active_pane().update(cx, |pane, cx| {
15575                    pane.add_item(
15576                        Box::new(proposed_changes_editor),
15577                        true,
15578                        true,
15579                        None,
15580                        window,
15581                        cx,
15582                    );
15583                });
15584            });
15585        });
15586    }
15587
15588    pub fn open_excerpts_in_split(
15589        &mut self,
15590        _: &OpenExcerptsSplit,
15591        window: &mut Window,
15592        cx: &mut Context<Self>,
15593    ) {
15594        self.open_excerpts_common(None, true, window, cx)
15595    }
15596
15597    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15598        self.open_excerpts_common(None, false, window, cx)
15599    }
15600
15601    fn open_excerpts_common(
15602        &mut self,
15603        jump_data: Option<JumpData>,
15604        split: bool,
15605        window: &mut Window,
15606        cx: &mut Context<Self>,
15607    ) {
15608        let Some(workspace) = self.workspace() else {
15609            cx.propagate();
15610            return;
15611        };
15612
15613        if self.buffer.read(cx).is_singleton() {
15614            cx.propagate();
15615            return;
15616        }
15617
15618        let mut new_selections_by_buffer = HashMap::default();
15619        match &jump_data {
15620            Some(JumpData::MultiBufferPoint {
15621                excerpt_id,
15622                position,
15623                anchor,
15624                line_offset_from_top,
15625            }) => {
15626                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15627                if let Some(buffer) = multi_buffer_snapshot
15628                    .buffer_id_for_excerpt(*excerpt_id)
15629                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15630                {
15631                    let buffer_snapshot = buffer.read(cx).snapshot();
15632                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15633                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15634                    } else {
15635                        buffer_snapshot.clip_point(*position, Bias::Left)
15636                    };
15637                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15638                    new_selections_by_buffer.insert(
15639                        buffer,
15640                        (
15641                            vec![jump_to_offset..jump_to_offset],
15642                            Some(*line_offset_from_top),
15643                        ),
15644                    );
15645                }
15646            }
15647            Some(JumpData::MultiBufferRow {
15648                row,
15649                line_offset_from_top,
15650            }) => {
15651                let point = MultiBufferPoint::new(row.0, 0);
15652                if let Some((buffer, buffer_point, _)) =
15653                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15654                {
15655                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15656                    new_selections_by_buffer
15657                        .entry(buffer)
15658                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15659                        .0
15660                        .push(buffer_offset..buffer_offset)
15661                }
15662            }
15663            None => {
15664                let selections = self.selections.all::<usize>(cx);
15665                let multi_buffer = self.buffer.read(cx);
15666                for selection in selections {
15667                    for (snapshot, range, _, anchor) in multi_buffer
15668                        .snapshot(cx)
15669                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15670                    {
15671                        if let Some(anchor) = anchor {
15672                            // selection is in a deleted hunk
15673                            let Some(buffer_id) = anchor.buffer_id else {
15674                                continue;
15675                            };
15676                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15677                                continue;
15678                            };
15679                            let offset = text::ToOffset::to_offset(
15680                                &anchor.text_anchor,
15681                                &buffer_handle.read(cx).snapshot(),
15682                            );
15683                            let range = offset..offset;
15684                            new_selections_by_buffer
15685                                .entry(buffer_handle)
15686                                .or_insert((Vec::new(), None))
15687                                .0
15688                                .push(range)
15689                        } else {
15690                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15691                            else {
15692                                continue;
15693                            };
15694                            new_selections_by_buffer
15695                                .entry(buffer_handle)
15696                                .or_insert((Vec::new(), None))
15697                                .0
15698                                .push(range)
15699                        }
15700                    }
15701                }
15702            }
15703        }
15704
15705        if new_selections_by_buffer.is_empty() {
15706            return;
15707        }
15708
15709        // We defer the pane interaction because we ourselves are a workspace item
15710        // and activating a new item causes the pane to call a method on us reentrantly,
15711        // which panics if we're on the stack.
15712        window.defer(cx, move |window, cx| {
15713            workspace.update(cx, |workspace, cx| {
15714                let pane = if split {
15715                    workspace.adjacent_pane(window, cx)
15716                } else {
15717                    workspace.active_pane().clone()
15718                };
15719
15720                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15721                    let editor = buffer
15722                        .read(cx)
15723                        .file()
15724                        .is_none()
15725                        .then(|| {
15726                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15727                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15728                            // Instead, we try to activate the existing editor in the pane first.
15729                            let (editor, pane_item_index) =
15730                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15731                                    let editor = item.downcast::<Editor>()?;
15732                                    let singleton_buffer =
15733                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15734                                    if singleton_buffer == buffer {
15735                                        Some((editor, i))
15736                                    } else {
15737                                        None
15738                                    }
15739                                })?;
15740                            pane.update(cx, |pane, cx| {
15741                                pane.activate_item(pane_item_index, true, true, window, cx)
15742                            });
15743                            Some(editor)
15744                        })
15745                        .flatten()
15746                        .unwrap_or_else(|| {
15747                            workspace.open_project_item::<Self>(
15748                                pane.clone(),
15749                                buffer,
15750                                true,
15751                                true,
15752                                window,
15753                                cx,
15754                            )
15755                        });
15756
15757                    editor.update(cx, |editor, cx| {
15758                        let autoscroll = match scroll_offset {
15759                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15760                            None => Autoscroll::newest(),
15761                        };
15762                        let nav_history = editor.nav_history.take();
15763                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15764                            s.select_ranges(ranges);
15765                        });
15766                        editor.nav_history = nav_history;
15767                    });
15768                }
15769            })
15770        });
15771    }
15772
15773    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15774        let snapshot = self.buffer.read(cx).read(cx);
15775        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15776        Some(
15777            ranges
15778                .iter()
15779                .map(move |range| {
15780                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15781                })
15782                .collect(),
15783        )
15784    }
15785
15786    fn selection_replacement_ranges(
15787        &self,
15788        range: Range<OffsetUtf16>,
15789        cx: &mut App,
15790    ) -> Vec<Range<OffsetUtf16>> {
15791        let selections = self.selections.all::<OffsetUtf16>(cx);
15792        let newest_selection = selections
15793            .iter()
15794            .max_by_key(|selection| selection.id)
15795            .unwrap();
15796        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15797        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15798        let snapshot = self.buffer.read(cx).read(cx);
15799        selections
15800            .into_iter()
15801            .map(|mut selection| {
15802                selection.start.0 =
15803                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15804                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15805                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15806                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15807            })
15808            .collect()
15809    }
15810
15811    fn report_editor_event(
15812        &self,
15813        event_type: &'static str,
15814        file_extension: Option<String>,
15815        cx: &App,
15816    ) {
15817        if cfg!(any(test, feature = "test-support")) {
15818            return;
15819        }
15820
15821        let Some(project) = &self.project else { return };
15822
15823        // If None, we are in a file without an extension
15824        let file = self
15825            .buffer
15826            .read(cx)
15827            .as_singleton()
15828            .and_then(|b| b.read(cx).file());
15829        let file_extension = file_extension.or(file
15830            .as_ref()
15831            .and_then(|file| Path::new(file.file_name(cx)).extension())
15832            .and_then(|e| e.to_str())
15833            .map(|a| a.to_string()));
15834
15835        let vim_mode = cx
15836            .global::<SettingsStore>()
15837            .raw_user_settings()
15838            .get("vim_mode")
15839            == Some(&serde_json::Value::Bool(true));
15840
15841        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15842        let copilot_enabled = edit_predictions_provider
15843            == language::language_settings::EditPredictionProvider::Copilot;
15844        let copilot_enabled_for_language = self
15845            .buffer
15846            .read(cx)
15847            .settings_at(0, cx)
15848            .show_edit_predictions;
15849
15850        let project = project.read(cx);
15851        telemetry::event!(
15852            event_type,
15853            file_extension,
15854            vim_mode,
15855            copilot_enabled,
15856            copilot_enabled_for_language,
15857            edit_predictions_provider,
15858            is_via_ssh = project.is_via_ssh(),
15859        );
15860    }
15861
15862    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15863    /// with each line being an array of {text, highlight} objects.
15864    fn copy_highlight_json(
15865        &mut self,
15866        _: &CopyHighlightJson,
15867        window: &mut Window,
15868        cx: &mut Context<Self>,
15869    ) {
15870        #[derive(Serialize)]
15871        struct Chunk<'a> {
15872            text: String,
15873            highlight: Option<&'a str>,
15874        }
15875
15876        let snapshot = self.buffer.read(cx).snapshot(cx);
15877        let range = self
15878            .selected_text_range(false, window, cx)
15879            .and_then(|selection| {
15880                if selection.range.is_empty() {
15881                    None
15882                } else {
15883                    Some(selection.range)
15884                }
15885            })
15886            .unwrap_or_else(|| 0..snapshot.len());
15887
15888        let chunks = snapshot.chunks(range, true);
15889        let mut lines = Vec::new();
15890        let mut line: VecDeque<Chunk> = VecDeque::new();
15891
15892        let Some(style) = self.style.as_ref() else {
15893            return;
15894        };
15895
15896        for chunk in chunks {
15897            let highlight = chunk
15898                .syntax_highlight_id
15899                .and_then(|id| id.name(&style.syntax));
15900            let mut chunk_lines = chunk.text.split('\n').peekable();
15901            while let Some(text) = chunk_lines.next() {
15902                let mut merged_with_last_token = false;
15903                if let Some(last_token) = line.back_mut() {
15904                    if last_token.highlight == highlight {
15905                        last_token.text.push_str(text);
15906                        merged_with_last_token = true;
15907                    }
15908                }
15909
15910                if !merged_with_last_token {
15911                    line.push_back(Chunk {
15912                        text: text.into(),
15913                        highlight,
15914                    });
15915                }
15916
15917                if chunk_lines.peek().is_some() {
15918                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15919                        line.pop_front();
15920                    }
15921                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15922                        line.pop_back();
15923                    }
15924
15925                    lines.push(mem::take(&mut line));
15926                }
15927            }
15928        }
15929
15930        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15931            return;
15932        };
15933        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15934    }
15935
15936    pub fn open_context_menu(
15937        &mut self,
15938        _: &OpenContextMenu,
15939        window: &mut Window,
15940        cx: &mut Context<Self>,
15941    ) {
15942        self.request_autoscroll(Autoscroll::newest(), cx);
15943        let position = self.selections.newest_display(cx).start;
15944        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15945    }
15946
15947    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15948        &self.inlay_hint_cache
15949    }
15950
15951    pub fn replay_insert_event(
15952        &mut self,
15953        text: &str,
15954        relative_utf16_range: Option<Range<isize>>,
15955        window: &mut Window,
15956        cx: &mut Context<Self>,
15957    ) {
15958        if !self.input_enabled {
15959            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15960            return;
15961        }
15962        if let Some(relative_utf16_range) = relative_utf16_range {
15963            let selections = self.selections.all::<OffsetUtf16>(cx);
15964            self.change_selections(None, window, cx, |s| {
15965                let new_ranges = selections.into_iter().map(|range| {
15966                    let start = OffsetUtf16(
15967                        range
15968                            .head()
15969                            .0
15970                            .saturating_add_signed(relative_utf16_range.start),
15971                    );
15972                    let end = OffsetUtf16(
15973                        range
15974                            .head()
15975                            .0
15976                            .saturating_add_signed(relative_utf16_range.end),
15977                    );
15978                    start..end
15979                });
15980                s.select_ranges(new_ranges);
15981            });
15982        }
15983
15984        self.handle_input(text, window, cx);
15985    }
15986
15987    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15988        let Some(provider) = self.semantics_provider.as_ref() else {
15989            return false;
15990        };
15991
15992        let mut supports = false;
15993        self.buffer().update(cx, |this, cx| {
15994            this.for_each_buffer(|buffer| {
15995                supports |= provider.supports_inlay_hints(buffer, cx);
15996            });
15997        });
15998
15999        supports
16000    }
16001
16002    pub fn is_focused(&self, window: &Window) -> bool {
16003        self.focus_handle.is_focused(window)
16004    }
16005
16006    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16007        cx.emit(EditorEvent::Focused);
16008
16009        if let Some(descendant) = self
16010            .last_focused_descendant
16011            .take()
16012            .and_then(|descendant| descendant.upgrade())
16013        {
16014            window.focus(&descendant);
16015        } else {
16016            if let Some(blame) = self.blame.as_ref() {
16017                blame.update(cx, GitBlame::focus)
16018            }
16019
16020            self.blink_manager.update(cx, BlinkManager::enable);
16021            self.show_cursor_names(window, cx);
16022            self.buffer.update(cx, |buffer, cx| {
16023                buffer.finalize_last_transaction(cx);
16024                if self.leader_peer_id.is_none() {
16025                    buffer.set_active_selections(
16026                        &self.selections.disjoint_anchors(),
16027                        self.selections.line_mode,
16028                        self.cursor_shape,
16029                        cx,
16030                    );
16031                }
16032            });
16033        }
16034    }
16035
16036    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16037        cx.emit(EditorEvent::FocusedIn)
16038    }
16039
16040    fn handle_focus_out(
16041        &mut self,
16042        event: FocusOutEvent,
16043        _window: &mut Window,
16044        cx: &mut Context<Self>,
16045    ) {
16046        if event.blurred != self.focus_handle {
16047            self.last_focused_descendant = Some(event.blurred);
16048        }
16049        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16050    }
16051
16052    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16053        self.blink_manager.update(cx, BlinkManager::disable);
16054        self.buffer
16055            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16056
16057        if let Some(blame) = self.blame.as_ref() {
16058            blame.update(cx, GitBlame::blur)
16059        }
16060        if !self.hover_state.focused(window, cx) {
16061            hide_hover(self, cx);
16062        }
16063        if !self
16064            .context_menu
16065            .borrow()
16066            .as_ref()
16067            .is_some_and(|context_menu| context_menu.focused(window, cx))
16068        {
16069            self.hide_context_menu(window, cx);
16070        }
16071        self.discard_inline_completion(false, cx);
16072        cx.emit(EditorEvent::Blurred);
16073        cx.notify();
16074    }
16075
16076    pub fn register_action<A: Action>(
16077        &mut self,
16078        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16079    ) -> Subscription {
16080        let id = self.next_editor_action_id.post_inc();
16081        let listener = Arc::new(listener);
16082        self.editor_actions.borrow_mut().insert(
16083            id,
16084            Box::new(move |window, _| {
16085                let listener = listener.clone();
16086                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16087                    let action = action.downcast_ref().unwrap();
16088                    if phase == DispatchPhase::Bubble {
16089                        listener(action, window, cx)
16090                    }
16091                })
16092            }),
16093        );
16094
16095        let editor_actions = self.editor_actions.clone();
16096        Subscription::new(move || {
16097            editor_actions.borrow_mut().remove(&id);
16098        })
16099    }
16100
16101    pub fn file_header_size(&self) -> u32 {
16102        FILE_HEADER_HEIGHT
16103    }
16104
16105    pub fn restore(
16106        &mut self,
16107        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16108        window: &mut Window,
16109        cx: &mut Context<Self>,
16110    ) {
16111        let workspace = self.workspace();
16112        let project = self.project.as_ref();
16113        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16114            let mut tasks = Vec::new();
16115            for (buffer_id, changes) in revert_changes {
16116                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16117                    buffer.update(cx, |buffer, cx| {
16118                        buffer.edit(
16119                            changes
16120                                .into_iter()
16121                                .map(|(range, text)| (range, text.to_string())),
16122                            None,
16123                            cx,
16124                        );
16125                    });
16126
16127                    if let Some(project) =
16128                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16129                    {
16130                        project.update(cx, |project, cx| {
16131                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16132                        })
16133                    }
16134                }
16135            }
16136            tasks
16137        });
16138        cx.spawn_in(window, |_, mut cx| async move {
16139            for (buffer, task) in save_tasks {
16140                let result = task.await;
16141                if result.is_err() {
16142                    let Some(path) = buffer
16143                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16144                        .ok()
16145                    else {
16146                        continue;
16147                    };
16148                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16149                        let Some(task) = cx
16150                            .update_window_entity(&workspace, |workspace, window, cx| {
16151                                workspace
16152                                    .open_path_preview(path, None, false, false, false, window, cx)
16153                            })
16154                            .ok()
16155                        else {
16156                            continue;
16157                        };
16158                        task.await.log_err();
16159                    }
16160                }
16161            }
16162        })
16163        .detach();
16164        self.change_selections(None, window, cx, |selections| selections.refresh());
16165    }
16166
16167    pub fn to_pixel_point(
16168        &self,
16169        source: multi_buffer::Anchor,
16170        editor_snapshot: &EditorSnapshot,
16171        window: &mut Window,
16172    ) -> Option<gpui::Point<Pixels>> {
16173        let source_point = source.to_display_point(editor_snapshot);
16174        self.display_to_pixel_point(source_point, editor_snapshot, window)
16175    }
16176
16177    pub fn display_to_pixel_point(
16178        &self,
16179        source: DisplayPoint,
16180        editor_snapshot: &EditorSnapshot,
16181        window: &mut Window,
16182    ) -> Option<gpui::Point<Pixels>> {
16183        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16184        let text_layout_details = self.text_layout_details(window);
16185        let scroll_top = text_layout_details
16186            .scroll_anchor
16187            .scroll_position(editor_snapshot)
16188            .y;
16189
16190        if source.row().as_f32() < scroll_top.floor() {
16191            return None;
16192        }
16193        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16194        let source_y = line_height * (source.row().as_f32() - scroll_top);
16195        Some(gpui::Point::new(source_x, source_y))
16196    }
16197
16198    pub fn has_visible_completions_menu(&self) -> bool {
16199        !self.edit_prediction_preview_is_active()
16200            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16201                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16202            })
16203    }
16204
16205    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16206        self.addons
16207            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16208    }
16209
16210    pub fn unregister_addon<T: Addon>(&mut self) {
16211        self.addons.remove(&std::any::TypeId::of::<T>());
16212    }
16213
16214    pub fn addon<T: Addon>(&self) -> Option<&T> {
16215        let type_id = std::any::TypeId::of::<T>();
16216        self.addons
16217            .get(&type_id)
16218            .and_then(|item| item.to_any().downcast_ref::<T>())
16219    }
16220
16221    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16222        let text_layout_details = self.text_layout_details(window);
16223        let style = &text_layout_details.editor_style;
16224        let font_id = window.text_system().resolve_font(&style.text.font());
16225        let font_size = style.text.font_size.to_pixels(window.rem_size());
16226        let line_height = style.text.line_height_in_pixels(window.rem_size());
16227        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16228
16229        gpui::Size::new(em_width, line_height)
16230    }
16231
16232    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16233        self.load_diff_task.clone()
16234    }
16235
16236    fn read_selections_from_db(
16237        &mut self,
16238        item_id: u64,
16239        workspace_id: WorkspaceId,
16240        window: &mut Window,
16241        cx: &mut Context<Editor>,
16242    ) {
16243        if !self.is_singleton(cx)
16244            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16245        {
16246            return;
16247        }
16248        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16249            return;
16250        };
16251        if selections.is_empty() {
16252            return;
16253        }
16254
16255        let snapshot = self.buffer.read(cx).snapshot(cx);
16256        self.change_selections(None, window, cx, |s| {
16257            s.select_ranges(selections.into_iter().map(|(start, end)| {
16258                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16259            }));
16260        });
16261    }
16262}
16263
16264fn insert_extra_newline_brackets(
16265    buffer: &MultiBufferSnapshot,
16266    range: Range<usize>,
16267    language: &language::LanguageScope,
16268) -> bool {
16269    let leading_whitespace_len = buffer
16270        .reversed_chars_at(range.start)
16271        .take_while(|c| c.is_whitespace() && *c != '\n')
16272        .map(|c| c.len_utf8())
16273        .sum::<usize>();
16274    let trailing_whitespace_len = buffer
16275        .chars_at(range.end)
16276        .take_while(|c| c.is_whitespace() && *c != '\n')
16277        .map(|c| c.len_utf8())
16278        .sum::<usize>();
16279    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16280
16281    language.brackets().any(|(pair, enabled)| {
16282        let pair_start = pair.start.trim_end();
16283        let pair_end = pair.end.trim_start();
16284
16285        enabled
16286            && pair.newline
16287            && buffer.contains_str_at(range.end, pair_end)
16288            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16289    })
16290}
16291
16292fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16293    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16294        [(buffer, range, _)] => (*buffer, range.clone()),
16295        _ => return false,
16296    };
16297    let pair = {
16298        let mut result: Option<BracketMatch> = None;
16299
16300        for pair in buffer
16301            .all_bracket_ranges(range.clone())
16302            .filter(move |pair| {
16303                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16304            })
16305        {
16306            let len = pair.close_range.end - pair.open_range.start;
16307
16308            if let Some(existing) = &result {
16309                let existing_len = existing.close_range.end - existing.open_range.start;
16310                if len > existing_len {
16311                    continue;
16312                }
16313            }
16314
16315            result = Some(pair);
16316        }
16317
16318        result
16319    };
16320    let Some(pair) = pair else {
16321        return false;
16322    };
16323    pair.newline_only
16324        && buffer
16325            .chars_for_range(pair.open_range.end..range.start)
16326            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16327            .all(|c| c.is_whitespace() && c != '\n')
16328}
16329
16330fn get_uncommitted_diff_for_buffer(
16331    project: &Entity<Project>,
16332    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16333    buffer: Entity<MultiBuffer>,
16334    cx: &mut App,
16335) -> Task<()> {
16336    let mut tasks = Vec::new();
16337    project.update(cx, |project, cx| {
16338        for buffer in buffers {
16339            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16340        }
16341    });
16342    cx.spawn(|mut cx| async move {
16343        let diffs = futures::future::join_all(tasks).await;
16344        buffer
16345            .update(&mut cx, |buffer, cx| {
16346                for diff in diffs.into_iter().flatten() {
16347                    buffer.add_diff(diff, cx);
16348                }
16349            })
16350            .ok();
16351    })
16352}
16353
16354fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16355    let tab_size = tab_size.get() as usize;
16356    let mut width = offset;
16357
16358    for ch in text.chars() {
16359        width += if ch == '\t' {
16360            tab_size - (width % tab_size)
16361        } else {
16362            1
16363        };
16364    }
16365
16366    width - offset
16367}
16368
16369#[cfg(test)]
16370mod tests {
16371    use super::*;
16372
16373    #[test]
16374    fn test_string_size_with_expanded_tabs() {
16375        let nz = |val| NonZeroU32::new(val).unwrap();
16376        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16377        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16378        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16379        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16380        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16381        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16382        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16383        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16384    }
16385}
16386
16387/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16388struct WordBreakingTokenizer<'a> {
16389    input: &'a str,
16390}
16391
16392impl<'a> WordBreakingTokenizer<'a> {
16393    fn new(input: &'a str) -> Self {
16394        Self { input }
16395    }
16396}
16397
16398fn is_char_ideographic(ch: char) -> bool {
16399    use unicode_script::Script::*;
16400    use unicode_script::UnicodeScript;
16401    matches!(ch.script(), Han | Tangut | Yi)
16402}
16403
16404fn is_grapheme_ideographic(text: &str) -> bool {
16405    text.chars().any(is_char_ideographic)
16406}
16407
16408fn is_grapheme_whitespace(text: &str) -> bool {
16409    text.chars().any(|x| x.is_whitespace())
16410}
16411
16412fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16413    text.chars().next().map_or(false, |ch| {
16414        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16415    })
16416}
16417
16418#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16419struct WordBreakToken<'a> {
16420    token: &'a str,
16421    grapheme_len: usize,
16422    is_whitespace: bool,
16423}
16424
16425impl<'a> Iterator for WordBreakingTokenizer<'a> {
16426    /// Yields a span, the count of graphemes in the token, and whether it was
16427    /// whitespace. Note that it also breaks at word boundaries.
16428    type Item = WordBreakToken<'a>;
16429
16430    fn next(&mut self) -> Option<Self::Item> {
16431        use unicode_segmentation::UnicodeSegmentation;
16432        if self.input.is_empty() {
16433            return None;
16434        }
16435
16436        let mut iter = self.input.graphemes(true).peekable();
16437        let mut offset = 0;
16438        let mut graphemes = 0;
16439        if let Some(first_grapheme) = iter.next() {
16440            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16441            offset += first_grapheme.len();
16442            graphemes += 1;
16443            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16444                if let Some(grapheme) = iter.peek().copied() {
16445                    if should_stay_with_preceding_ideograph(grapheme) {
16446                        offset += grapheme.len();
16447                        graphemes += 1;
16448                    }
16449                }
16450            } else {
16451                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16452                let mut next_word_bound = words.peek().copied();
16453                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16454                    next_word_bound = words.next();
16455                }
16456                while let Some(grapheme) = iter.peek().copied() {
16457                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16458                        break;
16459                    };
16460                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16461                        break;
16462                    };
16463                    offset += grapheme.len();
16464                    graphemes += 1;
16465                    iter.next();
16466                }
16467            }
16468            let token = &self.input[..offset];
16469            self.input = &self.input[offset..];
16470            if is_whitespace {
16471                Some(WordBreakToken {
16472                    token: " ",
16473                    grapheme_len: 1,
16474                    is_whitespace: true,
16475                })
16476            } else {
16477                Some(WordBreakToken {
16478                    token,
16479                    grapheme_len: graphemes,
16480                    is_whitespace: false,
16481                })
16482            }
16483        } else {
16484            None
16485        }
16486    }
16487}
16488
16489#[test]
16490fn test_word_breaking_tokenizer() {
16491    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16492        ("", &[]),
16493        ("  ", &[(" ", 1, true)]),
16494        ("Ʒ", &[("Ʒ", 1, false)]),
16495        ("Ǽ", &[("Ǽ", 1, false)]),
16496        ("", &[("", 1, false)]),
16497        ("⋑⋑", &[("⋑⋑", 2, false)]),
16498        (
16499            "原理,进而",
16500            &[
16501                ("", 1, false),
16502                ("理,", 2, false),
16503                ("", 1, false),
16504                ("", 1, false),
16505            ],
16506        ),
16507        (
16508            "hello world",
16509            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16510        ),
16511        (
16512            "hello, world",
16513            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16514        ),
16515        (
16516            "  hello world",
16517            &[
16518                (" ", 1, true),
16519                ("hello", 5, false),
16520                (" ", 1, true),
16521                ("world", 5, false),
16522            ],
16523        ),
16524        (
16525            "这是什么 \n 钢笔",
16526            &[
16527                ("", 1, false),
16528                ("", 1, false),
16529                ("", 1, false),
16530                ("", 1, false),
16531                (" ", 1, true),
16532                ("", 1, false),
16533                ("", 1, false),
16534            ],
16535        ),
16536        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16537    ];
16538
16539    for (input, result) in tests {
16540        assert_eq!(
16541            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16542            result
16543                .iter()
16544                .copied()
16545                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16546                    token,
16547                    grapheme_len,
16548                    is_whitespace,
16549                })
16550                .collect::<Vec<_>>()
16551        );
16552    }
16553}
16554
16555fn wrap_with_prefix(
16556    line_prefix: String,
16557    unwrapped_text: String,
16558    wrap_column: usize,
16559    tab_size: NonZeroU32,
16560) -> String {
16561    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16562    let mut wrapped_text = String::new();
16563    let mut current_line = line_prefix.clone();
16564
16565    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16566    let mut current_line_len = line_prefix_len;
16567    for WordBreakToken {
16568        token,
16569        grapheme_len,
16570        is_whitespace,
16571    } in tokenizer
16572    {
16573        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16574            wrapped_text.push_str(current_line.trim_end());
16575            wrapped_text.push('\n');
16576            current_line.truncate(line_prefix.len());
16577            current_line_len = line_prefix_len;
16578            if !is_whitespace {
16579                current_line.push_str(token);
16580                current_line_len += grapheme_len;
16581            }
16582        } else if !is_whitespace {
16583            current_line.push_str(token);
16584            current_line_len += grapheme_len;
16585        } else if current_line_len != line_prefix_len {
16586            current_line.push(' ');
16587            current_line_len += 1;
16588        }
16589    }
16590
16591    if !current_line.is_empty() {
16592        wrapped_text.push_str(&current_line);
16593    }
16594    wrapped_text
16595}
16596
16597#[test]
16598fn test_wrap_with_prefix() {
16599    assert_eq!(
16600        wrap_with_prefix(
16601            "# ".to_string(),
16602            "abcdefg".to_string(),
16603            4,
16604            NonZeroU32::new(4).unwrap()
16605        ),
16606        "# abcdefg"
16607    );
16608    assert_eq!(
16609        wrap_with_prefix(
16610            "".to_string(),
16611            "\thello world".to_string(),
16612            8,
16613            NonZeroU32::new(4).unwrap()
16614        ),
16615        "hello\nworld"
16616    );
16617    assert_eq!(
16618        wrap_with_prefix(
16619            "// ".to_string(),
16620            "xx \nyy zz aa bb cc".to_string(),
16621            12,
16622            NonZeroU32::new(4).unwrap()
16623        ),
16624        "// xx yy zz\n// aa bb cc"
16625    );
16626    assert_eq!(
16627        wrap_with_prefix(
16628            String::new(),
16629            "这是什么 \n 钢笔".to_string(),
16630            3,
16631            NonZeroU32::new(4).unwrap()
16632        ),
16633        "这是什\n么 钢\n"
16634    );
16635}
16636
16637pub trait CollaborationHub {
16638    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16639    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16640    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16641}
16642
16643impl CollaborationHub for Entity<Project> {
16644    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16645        self.read(cx).collaborators()
16646    }
16647
16648    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16649        self.read(cx).user_store().read(cx).participant_indices()
16650    }
16651
16652    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16653        let this = self.read(cx);
16654        let user_ids = this.collaborators().values().map(|c| c.user_id);
16655        this.user_store().read_with(cx, |user_store, cx| {
16656            user_store.participant_names(user_ids, cx)
16657        })
16658    }
16659}
16660
16661pub trait SemanticsProvider {
16662    fn hover(
16663        &self,
16664        buffer: &Entity<Buffer>,
16665        position: text::Anchor,
16666        cx: &mut App,
16667    ) -> Option<Task<Vec<project::Hover>>>;
16668
16669    fn inlay_hints(
16670        &self,
16671        buffer_handle: Entity<Buffer>,
16672        range: Range<text::Anchor>,
16673        cx: &mut App,
16674    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16675
16676    fn resolve_inlay_hint(
16677        &self,
16678        hint: InlayHint,
16679        buffer_handle: Entity<Buffer>,
16680        server_id: LanguageServerId,
16681        cx: &mut App,
16682    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16683
16684    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16685
16686    fn document_highlights(
16687        &self,
16688        buffer: &Entity<Buffer>,
16689        position: text::Anchor,
16690        cx: &mut App,
16691    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16692
16693    fn definitions(
16694        &self,
16695        buffer: &Entity<Buffer>,
16696        position: text::Anchor,
16697        kind: GotoDefinitionKind,
16698        cx: &mut App,
16699    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16700
16701    fn range_for_rename(
16702        &self,
16703        buffer: &Entity<Buffer>,
16704        position: text::Anchor,
16705        cx: &mut App,
16706    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16707
16708    fn perform_rename(
16709        &self,
16710        buffer: &Entity<Buffer>,
16711        position: text::Anchor,
16712        new_name: String,
16713        cx: &mut App,
16714    ) -> Option<Task<Result<ProjectTransaction>>>;
16715}
16716
16717pub trait CompletionProvider {
16718    fn completions(
16719        &self,
16720        buffer: &Entity<Buffer>,
16721        buffer_position: text::Anchor,
16722        trigger: CompletionContext,
16723        window: &mut Window,
16724        cx: &mut Context<Editor>,
16725    ) -> Task<Result<Vec<Completion>>>;
16726
16727    fn resolve_completions(
16728        &self,
16729        buffer: Entity<Buffer>,
16730        completion_indices: Vec<usize>,
16731        completions: Rc<RefCell<Box<[Completion]>>>,
16732        cx: &mut Context<Editor>,
16733    ) -> Task<Result<bool>>;
16734
16735    fn apply_additional_edits_for_completion(
16736        &self,
16737        _buffer: Entity<Buffer>,
16738        _completions: Rc<RefCell<Box<[Completion]>>>,
16739        _completion_index: usize,
16740        _push_to_history: bool,
16741        _cx: &mut Context<Editor>,
16742    ) -> Task<Result<Option<language::Transaction>>> {
16743        Task::ready(Ok(None))
16744    }
16745
16746    fn is_completion_trigger(
16747        &self,
16748        buffer: &Entity<Buffer>,
16749        position: language::Anchor,
16750        text: &str,
16751        trigger_in_words: bool,
16752        cx: &mut Context<Editor>,
16753    ) -> bool;
16754
16755    fn sort_completions(&self) -> bool {
16756        true
16757    }
16758}
16759
16760pub trait CodeActionProvider {
16761    fn id(&self) -> Arc<str>;
16762
16763    fn code_actions(
16764        &self,
16765        buffer: &Entity<Buffer>,
16766        range: Range<text::Anchor>,
16767        window: &mut Window,
16768        cx: &mut App,
16769    ) -> Task<Result<Vec<CodeAction>>>;
16770
16771    fn apply_code_action(
16772        &self,
16773        buffer_handle: Entity<Buffer>,
16774        action: CodeAction,
16775        excerpt_id: ExcerptId,
16776        push_to_history: bool,
16777        window: &mut Window,
16778        cx: &mut App,
16779    ) -> Task<Result<ProjectTransaction>>;
16780}
16781
16782impl CodeActionProvider for Entity<Project> {
16783    fn id(&self) -> Arc<str> {
16784        "project".into()
16785    }
16786
16787    fn code_actions(
16788        &self,
16789        buffer: &Entity<Buffer>,
16790        range: Range<text::Anchor>,
16791        _window: &mut Window,
16792        cx: &mut App,
16793    ) -> Task<Result<Vec<CodeAction>>> {
16794        self.update(cx, |project, cx| {
16795            project.code_actions(buffer, range, None, cx)
16796        })
16797    }
16798
16799    fn apply_code_action(
16800        &self,
16801        buffer_handle: Entity<Buffer>,
16802        action: CodeAction,
16803        _excerpt_id: ExcerptId,
16804        push_to_history: bool,
16805        _window: &mut Window,
16806        cx: &mut App,
16807    ) -> Task<Result<ProjectTransaction>> {
16808        self.update(cx, |project, cx| {
16809            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16810        })
16811    }
16812}
16813
16814fn snippet_completions(
16815    project: &Project,
16816    buffer: &Entity<Buffer>,
16817    buffer_position: text::Anchor,
16818    cx: &mut App,
16819) -> Task<Result<Vec<Completion>>> {
16820    let language = buffer.read(cx).language_at(buffer_position);
16821    let language_name = language.as_ref().map(|language| language.lsp_id());
16822    let snippet_store = project.snippets().read(cx);
16823    let snippets = snippet_store.snippets_for(language_name, cx);
16824
16825    if snippets.is_empty() {
16826        return Task::ready(Ok(vec![]));
16827    }
16828    let snapshot = buffer.read(cx).text_snapshot();
16829    let chars: String = snapshot
16830        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16831        .collect();
16832
16833    let scope = language.map(|language| language.default_scope());
16834    let executor = cx.background_executor().clone();
16835
16836    cx.background_spawn(async move {
16837        let classifier = CharClassifier::new(scope).for_completion(true);
16838        let mut last_word = chars
16839            .chars()
16840            .take_while(|c| classifier.is_word(*c))
16841            .collect::<String>();
16842        last_word = last_word.chars().rev().collect();
16843
16844        if last_word.is_empty() {
16845            return Ok(vec![]);
16846        }
16847
16848        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16849        let to_lsp = |point: &text::Anchor| {
16850            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16851            point_to_lsp(end)
16852        };
16853        let lsp_end = to_lsp(&buffer_position);
16854
16855        let candidates = snippets
16856            .iter()
16857            .enumerate()
16858            .flat_map(|(ix, snippet)| {
16859                snippet
16860                    .prefix
16861                    .iter()
16862                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16863            })
16864            .collect::<Vec<StringMatchCandidate>>();
16865
16866        let mut matches = fuzzy::match_strings(
16867            &candidates,
16868            &last_word,
16869            last_word.chars().any(|c| c.is_uppercase()),
16870            100,
16871            &Default::default(),
16872            executor,
16873        )
16874        .await;
16875
16876        // Remove all candidates where the query's start does not match the start of any word in the candidate
16877        if let Some(query_start) = last_word.chars().next() {
16878            matches.retain(|string_match| {
16879                split_words(&string_match.string).any(|word| {
16880                    // Check that the first codepoint of the word as lowercase matches the first
16881                    // codepoint of the query as lowercase
16882                    word.chars()
16883                        .flat_map(|codepoint| codepoint.to_lowercase())
16884                        .zip(query_start.to_lowercase())
16885                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16886                })
16887            });
16888        }
16889
16890        let matched_strings = matches
16891            .into_iter()
16892            .map(|m| m.string)
16893            .collect::<HashSet<_>>();
16894
16895        let result: Vec<Completion> = snippets
16896            .into_iter()
16897            .filter_map(|snippet| {
16898                let matching_prefix = snippet
16899                    .prefix
16900                    .iter()
16901                    .find(|prefix| matched_strings.contains(*prefix))?;
16902                let start = as_offset - last_word.len();
16903                let start = snapshot.anchor_before(start);
16904                let range = start..buffer_position;
16905                let lsp_start = to_lsp(&start);
16906                let lsp_range = lsp::Range {
16907                    start: lsp_start,
16908                    end: lsp_end,
16909                };
16910                Some(Completion {
16911                    old_range: range,
16912                    new_text: snippet.body.clone(),
16913                    resolved: false,
16914                    label: CodeLabel {
16915                        text: matching_prefix.clone(),
16916                        runs: vec![],
16917                        filter_range: 0..matching_prefix.len(),
16918                    },
16919                    server_id: LanguageServerId(usize::MAX),
16920                    documentation: snippet
16921                        .description
16922                        .clone()
16923                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16924                    lsp_completion: lsp::CompletionItem {
16925                        label: snippet.prefix.first().unwrap().clone(),
16926                        kind: Some(CompletionItemKind::SNIPPET),
16927                        label_details: snippet.description.as_ref().map(|description| {
16928                            lsp::CompletionItemLabelDetails {
16929                                detail: Some(description.clone()),
16930                                description: None,
16931                            }
16932                        }),
16933                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16934                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16935                            lsp::InsertReplaceEdit {
16936                                new_text: snippet.body.clone(),
16937                                insert: lsp_range,
16938                                replace: lsp_range,
16939                            },
16940                        )),
16941                        filter_text: Some(snippet.body.clone()),
16942                        sort_text: Some(char::MAX.to_string()),
16943                        ..Default::default()
16944                    },
16945                    confirm: None,
16946                })
16947            })
16948            .collect();
16949
16950        Ok(result)
16951    })
16952}
16953
16954impl CompletionProvider for Entity<Project> {
16955    fn completions(
16956        &self,
16957        buffer: &Entity<Buffer>,
16958        buffer_position: text::Anchor,
16959        options: CompletionContext,
16960        _window: &mut Window,
16961        cx: &mut Context<Editor>,
16962    ) -> Task<Result<Vec<Completion>>> {
16963        self.update(cx, |project, cx| {
16964            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16965            let project_completions = project.completions(buffer, buffer_position, options, cx);
16966            cx.background_spawn(async move {
16967                let mut completions = project_completions.await?;
16968                let snippets_completions = snippets.await?;
16969                completions.extend(snippets_completions);
16970                Ok(completions)
16971            })
16972        })
16973    }
16974
16975    fn resolve_completions(
16976        &self,
16977        buffer: Entity<Buffer>,
16978        completion_indices: Vec<usize>,
16979        completions: Rc<RefCell<Box<[Completion]>>>,
16980        cx: &mut Context<Editor>,
16981    ) -> Task<Result<bool>> {
16982        self.update(cx, |project, cx| {
16983            project.lsp_store().update(cx, |lsp_store, cx| {
16984                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16985            })
16986        })
16987    }
16988
16989    fn apply_additional_edits_for_completion(
16990        &self,
16991        buffer: Entity<Buffer>,
16992        completions: Rc<RefCell<Box<[Completion]>>>,
16993        completion_index: usize,
16994        push_to_history: bool,
16995        cx: &mut Context<Editor>,
16996    ) -> Task<Result<Option<language::Transaction>>> {
16997        self.update(cx, |project, cx| {
16998            project.lsp_store().update(cx, |lsp_store, cx| {
16999                lsp_store.apply_additional_edits_for_completion(
17000                    buffer,
17001                    completions,
17002                    completion_index,
17003                    push_to_history,
17004                    cx,
17005                )
17006            })
17007        })
17008    }
17009
17010    fn is_completion_trigger(
17011        &self,
17012        buffer: &Entity<Buffer>,
17013        position: language::Anchor,
17014        text: &str,
17015        trigger_in_words: bool,
17016        cx: &mut Context<Editor>,
17017    ) -> bool {
17018        let mut chars = text.chars();
17019        let char = if let Some(char) = chars.next() {
17020            char
17021        } else {
17022            return false;
17023        };
17024        if chars.next().is_some() {
17025            return false;
17026        }
17027
17028        let buffer = buffer.read(cx);
17029        let snapshot = buffer.snapshot();
17030        if !snapshot.settings_at(position, cx).show_completions_on_input {
17031            return false;
17032        }
17033        let classifier = snapshot.char_classifier_at(position).for_completion(true);
17034        if trigger_in_words && classifier.is_word(char) {
17035            return true;
17036        }
17037
17038        buffer.completion_triggers().contains(text)
17039    }
17040}
17041
17042impl SemanticsProvider for Entity<Project> {
17043    fn hover(
17044        &self,
17045        buffer: &Entity<Buffer>,
17046        position: text::Anchor,
17047        cx: &mut App,
17048    ) -> Option<Task<Vec<project::Hover>>> {
17049        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17050    }
17051
17052    fn document_highlights(
17053        &self,
17054        buffer: &Entity<Buffer>,
17055        position: text::Anchor,
17056        cx: &mut App,
17057    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17058        Some(self.update(cx, |project, cx| {
17059            project.document_highlights(buffer, position, cx)
17060        }))
17061    }
17062
17063    fn definitions(
17064        &self,
17065        buffer: &Entity<Buffer>,
17066        position: text::Anchor,
17067        kind: GotoDefinitionKind,
17068        cx: &mut App,
17069    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17070        Some(self.update(cx, |project, cx| match kind {
17071            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17072            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17073            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17074            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17075        }))
17076    }
17077
17078    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17079        // TODO: make this work for remote projects
17080        self.update(cx, |this, cx| {
17081            buffer.update(cx, |buffer, cx| {
17082                this.any_language_server_supports_inlay_hints(buffer, cx)
17083            })
17084        })
17085    }
17086
17087    fn inlay_hints(
17088        &self,
17089        buffer_handle: Entity<Buffer>,
17090        range: Range<text::Anchor>,
17091        cx: &mut App,
17092    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17093        Some(self.update(cx, |project, cx| {
17094            project.inlay_hints(buffer_handle, range, cx)
17095        }))
17096    }
17097
17098    fn resolve_inlay_hint(
17099        &self,
17100        hint: InlayHint,
17101        buffer_handle: Entity<Buffer>,
17102        server_id: LanguageServerId,
17103        cx: &mut App,
17104    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17105        Some(self.update(cx, |project, cx| {
17106            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17107        }))
17108    }
17109
17110    fn range_for_rename(
17111        &self,
17112        buffer: &Entity<Buffer>,
17113        position: text::Anchor,
17114        cx: &mut App,
17115    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17116        Some(self.update(cx, |project, cx| {
17117            let buffer = buffer.clone();
17118            let task = project.prepare_rename(buffer.clone(), position, cx);
17119            cx.spawn(|_, mut cx| async move {
17120                Ok(match task.await? {
17121                    PrepareRenameResponse::Success(range) => Some(range),
17122                    PrepareRenameResponse::InvalidPosition => None,
17123                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17124                        // Fallback on using TreeSitter info to determine identifier range
17125                        buffer.update(&mut cx, |buffer, _| {
17126                            let snapshot = buffer.snapshot();
17127                            let (range, kind) = snapshot.surrounding_word(position);
17128                            if kind != Some(CharKind::Word) {
17129                                return None;
17130                            }
17131                            Some(
17132                                snapshot.anchor_before(range.start)
17133                                    ..snapshot.anchor_after(range.end),
17134                            )
17135                        })?
17136                    }
17137                })
17138            })
17139        }))
17140    }
17141
17142    fn perform_rename(
17143        &self,
17144        buffer: &Entity<Buffer>,
17145        position: text::Anchor,
17146        new_name: String,
17147        cx: &mut App,
17148    ) -> Option<Task<Result<ProjectTransaction>>> {
17149        Some(self.update(cx, |project, cx| {
17150            project.perform_rename(buffer.clone(), position, new_name, cx)
17151        }))
17152    }
17153}
17154
17155fn inlay_hint_settings(
17156    location: Anchor,
17157    snapshot: &MultiBufferSnapshot,
17158    cx: &mut Context<Editor>,
17159) -> InlayHintSettings {
17160    let file = snapshot.file_at(location);
17161    let language = snapshot.language_at(location).map(|l| l.name());
17162    language_settings(language, file, cx).inlay_hints
17163}
17164
17165fn consume_contiguous_rows(
17166    contiguous_row_selections: &mut Vec<Selection<Point>>,
17167    selection: &Selection<Point>,
17168    display_map: &DisplaySnapshot,
17169    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17170) -> (MultiBufferRow, MultiBufferRow) {
17171    contiguous_row_selections.push(selection.clone());
17172    let start_row = MultiBufferRow(selection.start.row);
17173    let mut end_row = ending_row(selection, display_map);
17174
17175    while let Some(next_selection) = selections.peek() {
17176        if next_selection.start.row <= end_row.0 {
17177            end_row = ending_row(next_selection, display_map);
17178            contiguous_row_selections.push(selections.next().unwrap().clone());
17179        } else {
17180            break;
17181        }
17182    }
17183    (start_row, end_row)
17184}
17185
17186fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17187    if next_selection.end.column > 0 || next_selection.is_empty() {
17188        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17189    } else {
17190        MultiBufferRow(next_selection.end.row)
17191    }
17192}
17193
17194impl EditorSnapshot {
17195    pub fn remote_selections_in_range<'a>(
17196        &'a self,
17197        range: &'a Range<Anchor>,
17198        collaboration_hub: &dyn CollaborationHub,
17199        cx: &'a App,
17200    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17201        let participant_names = collaboration_hub.user_names(cx);
17202        let participant_indices = collaboration_hub.user_participant_indices(cx);
17203        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17204        let collaborators_by_replica_id = collaborators_by_peer_id
17205            .iter()
17206            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17207            .collect::<HashMap<_, _>>();
17208        self.buffer_snapshot
17209            .selections_in_range(range, false)
17210            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17211                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17212                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17213                let user_name = participant_names.get(&collaborator.user_id).cloned();
17214                Some(RemoteSelection {
17215                    replica_id,
17216                    selection,
17217                    cursor_shape,
17218                    line_mode,
17219                    participant_index,
17220                    peer_id: collaborator.peer_id,
17221                    user_name,
17222                })
17223            })
17224    }
17225
17226    pub fn hunks_for_ranges(
17227        &self,
17228        ranges: impl IntoIterator<Item = Range<Point>>,
17229    ) -> Vec<MultiBufferDiffHunk> {
17230        let mut hunks = Vec::new();
17231        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17232            HashMap::default();
17233        for query_range in ranges {
17234            let query_rows =
17235                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17236            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17237                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17238            ) {
17239                // Include deleted hunks that are adjacent to the query range, because
17240                // otherwise they would be missed.
17241                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17242                if hunk.status().is_deleted() {
17243                    intersects_range |= hunk.row_range.start == query_rows.end;
17244                    intersects_range |= hunk.row_range.end == query_rows.start;
17245                }
17246                if intersects_range {
17247                    if !processed_buffer_rows
17248                        .entry(hunk.buffer_id)
17249                        .or_default()
17250                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17251                    {
17252                        continue;
17253                    }
17254                    hunks.push(hunk);
17255                }
17256            }
17257        }
17258
17259        hunks
17260    }
17261
17262    fn display_diff_hunks_for_rows<'a>(
17263        &'a self,
17264        display_rows: Range<DisplayRow>,
17265        folded_buffers: &'a HashSet<BufferId>,
17266    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17267        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17268        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17269
17270        self.buffer_snapshot
17271            .diff_hunks_in_range(buffer_start..buffer_end)
17272            .filter_map(|hunk| {
17273                if folded_buffers.contains(&hunk.buffer_id) {
17274                    return None;
17275                }
17276
17277                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17278                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17279
17280                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17281                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17282
17283                let display_hunk = if hunk_display_start.column() != 0 {
17284                    DisplayDiffHunk::Folded {
17285                        display_row: hunk_display_start.row(),
17286                    }
17287                } else {
17288                    let mut end_row = hunk_display_end.row();
17289                    if hunk_display_end.column() > 0 {
17290                        end_row.0 += 1;
17291                    }
17292                    DisplayDiffHunk::Unfolded {
17293                        status: hunk.status(),
17294                        diff_base_byte_range: hunk.diff_base_byte_range,
17295                        display_row_range: hunk_display_start.row()..end_row,
17296                        multi_buffer_range: Anchor::range_in_buffer(
17297                            hunk.excerpt_id,
17298                            hunk.buffer_id,
17299                            hunk.buffer_range,
17300                        ),
17301                    }
17302                };
17303
17304                Some(display_hunk)
17305            })
17306    }
17307
17308    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17309        self.display_snapshot.buffer_snapshot.language_at(position)
17310    }
17311
17312    pub fn is_focused(&self) -> bool {
17313        self.is_focused
17314    }
17315
17316    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17317        self.placeholder_text.as_ref()
17318    }
17319
17320    pub fn scroll_position(&self) -> gpui::Point<f32> {
17321        self.scroll_anchor.scroll_position(&self.display_snapshot)
17322    }
17323
17324    fn gutter_dimensions(
17325        &self,
17326        font_id: FontId,
17327        font_size: Pixels,
17328        max_line_number_width: Pixels,
17329        cx: &App,
17330    ) -> Option<GutterDimensions> {
17331        if !self.show_gutter {
17332            return None;
17333        }
17334
17335        let descent = cx.text_system().descent(font_id, font_size);
17336        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17337        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17338
17339        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17340            matches!(
17341                ProjectSettings::get_global(cx).git.git_gutter,
17342                Some(GitGutterSetting::TrackedFiles)
17343            )
17344        });
17345        let gutter_settings = EditorSettings::get_global(cx).gutter;
17346        let show_line_numbers = self
17347            .show_line_numbers
17348            .unwrap_or(gutter_settings.line_numbers);
17349        let line_gutter_width = if show_line_numbers {
17350            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17351            let min_width_for_number_on_gutter = em_advance * 4.0;
17352            max_line_number_width.max(min_width_for_number_on_gutter)
17353        } else {
17354            0.0.into()
17355        };
17356
17357        let show_code_actions = self
17358            .show_code_actions
17359            .unwrap_or(gutter_settings.code_actions);
17360
17361        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17362
17363        let git_blame_entries_width =
17364            self.git_blame_gutter_max_author_length
17365                .map(|max_author_length| {
17366                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17367
17368                    /// The number of characters to dedicate to gaps and margins.
17369                    const SPACING_WIDTH: usize = 4;
17370
17371                    let max_char_count = max_author_length
17372                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17373                        + ::git::SHORT_SHA_LENGTH
17374                        + MAX_RELATIVE_TIMESTAMP.len()
17375                        + SPACING_WIDTH;
17376
17377                    em_advance * max_char_count
17378                });
17379
17380        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17381        left_padding += if show_code_actions || show_runnables {
17382            em_width * 3.0
17383        } else if show_git_gutter && show_line_numbers {
17384            em_width * 2.0
17385        } else if show_git_gutter || show_line_numbers {
17386            em_width
17387        } else {
17388            px(0.)
17389        };
17390
17391        let right_padding = if gutter_settings.folds && show_line_numbers {
17392            em_width * 4.0
17393        } else if gutter_settings.folds {
17394            em_width * 3.0
17395        } else if show_line_numbers {
17396            em_width
17397        } else {
17398            px(0.)
17399        };
17400
17401        Some(GutterDimensions {
17402            left_padding,
17403            right_padding,
17404            width: line_gutter_width + left_padding + right_padding,
17405            margin: -descent,
17406            git_blame_entries_width,
17407        })
17408    }
17409
17410    pub fn render_crease_toggle(
17411        &self,
17412        buffer_row: MultiBufferRow,
17413        row_contains_cursor: bool,
17414        editor: Entity<Editor>,
17415        window: &mut Window,
17416        cx: &mut App,
17417    ) -> Option<AnyElement> {
17418        let folded = self.is_line_folded(buffer_row);
17419        let mut is_foldable = false;
17420
17421        if let Some(crease) = self
17422            .crease_snapshot
17423            .query_row(buffer_row, &self.buffer_snapshot)
17424        {
17425            is_foldable = true;
17426            match crease {
17427                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17428                    if let Some(render_toggle) = render_toggle {
17429                        let toggle_callback =
17430                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17431                                if folded {
17432                                    editor.update(cx, |editor, cx| {
17433                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17434                                    });
17435                                } else {
17436                                    editor.update(cx, |editor, cx| {
17437                                        editor.unfold_at(
17438                                            &crate::UnfoldAt { buffer_row },
17439                                            window,
17440                                            cx,
17441                                        )
17442                                    });
17443                                }
17444                            });
17445                        return Some((render_toggle)(
17446                            buffer_row,
17447                            folded,
17448                            toggle_callback,
17449                            window,
17450                            cx,
17451                        ));
17452                    }
17453                }
17454            }
17455        }
17456
17457        is_foldable |= self.starts_indent(buffer_row);
17458
17459        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17460            Some(
17461                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17462                    .toggle_state(folded)
17463                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17464                        if folded {
17465                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17466                        } else {
17467                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17468                        }
17469                    }))
17470                    .into_any_element(),
17471            )
17472        } else {
17473            None
17474        }
17475    }
17476
17477    pub fn render_crease_trailer(
17478        &self,
17479        buffer_row: MultiBufferRow,
17480        window: &mut Window,
17481        cx: &mut App,
17482    ) -> Option<AnyElement> {
17483        let folded = self.is_line_folded(buffer_row);
17484        if let Crease::Inline { render_trailer, .. } = self
17485            .crease_snapshot
17486            .query_row(buffer_row, &self.buffer_snapshot)?
17487        {
17488            let render_trailer = render_trailer.as_ref()?;
17489            Some(render_trailer(buffer_row, folded, window, cx))
17490        } else {
17491            None
17492        }
17493    }
17494}
17495
17496impl Deref for EditorSnapshot {
17497    type Target = DisplaySnapshot;
17498
17499    fn deref(&self) -> &Self::Target {
17500        &self.display_snapshot
17501    }
17502}
17503
17504#[derive(Clone, Debug, PartialEq, Eq)]
17505pub enum EditorEvent {
17506    InputIgnored {
17507        text: Arc<str>,
17508    },
17509    InputHandled {
17510        utf16_range_to_replace: Option<Range<isize>>,
17511        text: Arc<str>,
17512    },
17513    ExcerptsAdded {
17514        buffer: Entity<Buffer>,
17515        predecessor: ExcerptId,
17516        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17517    },
17518    ExcerptsRemoved {
17519        ids: Vec<ExcerptId>,
17520    },
17521    BufferFoldToggled {
17522        ids: Vec<ExcerptId>,
17523        folded: bool,
17524    },
17525    ExcerptsEdited {
17526        ids: Vec<ExcerptId>,
17527    },
17528    ExcerptsExpanded {
17529        ids: Vec<ExcerptId>,
17530    },
17531    BufferEdited,
17532    Edited {
17533        transaction_id: clock::Lamport,
17534    },
17535    Reparsed(BufferId),
17536    Focused,
17537    FocusedIn,
17538    Blurred,
17539    DirtyChanged,
17540    Saved,
17541    TitleChanged,
17542    DiffBaseChanged,
17543    SelectionsChanged {
17544        local: bool,
17545    },
17546    ScrollPositionChanged {
17547        local: bool,
17548        autoscroll: bool,
17549    },
17550    Closed,
17551    TransactionUndone {
17552        transaction_id: clock::Lamport,
17553    },
17554    TransactionBegun {
17555        transaction_id: clock::Lamport,
17556    },
17557    Reloaded,
17558    CursorShapeChanged,
17559}
17560
17561impl EventEmitter<EditorEvent> for Editor {}
17562
17563impl Focusable for Editor {
17564    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17565        self.focus_handle.clone()
17566    }
17567}
17568
17569impl Render for Editor {
17570    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17571        let settings = ThemeSettings::get_global(cx);
17572
17573        let mut text_style = match self.mode {
17574            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17575                color: cx.theme().colors().editor_foreground,
17576                font_family: settings.ui_font.family.clone(),
17577                font_features: settings.ui_font.features.clone(),
17578                font_fallbacks: settings.ui_font.fallbacks.clone(),
17579                font_size: rems(0.875).into(),
17580                font_weight: settings.ui_font.weight,
17581                line_height: relative(settings.buffer_line_height.value()),
17582                ..Default::default()
17583            },
17584            EditorMode::Full => TextStyle {
17585                color: cx.theme().colors().editor_foreground,
17586                font_family: settings.buffer_font.family.clone(),
17587                font_features: settings.buffer_font.features.clone(),
17588                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17589                font_size: settings.buffer_font_size(cx).into(),
17590                font_weight: settings.buffer_font.weight,
17591                line_height: relative(settings.buffer_line_height.value()),
17592                ..Default::default()
17593            },
17594        };
17595        if let Some(text_style_refinement) = &self.text_style_refinement {
17596            text_style.refine(text_style_refinement)
17597        }
17598
17599        let background = match self.mode {
17600            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17601            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17602            EditorMode::Full => cx.theme().colors().editor_background,
17603        };
17604
17605        EditorElement::new(
17606            &cx.entity(),
17607            EditorStyle {
17608                background,
17609                local_player: cx.theme().players().local(),
17610                text: text_style,
17611                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17612                syntax: cx.theme().syntax().clone(),
17613                status: cx.theme().status().clone(),
17614                inlay_hints_style: make_inlay_hints_style(cx),
17615                inline_completion_styles: make_suggestion_styles(cx),
17616                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17617            },
17618        )
17619    }
17620}
17621
17622impl EntityInputHandler for Editor {
17623    fn text_for_range(
17624        &mut self,
17625        range_utf16: Range<usize>,
17626        adjusted_range: &mut Option<Range<usize>>,
17627        _: &mut Window,
17628        cx: &mut Context<Self>,
17629    ) -> Option<String> {
17630        let snapshot = self.buffer.read(cx).read(cx);
17631        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17632        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17633        if (start.0..end.0) != range_utf16 {
17634            adjusted_range.replace(start.0..end.0);
17635        }
17636        Some(snapshot.text_for_range(start..end).collect())
17637    }
17638
17639    fn selected_text_range(
17640        &mut self,
17641        ignore_disabled_input: bool,
17642        _: &mut Window,
17643        cx: &mut Context<Self>,
17644    ) -> Option<UTF16Selection> {
17645        // Prevent the IME menu from appearing when holding down an alphabetic key
17646        // while input is disabled.
17647        if !ignore_disabled_input && !self.input_enabled {
17648            return None;
17649        }
17650
17651        let selection = self.selections.newest::<OffsetUtf16>(cx);
17652        let range = selection.range();
17653
17654        Some(UTF16Selection {
17655            range: range.start.0..range.end.0,
17656            reversed: selection.reversed,
17657        })
17658    }
17659
17660    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17661        let snapshot = self.buffer.read(cx).read(cx);
17662        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17663        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17664    }
17665
17666    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17667        self.clear_highlights::<InputComposition>(cx);
17668        self.ime_transaction.take();
17669    }
17670
17671    fn replace_text_in_range(
17672        &mut self,
17673        range_utf16: Option<Range<usize>>,
17674        text: &str,
17675        window: &mut Window,
17676        cx: &mut Context<Self>,
17677    ) {
17678        if !self.input_enabled {
17679            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17680            return;
17681        }
17682
17683        self.transact(window, cx, |this, window, cx| {
17684            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17685                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17686                Some(this.selection_replacement_ranges(range_utf16, cx))
17687            } else {
17688                this.marked_text_ranges(cx)
17689            };
17690
17691            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17692                let newest_selection_id = this.selections.newest_anchor().id;
17693                this.selections
17694                    .all::<OffsetUtf16>(cx)
17695                    .iter()
17696                    .zip(ranges_to_replace.iter())
17697                    .find_map(|(selection, range)| {
17698                        if selection.id == newest_selection_id {
17699                            Some(
17700                                (range.start.0 as isize - selection.head().0 as isize)
17701                                    ..(range.end.0 as isize - selection.head().0 as isize),
17702                            )
17703                        } else {
17704                            None
17705                        }
17706                    })
17707            });
17708
17709            cx.emit(EditorEvent::InputHandled {
17710                utf16_range_to_replace: range_to_replace,
17711                text: text.into(),
17712            });
17713
17714            if let Some(new_selected_ranges) = new_selected_ranges {
17715                this.change_selections(None, window, cx, |selections| {
17716                    selections.select_ranges(new_selected_ranges)
17717                });
17718                this.backspace(&Default::default(), window, cx);
17719            }
17720
17721            this.handle_input(text, window, cx);
17722        });
17723
17724        if let Some(transaction) = self.ime_transaction {
17725            self.buffer.update(cx, |buffer, cx| {
17726                buffer.group_until_transaction(transaction, cx);
17727            });
17728        }
17729
17730        self.unmark_text(window, cx);
17731    }
17732
17733    fn replace_and_mark_text_in_range(
17734        &mut self,
17735        range_utf16: Option<Range<usize>>,
17736        text: &str,
17737        new_selected_range_utf16: Option<Range<usize>>,
17738        window: &mut Window,
17739        cx: &mut Context<Self>,
17740    ) {
17741        if !self.input_enabled {
17742            return;
17743        }
17744
17745        let transaction = self.transact(window, cx, |this, window, cx| {
17746            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17747                let snapshot = this.buffer.read(cx).read(cx);
17748                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17749                    for marked_range in &mut marked_ranges {
17750                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17751                        marked_range.start.0 += relative_range_utf16.start;
17752                        marked_range.start =
17753                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17754                        marked_range.end =
17755                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17756                    }
17757                }
17758                Some(marked_ranges)
17759            } else if let Some(range_utf16) = range_utf16 {
17760                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17761                Some(this.selection_replacement_ranges(range_utf16, cx))
17762            } else {
17763                None
17764            };
17765
17766            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17767                let newest_selection_id = this.selections.newest_anchor().id;
17768                this.selections
17769                    .all::<OffsetUtf16>(cx)
17770                    .iter()
17771                    .zip(ranges_to_replace.iter())
17772                    .find_map(|(selection, range)| {
17773                        if selection.id == newest_selection_id {
17774                            Some(
17775                                (range.start.0 as isize - selection.head().0 as isize)
17776                                    ..(range.end.0 as isize - selection.head().0 as isize),
17777                            )
17778                        } else {
17779                            None
17780                        }
17781                    })
17782            });
17783
17784            cx.emit(EditorEvent::InputHandled {
17785                utf16_range_to_replace: range_to_replace,
17786                text: text.into(),
17787            });
17788
17789            if let Some(ranges) = ranges_to_replace {
17790                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17791            }
17792
17793            let marked_ranges = {
17794                let snapshot = this.buffer.read(cx).read(cx);
17795                this.selections
17796                    .disjoint_anchors()
17797                    .iter()
17798                    .map(|selection| {
17799                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17800                    })
17801                    .collect::<Vec<_>>()
17802            };
17803
17804            if text.is_empty() {
17805                this.unmark_text(window, cx);
17806            } else {
17807                this.highlight_text::<InputComposition>(
17808                    marked_ranges.clone(),
17809                    HighlightStyle {
17810                        underline: Some(UnderlineStyle {
17811                            thickness: px(1.),
17812                            color: None,
17813                            wavy: false,
17814                        }),
17815                        ..Default::default()
17816                    },
17817                    cx,
17818                );
17819            }
17820
17821            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17822            let use_autoclose = this.use_autoclose;
17823            let use_auto_surround = this.use_auto_surround;
17824            this.set_use_autoclose(false);
17825            this.set_use_auto_surround(false);
17826            this.handle_input(text, window, cx);
17827            this.set_use_autoclose(use_autoclose);
17828            this.set_use_auto_surround(use_auto_surround);
17829
17830            if let Some(new_selected_range) = new_selected_range_utf16 {
17831                let snapshot = this.buffer.read(cx).read(cx);
17832                let new_selected_ranges = marked_ranges
17833                    .into_iter()
17834                    .map(|marked_range| {
17835                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17836                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17837                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17838                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17839                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17840                    })
17841                    .collect::<Vec<_>>();
17842
17843                drop(snapshot);
17844                this.change_selections(None, window, cx, |selections| {
17845                    selections.select_ranges(new_selected_ranges)
17846                });
17847            }
17848        });
17849
17850        self.ime_transaction = self.ime_transaction.or(transaction);
17851        if let Some(transaction) = self.ime_transaction {
17852            self.buffer.update(cx, |buffer, cx| {
17853                buffer.group_until_transaction(transaction, cx);
17854            });
17855        }
17856
17857        if self.text_highlights::<InputComposition>(cx).is_none() {
17858            self.ime_transaction.take();
17859        }
17860    }
17861
17862    fn bounds_for_range(
17863        &mut self,
17864        range_utf16: Range<usize>,
17865        element_bounds: gpui::Bounds<Pixels>,
17866        window: &mut Window,
17867        cx: &mut Context<Self>,
17868    ) -> Option<gpui::Bounds<Pixels>> {
17869        let text_layout_details = self.text_layout_details(window);
17870        let gpui::Size {
17871            width: em_width,
17872            height: line_height,
17873        } = self.character_size(window);
17874
17875        let snapshot = self.snapshot(window, cx);
17876        let scroll_position = snapshot.scroll_position();
17877        let scroll_left = scroll_position.x * em_width;
17878
17879        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17880        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17881            + self.gutter_dimensions.width
17882            + self.gutter_dimensions.margin;
17883        let y = line_height * (start.row().as_f32() - scroll_position.y);
17884
17885        Some(Bounds {
17886            origin: element_bounds.origin + point(x, y),
17887            size: size(em_width, line_height),
17888        })
17889    }
17890
17891    fn character_index_for_point(
17892        &mut self,
17893        point: gpui::Point<Pixels>,
17894        _window: &mut Window,
17895        _cx: &mut Context<Self>,
17896    ) -> Option<usize> {
17897        let position_map = self.last_position_map.as_ref()?;
17898        if !position_map.text_hitbox.contains(&point) {
17899            return None;
17900        }
17901        let display_point = position_map.point_for_position(point).previous_valid;
17902        let anchor = position_map
17903            .snapshot
17904            .display_point_to_anchor(display_point, Bias::Left);
17905        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17906        Some(utf16_offset.0)
17907    }
17908}
17909
17910trait SelectionExt {
17911    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17912    fn spanned_rows(
17913        &self,
17914        include_end_if_at_line_start: bool,
17915        map: &DisplaySnapshot,
17916    ) -> Range<MultiBufferRow>;
17917}
17918
17919impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17920    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17921        let start = self
17922            .start
17923            .to_point(&map.buffer_snapshot)
17924            .to_display_point(map);
17925        let end = self
17926            .end
17927            .to_point(&map.buffer_snapshot)
17928            .to_display_point(map);
17929        if self.reversed {
17930            end..start
17931        } else {
17932            start..end
17933        }
17934    }
17935
17936    fn spanned_rows(
17937        &self,
17938        include_end_if_at_line_start: bool,
17939        map: &DisplaySnapshot,
17940    ) -> Range<MultiBufferRow> {
17941        let start = self.start.to_point(&map.buffer_snapshot);
17942        let mut end = self.end.to_point(&map.buffer_snapshot);
17943        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17944            end.row -= 1;
17945        }
17946
17947        let buffer_start = map.prev_line_boundary(start).0;
17948        let buffer_end = map.next_line_boundary(end).0;
17949        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17950    }
17951}
17952
17953impl<T: InvalidationRegion> InvalidationStack<T> {
17954    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17955    where
17956        S: Clone + ToOffset,
17957    {
17958        while let Some(region) = self.last() {
17959            let all_selections_inside_invalidation_ranges =
17960                if selections.len() == region.ranges().len() {
17961                    selections
17962                        .iter()
17963                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17964                        .all(|(selection, invalidation_range)| {
17965                            let head = selection.head().to_offset(buffer);
17966                            invalidation_range.start <= head && invalidation_range.end >= head
17967                        })
17968                } else {
17969                    false
17970                };
17971
17972            if all_selections_inside_invalidation_ranges {
17973                break;
17974            } else {
17975                self.pop();
17976            }
17977        }
17978    }
17979}
17980
17981impl<T> Default for InvalidationStack<T> {
17982    fn default() -> Self {
17983        Self(Default::default())
17984    }
17985}
17986
17987impl<T> Deref for InvalidationStack<T> {
17988    type Target = Vec<T>;
17989
17990    fn deref(&self) -> &Self::Target {
17991        &self.0
17992    }
17993}
17994
17995impl<T> DerefMut for InvalidationStack<T> {
17996    fn deref_mut(&mut self) -> &mut Self::Target {
17997        &mut self.0
17998    }
17999}
18000
18001impl InvalidationRegion for SnippetState {
18002    fn ranges(&self) -> &[Range<Anchor>] {
18003        &self.ranges[self.active_index]
18004    }
18005}
18006
18007pub fn diagnostic_block_renderer(
18008    diagnostic: Diagnostic,
18009    max_message_rows: Option<u8>,
18010    allow_closing: bool,
18011) -> RenderBlock {
18012    let (text_without_backticks, code_ranges) =
18013        highlight_diagnostic_message(&diagnostic, max_message_rows);
18014
18015    Arc::new(move |cx: &mut BlockContext| {
18016        let group_id: SharedString = cx.block_id.to_string().into();
18017
18018        let mut text_style = cx.window.text_style().clone();
18019        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18020        let theme_settings = ThemeSettings::get_global(cx);
18021        text_style.font_family = theme_settings.buffer_font.family.clone();
18022        text_style.font_style = theme_settings.buffer_font.style;
18023        text_style.font_features = theme_settings.buffer_font.features.clone();
18024        text_style.font_weight = theme_settings.buffer_font.weight;
18025
18026        let multi_line_diagnostic = diagnostic.message.contains('\n');
18027
18028        let buttons = |diagnostic: &Diagnostic| {
18029            if multi_line_diagnostic {
18030                v_flex()
18031            } else {
18032                h_flex()
18033            }
18034            .when(allow_closing, |div| {
18035                div.children(diagnostic.is_primary.then(|| {
18036                    IconButton::new("close-block", IconName::XCircle)
18037                        .icon_color(Color::Muted)
18038                        .size(ButtonSize::Compact)
18039                        .style(ButtonStyle::Transparent)
18040                        .visible_on_hover(group_id.clone())
18041                        .on_click(move |_click, window, cx| {
18042                            window.dispatch_action(Box::new(Cancel), cx)
18043                        })
18044                        .tooltip(|window, cx| {
18045                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18046                        })
18047                }))
18048            })
18049            .child(
18050                IconButton::new("copy-block", IconName::Copy)
18051                    .icon_color(Color::Muted)
18052                    .size(ButtonSize::Compact)
18053                    .style(ButtonStyle::Transparent)
18054                    .visible_on_hover(group_id.clone())
18055                    .on_click({
18056                        let message = diagnostic.message.clone();
18057                        move |_click, _, cx| {
18058                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18059                        }
18060                    })
18061                    .tooltip(Tooltip::text("Copy diagnostic message")),
18062            )
18063        };
18064
18065        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18066            AvailableSpace::min_size(),
18067            cx.window,
18068            cx.app,
18069        );
18070
18071        h_flex()
18072            .id(cx.block_id)
18073            .group(group_id.clone())
18074            .relative()
18075            .size_full()
18076            .block_mouse_down()
18077            .pl(cx.gutter_dimensions.width)
18078            .w(cx.max_width - cx.gutter_dimensions.full_width())
18079            .child(
18080                div()
18081                    .flex()
18082                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18083                    .flex_shrink(),
18084            )
18085            .child(buttons(&diagnostic))
18086            .child(div().flex().flex_shrink_0().child(
18087                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18088                    &text_style,
18089                    code_ranges.iter().map(|range| {
18090                        (
18091                            range.clone(),
18092                            HighlightStyle {
18093                                font_weight: Some(FontWeight::BOLD),
18094                                ..Default::default()
18095                            },
18096                        )
18097                    }),
18098                ),
18099            ))
18100            .into_any_element()
18101    })
18102}
18103
18104fn inline_completion_edit_text(
18105    current_snapshot: &BufferSnapshot,
18106    edits: &[(Range<Anchor>, String)],
18107    edit_preview: &EditPreview,
18108    include_deletions: bool,
18109    cx: &App,
18110) -> HighlightedText {
18111    let edits = edits
18112        .iter()
18113        .map(|(anchor, text)| {
18114            (
18115                anchor.start.text_anchor..anchor.end.text_anchor,
18116                text.clone(),
18117            )
18118        })
18119        .collect::<Vec<_>>();
18120
18121    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18122}
18123
18124pub fn highlight_diagnostic_message(
18125    diagnostic: &Diagnostic,
18126    mut max_message_rows: Option<u8>,
18127) -> (SharedString, Vec<Range<usize>>) {
18128    let mut text_without_backticks = String::new();
18129    let mut code_ranges = Vec::new();
18130
18131    if let Some(source) = &diagnostic.source {
18132        text_without_backticks.push_str(source);
18133        code_ranges.push(0..source.len());
18134        text_without_backticks.push_str(": ");
18135    }
18136
18137    let mut prev_offset = 0;
18138    let mut in_code_block = false;
18139    let has_row_limit = max_message_rows.is_some();
18140    let mut newline_indices = diagnostic
18141        .message
18142        .match_indices('\n')
18143        .filter(|_| has_row_limit)
18144        .map(|(ix, _)| ix)
18145        .fuse()
18146        .peekable();
18147
18148    for (quote_ix, _) in diagnostic
18149        .message
18150        .match_indices('`')
18151        .chain([(diagnostic.message.len(), "")])
18152    {
18153        let mut first_newline_ix = None;
18154        let mut last_newline_ix = None;
18155        while let Some(newline_ix) = newline_indices.peek() {
18156            if *newline_ix < quote_ix {
18157                if first_newline_ix.is_none() {
18158                    first_newline_ix = Some(*newline_ix);
18159                }
18160                last_newline_ix = Some(*newline_ix);
18161
18162                if let Some(rows_left) = &mut max_message_rows {
18163                    if *rows_left == 0 {
18164                        break;
18165                    } else {
18166                        *rows_left -= 1;
18167                    }
18168                }
18169                let _ = newline_indices.next();
18170            } else {
18171                break;
18172            }
18173        }
18174        let prev_len = text_without_backticks.len();
18175        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18176        text_without_backticks.push_str(new_text);
18177        if in_code_block {
18178            code_ranges.push(prev_len..text_without_backticks.len());
18179        }
18180        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18181        in_code_block = !in_code_block;
18182        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18183            text_without_backticks.push_str("...");
18184            break;
18185        }
18186    }
18187
18188    (text_without_backticks.into(), code_ranges)
18189}
18190
18191fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18192    match severity {
18193        DiagnosticSeverity::ERROR => colors.error,
18194        DiagnosticSeverity::WARNING => colors.warning,
18195        DiagnosticSeverity::INFORMATION => colors.info,
18196        DiagnosticSeverity::HINT => colors.info,
18197        _ => colors.ignored,
18198    }
18199}
18200
18201pub fn styled_runs_for_code_label<'a>(
18202    label: &'a CodeLabel,
18203    syntax_theme: &'a theme::SyntaxTheme,
18204) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18205    let fade_out = HighlightStyle {
18206        fade_out: Some(0.35),
18207        ..Default::default()
18208    };
18209
18210    let mut prev_end = label.filter_range.end;
18211    label
18212        .runs
18213        .iter()
18214        .enumerate()
18215        .flat_map(move |(ix, (range, highlight_id))| {
18216            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18217                style
18218            } else {
18219                return Default::default();
18220            };
18221            let mut muted_style = style;
18222            muted_style.highlight(fade_out);
18223
18224            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18225            if range.start >= label.filter_range.end {
18226                if range.start > prev_end {
18227                    runs.push((prev_end..range.start, fade_out));
18228                }
18229                runs.push((range.clone(), muted_style));
18230            } else if range.end <= label.filter_range.end {
18231                runs.push((range.clone(), style));
18232            } else {
18233                runs.push((range.start..label.filter_range.end, style));
18234                runs.push((label.filter_range.end..range.end, muted_style));
18235            }
18236            prev_end = cmp::max(prev_end, range.end);
18237
18238            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18239                runs.push((prev_end..label.text.len(), fade_out));
18240            }
18241
18242            runs
18243        })
18244}
18245
18246pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18247    let mut prev_index = 0;
18248    let mut prev_codepoint: Option<char> = None;
18249    text.char_indices()
18250        .chain([(text.len(), '\0')])
18251        .filter_map(move |(index, codepoint)| {
18252            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18253            let is_boundary = index == text.len()
18254                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18255                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18256            if is_boundary {
18257                let chunk = &text[prev_index..index];
18258                prev_index = index;
18259                Some(chunk)
18260            } else {
18261                None
18262            }
18263        })
18264}
18265
18266pub trait RangeToAnchorExt: Sized {
18267    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18268
18269    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18270        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18271        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18272    }
18273}
18274
18275impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18276    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18277        let start_offset = self.start.to_offset(snapshot);
18278        let end_offset = self.end.to_offset(snapshot);
18279        if start_offset == end_offset {
18280            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18281        } else {
18282            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18283        }
18284    }
18285}
18286
18287pub trait RowExt {
18288    fn as_f32(&self) -> f32;
18289
18290    fn next_row(&self) -> Self;
18291
18292    fn previous_row(&self) -> Self;
18293
18294    fn minus(&self, other: Self) -> u32;
18295}
18296
18297impl RowExt for DisplayRow {
18298    fn as_f32(&self) -> f32 {
18299        self.0 as f32
18300    }
18301
18302    fn next_row(&self) -> Self {
18303        Self(self.0 + 1)
18304    }
18305
18306    fn previous_row(&self) -> Self {
18307        Self(self.0.saturating_sub(1))
18308    }
18309
18310    fn minus(&self, other: Self) -> u32 {
18311        self.0 - other.0
18312    }
18313}
18314
18315impl RowExt for MultiBufferRow {
18316    fn as_f32(&self) -> f32 {
18317        self.0 as f32
18318    }
18319
18320    fn next_row(&self) -> Self {
18321        Self(self.0 + 1)
18322    }
18323
18324    fn previous_row(&self) -> Self {
18325        Self(self.0.saturating_sub(1))
18326    }
18327
18328    fn minus(&self, other: Self) -> u32 {
18329        self.0 - other.0
18330    }
18331}
18332
18333trait RowRangeExt {
18334    type Row;
18335
18336    fn len(&self) -> usize;
18337
18338    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18339}
18340
18341impl RowRangeExt for Range<MultiBufferRow> {
18342    type Row = MultiBufferRow;
18343
18344    fn len(&self) -> usize {
18345        (self.end.0 - self.start.0) as usize
18346    }
18347
18348    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18349        (self.start.0..self.end.0).map(MultiBufferRow)
18350    }
18351}
18352
18353impl RowRangeExt for Range<DisplayRow> {
18354    type Row = DisplayRow;
18355
18356    fn len(&self) -> usize {
18357        (self.end.0 - self.start.0) as usize
18358    }
18359
18360    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18361        (self.start.0..self.end.0).map(DisplayRow)
18362    }
18363}
18364
18365/// If select range has more than one line, we
18366/// just point the cursor to range.start.
18367fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18368    if range.start.row == range.end.row {
18369        range
18370    } else {
18371        range.start..range.start
18372    }
18373}
18374pub struct KillRing(ClipboardItem);
18375impl Global for KillRing {}
18376
18377const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18378
18379fn all_edits_insertions_or_deletions(
18380    edits: &Vec<(Range<Anchor>, String)>,
18381    snapshot: &MultiBufferSnapshot,
18382) -> bool {
18383    let mut all_insertions = true;
18384    let mut all_deletions = true;
18385
18386    for (range, new_text) in edits.iter() {
18387        let range_is_empty = range.to_offset(&snapshot).is_empty();
18388        let text_is_empty = new_text.is_empty();
18389
18390        if range_is_empty != text_is_empty {
18391            if range_is_empty {
18392                all_deletions = false;
18393            } else {
18394                all_insertions = false;
18395            }
18396        } else {
18397            return false;
18398        }
18399
18400        if !all_insertions && !all_deletions {
18401            return false;
18402        }
18403    }
18404    all_insertions || all_deletions
18405}
18406
18407struct MissingEditPredictionKeybindingTooltip;
18408
18409impl Render for MissingEditPredictionKeybindingTooltip {
18410    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18411        ui::tooltip_container(window, cx, |container, _, cx| {
18412            container
18413                .flex_shrink_0()
18414                .max_w_80()
18415                .min_h(rems_from_px(124.))
18416                .justify_between()
18417                .child(
18418                    v_flex()
18419                        .flex_1()
18420                        .text_ui_sm(cx)
18421                        .child(Label::new("Conflict with Accept Keybinding"))
18422                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18423                )
18424                .child(
18425                    h_flex()
18426                        .pb_1()
18427                        .gap_1()
18428                        .items_end()
18429                        .w_full()
18430                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18431                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18432                        }))
18433                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18434                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18435                        })),
18436                )
18437        })
18438    }
18439}