editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   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::{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 code_context_menus::{
   77    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   78    CompletionsMenu, ContextMenuOrigin,
   79};
   80use git::blame::GitBlame;
   81use gpui::{
   82    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   83    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry,
   84    ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter,
   85    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   86    InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement,
   87    Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task, TextStyle,
   88    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
   89    WeakFocusHandle, Window,
   90};
   91use highlight_matching_bracket::refresh_matching_bracket_highlights;
   92use hover_popover::{hide_hover, HoverState};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
  103    HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
  104    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  105};
  106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  107use linked_editing_ranges::refresh_linked_ranges;
  108use mouse_context_menu::MouseContextMenu;
  109pub use proposed_changes_editor::{
  110    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  111};
  112use similar::{ChangeTag, TextDiff};
  113use std::iter::Peekable;
  114use task::{ResolvedTask, TaskTemplate, TaskVariables};
  115
  116use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  117pub use lsp::CompletionContext;
  118use lsp::{
  119    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  120    LanguageServerId, LanguageServerName,
  121};
  122
  123use language::BufferSnapshot;
  124use movement::TextLayoutDetails;
  125pub use multi_buffer::{
  126    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  127    ToOffset, ToPoint,
  128};
  129use multi_buffer::{
  130    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  131    ToOffsetUtf16,
  132};
  133use project::{
  134    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  135    project_settings::{GitGutterSetting, ProjectSettings},
  136    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  137    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  138};
  139use rand::prelude::*;
  140use rpc::{proto::*, ErrorExt};
  141use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  142use selections_collection::{
  143    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  144};
  145use serde::{Deserialize, Serialize};
  146use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  147use smallvec::SmallVec;
  148use snippet::Snippet;
  149use std::{
  150    any::TypeId,
  151    borrow::Cow,
  152    cell::RefCell,
  153    cmp::{self, Ordering, Reverse},
  154    mem,
  155    num::NonZeroU32,
  156    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  157    path::{Path, PathBuf},
  158    rc::Rc,
  159    sync::Arc,
  160    time::{Duration, Instant},
  161};
  162pub use sum_tree::Bias;
  163use sum_tree::TreeMap;
  164use text::{BufferId, OffsetUtf16, Rope};
  165use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  166use ui::{
  167    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  168    Tooltip,
  169};
  170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  171use workspace::item::{ItemHandle, PreviewTabsSettings};
  172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  173use workspace::{
  174    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  175};
  176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  177
  178use crate::hover_links::{find_url, find_url_from_range};
  179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  180
  181pub const FILE_HEADER_HEIGHT: u32 = 2;
  182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  186const MAX_LINE_LEN: usize = 1024;
  187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  190#[doc(hidden)]
  191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  192
  193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  195
  196pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  197pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  198
  199pub fn render_parsed_markdown(
  200    element_id: impl Into<ElementId>,
  201    parsed: &language::ParsedMarkdown,
  202    editor_style: &EditorStyle,
  203    workspace: Option<WeakEntity<Workspace>>,
  204    cx: &mut App,
  205) -> InteractiveText {
  206    let code_span_background_color = cx
  207        .theme()
  208        .colors()
  209        .editor_document_highlight_read_background;
  210
  211    let highlights = gpui::combine_highlights(
  212        parsed.highlights.iter().filter_map(|(range, highlight)| {
  213            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  214            Some((range.clone(), highlight))
  215        }),
  216        parsed
  217            .regions
  218            .iter()
  219            .zip(&parsed.region_ranges)
  220            .filter_map(|(region, range)| {
  221                if region.code {
  222                    Some((
  223                        range.clone(),
  224                        HighlightStyle {
  225                            background_color: Some(code_span_background_color),
  226                            ..Default::default()
  227                        },
  228                    ))
  229                } else {
  230                    None
  231                }
  232            }),
  233    );
  234
  235    let mut links = Vec::new();
  236    let mut link_ranges = Vec::new();
  237    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  238        if let Some(link) = region.link.clone() {
  239            links.push(link);
  240            link_ranges.push(range.clone());
  241        }
  242    }
  243
  244    InteractiveText::new(
  245        element_id,
  246        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  247    )
  248    .on_click(
  249        link_ranges,
  250        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  251            markdown::Link::Web { url } => cx.open_url(url),
  252            markdown::Link::Path { path } => {
  253                if let Some(workspace) = &workspace {
  254                    _ = workspace.update(cx, |workspace, cx| {
  255                        workspace
  256                            .open_abs_path(path.clone(), false, window, cx)
  257                            .detach();
  258                    });
  259                }
  260            }
  261        },
  262    )
  263}
  264
  265#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  266pub enum InlayId {
  267    InlineCompletion(usize),
  268    Hint(usize),
  269}
  270
  271impl InlayId {
  272    fn id(&self) -> usize {
  273        match self {
  274            Self::InlineCompletion(id) => *id,
  275            Self::Hint(id) => *id,
  276        }
  277    }
  278}
  279
  280enum DocumentHighlightRead {}
  281enum DocumentHighlightWrite {}
  282enum InputComposition {}
  283
  284#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  285pub enum Navigated {
  286    Yes,
  287    No,
  288}
  289
  290impl Navigated {
  291    pub fn from_bool(yes: bool) -> Navigated {
  292        if yes {
  293            Navigated::Yes
  294        } else {
  295            Navigated::No
  296        }
  297    }
  298}
  299
  300pub fn init_settings(cx: &mut App) {
  301    EditorSettings::register(cx);
  302}
  303
  304pub fn init(cx: &mut App) {
  305    init_settings(cx);
  306
  307    workspace::register_project_item::<Editor>(cx);
  308    workspace::FollowableViewRegistry::register::<Editor>(cx);
  309    workspace::register_serializable_item::<Editor>(cx);
  310
  311    cx.observe_new(
  312        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  313            workspace.register_action(Editor::new_file);
  314            workspace.register_action(Editor::new_file_vertical);
  315            workspace.register_action(Editor::new_file_horizontal);
  316            workspace.register_action(Editor::cancel_language_server_work);
  317        },
  318    )
  319    .detach();
  320
  321    cx.on_action(move |_: &workspace::NewFile, cx| {
  322        let app_state = workspace::AppState::global(cx);
  323        if let Some(app_state) = app_state.upgrade() {
  324            workspace::open_new(
  325                Default::default(),
  326                app_state,
  327                cx,
  328                |workspace, window, cx| {
  329                    Editor::new_file(workspace, &Default::default(), window, cx)
  330                },
  331            )
  332            .detach();
  333        }
  334    });
  335    cx.on_action(move |_: &workspace::NewWindow, cx| {
  336        let app_state = workspace::AppState::global(cx);
  337        if let Some(app_state) = app_state.upgrade() {
  338            workspace::open_new(
  339                Default::default(),
  340                app_state,
  341                cx,
  342                |workspace, window, cx| {
  343                    cx.activate(true);
  344                    Editor::new_file(workspace, &Default::default(), window, cx)
  345                },
  346            )
  347            .detach();
  348        }
  349    });
  350}
  351
  352pub struct SearchWithinRange;
  353
  354trait InvalidationRegion {
  355    fn ranges(&self) -> &[Range<Anchor>];
  356}
  357
  358#[derive(Clone, Debug, PartialEq)]
  359pub enum SelectPhase {
  360    Begin {
  361        position: DisplayPoint,
  362        add: bool,
  363        click_count: usize,
  364    },
  365    BeginColumnar {
  366        position: DisplayPoint,
  367        reset: bool,
  368        goal_column: u32,
  369    },
  370    Extend {
  371        position: DisplayPoint,
  372        click_count: usize,
  373    },
  374    Update {
  375        position: DisplayPoint,
  376        goal_column: u32,
  377        scroll_delta: gpui::Point<f32>,
  378    },
  379    End,
  380}
  381
  382#[derive(Clone, Debug)]
  383pub enum SelectMode {
  384    Character,
  385    Word(Range<Anchor>),
  386    Line(Range<Anchor>),
  387    All,
  388}
  389
  390#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  391pub enum EditorMode {
  392    SingleLine { auto_width: bool },
  393    AutoHeight { max_lines: usize },
  394    Full,
  395}
  396
  397#[derive(Copy, Clone, Debug)]
  398pub enum SoftWrap {
  399    /// Prefer not to wrap at all.
  400    ///
  401    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  402    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  403    GitDiff,
  404    /// Prefer a single line generally, unless an overly long line is encountered.
  405    None,
  406    /// Soft wrap lines that exceed the editor width.
  407    EditorWidth,
  408    /// Soft wrap lines at the preferred line length.
  409    Column(u32),
  410    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  411    Bounded(u32),
  412}
  413
  414#[derive(Clone)]
  415pub struct EditorStyle {
  416    pub background: Hsla,
  417    pub local_player: PlayerColor,
  418    pub text: TextStyle,
  419    pub scrollbar_width: Pixels,
  420    pub syntax: Arc<SyntaxTheme>,
  421    pub status: StatusColors,
  422    pub inlay_hints_style: HighlightStyle,
  423    pub inline_completion_styles: InlineCompletionStyles,
  424    pub unnecessary_code_fade: f32,
  425}
  426
  427impl Default for EditorStyle {
  428    fn default() -> Self {
  429        Self {
  430            background: Hsla::default(),
  431            local_player: PlayerColor::default(),
  432            text: TextStyle::default(),
  433            scrollbar_width: Pixels::default(),
  434            syntax: Default::default(),
  435            // HACK: Status colors don't have a real default.
  436            // We should look into removing the status colors from the editor
  437            // style and retrieve them directly from the theme.
  438            status: StatusColors::dark(),
  439            inlay_hints_style: HighlightStyle::default(),
  440            inline_completion_styles: InlineCompletionStyles {
  441                insertion: HighlightStyle::default(),
  442                whitespace: HighlightStyle::default(),
  443            },
  444            unnecessary_code_fade: Default::default(),
  445        }
  446    }
  447}
  448
  449pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  450    let show_background = language_settings::language_settings(None, None, cx)
  451        .inlay_hints
  452        .show_background;
  453
  454    HighlightStyle {
  455        color: Some(cx.theme().status().hint),
  456        background_color: show_background.then(|| cx.theme().status().hint_background),
  457        ..HighlightStyle::default()
  458    }
  459}
  460
  461pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  462    InlineCompletionStyles {
  463        insertion: HighlightStyle {
  464            color: Some(cx.theme().status().predictive),
  465            ..HighlightStyle::default()
  466        },
  467        whitespace: HighlightStyle {
  468            background_color: Some(cx.theme().status().created_background),
  469            ..HighlightStyle::default()
  470        },
  471    }
  472}
  473
  474type CompletionId = usize;
  475
  476pub(crate) enum EditDisplayMode {
  477    TabAccept,
  478    DiffPopover,
  479    Inline,
  480}
  481
  482enum InlineCompletion {
  483    Edit {
  484        edits: Vec<(Range<Anchor>, String)>,
  485        edit_preview: Option<EditPreview>,
  486        display_mode: EditDisplayMode,
  487        snapshot: BufferSnapshot,
  488    },
  489    Move {
  490        target: Anchor,
  491        snapshot: BufferSnapshot,
  492    },
  493}
  494
  495struct InlineCompletionState {
  496    inlay_ids: Vec<InlayId>,
  497    completion: InlineCompletion,
  498    completion_id: Option<SharedString>,
  499    invalidation_range: Range<Anchor>,
  500}
  501
  502enum EditPredictionSettings {
  503    Disabled,
  504    Enabled {
  505        show_in_menu: bool,
  506        preview_requires_modifier: bool,
  507    },
  508}
  509
  510impl EditPredictionSettings {
  511    pub fn is_enabled(&self) -> bool {
  512        match self {
  513            EditPredictionSettings::Disabled => false,
  514            EditPredictionSettings::Enabled { .. } => true,
  515        }
  516    }
  517}
  518
  519enum InlineCompletionHighlight {}
  520
  521pub enum MenuInlineCompletionsPolicy {
  522    Never,
  523    ByProvider,
  524}
  525
  526pub enum EditPredictionPreview {
  527    /// Modifier is not pressed
  528    Inactive,
  529    /// Modifier pressed
  530    Active {
  531        previous_scroll_position: Option<ScrollAnchor>,
  532    },
  533}
  534
  535#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  536struct EditorActionId(usize);
  537
  538impl EditorActionId {
  539    pub fn post_inc(&mut self) -> Self {
  540        let answer = self.0;
  541
  542        *self = Self(answer + 1);
  543
  544        Self(answer)
  545    }
  546}
  547
  548// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  549// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  550
  551type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  552type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  553
  554#[derive(Default)]
  555struct ScrollbarMarkerState {
  556    scrollbar_size: Size<Pixels>,
  557    dirty: bool,
  558    markers: Arc<[PaintQuad]>,
  559    pending_refresh: Option<Task<Result<()>>>,
  560}
  561
  562impl ScrollbarMarkerState {
  563    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  564        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  565    }
  566}
  567
  568#[derive(Clone, Debug)]
  569struct RunnableTasks {
  570    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  571    offset: MultiBufferOffset,
  572    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  573    column: u32,
  574    // Values of all named captures, including those starting with '_'
  575    extra_variables: HashMap<String, String>,
  576    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  577    context_range: Range<BufferOffset>,
  578}
  579
  580impl RunnableTasks {
  581    fn resolve<'a>(
  582        &'a self,
  583        cx: &'a task::TaskContext,
  584    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  585        self.templates.iter().filter_map(|(kind, template)| {
  586            template
  587                .resolve_task(&kind.to_id_base(), cx)
  588                .map(|task| (kind.clone(), task))
  589        })
  590    }
  591}
  592
  593#[derive(Clone)]
  594struct ResolvedTasks {
  595    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  596    position: Anchor,
  597}
  598#[derive(Copy, Clone, Debug)]
  599struct MultiBufferOffset(usize);
  600#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  601struct BufferOffset(usize);
  602
  603// Addons allow storing per-editor state in other crates (e.g. Vim)
  604pub trait Addon: 'static {
  605    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  606
  607    fn render_buffer_header_controls(
  608        &self,
  609        _: &ExcerptInfo,
  610        _: &Window,
  611        _: &App,
  612    ) -> Option<AnyElement> {
  613        None
  614    }
  615
  616    fn to_any(&self) -> &dyn std::any::Any;
  617}
  618
  619#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  620pub enum IsVimMode {
  621    Yes,
  622    No,
  623}
  624
  625/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  626///
  627/// See the [module level documentation](self) for more information.
  628pub struct Editor {
  629    focus_handle: FocusHandle,
  630    last_focused_descendant: Option<WeakFocusHandle>,
  631    /// The text buffer being edited
  632    buffer: Entity<MultiBuffer>,
  633    /// Map of how text in the buffer should be displayed.
  634    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  635    pub display_map: Entity<DisplayMap>,
  636    pub selections: SelectionsCollection,
  637    pub scroll_manager: ScrollManager,
  638    /// When inline assist editors are linked, they all render cursors because
  639    /// typing enters text into each of them, even the ones that aren't focused.
  640    pub(crate) show_cursor_when_unfocused: bool,
  641    columnar_selection_tail: Option<Anchor>,
  642    add_selections_state: Option<AddSelectionsState>,
  643    select_next_state: Option<SelectNextState>,
  644    select_prev_state: Option<SelectNextState>,
  645    selection_history: SelectionHistory,
  646    autoclose_regions: Vec<AutocloseRegion>,
  647    snippet_stack: InvalidationStack<SnippetState>,
  648    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  649    ime_transaction: Option<TransactionId>,
  650    active_diagnostics: Option<ActiveDiagnosticGroup>,
  651    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  652
  653    // TODO: make this a access method
  654    pub project: Option<Entity<Project>>,
  655    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  656    completion_provider: Option<Box<dyn CompletionProvider>>,
  657    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  658    blink_manager: Entity<BlinkManager>,
  659    show_cursor_names: bool,
  660    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  661    pub show_local_selections: bool,
  662    mode: EditorMode,
  663    show_breadcrumbs: bool,
  664    show_gutter: bool,
  665    show_scrollbars: bool,
  666    show_line_numbers: Option<bool>,
  667    use_relative_line_numbers: Option<bool>,
  668    show_git_diff_gutter: Option<bool>,
  669    show_code_actions: Option<bool>,
  670    show_runnables: Option<bool>,
  671    show_wrap_guides: Option<bool>,
  672    show_indent_guides: Option<bool>,
  673    placeholder_text: Option<Arc<str>>,
  674    highlight_order: usize,
  675    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  676    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  677    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  678    scrollbar_marker_state: ScrollbarMarkerState,
  679    active_indent_guides_state: ActiveIndentGuidesState,
  680    nav_history: Option<ItemNavHistory>,
  681    context_menu: RefCell<Option<CodeContextMenu>>,
  682    mouse_context_menu: Option<MouseContextMenu>,
  683    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  684    signature_help_state: SignatureHelpState,
  685    auto_signature_help: Option<bool>,
  686    find_all_references_task_sources: Vec<Anchor>,
  687    next_completion_id: CompletionId,
  688    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  689    code_actions_task: Option<Task<Result<()>>>,
  690    document_highlights_task: Option<Task<()>>,
  691    linked_editing_range_task: Option<Task<Option<()>>>,
  692    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  693    pending_rename: Option<RenameState>,
  694    searchable: bool,
  695    cursor_shape: CursorShape,
  696    current_line_highlight: Option<CurrentLineHighlight>,
  697    collapse_matches: bool,
  698    autoindent_mode: Option<AutoindentMode>,
  699    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  700    input_enabled: bool,
  701    use_modal_editing: bool,
  702    read_only: bool,
  703    leader_peer_id: Option<PeerId>,
  704    remote_id: Option<ViewId>,
  705    hover_state: HoverState,
  706    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  707    gutter_hovered: bool,
  708    hovered_link_state: Option<HoveredLinkState>,
  709    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  710    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  711    active_inline_completion: Option<InlineCompletionState>,
  712    /// Used to prevent flickering as the user types while the menu is open
  713    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  714    edit_prediction_settings: EditPredictionSettings,
  715    inline_completions_hidden_for_vim_mode: bool,
  716    show_inline_completions_override: Option<bool>,
  717    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  718    edit_prediction_preview: EditPredictionPreview,
  719    edit_prediction_cursor_on_leading_whitespace: bool,
  720    edit_prediction_requires_modifier_in_leading_space: bool,
  721    inlay_hint_cache: InlayHintCache,
  722    next_inlay_id: usize,
  723    _subscriptions: Vec<Subscription>,
  724    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  725    gutter_dimensions: GutterDimensions,
  726    style: Option<EditorStyle>,
  727    text_style_refinement: Option<TextStyleRefinement>,
  728    next_editor_action_id: EditorActionId,
  729    editor_actions:
  730        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  731    use_autoclose: bool,
  732    use_auto_surround: bool,
  733    auto_replace_emoji_shortcode: bool,
  734    show_git_blame_gutter: bool,
  735    show_git_blame_inline: bool,
  736    show_git_blame_inline_delay_task: Option<Task<()>>,
  737    distinguish_unstaged_diff_hunks: bool,
  738    git_blame_inline_enabled: bool,
  739    serialize_dirty_buffers: bool,
  740    show_selection_menu: Option<bool>,
  741    blame: Option<Entity<GitBlame>>,
  742    blame_subscription: Option<Subscription>,
  743    custom_context_menu: Option<
  744        Box<
  745            dyn 'static
  746                + Fn(
  747                    &mut Self,
  748                    DisplayPoint,
  749                    &mut Window,
  750                    &mut Context<Self>,
  751                ) -> Option<Entity<ui::ContextMenu>>,
  752        >,
  753    >,
  754    last_bounds: Option<Bounds<Pixels>>,
  755    last_position_map: Option<Rc<PositionMap>>,
  756    expect_bounds_change: Option<Bounds<Pixels>>,
  757    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  758    tasks_update_task: Option<Task<()>>,
  759    in_project_search: bool,
  760    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  761    breadcrumb_header: Option<String>,
  762    focused_block: Option<FocusedBlock>,
  763    next_scroll_position: NextScrollCursorCenterTopBottom,
  764    addons: HashMap<TypeId, Box<dyn Addon>>,
  765    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  766    load_diff_task: Option<Shared<Task<()>>>,
  767    selection_mark_mode: bool,
  768    toggle_fold_multiple_buffers: Task<()>,
  769    _scroll_cursor_center_top_bottom_task: Task<()>,
  770}
  771
  772#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  773enum NextScrollCursorCenterTopBottom {
  774    #[default]
  775    Center,
  776    Top,
  777    Bottom,
  778}
  779
  780impl NextScrollCursorCenterTopBottom {
  781    fn next(&self) -> Self {
  782        match self {
  783            Self::Center => Self::Top,
  784            Self::Top => Self::Bottom,
  785            Self::Bottom => Self::Center,
  786        }
  787    }
  788}
  789
  790#[derive(Clone)]
  791pub struct EditorSnapshot {
  792    pub mode: EditorMode,
  793    show_gutter: bool,
  794    show_line_numbers: Option<bool>,
  795    show_git_diff_gutter: Option<bool>,
  796    show_code_actions: Option<bool>,
  797    show_runnables: Option<bool>,
  798    git_blame_gutter_max_author_length: Option<usize>,
  799    pub display_snapshot: DisplaySnapshot,
  800    pub placeholder_text: Option<Arc<str>>,
  801    is_focused: bool,
  802    scroll_anchor: ScrollAnchor,
  803    ongoing_scroll: OngoingScroll,
  804    current_line_highlight: CurrentLineHighlight,
  805    gutter_hovered: bool,
  806}
  807
  808const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  809
  810#[derive(Default, Debug, Clone, Copy)]
  811pub struct GutterDimensions {
  812    pub left_padding: Pixels,
  813    pub right_padding: Pixels,
  814    pub width: Pixels,
  815    pub margin: Pixels,
  816    pub git_blame_entries_width: Option<Pixels>,
  817}
  818
  819impl GutterDimensions {
  820    /// The full width of the space taken up by the gutter.
  821    pub fn full_width(&self) -> Pixels {
  822        self.margin + self.width
  823    }
  824
  825    /// The width of the space reserved for the fold indicators,
  826    /// use alongside 'justify_end' and `gutter_width` to
  827    /// right align content with the line numbers
  828    pub fn fold_area_width(&self) -> Pixels {
  829        self.margin + self.right_padding
  830    }
  831}
  832
  833#[derive(Debug)]
  834pub struct RemoteSelection {
  835    pub replica_id: ReplicaId,
  836    pub selection: Selection<Anchor>,
  837    pub cursor_shape: CursorShape,
  838    pub peer_id: PeerId,
  839    pub line_mode: bool,
  840    pub participant_index: Option<ParticipantIndex>,
  841    pub user_name: Option<SharedString>,
  842}
  843
  844#[derive(Clone, Debug)]
  845struct SelectionHistoryEntry {
  846    selections: Arc<[Selection<Anchor>]>,
  847    select_next_state: Option<SelectNextState>,
  848    select_prev_state: Option<SelectNextState>,
  849    add_selections_state: Option<AddSelectionsState>,
  850}
  851
  852enum SelectionHistoryMode {
  853    Normal,
  854    Undoing,
  855    Redoing,
  856}
  857
  858#[derive(Clone, PartialEq, Eq, Hash)]
  859struct HoveredCursor {
  860    replica_id: u16,
  861    selection_id: usize,
  862}
  863
  864impl Default for SelectionHistoryMode {
  865    fn default() -> Self {
  866        Self::Normal
  867    }
  868}
  869
  870#[derive(Default)]
  871struct SelectionHistory {
  872    #[allow(clippy::type_complexity)]
  873    selections_by_transaction:
  874        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  875    mode: SelectionHistoryMode,
  876    undo_stack: VecDeque<SelectionHistoryEntry>,
  877    redo_stack: VecDeque<SelectionHistoryEntry>,
  878}
  879
  880impl SelectionHistory {
  881    fn insert_transaction(
  882        &mut self,
  883        transaction_id: TransactionId,
  884        selections: Arc<[Selection<Anchor>]>,
  885    ) {
  886        self.selections_by_transaction
  887            .insert(transaction_id, (selections, None));
  888    }
  889
  890    #[allow(clippy::type_complexity)]
  891    fn transaction(
  892        &self,
  893        transaction_id: TransactionId,
  894    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  895        self.selections_by_transaction.get(&transaction_id)
  896    }
  897
  898    #[allow(clippy::type_complexity)]
  899    fn transaction_mut(
  900        &mut self,
  901        transaction_id: TransactionId,
  902    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  903        self.selections_by_transaction.get_mut(&transaction_id)
  904    }
  905
  906    fn push(&mut self, entry: SelectionHistoryEntry) {
  907        if !entry.selections.is_empty() {
  908            match self.mode {
  909                SelectionHistoryMode::Normal => {
  910                    self.push_undo(entry);
  911                    self.redo_stack.clear();
  912                }
  913                SelectionHistoryMode::Undoing => self.push_redo(entry),
  914                SelectionHistoryMode::Redoing => self.push_undo(entry),
  915            }
  916        }
  917    }
  918
  919    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  920        if self
  921            .undo_stack
  922            .back()
  923            .map_or(true, |e| e.selections != entry.selections)
  924        {
  925            self.undo_stack.push_back(entry);
  926            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  927                self.undo_stack.pop_front();
  928            }
  929        }
  930    }
  931
  932    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  933        if self
  934            .redo_stack
  935            .back()
  936            .map_or(true, |e| e.selections != entry.selections)
  937        {
  938            self.redo_stack.push_back(entry);
  939            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  940                self.redo_stack.pop_front();
  941            }
  942        }
  943    }
  944}
  945
  946struct RowHighlight {
  947    index: usize,
  948    range: Range<Anchor>,
  949    color: Hsla,
  950    should_autoscroll: bool,
  951}
  952
  953#[derive(Clone, Debug)]
  954struct AddSelectionsState {
  955    above: bool,
  956    stack: Vec<usize>,
  957}
  958
  959#[derive(Clone)]
  960struct SelectNextState {
  961    query: AhoCorasick,
  962    wordwise: bool,
  963    done: bool,
  964}
  965
  966impl std::fmt::Debug for SelectNextState {
  967    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  968        f.debug_struct(std::any::type_name::<Self>())
  969            .field("wordwise", &self.wordwise)
  970            .field("done", &self.done)
  971            .finish()
  972    }
  973}
  974
  975#[derive(Debug)]
  976struct AutocloseRegion {
  977    selection_id: usize,
  978    range: Range<Anchor>,
  979    pair: BracketPair,
  980}
  981
  982#[derive(Debug)]
  983struct SnippetState {
  984    ranges: Vec<Vec<Range<Anchor>>>,
  985    active_index: usize,
  986    choices: Vec<Option<Vec<String>>>,
  987}
  988
  989#[doc(hidden)]
  990pub struct RenameState {
  991    pub range: Range<Anchor>,
  992    pub old_name: Arc<str>,
  993    pub editor: Entity<Editor>,
  994    block_id: CustomBlockId,
  995}
  996
  997struct InvalidationStack<T>(Vec<T>);
  998
  999struct RegisteredInlineCompletionProvider {
 1000    provider: Arc<dyn InlineCompletionProviderHandle>,
 1001    _subscription: Subscription,
 1002}
 1003
 1004#[derive(Debug)]
 1005struct ActiveDiagnosticGroup {
 1006    primary_range: Range<Anchor>,
 1007    primary_message: String,
 1008    group_id: usize,
 1009    blocks: HashMap<CustomBlockId, Diagnostic>,
 1010    is_valid: bool,
 1011}
 1012
 1013#[derive(Serialize, Deserialize, Clone, Debug)]
 1014pub struct ClipboardSelection {
 1015    pub len: usize,
 1016    pub is_entire_line: bool,
 1017    pub first_line_indent: u32,
 1018}
 1019
 1020#[derive(Debug)]
 1021pub(crate) struct NavigationData {
 1022    cursor_anchor: Anchor,
 1023    cursor_position: Point,
 1024    scroll_anchor: ScrollAnchor,
 1025    scroll_top_row: u32,
 1026}
 1027
 1028#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1029pub enum GotoDefinitionKind {
 1030    Symbol,
 1031    Declaration,
 1032    Type,
 1033    Implementation,
 1034}
 1035
 1036#[derive(Debug, Clone)]
 1037enum InlayHintRefreshReason {
 1038    Toggle(bool),
 1039    SettingsChange(InlayHintSettings),
 1040    NewLinesShown,
 1041    BufferEdited(HashSet<Arc<Language>>),
 1042    RefreshRequested,
 1043    ExcerptsRemoved(Vec<ExcerptId>),
 1044}
 1045
 1046impl InlayHintRefreshReason {
 1047    fn description(&self) -> &'static str {
 1048        match self {
 1049            Self::Toggle(_) => "toggle",
 1050            Self::SettingsChange(_) => "settings change",
 1051            Self::NewLinesShown => "new lines shown",
 1052            Self::BufferEdited(_) => "buffer edited",
 1053            Self::RefreshRequested => "refresh requested",
 1054            Self::ExcerptsRemoved(_) => "excerpts removed",
 1055        }
 1056    }
 1057}
 1058
 1059pub enum FormatTarget {
 1060    Buffers,
 1061    Ranges(Vec<Range<MultiBufferPoint>>),
 1062}
 1063
 1064pub(crate) struct FocusedBlock {
 1065    id: BlockId,
 1066    focus_handle: WeakFocusHandle,
 1067}
 1068
 1069#[derive(Clone)]
 1070enum JumpData {
 1071    MultiBufferRow {
 1072        row: MultiBufferRow,
 1073        line_offset_from_top: u32,
 1074    },
 1075    MultiBufferPoint {
 1076        excerpt_id: ExcerptId,
 1077        position: Point,
 1078        anchor: text::Anchor,
 1079        line_offset_from_top: u32,
 1080    },
 1081}
 1082
 1083pub enum MultibufferSelectionMode {
 1084    First,
 1085    All,
 1086}
 1087
 1088impl Editor {
 1089    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1090        let buffer = cx.new(|cx| Buffer::local("", cx));
 1091        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1092        Self::new(
 1093            EditorMode::SingleLine { auto_width: false },
 1094            buffer,
 1095            None,
 1096            false,
 1097            window,
 1098            cx,
 1099        )
 1100    }
 1101
 1102    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1103        let buffer = cx.new(|cx| Buffer::local("", cx));
 1104        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1105        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1106    }
 1107
 1108    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1109        let buffer = cx.new(|cx| Buffer::local("", cx));
 1110        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1111        Self::new(
 1112            EditorMode::SingleLine { auto_width: true },
 1113            buffer,
 1114            None,
 1115            false,
 1116            window,
 1117            cx,
 1118        )
 1119    }
 1120
 1121    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1122        let buffer = cx.new(|cx| Buffer::local("", cx));
 1123        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1124        Self::new(
 1125            EditorMode::AutoHeight { max_lines },
 1126            buffer,
 1127            None,
 1128            false,
 1129            window,
 1130            cx,
 1131        )
 1132    }
 1133
 1134    pub fn for_buffer(
 1135        buffer: Entity<Buffer>,
 1136        project: Option<Entity<Project>>,
 1137        window: &mut Window,
 1138        cx: &mut Context<Self>,
 1139    ) -> Self {
 1140        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1141        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1142    }
 1143
 1144    pub fn for_multibuffer(
 1145        buffer: Entity<MultiBuffer>,
 1146        project: Option<Entity<Project>>,
 1147        show_excerpt_controls: bool,
 1148        window: &mut Window,
 1149        cx: &mut Context<Self>,
 1150    ) -> Self {
 1151        Self::new(
 1152            EditorMode::Full,
 1153            buffer,
 1154            project,
 1155            show_excerpt_controls,
 1156            window,
 1157            cx,
 1158        )
 1159    }
 1160
 1161    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1162        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1163        let mut clone = Self::new(
 1164            self.mode,
 1165            self.buffer.clone(),
 1166            self.project.clone(),
 1167            show_excerpt_controls,
 1168            window,
 1169            cx,
 1170        );
 1171        self.display_map.update(cx, |display_map, cx| {
 1172            let snapshot = display_map.snapshot(cx);
 1173            clone.display_map.update(cx, |display_map, cx| {
 1174                display_map.set_state(&snapshot, cx);
 1175            });
 1176        });
 1177        clone.selections.clone_state(&self.selections);
 1178        clone.scroll_manager.clone_state(&self.scroll_manager);
 1179        clone.searchable = self.searchable;
 1180        clone
 1181    }
 1182
 1183    pub fn new(
 1184        mode: EditorMode,
 1185        buffer: Entity<MultiBuffer>,
 1186        project: Option<Entity<Project>>,
 1187        show_excerpt_controls: bool,
 1188        window: &mut Window,
 1189        cx: &mut Context<Self>,
 1190    ) -> Self {
 1191        let style = window.text_style();
 1192        let font_size = style.font_size.to_pixels(window.rem_size());
 1193        let editor = cx.entity().downgrade();
 1194        let fold_placeholder = FoldPlaceholder {
 1195            constrain_width: true,
 1196            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1197                let editor = editor.clone();
 1198                div()
 1199                    .id(fold_id)
 1200                    .bg(cx.theme().colors().ghost_element_background)
 1201                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1202                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1203                    .rounded_sm()
 1204                    .size_full()
 1205                    .cursor_pointer()
 1206                    .child("")
 1207                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1208                    .on_click(move |_, _window, cx| {
 1209                        editor
 1210                            .update(cx, |editor, cx| {
 1211                                editor.unfold_ranges(
 1212                                    &[fold_range.start..fold_range.end],
 1213                                    true,
 1214                                    false,
 1215                                    cx,
 1216                                );
 1217                                cx.stop_propagation();
 1218                            })
 1219                            .ok();
 1220                    })
 1221                    .into_any()
 1222            }),
 1223            merge_adjacent: true,
 1224            ..Default::default()
 1225        };
 1226        let display_map = cx.new(|cx| {
 1227            DisplayMap::new(
 1228                buffer.clone(),
 1229                style.font(),
 1230                font_size,
 1231                None,
 1232                show_excerpt_controls,
 1233                FILE_HEADER_HEIGHT,
 1234                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1235                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1236                fold_placeholder,
 1237                cx,
 1238            )
 1239        });
 1240
 1241        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1242
 1243        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1244
 1245        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1246            .then(|| language_settings::SoftWrap::None);
 1247
 1248        let mut project_subscriptions = Vec::new();
 1249        if mode == EditorMode::Full {
 1250            if let Some(project) = project.as_ref() {
 1251                if buffer.read(cx).is_singleton() {
 1252                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1253                        cx.emit(EditorEvent::TitleChanged);
 1254                    }));
 1255                }
 1256                project_subscriptions.push(cx.subscribe_in(
 1257                    project,
 1258                    window,
 1259                    |editor, _, event, window, cx| {
 1260                        if let project::Event::RefreshInlayHints = event {
 1261                            editor
 1262                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1263                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1264                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1265                                let focus_handle = editor.focus_handle(cx);
 1266                                if focus_handle.is_focused(window) {
 1267                                    let snapshot = buffer.read(cx).snapshot();
 1268                                    for (range, snippet) in snippet_edits {
 1269                                        let editor_range =
 1270                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1271                                        editor
 1272                                            .insert_snippet(
 1273                                                &[editor_range],
 1274                                                snippet.clone(),
 1275                                                window,
 1276                                                cx,
 1277                                            )
 1278                                            .ok();
 1279                                    }
 1280                                }
 1281                            }
 1282                        }
 1283                    },
 1284                ));
 1285                if let Some(task_inventory) = project
 1286                    .read(cx)
 1287                    .task_store()
 1288                    .read(cx)
 1289                    .task_inventory()
 1290                    .cloned()
 1291                {
 1292                    project_subscriptions.push(cx.observe_in(
 1293                        &task_inventory,
 1294                        window,
 1295                        |editor, _, window, cx| {
 1296                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1297                        },
 1298                    ));
 1299                }
 1300            }
 1301        }
 1302
 1303        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1304
 1305        let inlay_hint_settings =
 1306            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1307        let focus_handle = cx.focus_handle();
 1308        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1309            .detach();
 1310        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1311            .detach();
 1312        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1313            .detach();
 1314        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1315            .detach();
 1316
 1317        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1318            Some(false)
 1319        } else {
 1320            None
 1321        };
 1322
 1323        let mut code_action_providers = Vec::new();
 1324        let mut load_uncommitted_diff = None;
 1325        if let Some(project) = project.clone() {
 1326            load_uncommitted_diff = Some(
 1327                get_uncommitted_diff_for_buffer(
 1328                    &project,
 1329                    buffer.read(cx).all_buffers(),
 1330                    buffer.clone(),
 1331                    cx,
 1332                )
 1333                .shared(),
 1334            );
 1335            code_action_providers.push(Rc::new(project) as Rc<_>);
 1336        }
 1337
 1338        let mut this = Self {
 1339            focus_handle,
 1340            show_cursor_when_unfocused: false,
 1341            last_focused_descendant: None,
 1342            buffer: buffer.clone(),
 1343            display_map: display_map.clone(),
 1344            selections,
 1345            scroll_manager: ScrollManager::new(cx),
 1346            columnar_selection_tail: None,
 1347            add_selections_state: None,
 1348            select_next_state: None,
 1349            select_prev_state: None,
 1350            selection_history: Default::default(),
 1351            autoclose_regions: Default::default(),
 1352            snippet_stack: Default::default(),
 1353            select_larger_syntax_node_stack: Vec::new(),
 1354            ime_transaction: Default::default(),
 1355            active_diagnostics: None,
 1356            soft_wrap_mode_override,
 1357            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1358            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1359            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1360            project,
 1361            blink_manager: blink_manager.clone(),
 1362            show_local_selections: true,
 1363            show_scrollbars: true,
 1364            mode,
 1365            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1366            show_gutter: mode == EditorMode::Full,
 1367            show_line_numbers: None,
 1368            use_relative_line_numbers: None,
 1369            show_git_diff_gutter: None,
 1370            show_code_actions: None,
 1371            show_runnables: None,
 1372            show_wrap_guides: None,
 1373            show_indent_guides,
 1374            placeholder_text: None,
 1375            highlight_order: 0,
 1376            highlighted_rows: HashMap::default(),
 1377            background_highlights: Default::default(),
 1378            gutter_highlights: TreeMap::default(),
 1379            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1380            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1381            nav_history: None,
 1382            context_menu: RefCell::new(None),
 1383            mouse_context_menu: None,
 1384            completion_tasks: Default::default(),
 1385            signature_help_state: SignatureHelpState::default(),
 1386            auto_signature_help: None,
 1387            find_all_references_task_sources: Vec::new(),
 1388            next_completion_id: 0,
 1389            next_inlay_id: 0,
 1390            code_action_providers,
 1391            available_code_actions: Default::default(),
 1392            code_actions_task: Default::default(),
 1393            document_highlights_task: Default::default(),
 1394            linked_editing_range_task: Default::default(),
 1395            pending_rename: Default::default(),
 1396            searchable: true,
 1397            cursor_shape: EditorSettings::get_global(cx)
 1398                .cursor_shape
 1399                .unwrap_or_default(),
 1400            current_line_highlight: None,
 1401            autoindent_mode: Some(AutoindentMode::EachLine),
 1402            collapse_matches: false,
 1403            workspace: None,
 1404            input_enabled: true,
 1405            use_modal_editing: mode == EditorMode::Full,
 1406            read_only: false,
 1407            use_autoclose: true,
 1408            use_auto_surround: true,
 1409            auto_replace_emoji_shortcode: false,
 1410            leader_peer_id: None,
 1411            remote_id: None,
 1412            hover_state: Default::default(),
 1413            pending_mouse_down: None,
 1414            hovered_link_state: Default::default(),
 1415            edit_prediction_provider: None,
 1416            active_inline_completion: None,
 1417            stale_inline_completion_in_menu: None,
 1418            edit_prediction_preview: EditPredictionPreview::Inactive,
 1419            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1420
 1421            gutter_hovered: false,
 1422            pixel_position_of_newest_cursor: None,
 1423            last_bounds: None,
 1424            last_position_map: None,
 1425            expect_bounds_change: None,
 1426            gutter_dimensions: GutterDimensions::default(),
 1427            style: None,
 1428            show_cursor_names: false,
 1429            hovered_cursors: Default::default(),
 1430            next_editor_action_id: EditorActionId::default(),
 1431            editor_actions: Rc::default(),
 1432            inline_completions_hidden_for_vim_mode: false,
 1433            show_inline_completions_override: None,
 1434            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1435            edit_prediction_settings: EditPredictionSettings::Disabled,
 1436            edit_prediction_cursor_on_leading_whitespace: false,
 1437            edit_prediction_requires_modifier_in_leading_space: true,
 1438            custom_context_menu: None,
 1439            show_git_blame_gutter: false,
 1440            show_git_blame_inline: false,
 1441            distinguish_unstaged_diff_hunks: false,
 1442            show_selection_menu: None,
 1443            show_git_blame_inline_delay_task: None,
 1444            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1445            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1446                .session
 1447                .restore_unsaved_buffers,
 1448            blame: None,
 1449            blame_subscription: None,
 1450            tasks: Default::default(),
 1451            _subscriptions: vec![
 1452                cx.observe(&buffer, Self::on_buffer_changed),
 1453                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1454                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1455                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1456                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1457                cx.observe_window_activation(window, |editor, window, cx| {
 1458                    let active = window.is_window_active();
 1459                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1460                        if active {
 1461                            blink_manager.enable(cx);
 1462                        } else {
 1463                            blink_manager.disable(cx);
 1464                        }
 1465                    });
 1466                }),
 1467            ],
 1468            tasks_update_task: None,
 1469            linked_edit_ranges: Default::default(),
 1470            in_project_search: false,
 1471            previous_search_ranges: None,
 1472            breadcrumb_header: None,
 1473            focused_block: None,
 1474            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1475            addons: HashMap::default(),
 1476            registered_buffers: HashMap::default(),
 1477            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1478            selection_mark_mode: false,
 1479            toggle_fold_multiple_buffers: Task::ready(()),
 1480            text_style_refinement: None,
 1481            load_diff_task: load_uncommitted_diff,
 1482        };
 1483        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1484        this._subscriptions.extend(project_subscriptions);
 1485
 1486        this.end_selection(window, cx);
 1487        this.scroll_manager.show_scrollbar(window, cx);
 1488
 1489        if mode == EditorMode::Full {
 1490            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1491            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1492
 1493            if this.git_blame_inline_enabled {
 1494                this.git_blame_inline_enabled = true;
 1495                this.start_git_blame_inline(false, window, cx);
 1496            }
 1497
 1498            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1499                if let Some(project) = this.project.as_ref() {
 1500                    let lsp_store = project.read(cx).lsp_store();
 1501                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1502                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1503                    });
 1504                    this.registered_buffers
 1505                        .insert(buffer.read(cx).remote_id(), handle);
 1506                }
 1507            }
 1508        }
 1509
 1510        this.report_editor_event("Editor Opened", None, cx);
 1511        this
 1512    }
 1513
 1514    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1515        self.mouse_context_menu
 1516            .as_ref()
 1517            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1518    }
 1519
 1520    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1521        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1522    }
 1523
 1524    fn key_context_internal(
 1525        &self,
 1526        has_active_edit_prediction: bool,
 1527        window: &Window,
 1528        cx: &App,
 1529    ) -> KeyContext {
 1530        let mut key_context = KeyContext::new_with_defaults();
 1531        key_context.add("Editor");
 1532        let mode = match self.mode {
 1533            EditorMode::SingleLine { .. } => "single_line",
 1534            EditorMode::AutoHeight { .. } => "auto_height",
 1535            EditorMode::Full => "full",
 1536        };
 1537
 1538        if EditorSettings::jupyter_enabled(cx) {
 1539            key_context.add("jupyter");
 1540        }
 1541
 1542        key_context.set("mode", mode);
 1543        if self.pending_rename.is_some() {
 1544            key_context.add("renaming");
 1545        }
 1546
 1547        match self.context_menu.borrow().as_ref() {
 1548            Some(CodeContextMenu::Completions(_)) => {
 1549                key_context.add("menu");
 1550                key_context.add("showing_completions");
 1551            }
 1552            Some(CodeContextMenu::CodeActions(_)) => {
 1553                key_context.add("menu");
 1554                key_context.add("showing_code_actions")
 1555            }
 1556            None => {}
 1557        }
 1558
 1559        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1560        if !self.focus_handle(cx).contains_focused(window, cx)
 1561            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1562        {
 1563            for addon in self.addons.values() {
 1564                addon.extend_key_context(&mut key_context, cx)
 1565            }
 1566        }
 1567
 1568        if let Some(extension) = self
 1569            .buffer
 1570            .read(cx)
 1571            .as_singleton()
 1572            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1573        {
 1574            key_context.set("extension", extension.to_string());
 1575        }
 1576
 1577        if has_active_edit_prediction {
 1578            if self.edit_prediction_in_conflict() {
 1579                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1580            } else {
 1581                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1582                key_context.add("copilot_suggestion");
 1583            }
 1584        }
 1585
 1586        if self.selection_mark_mode {
 1587            key_context.add("selection_mode");
 1588        }
 1589
 1590        key_context
 1591    }
 1592
 1593    pub fn edit_prediction_in_conflict(&self) -> bool {
 1594        if !self.show_edit_predictions_in_menu() {
 1595            return false;
 1596        }
 1597
 1598        let showing_completions = self
 1599            .context_menu
 1600            .borrow()
 1601            .as_ref()
 1602            .map_or(false, |context| {
 1603                matches!(context, CodeContextMenu::Completions(_))
 1604            });
 1605
 1606        showing_completions
 1607            || self.edit_prediction_requires_modifier()
 1608            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1609            // bindings to insert tab characters.
 1610            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1611    }
 1612
 1613    pub fn accept_edit_prediction_keybind(
 1614        &self,
 1615        window: &Window,
 1616        cx: &App,
 1617    ) -> AcceptEditPredictionBinding {
 1618        let key_context = self.key_context_internal(true, window, cx);
 1619        let in_conflict = self.edit_prediction_in_conflict();
 1620
 1621        AcceptEditPredictionBinding(
 1622            window
 1623                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1624                .into_iter()
 1625                .filter(|binding| {
 1626                    !in_conflict
 1627                        || binding
 1628                            .keystrokes()
 1629                            .first()
 1630                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1631                })
 1632                .rev()
 1633                .min_by_key(|binding| {
 1634                    binding
 1635                        .keystrokes()
 1636                        .first()
 1637                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1638                }),
 1639        )
 1640    }
 1641
 1642    pub fn new_file(
 1643        workspace: &mut Workspace,
 1644        _: &workspace::NewFile,
 1645        window: &mut Window,
 1646        cx: &mut Context<Workspace>,
 1647    ) {
 1648        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1649            "Failed to create buffer",
 1650            window,
 1651            cx,
 1652            |e, _, _| match e.error_code() {
 1653                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1654                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1655                e.error_tag("required").unwrap_or("the latest version")
 1656            )),
 1657                _ => None,
 1658            },
 1659        );
 1660    }
 1661
 1662    pub fn new_in_workspace(
 1663        workspace: &mut Workspace,
 1664        window: &mut Window,
 1665        cx: &mut Context<Workspace>,
 1666    ) -> Task<Result<Entity<Editor>>> {
 1667        let project = workspace.project().clone();
 1668        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1669
 1670        cx.spawn_in(window, |workspace, mut cx| async move {
 1671            let buffer = create.await?;
 1672            workspace.update_in(&mut cx, |workspace, window, cx| {
 1673                let editor =
 1674                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1675                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1676                editor
 1677            })
 1678        })
 1679    }
 1680
 1681    fn new_file_vertical(
 1682        workspace: &mut Workspace,
 1683        _: &workspace::NewFileSplitVertical,
 1684        window: &mut Window,
 1685        cx: &mut Context<Workspace>,
 1686    ) {
 1687        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1688    }
 1689
 1690    fn new_file_horizontal(
 1691        workspace: &mut Workspace,
 1692        _: &workspace::NewFileSplitHorizontal,
 1693        window: &mut Window,
 1694        cx: &mut Context<Workspace>,
 1695    ) {
 1696        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1697    }
 1698
 1699    fn new_file_in_direction(
 1700        workspace: &mut Workspace,
 1701        direction: SplitDirection,
 1702        window: &mut Window,
 1703        cx: &mut Context<Workspace>,
 1704    ) {
 1705        let project = workspace.project().clone();
 1706        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1707
 1708        cx.spawn_in(window, |workspace, mut cx| async move {
 1709            let buffer = create.await?;
 1710            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1711                workspace.split_item(
 1712                    direction,
 1713                    Box::new(
 1714                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1715                    ),
 1716                    window,
 1717                    cx,
 1718                )
 1719            })?;
 1720            anyhow::Ok(())
 1721        })
 1722        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1723            match e.error_code() {
 1724                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1725                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1726                e.error_tag("required").unwrap_or("the latest version")
 1727            )),
 1728                _ => None,
 1729            }
 1730        });
 1731    }
 1732
 1733    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1734        self.leader_peer_id
 1735    }
 1736
 1737    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1738        &self.buffer
 1739    }
 1740
 1741    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1742        self.workspace.as_ref()?.0.upgrade()
 1743    }
 1744
 1745    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1746        self.buffer().read(cx).title(cx)
 1747    }
 1748
 1749    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1750        let git_blame_gutter_max_author_length = self
 1751            .render_git_blame_gutter(cx)
 1752            .then(|| {
 1753                if let Some(blame) = self.blame.as_ref() {
 1754                    let max_author_length =
 1755                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1756                    Some(max_author_length)
 1757                } else {
 1758                    None
 1759                }
 1760            })
 1761            .flatten();
 1762
 1763        EditorSnapshot {
 1764            mode: self.mode,
 1765            show_gutter: self.show_gutter,
 1766            show_line_numbers: self.show_line_numbers,
 1767            show_git_diff_gutter: self.show_git_diff_gutter,
 1768            show_code_actions: self.show_code_actions,
 1769            show_runnables: self.show_runnables,
 1770            git_blame_gutter_max_author_length,
 1771            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1772            scroll_anchor: self.scroll_manager.anchor(),
 1773            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1774            placeholder_text: self.placeholder_text.clone(),
 1775            is_focused: self.focus_handle.is_focused(window),
 1776            current_line_highlight: self
 1777                .current_line_highlight
 1778                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1779            gutter_hovered: self.gutter_hovered,
 1780        }
 1781    }
 1782
 1783    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1784        self.buffer.read(cx).language_at(point, cx)
 1785    }
 1786
 1787    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1788        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1789    }
 1790
 1791    pub fn active_excerpt(
 1792        &self,
 1793        cx: &App,
 1794    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1795        self.buffer
 1796            .read(cx)
 1797            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1798    }
 1799
 1800    pub fn mode(&self) -> EditorMode {
 1801        self.mode
 1802    }
 1803
 1804    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1805        self.collaboration_hub.as_deref()
 1806    }
 1807
 1808    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1809        self.collaboration_hub = Some(hub);
 1810    }
 1811
 1812    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1813        self.in_project_search = in_project_search;
 1814    }
 1815
 1816    pub fn set_custom_context_menu(
 1817        &mut self,
 1818        f: impl 'static
 1819            + Fn(
 1820                &mut Self,
 1821                DisplayPoint,
 1822                &mut Window,
 1823                &mut Context<Self>,
 1824            ) -> Option<Entity<ui::ContextMenu>>,
 1825    ) {
 1826        self.custom_context_menu = Some(Box::new(f))
 1827    }
 1828
 1829    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1830        self.completion_provider = provider;
 1831    }
 1832
 1833    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1834        self.semantics_provider.clone()
 1835    }
 1836
 1837    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1838        self.semantics_provider = provider;
 1839    }
 1840
 1841    pub fn set_edit_prediction_provider<T>(
 1842        &mut self,
 1843        provider: Option<Entity<T>>,
 1844        window: &mut Window,
 1845        cx: &mut Context<Self>,
 1846    ) where
 1847        T: EditPredictionProvider,
 1848    {
 1849        self.edit_prediction_provider =
 1850            provider.map(|provider| RegisteredInlineCompletionProvider {
 1851                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1852                    if this.focus_handle.is_focused(window) {
 1853                        this.update_visible_inline_completion(window, cx);
 1854                    }
 1855                }),
 1856                provider: Arc::new(provider),
 1857            });
 1858        self.refresh_inline_completion(false, false, window, cx);
 1859    }
 1860
 1861    pub fn placeholder_text(&self) -> Option<&str> {
 1862        self.placeholder_text.as_deref()
 1863    }
 1864
 1865    pub fn set_placeholder_text(
 1866        &mut self,
 1867        placeholder_text: impl Into<Arc<str>>,
 1868        cx: &mut Context<Self>,
 1869    ) {
 1870        let placeholder_text = Some(placeholder_text.into());
 1871        if self.placeholder_text != placeholder_text {
 1872            self.placeholder_text = placeholder_text;
 1873            cx.notify();
 1874        }
 1875    }
 1876
 1877    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1878        self.cursor_shape = cursor_shape;
 1879
 1880        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1881        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1882
 1883        cx.notify();
 1884    }
 1885
 1886    pub fn set_current_line_highlight(
 1887        &mut self,
 1888        current_line_highlight: Option<CurrentLineHighlight>,
 1889    ) {
 1890        self.current_line_highlight = current_line_highlight;
 1891    }
 1892
 1893    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1894        self.collapse_matches = collapse_matches;
 1895    }
 1896
 1897    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1898        let buffers = self.buffer.read(cx).all_buffers();
 1899        let Some(lsp_store) = self.lsp_store(cx) else {
 1900            return;
 1901        };
 1902        lsp_store.update(cx, |lsp_store, cx| {
 1903            for buffer in buffers {
 1904                self.registered_buffers
 1905                    .entry(buffer.read(cx).remote_id())
 1906                    .or_insert_with(|| {
 1907                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1908                    });
 1909            }
 1910        })
 1911    }
 1912
 1913    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1914        if self.collapse_matches {
 1915            return range.start..range.start;
 1916        }
 1917        range.clone()
 1918    }
 1919
 1920    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1921        if self.display_map.read(cx).clip_at_line_ends != clip {
 1922            self.display_map
 1923                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1924        }
 1925    }
 1926
 1927    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1928        self.input_enabled = input_enabled;
 1929    }
 1930
 1931    pub fn set_inline_completions_hidden_for_vim_mode(
 1932        &mut self,
 1933        hidden: bool,
 1934        window: &mut Window,
 1935        cx: &mut Context<Self>,
 1936    ) {
 1937        if hidden != self.inline_completions_hidden_for_vim_mode {
 1938            self.inline_completions_hidden_for_vim_mode = hidden;
 1939            if hidden {
 1940                self.update_visible_inline_completion(window, cx);
 1941            } else {
 1942                self.refresh_inline_completion(true, false, window, cx);
 1943            }
 1944        }
 1945    }
 1946
 1947    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1948        self.menu_inline_completions_policy = value;
 1949    }
 1950
 1951    pub fn set_autoindent(&mut self, autoindent: bool) {
 1952        if autoindent {
 1953            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1954        } else {
 1955            self.autoindent_mode = None;
 1956        }
 1957    }
 1958
 1959    pub fn read_only(&self, cx: &App) -> bool {
 1960        self.read_only || self.buffer.read(cx).read_only()
 1961    }
 1962
 1963    pub fn set_read_only(&mut self, read_only: bool) {
 1964        self.read_only = read_only;
 1965    }
 1966
 1967    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1968        self.use_autoclose = autoclose;
 1969    }
 1970
 1971    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1972        self.use_auto_surround = auto_surround;
 1973    }
 1974
 1975    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1976        self.auto_replace_emoji_shortcode = auto_replace;
 1977    }
 1978
 1979    pub fn toggle_inline_completions(
 1980        &mut self,
 1981        _: &ToggleEditPrediction,
 1982        window: &mut Window,
 1983        cx: &mut Context<Self>,
 1984    ) {
 1985        if self.show_inline_completions_override.is_some() {
 1986            self.set_show_edit_predictions(None, window, cx);
 1987        } else {
 1988            let show_edit_predictions = !self.edit_predictions_enabled();
 1989            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1990        }
 1991    }
 1992
 1993    pub fn set_show_edit_predictions(
 1994        &mut self,
 1995        show_edit_predictions: Option<bool>,
 1996        window: &mut Window,
 1997        cx: &mut Context<Self>,
 1998    ) {
 1999        self.show_inline_completions_override = show_edit_predictions;
 2000        self.refresh_inline_completion(false, true, window, cx);
 2001    }
 2002
 2003    fn inline_completions_disabled_in_scope(
 2004        &self,
 2005        buffer: &Entity<Buffer>,
 2006        buffer_position: language::Anchor,
 2007        cx: &App,
 2008    ) -> bool {
 2009        let snapshot = buffer.read(cx).snapshot();
 2010        let settings = snapshot.settings_at(buffer_position, cx);
 2011
 2012        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2013            return false;
 2014        };
 2015
 2016        scope.override_name().map_or(false, |scope_name| {
 2017            settings
 2018                .edit_predictions_disabled_in
 2019                .iter()
 2020                .any(|s| s == scope_name)
 2021        })
 2022    }
 2023
 2024    pub fn set_use_modal_editing(&mut self, to: bool) {
 2025        self.use_modal_editing = to;
 2026    }
 2027
 2028    pub fn use_modal_editing(&self) -> bool {
 2029        self.use_modal_editing
 2030    }
 2031
 2032    fn selections_did_change(
 2033        &mut self,
 2034        local: bool,
 2035        old_cursor_position: &Anchor,
 2036        show_completions: bool,
 2037        window: &mut Window,
 2038        cx: &mut Context<Self>,
 2039    ) {
 2040        window.invalidate_character_coordinates();
 2041
 2042        // Copy selections to primary selection buffer
 2043        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2044        if local {
 2045            let selections = self.selections.all::<usize>(cx);
 2046            let buffer_handle = self.buffer.read(cx).read(cx);
 2047
 2048            let mut text = String::new();
 2049            for (index, selection) in selections.iter().enumerate() {
 2050                let text_for_selection = buffer_handle
 2051                    .text_for_range(selection.start..selection.end)
 2052                    .collect::<String>();
 2053
 2054                text.push_str(&text_for_selection);
 2055                if index != selections.len() - 1 {
 2056                    text.push('\n');
 2057                }
 2058            }
 2059
 2060            if !text.is_empty() {
 2061                cx.write_to_primary(ClipboardItem::new_string(text));
 2062            }
 2063        }
 2064
 2065        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2066            self.buffer.update(cx, |buffer, cx| {
 2067                buffer.set_active_selections(
 2068                    &self.selections.disjoint_anchors(),
 2069                    self.selections.line_mode,
 2070                    self.cursor_shape,
 2071                    cx,
 2072                )
 2073            });
 2074        }
 2075        let display_map = self
 2076            .display_map
 2077            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2078        let buffer = &display_map.buffer_snapshot;
 2079        self.add_selections_state = None;
 2080        self.select_next_state = None;
 2081        self.select_prev_state = None;
 2082        self.select_larger_syntax_node_stack.clear();
 2083        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2084        self.snippet_stack
 2085            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2086        self.take_rename(false, window, cx);
 2087
 2088        let new_cursor_position = self.selections.newest_anchor().head();
 2089
 2090        self.push_to_nav_history(
 2091            *old_cursor_position,
 2092            Some(new_cursor_position.to_point(buffer)),
 2093            cx,
 2094        );
 2095
 2096        if local {
 2097            let new_cursor_position = self.selections.newest_anchor().head();
 2098            let mut context_menu = self.context_menu.borrow_mut();
 2099            let completion_menu = match context_menu.as_ref() {
 2100                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2101                _ => {
 2102                    *context_menu = None;
 2103                    None
 2104                }
 2105            };
 2106            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2107                if !self.registered_buffers.contains_key(&buffer_id) {
 2108                    if let Some(lsp_store) = self.lsp_store(cx) {
 2109                        lsp_store.update(cx, |lsp_store, cx| {
 2110                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2111                                return;
 2112                            };
 2113                            self.registered_buffers.insert(
 2114                                buffer_id,
 2115                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2116                            );
 2117                        })
 2118                    }
 2119                }
 2120            }
 2121
 2122            if let Some(completion_menu) = completion_menu {
 2123                let cursor_position = new_cursor_position.to_offset(buffer);
 2124                let (word_range, kind) =
 2125                    buffer.surrounding_word(completion_menu.initial_position, true);
 2126                if kind == Some(CharKind::Word)
 2127                    && word_range.to_inclusive().contains(&cursor_position)
 2128                {
 2129                    let mut completion_menu = completion_menu.clone();
 2130                    drop(context_menu);
 2131
 2132                    let query = Self::completion_query(buffer, cursor_position);
 2133                    cx.spawn(move |this, mut cx| async move {
 2134                        completion_menu
 2135                            .filter(query.as_deref(), cx.background_executor().clone())
 2136                            .await;
 2137
 2138                        this.update(&mut cx, |this, cx| {
 2139                            let mut context_menu = this.context_menu.borrow_mut();
 2140                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2141                            else {
 2142                                return;
 2143                            };
 2144
 2145                            if menu.id > completion_menu.id {
 2146                                return;
 2147                            }
 2148
 2149                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2150                            drop(context_menu);
 2151                            cx.notify();
 2152                        })
 2153                    })
 2154                    .detach();
 2155
 2156                    if show_completions {
 2157                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2158                    }
 2159                } else {
 2160                    drop(context_menu);
 2161                    self.hide_context_menu(window, cx);
 2162                }
 2163            } else {
 2164                drop(context_menu);
 2165            }
 2166
 2167            hide_hover(self, cx);
 2168
 2169            if old_cursor_position.to_display_point(&display_map).row()
 2170                != new_cursor_position.to_display_point(&display_map).row()
 2171            {
 2172                self.available_code_actions.take();
 2173            }
 2174            self.refresh_code_actions(window, cx);
 2175            self.refresh_document_highlights(cx);
 2176            refresh_matching_bracket_highlights(self, window, cx);
 2177            self.update_visible_inline_completion(window, cx);
 2178            self.edit_prediction_requires_modifier_in_leading_space = true;
 2179            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2180            if self.git_blame_inline_enabled {
 2181                self.start_inline_blame_timer(window, cx);
 2182            }
 2183        }
 2184
 2185        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2186        cx.emit(EditorEvent::SelectionsChanged { local });
 2187
 2188        if self.selections.disjoint_anchors().len() == 1 {
 2189            cx.emit(SearchEvent::ActiveMatchChanged)
 2190        }
 2191        cx.notify();
 2192    }
 2193
 2194    pub fn change_selections<R>(
 2195        &mut self,
 2196        autoscroll: Option<Autoscroll>,
 2197        window: &mut Window,
 2198        cx: &mut Context<Self>,
 2199        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2200    ) -> R {
 2201        self.change_selections_inner(autoscroll, true, window, cx, change)
 2202    }
 2203
 2204    pub fn change_selections_inner<R>(
 2205        &mut self,
 2206        autoscroll: Option<Autoscroll>,
 2207        request_completions: bool,
 2208        window: &mut Window,
 2209        cx: &mut Context<Self>,
 2210        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2211    ) -> R {
 2212        let old_cursor_position = self.selections.newest_anchor().head();
 2213        self.push_to_selection_history();
 2214
 2215        let (changed, result) = self.selections.change_with(cx, change);
 2216
 2217        if changed {
 2218            if let Some(autoscroll) = autoscroll {
 2219                self.request_autoscroll(autoscroll, cx);
 2220            }
 2221            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2222
 2223            if self.should_open_signature_help_automatically(
 2224                &old_cursor_position,
 2225                self.signature_help_state.backspace_pressed(),
 2226                cx,
 2227            ) {
 2228                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2229            }
 2230            self.signature_help_state.set_backspace_pressed(false);
 2231        }
 2232
 2233        result
 2234    }
 2235
 2236    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2237    where
 2238        I: IntoIterator<Item = (Range<S>, T)>,
 2239        S: ToOffset,
 2240        T: Into<Arc<str>>,
 2241    {
 2242        if self.read_only(cx) {
 2243            return;
 2244        }
 2245
 2246        self.buffer
 2247            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2248    }
 2249
 2250    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2251    where
 2252        I: IntoIterator<Item = (Range<S>, T)>,
 2253        S: ToOffset,
 2254        T: Into<Arc<str>>,
 2255    {
 2256        if self.read_only(cx) {
 2257            return;
 2258        }
 2259
 2260        self.buffer.update(cx, |buffer, cx| {
 2261            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2262        });
 2263    }
 2264
 2265    pub fn edit_with_block_indent<I, S, T>(
 2266        &mut self,
 2267        edits: I,
 2268        original_indent_columns: Vec<u32>,
 2269        cx: &mut Context<Self>,
 2270    ) where
 2271        I: IntoIterator<Item = (Range<S>, T)>,
 2272        S: ToOffset,
 2273        T: Into<Arc<str>>,
 2274    {
 2275        if self.read_only(cx) {
 2276            return;
 2277        }
 2278
 2279        self.buffer.update(cx, |buffer, cx| {
 2280            buffer.edit(
 2281                edits,
 2282                Some(AutoindentMode::Block {
 2283                    original_indent_columns,
 2284                }),
 2285                cx,
 2286            )
 2287        });
 2288    }
 2289
 2290    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2291        self.hide_context_menu(window, cx);
 2292
 2293        match phase {
 2294            SelectPhase::Begin {
 2295                position,
 2296                add,
 2297                click_count,
 2298            } => self.begin_selection(position, add, click_count, window, cx),
 2299            SelectPhase::BeginColumnar {
 2300                position,
 2301                goal_column,
 2302                reset,
 2303            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2304            SelectPhase::Extend {
 2305                position,
 2306                click_count,
 2307            } => self.extend_selection(position, click_count, window, cx),
 2308            SelectPhase::Update {
 2309                position,
 2310                goal_column,
 2311                scroll_delta,
 2312            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2313            SelectPhase::End => self.end_selection(window, cx),
 2314        }
 2315    }
 2316
 2317    fn extend_selection(
 2318        &mut self,
 2319        position: DisplayPoint,
 2320        click_count: usize,
 2321        window: &mut Window,
 2322        cx: &mut Context<Self>,
 2323    ) {
 2324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2325        let tail = self.selections.newest::<usize>(cx).tail();
 2326        self.begin_selection(position, false, click_count, window, cx);
 2327
 2328        let position = position.to_offset(&display_map, Bias::Left);
 2329        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2330
 2331        let mut pending_selection = self
 2332            .selections
 2333            .pending_anchor()
 2334            .expect("extend_selection not called with pending selection");
 2335        if position >= tail {
 2336            pending_selection.start = tail_anchor;
 2337        } else {
 2338            pending_selection.end = tail_anchor;
 2339            pending_selection.reversed = true;
 2340        }
 2341
 2342        let mut pending_mode = self.selections.pending_mode().unwrap();
 2343        match &mut pending_mode {
 2344            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2345            _ => {}
 2346        }
 2347
 2348        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2349            s.set_pending(pending_selection, pending_mode)
 2350        });
 2351    }
 2352
 2353    fn begin_selection(
 2354        &mut self,
 2355        position: DisplayPoint,
 2356        add: bool,
 2357        click_count: usize,
 2358        window: &mut Window,
 2359        cx: &mut Context<Self>,
 2360    ) {
 2361        if !self.focus_handle.is_focused(window) {
 2362            self.last_focused_descendant = None;
 2363            window.focus(&self.focus_handle);
 2364        }
 2365
 2366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2367        let buffer = &display_map.buffer_snapshot;
 2368        let newest_selection = self.selections.newest_anchor().clone();
 2369        let position = display_map.clip_point(position, Bias::Left);
 2370
 2371        let start;
 2372        let end;
 2373        let mode;
 2374        let mut auto_scroll;
 2375        match click_count {
 2376            1 => {
 2377                start = buffer.anchor_before(position.to_point(&display_map));
 2378                end = start;
 2379                mode = SelectMode::Character;
 2380                auto_scroll = true;
 2381            }
 2382            2 => {
 2383                let range = movement::surrounding_word(&display_map, position);
 2384                start = buffer.anchor_before(range.start.to_point(&display_map));
 2385                end = buffer.anchor_before(range.end.to_point(&display_map));
 2386                mode = SelectMode::Word(start..end);
 2387                auto_scroll = true;
 2388            }
 2389            3 => {
 2390                let position = display_map
 2391                    .clip_point(position, Bias::Left)
 2392                    .to_point(&display_map);
 2393                let line_start = display_map.prev_line_boundary(position).0;
 2394                let next_line_start = buffer.clip_point(
 2395                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2396                    Bias::Left,
 2397                );
 2398                start = buffer.anchor_before(line_start);
 2399                end = buffer.anchor_before(next_line_start);
 2400                mode = SelectMode::Line(start..end);
 2401                auto_scroll = true;
 2402            }
 2403            _ => {
 2404                start = buffer.anchor_before(0);
 2405                end = buffer.anchor_before(buffer.len());
 2406                mode = SelectMode::All;
 2407                auto_scroll = false;
 2408            }
 2409        }
 2410        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2411
 2412        let point_to_delete: Option<usize> = {
 2413            let selected_points: Vec<Selection<Point>> =
 2414                self.selections.disjoint_in_range(start..end, cx);
 2415
 2416            if !add || click_count > 1 {
 2417                None
 2418            } else if !selected_points.is_empty() {
 2419                Some(selected_points[0].id)
 2420            } else {
 2421                let clicked_point_already_selected =
 2422                    self.selections.disjoint.iter().find(|selection| {
 2423                        selection.start.to_point(buffer) == start.to_point(buffer)
 2424                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2425                    });
 2426
 2427                clicked_point_already_selected.map(|selection| selection.id)
 2428            }
 2429        };
 2430
 2431        let selections_count = self.selections.count();
 2432
 2433        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2434            if let Some(point_to_delete) = point_to_delete {
 2435                s.delete(point_to_delete);
 2436
 2437                if selections_count == 1 {
 2438                    s.set_pending_anchor_range(start..end, mode);
 2439                }
 2440            } else {
 2441                if !add {
 2442                    s.clear_disjoint();
 2443                } else if click_count > 1 {
 2444                    s.delete(newest_selection.id)
 2445                }
 2446
 2447                s.set_pending_anchor_range(start..end, mode);
 2448            }
 2449        });
 2450    }
 2451
 2452    fn begin_columnar_selection(
 2453        &mut self,
 2454        position: DisplayPoint,
 2455        goal_column: u32,
 2456        reset: bool,
 2457        window: &mut Window,
 2458        cx: &mut Context<Self>,
 2459    ) {
 2460        if !self.focus_handle.is_focused(window) {
 2461            self.last_focused_descendant = None;
 2462            window.focus(&self.focus_handle);
 2463        }
 2464
 2465        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2466
 2467        if reset {
 2468            let pointer_position = display_map
 2469                .buffer_snapshot
 2470                .anchor_before(position.to_point(&display_map));
 2471
 2472            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2473                s.clear_disjoint();
 2474                s.set_pending_anchor_range(
 2475                    pointer_position..pointer_position,
 2476                    SelectMode::Character,
 2477                );
 2478            });
 2479        }
 2480
 2481        let tail = self.selections.newest::<Point>(cx).tail();
 2482        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2483
 2484        if !reset {
 2485            self.select_columns(
 2486                tail.to_display_point(&display_map),
 2487                position,
 2488                goal_column,
 2489                &display_map,
 2490                window,
 2491                cx,
 2492            );
 2493        }
 2494    }
 2495
 2496    fn update_selection(
 2497        &mut self,
 2498        position: DisplayPoint,
 2499        goal_column: u32,
 2500        scroll_delta: gpui::Point<f32>,
 2501        window: &mut Window,
 2502        cx: &mut Context<Self>,
 2503    ) {
 2504        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2505
 2506        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2507            let tail = tail.to_display_point(&display_map);
 2508            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2509        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2510            let buffer = self.buffer.read(cx).snapshot(cx);
 2511            let head;
 2512            let tail;
 2513            let mode = self.selections.pending_mode().unwrap();
 2514            match &mode {
 2515                SelectMode::Character => {
 2516                    head = position.to_point(&display_map);
 2517                    tail = pending.tail().to_point(&buffer);
 2518                }
 2519                SelectMode::Word(original_range) => {
 2520                    let original_display_range = original_range.start.to_display_point(&display_map)
 2521                        ..original_range.end.to_display_point(&display_map);
 2522                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2523                        ..original_display_range.end.to_point(&display_map);
 2524                    if movement::is_inside_word(&display_map, position)
 2525                        || original_display_range.contains(&position)
 2526                    {
 2527                        let word_range = movement::surrounding_word(&display_map, position);
 2528                        if word_range.start < original_display_range.start {
 2529                            head = word_range.start.to_point(&display_map);
 2530                        } else {
 2531                            head = word_range.end.to_point(&display_map);
 2532                        }
 2533                    } else {
 2534                        head = position.to_point(&display_map);
 2535                    }
 2536
 2537                    if head <= original_buffer_range.start {
 2538                        tail = original_buffer_range.end;
 2539                    } else {
 2540                        tail = original_buffer_range.start;
 2541                    }
 2542                }
 2543                SelectMode::Line(original_range) => {
 2544                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2545
 2546                    let position = display_map
 2547                        .clip_point(position, Bias::Left)
 2548                        .to_point(&display_map);
 2549                    let line_start = display_map.prev_line_boundary(position).0;
 2550                    let next_line_start = buffer.clip_point(
 2551                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2552                        Bias::Left,
 2553                    );
 2554
 2555                    if line_start < original_range.start {
 2556                        head = line_start
 2557                    } else {
 2558                        head = next_line_start
 2559                    }
 2560
 2561                    if head <= original_range.start {
 2562                        tail = original_range.end;
 2563                    } else {
 2564                        tail = original_range.start;
 2565                    }
 2566                }
 2567                SelectMode::All => {
 2568                    return;
 2569                }
 2570            };
 2571
 2572            if head < tail {
 2573                pending.start = buffer.anchor_before(head);
 2574                pending.end = buffer.anchor_before(tail);
 2575                pending.reversed = true;
 2576            } else {
 2577                pending.start = buffer.anchor_before(tail);
 2578                pending.end = buffer.anchor_before(head);
 2579                pending.reversed = false;
 2580            }
 2581
 2582            self.change_selections(None, window, cx, |s| {
 2583                s.set_pending(pending, mode);
 2584            });
 2585        } else {
 2586            log::error!("update_selection dispatched with no pending selection");
 2587            return;
 2588        }
 2589
 2590        self.apply_scroll_delta(scroll_delta, window, cx);
 2591        cx.notify();
 2592    }
 2593
 2594    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2595        self.columnar_selection_tail.take();
 2596        if self.selections.pending_anchor().is_some() {
 2597            let selections = self.selections.all::<usize>(cx);
 2598            self.change_selections(None, window, cx, |s| {
 2599                s.select(selections);
 2600                s.clear_pending();
 2601            });
 2602        }
 2603    }
 2604
 2605    fn select_columns(
 2606        &mut self,
 2607        tail: DisplayPoint,
 2608        head: DisplayPoint,
 2609        goal_column: u32,
 2610        display_map: &DisplaySnapshot,
 2611        window: &mut Window,
 2612        cx: &mut Context<Self>,
 2613    ) {
 2614        let start_row = cmp::min(tail.row(), head.row());
 2615        let end_row = cmp::max(tail.row(), head.row());
 2616        let start_column = cmp::min(tail.column(), goal_column);
 2617        let end_column = cmp::max(tail.column(), goal_column);
 2618        let reversed = start_column < tail.column();
 2619
 2620        let selection_ranges = (start_row.0..=end_row.0)
 2621            .map(DisplayRow)
 2622            .filter_map(|row| {
 2623                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2624                    let start = display_map
 2625                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2626                        .to_point(display_map);
 2627                    let end = display_map
 2628                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2629                        .to_point(display_map);
 2630                    if reversed {
 2631                        Some(end..start)
 2632                    } else {
 2633                        Some(start..end)
 2634                    }
 2635                } else {
 2636                    None
 2637                }
 2638            })
 2639            .collect::<Vec<_>>();
 2640
 2641        self.change_selections(None, window, cx, |s| {
 2642            s.select_ranges(selection_ranges);
 2643        });
 2644        cx.notify();
 2645    }
 2646
 2647    pub fn has_pending_nonempty_selection(&self) -> bool {
 2648        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2649            Some(Selection { start, end, .. }) => start != end,
 2650            None => false,
 2651        };
 2652
 2653        pending_nonempty_selection
 2654            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2655    }
 2656
 2657    pub fn has_pending_selection(&self) -> bool {
 2658        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2659    }
 2660
 2661    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2662        self.selection_mark_mode = false;
 2663
 2664        if self.clear_expanded_diff_hunks(cx) {
 2665            cx.notify();
 2666            return;
 2667        }
 2668        if self.dismiss_menus_and_popups(true, window, cx) {
 2669            return;
 2670        }
 2671
 2672        if self.mode == EditorMode::Full
 2673            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2674        {
 2675            return;
 2676        }
 2677
 2678        cx.propagate();
 2679    }
 2680
 2681    pub fn dismiss_menus_and_popups(
 2682        &mut self,
 2683        is_user_requested: bool,
 2684        window: &mut Window,
 2685        cx: &mut Context<Self>,
 2686    ) -> bool {
 2687        if self.take_rename(false, window, cx).is_some() {
 2688            return true;
 2689        }
 2690
 2691        if hide_hover(self, cx) {
 2692            return true;
 2693        }
 2694
 2695        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2696            return true;
 2697        }
 2698
 2699        if self.hide_context_menu(window, cx).is_some() {
 2700            return true;
 2701        }
 2702
 2703        if self.mouse_context_menu.take().is_some() {
 2704            return true;
 2705        }
 2706
 2707        if is_user_requested && self.discard_inline_completion(true, cx) {
 2708            return true;
 2709        }
 2710
 2711        if self.snippet_stack.pop().is_some() {
 2712            return true;
 2713        }
 2714
 2715        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2716            self.dismiss_diagnostics(cx);
 2717            return true;
 2718        }
 2719
 2720        false
 2721    }
 2722
 2723    fn linked_editing_ranges_for(
 2724        &self,
 2725        selection: Range<text::Anchor>,
 2726        cx: &App,
 2727    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2728        if self.linked_edit_ranges.is_empty() {
 2729            return None;
 2730        }
 2731        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2732            selection.end.buffer_id.and_then(|end_buffer_id| {
 2733                if selection.start.buffer_id != Some(end_buffer_id) {
 2734                    return None;
 2735                }
 2736                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2737                let snapshot = buffer.read(cx).snapshot();
 2738                self.linked_edit_ranges
 2739                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2740                    .map(|ranges| (ranges, snapshot, buffer))
 2741            })?;
 2742        use text::ToOffset as TO;
 2743        // find offset from the start of current range to current cursor position
 2744        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2745
 2746        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2747        let start_difference = start_offset - start_byte_offset;
 2748        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2749        let end_difference = end_offset - start_byte_offset;
 2750        // Current range has associated linked ranges.
 2751        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2752        for range in linked_ranges.iter() {
 2753            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2754            let end_offset = start_offset + end_difference;
 2755            let start_offset = start_offset + start_difference;
 2756            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2757                continue;
 2758            }
 2759            if self.selections.disjoint_anchor_ranges().any(|s| {
 2760                if s.start.buffer_id != selection.start.buffer_id
 2761                    || s.end.buffer_id != selection.end.buffer_id
 2762                {
 2763                    return false;
 2764                }
 2765                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2766                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2767            }) {
 2768                continue;
 2769            }
 2770            let start = buffer_snapshot.anchor_after(start_offset);
 2771            let end = buffer_snapshot.anchor_after(end_offset);
 2772            linked_edits
 2773                .entry(buffer.clone())
 2774                .or_default()
 2775                .push(start..end);
 2776        }
 2777        Some(linked_edits)
 2778    }
 2779
 2780    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2781        let text: Arc<str> = text.into();
 2782
 2783        if self.read_only(cx) {
 2784            return;
 2785        }
 2786
 2787        let selections = self.selections.all_adjusted(cx);
 2788        let mut bracket_inserted = false;
 2789        let mut edits = Vec::new();
 2790        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2791        let mut new_selections = Vec::with_capacity(selections.len());
 2792        let mut new_autoclose_regions = Vec::new();
 2793        let snapshot = self.buffer.read(cx).read(cx);
 2794
 2795        for (selection, autoclose_region) in
 2796            self.selections_with_autoclose_regions(selections, &snapshot)
 2797        {
 2798            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2799                // Determine if the inserted text matches the opening or closing
 2800                // bracket of any of this language's bracket pairs.
 2801                let mut bracket_pair = None;
 2802                let mut is_bracket_pair_start = false;
 2803                let mut is_bracket_pair_end = false;
 2804                if !text.is_empty() {
 2805                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2806                    //  and they are removing the character that triggered IME popup.
 2807                    for (pair, enabled) in scope.brackets() {
 2808                        if !pair.close && !pair.surround {
 2809                            continue;
 2810                        }
 2811
 2812                        if enabled && pair.start.ends_with(text.as_ref()) {
 2813                            let prefix_len = pair.start.len() - text.len();
 2814                            let preceding_text_matches_prefix = prefix_len == 0
 2815                                || (selection.start.column >= (prefix_len as u32)
 2816                                    && snapshot.contains_str_at(
 2817                                        Point::new(
 2818                                            selection.start.row,
 2819                                            selection.start.column - (prefix_len as u32),
 2820                                        ),
 2821                                        &pair.start[..prefix_len],
 2822                                    ));
 2823                            if preceding_text_matches_prefix {
 2824                                bracket_pair = Some(pair.clone());
 2825                                is_bracket_pair_start = true;
 2826                                break;
 2827                            }
 2828                        }
 2829                        if pair.end.as_str() == text.as_ref() {
 2830                            bracket_pair = Some(pair.clone());
 2831                            is_bracket_pair_end = true;
 2832                            break;
 2833                        }
 2834                    }
 2835                }
 2836
 2837                if let Some(bracket_pair) = bracket_pair {
 2838                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2839                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2840                    let auto_surround =
 2841                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2842                    if selection.is_empty() {
 2843                        if is_bracket_pair_start {
 2844                            // If the inserted text is a suffix of an opening bracket and the
 2845                            // selection is preceded by the rest of the opening bracket, then
 2846                            // insert the closing bracket.
 2847                            let following_text_allows_autoclose = snapshot
 2848                                .chars_at(selection.start)
 2849                                .next()
 2850                                .map_or(true, |c| scope.should_autoclose_before(c));
 2851
 2852                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2853                                && bracket_pair.start.len() == 1
 2854                            {
 2855                                let target = bracket_pair.start.chars().next().unwrap();
 2856                                let current_line_count = snapshot
 2857                                    .reversed_chars_at(selection.start)
 2858                                    .take_while(|&c| c != '\n')
 2859                                    .filter(|&c| c == target)
 2860                                    .count();
 2861                                current_line_count % 2 == 1
 2862                            } else {
 2863                                false
 2864                            };
 2865
 2866                            if autoclose
 2867                                && bracket_pair.close
 2868                                && following_text_allows_autoclose
 2869                                && !is_closing_quote
 2870                            {
 2871                                let anchor = snapshot.anchor_before(selection.end);
 2872                                new_selections.push((selection.map(|_| anchor), text.len()));
 2873                                new_autoclose_regions.push((
 2874                                    anchor,
 2875                                    text.len(),
 2876                                    selection.id,
 2877                                    bracket_pair.clone(),
 2878                                ));
 2879                                edits.push((
 2880                                    selection.range(),
 2881                                    format!("{}{}", text, bracket_pair.end).into(),
 2882                                ));
 2883                                bracket_inserted = true;
 2884                                continue;
 2885                            }
 2886                        }
 2887
 2888                        if let Some(region) = autoclose_region {
 2889                            // If the selection is followed by an auto-inserted closing bracket,
 2890                            // then don't insert that closing bracket again; just move the selection
 2891                            // past the closing bracket.
 2892                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2893                                && text.as_ref() == region.pair.end.as_str();
 2894                            if should_skip {
 2895                                let anchor = snapshot.anchor_after(selection.end);
 2896                                new_selections
 2897                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2898                                continue;
 2899                            }
 2900                        }
 2901
 2902                        let always_treat_brackets_as_autoclosed = snapshot
 2903                            .settings_at(selection.start, cx)
 2904                            .always_treat_brackets_as_autoclosed;
 2905                        if always_treat_brackets_as_autoclosed
 2906                            && is_bracket_pair_end
 2907                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2908                        {
 2909                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2910                            // and the inserted text is a closing bracket and the selection is followed
 2911                            // by the closing bracket then move the selection past the closing bracket.
 2912                            let anchor = snapshot.anchor_after(selection.end);
 2913                            new_selections.push((selection.map(|_| anchor), text.len()));
 2914                            continue;
 2915                        }
 2916                    }
 2917                    // If an opening bracket is 1 character long and is typed while
 2918                    // text is selected, then surround that text with the bracket pair.
 2919                    else if auto_surround
 2920                        && bracket_pair.surround
 2921                        && is_bracket_pair_start
 2922                        && bracket_pair.start.chars().count() == 1
 2923                    {
 2924                        edits.push((selection.start..selection.start, text.clone()));
 2925                        edits.push((
 2926                            selection.end..selection.end,
 2927                            bracket_pair.end.as_str().into(),
 2928                        ));
 2929                        bracket_inserted = true;
 2930                        new_selections.push((
 2931                            Selection {
 2932                                id: selection.id,
 2933                                start: snapshot.anchor_after(selection.start),
 2934                                end: snapshot.anchor_before(selection.end),
 2935                                reversed: selection.reversed,
 2936                                goal: selection.goal,
 2937                            },
 2938                            0,
 2939                        ));
 2940                        continue;
 2941                    }
 2942                }
 2943            }
 2944
 2945            if self.auto_replace_emoji_shortcode
 2946                && selection.is_empty()
 2947                && text.as_ref().ends_with(':')
 2948            {
 2949                if let Some(possible_emoji_short_code) =
 2950                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2951                {
 2952                    if !possible_emoji_short_code.is_empty() {
 2953                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2954                            let emoji_shortcode_start = Point::new(
 2955                                selection.start.row,
 2956                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2957                            );
 2958
 2959                            // Remove shortcode from buffer
 2960                            edits.push((
 2961                                emoji_shortcode_start..selection.start,
 2962                                "".to_string().into(),
 2963                            ));
 2964                            new_selections.push((
 2965                                Selection {
 2966                                    id: selection.id,
 2967                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2968                                    end: snapshot.anchor_before(selection.start),
 2969                                    reversed: selection.reversed,
 2970                                    goal: selection.goal,
 2971                                },
 2972                                0,
 2973                            ));
 2974
 2975                            // Insert emoji
 2976                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2977                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2978                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2979
 2980                            continue;
 2981                        }
 2982                    }
 2983                }
 2984            }
 2985
 2986            // If not handling any auto-close operation, then just replace the selected
 2987            // text with the given input and move the selection to the end of the
 2988            // newly inserted text.
 2989            let anchor = snapshot.anchor_after(selection.end);
 2990            if !self.linked_edit_ranges.is_empty() {
 2991                let start_anchor = snapshot.anchor_before(selection.start);
 2992
 2993                let is_word_char = text.chars().next().map_or(true, |char| {
 2994                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2995                    classifier.is_word(char)
 2996                });
 2997
 2998                if is_word_char {
 2999                    if let Some(ranges) = self
 3000                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3001                    {
 3002                        for (buffer, edits) in ranges {
 3003                            linked_edits
 3004                                .entry(buffer.clone())
 3005                                .or_default()
 3006                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3007                        }
 3008                    }
 3009                }
 3010            }
 3011
 3012            new_selections.push((selection.map(|_| anchor), 0));
 3013            edits.push((selection.start..selection.end, text.clone()));
 3014        }
 3015
 3016        drop(snapshot);
 3017
 3018        self.transact(window, cx, |this, window, cx| {
 3019            this.buffer.update(cx, |buffer, cx| {
 3020                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3021            });
 3022            for (buffer, edits) in linked_edits {
 3023                buffer.update(cx, |buffer, cx| {
 3024                    let snapshot = buffer.snapshot();
 3025                    let edits = edits
 3026                        .into_iter()
 3027                        .map(|(range, text)| {
 3028                            use text::ToPoint as TP;
 3029                            let end_point = TP::to_point(&range.end, &snapshot);
 3030                            let start_point = TP::to_point(&range.start, &snapshot);
 3031                            (start_point..end_point, text)
 3032                        })
 3033                        .sorted_by_key(|(range, _)| range.start)
 3034                        .collect::<Vec<_>>();
 3035                    buffer.edit(edits, None, cx);
 3036                })
 3037            }
 3038            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3039            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3040            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3041            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3042                .zip(new_selection_deltas)
 3043                .map(|(selection, delta)| Selection {
 3044                    id: selection.id,
 3045                    start: selection.start + delta,
 3046                    end: selection.end + delta,
 3047                    reversed: selection.reversed,
 3048                    goal: SelectionGoal::None,
 3049                })
 3050                .collect::<Vec<_>>();
 3051
 3052            let mut i = 0;
 3053            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3054                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3055                let start = map.buffer_snapshot.anchor_before(position);
 3056                let end = map.buffer_snapshot.anchor_after(position);
 3057                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3058                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3059                        Ordering::Less => i += 1,
 3060                        Ordering::Greater => break,
 3061                        Ordering::Equal => {
 3062                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3063                                Ordering::Less => i += 1,
 3064                                Ordering::Equal => break,
 3065                                Ordering::Greater => break,
 3066                            }
 3067                        }
 3068                    }
 3069                }
 3070                this.autoclose_regions.insert(
 3071                    i,
 3072                    AutocloseRegion {
 3073                        selection_id,
 3074                        range: start..end,
 3075                        pair,
 3076                    },
 3077                );
 3078            }
 3079
 3080            let had_active_inline_completion = this.has_active_inline_completion();
 3081            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3082                s.select(new_selections)
 3083            });
 3084
 3085            if !bracket_inserted {
 3086                if let Some(on_type_format_task) =
 3087                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3088                {
 3089                    on_type_format_task.detach_and_log_err(cx);
 3090                }
 3091            }
 3092
 3093            let editor_settings = EditorSettings::get_global(cx);
 3094            if bracket_inserted
 3095                && (editor_settings.auto_signature_help
 3096                    || editor_settings.show_signature_help_after_edits)
 3097            {
 3098                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3099            }
 3100
 3101            let trigger_in_words =
 3102                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3103            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3104            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3105            this.refresh_inline_completion(true, false, window, cx);
 3106        });
 3107    }
 3108
 3109    fn find_possible_emoji_shortcode_at_position(
 3110        snapshot: &MultiBufferSnapshot,
 3111        position: Point,
 3112    ) -> Option<String> {
 3113        let mut chars = Vec::new();
 3114        let mut found_colon = false;
 3115        for char in snapshot.reversed_chars_at(position).take(100) {
 3116            // Found a possible emoji shortcode in the middle of the buffer
 3117            if found_colon {
 3118                if char.is_whitespace() {
 3119                    chars.reverse();
 3120                    return Some(chars.iter().collect());
 3121                }
 3122                // If the previous character is not a whitespace, we are in the middle of a word
 3123                // and we only want to complete the shortcode if the word is made up of other emojis
 3124                let mut containing_word = String::new();
 3125                for ch in snapshot
 3126                    .reversed_chars_at(position)
 3127                    .skip(chars.len() + 1)
 3128                    .take(100)
 3129                {
 3130                    if ch.is_whitespace() {
 3131                        break;
 3132                    }
 3133                    containing_word.push(ch);
 3134                }
 3135                let containing_word = containing_word.chars().rev().collect::<String>();
 3136                if util::word_consists_of_emojis(containing_word.as_str()) {
 3137                    chars.reverse();
 3138                    return Some(chars.iter().collect());
 3139                }
 3140            }
 3141
 3142            if char.is_whitespace() || !char.is_ascii() {
 3143                return None;
 3144            }
 3145            if char == ':' {
 3146                found_colon = true;
 3147            } else {
 3148                chars.push(char);
 3149            }
 3150        }
 3151        // Found a possible emoji shortcode at the beginning of the buffer
 3152        chars.reverse();
 3153        Some(chars.iter().collect())
 3154    }
 3155
 3156    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3157        self.transact(window, cx, |this, window, cx| {
 3158            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3159                let selections = this.selections.all::<usize>(cx);
 3160                let multi_buffer = this.buffer.read(cx);
 3161                let buffer = multi_buffer.snapshot(cx);
 3162                selections
 3163                    .iter()
 3164                    .map(|selection| {
 3165                        let start_point = selection.start.to_point(&buffer);
 3166                        let mut indent =
 3167                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3168                        indent.len = cmp::min(indent.len, start_point.column);
 3169                        let start = selection.start;
 3170                        let end = selection.end;
 3171                        let selection_is_empty = start == end;
 3172                        let language_scope = buffer.language_scope_at(start);
 3173                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3174                            &language_scope
 3175                        {
 3176                            let leading_whitespace_len = buffer
 3177                                .reversed_chars_at(start)
 3178                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3179                                .map(|c| c.len_utf8())
 3180                                .sum::<usize>();
 3181
 3182                            let trailing_whitespace_len = buffer
 3183                                .chars_at(end)
 3184                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3185                                .map(|c| c.len_utf8())
 3186                                .sum::<usize>();
 3187
 3188                            let insert_extra_newline =
 3189                                language.brackets().any(|(pair, enabled)| {
 3190                                    let pair_start = pair.start.trim_end();
 3191                                    let pair_end = pair.end.trim_start();
 3192
 3193                                    enabled
 3194                                        && pair.newline
 3195                                        && buffer.contains_str_at(
 3196                                            end + trailing_whitespace_len,
 3197                                            pair_end,
 3198                                        )
 3199                                        && buffer.contains_str_at(
 3200                                            (start - leading_whitespace_len)
 3201                                                .saturating_sub(pair_start.len()),
 3202                                            pair_start,
 3203                                        )
 3204                                });
 3205
 3206                            // Comment extension on newline is allowed only for cursor selections
 3207                            let comment_delimiter = maybe!({
 3208                                if !selection_is_empty {
 3209                                    return None;
 3210                                }
 3211
 3212                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3213                                    return None;
 3214                                }
 3215
 3216                                let delimiters = language.line_comment_prefixes();
 3217                                let max_len_of_delimiter =
 3218                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3219                                let (snapshot, range) =
 3220                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3221
 3222                                let mut index_of_first_non_whitespace = 0;
 3223                                let comment_candidate = snapshot
 3224                                    .chars_for_range(range)
 3225                                    .skip_while(|c| {
 3226                                        let should_skip = c.is_whitespace();
 3227                                        if should_skip {
 3228                                            index_of_first_non_whitespace += 1;
 3229                                        }
 3230                                        should_skip
 3231                                    })
 3232                                    .take(max_len_of_delimiter)
 3233                                    .collect::<String>();
 3234                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3235                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3236                                })?;
 3237                                let cursor_is_placed_after_comment_marker =
 3238                                    index_of_first_non_whitespace + comment_prefix.len()
 3239                                        <= start_point.column as usize;
 3240                                if cursor_is_placed_after_comment_marker {
 3241                                    Some(comment_prefix.clone())
 3242                                } else {
 3243                                    None
 3244                                }
 3245                            });
 3246                            (comment_delimiter, insert_extra_newline)
 3247                        } else {
 3248                            (None, false)
 3249                        };
 3250
 3251                        let capacity_for_delimiter = comment_delimiter
 3252                            .as_deref()
 3253                            .map(str::len)
 3254                            .unwrap_or_default();
 3255                        let mut new_text =
 3256                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3257                        new_text.push('\n');
 3258                        new_text.extend(indent.chars());
 3259                        if let Some(delimiter) = &comment_delimiter {
 3260                            new_text.push_str(delimiter);
 3261                        }
 3262                        if insert_extra_newline {
 3263                            new_text = new_text.repeat(2);
 3264                        }
 3265
 3266                        let anchor = buffer.anchor_after(end);
 3267                        let new_selection = selection.map(|_| anchor);
 3268                        (
 3269                            (start..end, new_text),
 3270                            (insert_extra_newline, new_selection),
 3271                        )
 3272                    })
 3273                    .unzip()
 3274            };
 3275
 3276            this.edit_with_autoindent(edits, cx);
 3277            let buffer = this.buffer.read(cx).snapshot(cx);
 3278            let new_selections = selection_fixup_info
 3279                .into_iter()
 3280                .map(|(extra_newline_inserted, new_selection)| {
 3281                    let mut cursor = new_selection.end.to_point(&buffer);
 3282                    if extra_newline_inserted {
 3283                        cursor.row -= 1;
 3284                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3285                    }
 3286                    new_selection.map(|_| cursor)
 3287                })
 3288                .collect();
 3289
 3290            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3291                s.select(new_selections)
 3292            });
 3293            this.refresh_inline_completion(true, false, window, cx);
 3294        });
 3295    }
 3296
 3297    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3298        let buffer = self.buffer.read(cx);
 3299        let snapshot = buffer.snapshot(cx);
 3300
 3301        let mut edits = Vec::new();
 3302        let mut rows = Vec::new();
 3303
 3304        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3305            let cursor = selection.head();
 3306            let row = cursor.row;
 3307
 3308            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3309
 3310            let newline = "\n".to_string();
 3311            edits.push((start_of_line..start_of_line, newline));
 3312
 3313            rows.push(row + rows_inserted as u32);
 3314        }
 3315
 3316        self.transact(window, cx, |editor, window, cx| {
 3317            editor.edit(edits, cx);
 3318
 3319            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3320                let mut index = 0;
 3321                s.move_cursors_with(|map, _, _| {
 3322                    let row = rows[index];
 3323                    index += 1;
 3324
 3325                    let point = Point::new(row, 0);
 3326                    let boundary = map.next_line_boundary(point).1;
 3327                    let clipped = map.clip_point(boundary, Bias::Left);
 3328
 3329                    (clipped, SelectionGoal::None)
 3330                });
 3331            });
 3332
 3333            let mut indent_edits = Vec::new();
 3334            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3335            for row in rows {
 3336                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3337                for (row, indent) in indents {
 3338                    if indent.len == 0 {
 3339                        continue;
 3340                    }
 3341
 3342                    let text = match indent.kind {
 3343                        IndentKind::Space => " ".repeat(indent.len as usize),
 3344                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3345                    };
 3346                    let point = Point::new(row.0, 0);
 3347                    indent_edits.push((point..point, text));
 3348                }
 3349            }
 3350            editor.edit(indent_edits, cx);
 3351        });
 3352    }
 3353
 3354    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3355        let buffer = self.buffer.read(cx);
 3356        let snapshot = buffer.snapshot(cx);
 3357
 3358        let mut edits = Vec::new();
 3359        let mut rows = Vec::new();
 3360        let mut rows_inserted = 0;
 3361
 3362        for selection in self.selections.all_adjusted(cx) {
 3363            let cursor = selection.head();
 3364            let row = cursor.row;
 3365
 3366            let point = Point::new(row + 1, 0);
 3367            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3368
 3369            let newline = "\n".to_string();
 3370            edits.push((start_of_line..start_of_line, newline));
 3371
 3372            rows_inserted += 1;
 3373            rows.push(row + rows_inserted);
 3374        }
 3375
 3376        self.transact(window, cx, |editor, window, cx| {
 3377            editor.edit(edits, cx);
 3378
 3379            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3380                let mut index = 0;
 3381                s.move_cursors_with(|map, _, _| {
 3382                    let row = rows[index];
 3383                    index += 1;
 3384
 3385                    let point = Point::new(row, 0);
 3386                    let boundary = map.next_line_boundary(point).1;
 3387                    let clipped = map.clip_point(boundary, Bias::Left);
 3388
 3389                    (clipped, SelectionGoal::None)
 3390                });
 3391            });
 3392
 3393            let mut indent_edits = Vec::new();
 3394            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3395            for row in rows {
 3396                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3397                for (row, indent) in indents {
 3398                    if indent.len == 0 {
 3399                        continue;
 3400                    }
 3401
 3402                    let text = match indent.kind {
 3403                        IndentKind::Space => " ".repeat(indent.len as usize),
 3404                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3405                    };
 3406                    let point = Point::new(row.0, 0);
 3407                    indent_edits.push((point..point, text));
 3408                }
 3409            }
 3410            editor.edit(indent_edits, cx);
 3411        });
 3412    }
 3413
 3414    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3415        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3416            original_indent_columns: Vec::new(),
 3417        });
 3418        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3419    }
 3420
 3421    fn insert_with_autoindent_mode(
 3422        &mut self,
 3423        text: &str,
 3424        autoindent_mode: Option<AutoindentMode>,
 3425        window: &mut Window,
 3426        cx: &mut Context<Self>,
 3427    ) {
 3428        if self.read_only(cx) {
 3429            return;
 3430        }
 3431
 3432        let text: Arc<str> = text.into();
 3433        self.transact(window, cx, |this, window, cx| {
 3434            let old_selections = this.selections.all_adjusted(cx);
 3435            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3436                let anchors = {
 3437                    let snapshot = buffer.read(cx);
 3438                    old_selections
 3439                        .iter()
 3440                        .map(|s| {
 3441                            let anchor = snapshot.anchor_after(s.head());
 3442                            s.map(|_| anchor)
 3443                        })
 3444                        .collect::<Vec<_>>()
 3445                };
 3446                buffer.edit(
 3447                    old_selections
 3448                        .iter()
 3449                        .map(|s| (s.start..s.end, text.clone())),
 3450                    autoindent_mode,
 3451                    cx,
 3452                );
 3453                anchors
 3454            });
 3455
 3456            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3457                s.select_anchors(selection_anchors);
 3458            });
 3459
 3460            cx.notify();
 3461        });
 3462    }
 3463
 3464    fn trigger_completion_on_input(
 3465        &mut self,
 3466        text: &str,
 3467        trigger_in_words: bool,
 3468        window: &mut Window,
 3469        cx: &mut Context<Self>,
 3470    ) {
 3471        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3472            self.show_completions(
 3473                &ShowCompletions {
 3474                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3475                },
 3476                window,
 3477                cx,
 3478            );
 3479        } else {
 3480            self.hide_context_menu(window, cx);
 3481        }
 3482    }
 3483
 3484    fn is_completion_trigger(
 3485        &self,
 3486        text: &str,
 3487        trigger_in_words: bool,
 3488        cx: &mut Context<Self>,
 3489    ) -> bool {
 3490        let position = self.selections.newest_anchor().head();
 3491        let multibuffer = self.buffer.read(cx);
 3492        let Some(buffer) = position
 3493            .buffer_id
 3494            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3495        else {
 3496            return false;
 3497        };
 3498
 3499        if let Some(completion_provider) = &self.completion_provider {
 3500            completion_provider.is_completion_trigger(
 3501                &buffer,
 3502                position.text_anchor,
 3503                text,
 3504                trigger_in_words,
 3505                cx,
 3506            )
 3507        } else {
 3508            false
 3509        }
 3510    }
 3511
 3512    /// If any empty selections is touching the start of its innermost containing autoclose
 3513    /// region, expand it to select the brackets.
 3514    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3515        let selections = self.selections.all::<usize>(cx);
 3516        let buffer = self.buffer.read(cx).read(cx);
 3517        let new_selections = self
 3518            .selections_with_autoclose_regions(selections, &buffer)
 3519            .map(|(mut selection, region)| {
 3520                if !selection.is_empty() {
 3521                    return selection;
 3522                }
 3523
 3524                if let Some(region) = region {
 3525                    let mut range = region.range.to_offset(&buffer);
 3526                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3527                        range.start -= region.pair.start.len();
 3528                        if buffer.contains_str_at(range.start, &region.pair.start)
 3529                            && buffer.contains_str_at(range.end, &region.pair.end)
 3530                        {
 3531                            range.end += region.pair.end.len();
 3532                            selection.start = range.start;
 3533                            selection.end = range.end;
 3534
 3535                            return selection;
 3536                        }
 3537                    }
 3538                }
 3539
 3540                let always_treat_brackets_as_autoclosed = buffer
 3541                    .settings_at(selection.start, cx)
 3542                    .always_treat_brackets_as_autoclosed;
 3543
 3544                if !always_treat_brackets_as_autoclosed {
 3545                    return selection;
 3546                }
 3547
 3548                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3549                    for (pair, enabled) in scope.brackets() {
 3550                        if !enabled || !pair.close {
 3551                            continue;
 3552                        }
 3553
 3554                        if buffer.contains_str_at(selection.start, &pair.end) {
 3555                            let pair_start_len = pair.start.len();
 3556                            if buffer.contains_str_at(
 3557                                selection.start.saturating_sub(pair_start_len),
 3558                                &pair.start,
 3559                            ) {
 3560                                selection.start -= pair_start_len;
 3561                                selection.end += pair.end.len();
 3562
 3563                                return selection;
 3564                            }
 3565                        }
 3566                    }
 3567                }
 3568
 3569                selection
 3570            })
 3571            .collect();
 3572
 3573        drop(buffer);
 3574        self.change_selections(None, window, cx, |selections| {
 3575            selections.select(new_selections)
 3576        });
 3577    }
 3578
 3579    /// Iterate the given selections, and for each one, find the smallest surrounding
 3580    /// autoclose region. This uses the ordering of the selections and the autoclose
 3581    /// regions to avoid repeated comparisons.
 3582    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3583        &'a self,
 3584        selections: impl IntoIterator<Item = Selection<D>>,
 3585        buffer: &'a MultiBufferSnapshot,
 3586    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3587        let mut i = 0;
 3588        let mut regions = self.autoclose_regions.as_slice();
 3589        selections.into_iter().map(move |selection| {
 3590            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3591
 3592            let mut enclosing = None;
 3593            while let Some(pair_state) = regions.get(i) {
 3594                if pair_state.range.end.to_offset(buffer) < range.start {
 3595                    regions = &regions[i + 1..];
 3596                    i = 0;
 3597                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3598                    break;
 3599                } else {
 3600                    if pair_state.selection_id == selection.id {
 3601                        enclosing = Some(pair_state);
 3602                    }
 3603                    i += 1;
 3604                }
 3605            }
 3606
 3607            (selection, enclosing)
 3608        })
 3609    }
 3610
 3611    /// Remove any autoclose regions that no longer contain their selection.
 3612    fn invalidate_autoclose_regions(
 3613        &mut self,
 3614        mut selections: &[Selection<Anchor>],
 3615        buffer: &MultiBufferSnapshot,
 3616    ) {
 3617        self.autoclose_regions.retain(|state| {
 3618            let mut i = 0;
 3619            while let Some(selection) = selections.get(i) {
 3620                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3621                    selections = &selections[1..];
 3622                    continue;
 3623                }
 3624                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3625                    break;
 3626                }
 3627                if selection.id == state.selection_id {
 3628                    return true;
 3629                } else {
 3630                    i += 1;
 3631                }
 3632            }
 3633            false
 3634        });
 3635    }
 3636
 3637    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3638        let offset = position.to_offset(buffer);
 3639        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3640        if offset > word_range.start && kind == Some(CharKind::Word) {
 3641            Some(
 3642                buffer
 3643                    .text_for_range(word_range.start..offset)
 3644                    .collect::<String>(),
 3645            )
 3646        } else {
 3647            None
 3648        }
 3649    }
 3650
 3651    pub fn toggle_inlay_hints(
 3652        &mut self,
 3653        _: &ToggleInlayHints,
 3654        _: &mut Window,
 3655        cx: &mut Context<Self>,
 3656    ) {
 3657        self.refresh_inlay_hints(
 3658            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3659            cx,
 3660        );
 3661    }
 3662
 3663    pub fn inlay_hints_enabled(&self) -> bool {
 3664        self.inlay_hint_cache.enabled
 3665    }
 3666
 3667    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3668        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3669            return;
 3670        }
 3671
 3672        let reason_description = reason.description();
 3673        let ignore_debounce = matches!(
 3674            reason,
 3675            InlayHintRefreshReason::SettingsChange(_)
 3676                | InlayHintRefreshReason::Toggle(_)
 3677                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3678        );
 3679        let (invalidate_cache, required_languages) = match reason {
 3680            InlayHintRefreshReason::Toggle(enabled) => {
 3681                self.inlay_hint_cache.enabled = enabled;
 3682                if enabled {
 3683                    (InvalidationStrategy::RefreshRequested, None)
 3684                } else {
 3685                    self.inlay_hint_cache.clear();
 3686                    self.splice_inlays(
 3687                        &self
 3688                            .visible_inlay_hints(cx)
 3689                            .iter()
 3690                            .map(|inlay| inlay.id)
 3691                            .collect::<Vec<InlayId>>(),
 3692                        Vec::new(),
 3693                        cx,
 3694                    );
 3695                    return;
 3696                }
 3697            }
 3698            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3699                match self.inlay_hint_cache.update_settings(
 3700                    &self.buffer,
 3701                    new_settings,
 3702                    self.visible_inlay_hints(cx),
 3703                    cx,
 3704                ) {
 3705                    ControlFlow::Break(Some(InlaySplice {
 3706                        to_remove,
 3707                        to_insert,
 3708                    })) => {
 3709                        self.splice_inlays(&to_remove, to_insert, cx);
 3710                        return;
 3711                    }
 3712                    ControlFlow::Break(None) => return,
 3713                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3714                }
 3715            }
 3716            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3717                if let Some(InlaySplice {
 3718                    to_remove,
 3719                    to_insert,
 3720                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3721                {
 3722                    self.splice_inlays(&to_remove, to_insert, cx);
 3723                }
 3724                return;
 3725            }
 3726            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3727            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3728                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3729            }
 3730            InlayHintRefreshReason::RefreshRequested => {
 3731                (InvalidationStrategy::RefreshRequested, None)
 3732            }
 3733        };
 3734
 3735        if let Some(InlaySplice {
 3736            to_remove,
 3737            to_insert,
 3738        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3739            reason_description,
 3740            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3741            invalidate_cache,
 3742            ignore_debounce,
 3743            cx,
 3744        ) {
 3745            self.splice_inlays(&to_remove, to_insert, cx);
 3746        }
 3747    }
 3748
 3749    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3750        self.display_map
 3751            .read(cx)
 3752            .current_inlays()
 3753            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3754            .cloned()
 3755            .collect()
 3756    }
 3757
 3758    pub fn excerpts_for_inlay_hints_query(
 3759        &self,
 3760        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3761        cx: &mut Context<Editor>,
 3762    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3763        let Some(project) = self.project.as_ref() else {
 3764            return HashMap::default();
 3765        };
 3766        let project = project.read(cx);
 3767        let multi_buffer = self.buffer().read(cx);
 3768        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3769        let multi_buffer_visible_start = self
 3770            .scroll_manager
 3771            .anchor()
 3772            .anchor
 3773            .to_point(&multi_buffer_snapshot);
 3774        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3775            multi_buffer_visible_start
 3776                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3777            Bias::Left,
 3778        );
 3779        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3780        multi_buffer_snapshot
 3781            .range_to_buffer_ranges(multi_buffer_visible_range)
 3782            .into_iter()
 3783            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3784            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3785                let buffer_file = project::File::from_dyn(buffer.file())?;
 3786                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3787                let worktree_entry = buffer_worktree
 3788                    .read(cx)
 3789                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3790                if worktree_entry.is_ignored {
 3791                    return None;
 3792                }
 3793
 3794                let language = buffer.language()?;
 3795                if let Some(restrict_to_languages) = restrict_to_languages {
 3796                    if !restrict_to_languages.contains(language) {
 3797                        return None;
 3798                    }
 3799                }
 3800                Some((
 3801                    excerpt_id,
 3802                    (
 3803                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3804                        buffer.version().clone(),
 3805                        excerpt_visible_range,
 3806                    ),
 3807                ))
 3808            })
 3809            .collect()
 3810    }
 3811
 3812    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3813        TextLayoutDetails {
 3814            text_system: window.text_system().clone(),
 3815            editor_style: self.style.clone().unwrap(),
 3816            rem_size: window.rem_size(),
 3817            scroll_anchor: self.scroll_manager.anchor(),
 3818            visible_rows: self.visible_line_count(),
 3819            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3820        }
 3821    }
 3822
 3823    pub fn splice_inlays(
 3824        &self,
 3825        to_remove: &[InlayId],
 3826        to_insert: Vec<Inlay>,
 3827        cx: &mut Context<Self>,
 3828    ) {
 3829        self.display_map.update(cx, |display_map, cx| {
 3830            display_map.splice_inlays(to_remove, to_insert, cx)
 3831        });
 3832        cx.notify();
 3833    }
 3834
 3835    fn trigger_on_type_formatting(
 3836        &self,
 3837        input: String,
 3838        window: &mut Window,
 3839        cx: &mut Context<Self>,
 3840    ) -> Option<Task<Result<()>>> {
 3841        if input.len() != 1 {
 3842            return None;
 3843        }
 3844
 3845        let project = self.project.as_ref()?;
 3846        let position = self.selections.newest_anchor().head();
 3847        let (buffer, buffer_position) = self
 3848            .buffer
 3849            .read(cx)
 3850            .text_anchor_for_position(position, cx)?;
 3851
 3852        let settings = language_settings::language_settings(
 3853            buffer
 3854                .read(cx)
 3855                .language_at(buffer_position)
 3856                .map(|l| l.name()),
 3857            buffer.read(cx).file(),
 3858            cx,
 3859        );
 3860        if !settings.use_on_type_format {
 3861            return None;
 3862        }
 3863
 3864        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3865        // hence we do LSP request & edit on host side only — add formats to host's history.
 3866        let push_to_lsp_host_history = true;
 3867        // If this is not the host, append its history with new edits.
 3868        let push_to_client_history = project.read(cx).is_via_collab();
 3869
 3870        let on_type_formatting = project.update(cx, |project, cx| {
 3871            project.on_type_format(
 3872                buffer.clone(),
 3873                buffer_position,
 3874                input,
 3875                push_to_lsp_host_history,
 3876                cx,
 3877            )
 3878        });
 3879        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3880            if let Some(transaction) = on_type_formatting.await? {
 3881                if push_to_client_history {
 3882                    buffer
 3883                        .update(&mut cx, |buffer, _| {
 3884                            buffer.push_transaction(transaction, Instant::now());
 3885                        })
 3886                        .ok();
 3887                }
 3888                editor.update(&mut cx, |editor, cx| {
 3889                    editor.refresh_document_highlights(cx);
 3890                })?;
 3891            }
 3892            Ok(())
 3893        }))
 3894    }
 3895
 3896    pub fn show_completions(
 3897        &mut self,
 3898        options: &ShowCompletions,
 3899        window: &mut Window,
 3900        cx: &mut Context<Self>,
 3901    ) {
 3902        if self.pending_rename.is_some() {
 3903            return;
 3904        }
 3905
 3906        let Some(provider) = self.completion_provider.as_ref() else {
 3907            return;
 3908        };
 3909
 3910        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3911            return;
 3912        }
 3913
 3914        let position = self.selections.newest_anchor().head();
 3915        if position.diff_base_anchor.is_some() {
 3916            return;
 3917        }
 3918        let (buffer, buffer_position) =
 3919            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3920                output
 3921            } else {
 3922                return;
 3923            };
 3924        let show_completion_documentation = buffer
 3925            .read(cx)
 3926            .snapshot()
 3927            .settings_at(buffer_position, cx)
 3928            .show_completion_documentation;
 3929
 3930        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3931
 3932        let trigger_kind = match &options.trigger {
 3933            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3934                CompletionTriggerKind::TRIGGER_CHARACTER
 3935            }
 3936            _ => CompletionTriggerKind::INVOKED,
 3937        };
 3938        let completion_context = CompletionContext {
 3939            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3940                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3941                    Some(String::from(trigger))
 3942                } else {
 3943                    None
 3944                }
 3945            }),
 3946            trigger_kind,
 3947        };
 3948        let completions =
 3949            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3950        let sort_completions = provider.sort_completions();
 3951
 3952        let id = post_inc(&mut self.next_completion_id);
 3953        let task = cx.spawn_in(window, |editor, mut cx| {
 3954            async move {
 3955                editor.update(&mut cx, |this, _| {
 3956                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3957                })?;
 3958                let completions = completions.await.log_err();
 3959                let menu = if let Some(completions) = completions {
 3960                    let mut menu = CompletionsMenu::new(
 3961                        id,
 3962                        sort_completions,
 3963                        show_completion_documentation,
 3964                        position,
 3965                        buffer.clone(),
 3966                        completions.into(),
 3967                    );
 3968
 3969                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3970                        .await;
 3971
 3972                    menu.visible().then_some(menu)
 3973                } else {
 3974                    None
 3975                };
 3976
 3977                editor.update_in(&mut cx, |editor, window, cx| {
 3978                    match editor.context_menu.borrow().as_ref() {
 3979                        None => {}
 3980                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3981                            if prev_menu.id > id {
 3982                                return;
 3983                            }
 3984                        }
 3985                        _ => return,
 3986                    }
 3987
 3988                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3989                        let mut menu = menu.unwrap();
 3990                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3991
 3992                        *editor.context_menu.borrow_mut() =
 3993                            Some(CodeContextMenu::Completions(menu));
 3994
 3995                        if editor.show_edit_predictions_in_menu() {
 3996                            editor.update_visible_inline_completion(window, cx);
 3997                        } else {
 3998                            editor.discard_inline_completion(false, cx);
 3999                        }
 4000
 4001                        cx.notify();
 4002                    } else if editor.completion_tasks.len() <= 1 {
 4003                        // If there are no more completion tasks and the last menu was
 4004                        // empty, we should hide it.
 4005                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4006                        // If it was already hidden and we don't show inline
 4007                        // completions in the menu, we should also show the
 4008                        // inline-completion when available.
 4009                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4010                            editor.update_visible_inline_completion(window, cx);
 4011                        }
 4012                    }
 4013                })?;
 4014
 4015                Ok::<_, anyhow::Error>(())
 4016            }
 4017            .log_err()
 4018        });
 4019
 4020        self.completion_tasks.push((id, task));
 4021    }
 4022
 4023    pub fn confirm_completion(
 4024        &mut self,
 4025        action: &ConfirmCompletion,
 4026        window: &mut Window,
 4027        cx: &mut Context<Self>,
 4028    ) -> Option<Task<Result<()>>> {
 4029        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4030    }
 4031
 4032    pub fn compose_completion(
 4033        &mut self,
 4034        action: &ComposeCompletion,
 4035        window: &mut Window,
 4036        cx: &mut Context<Self>,
 4037    ) -> Option<Task<Result<()>>> {
 4038        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4039    }
 4040
 4041    fn do_completion(
 4042        &mut self,
 4043        item_ix: Option<usize>,
 4044        intent: CompletionIntent,
 4045        window: &mut Window,
 4046        cx: &mut Context<Editor>,
 4047    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4048        use language::ToOffset as _;
 4049
 4050        let completions_menu =
 4051            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4052                menu
 4053            } else {
 4054                return None;
 4055            };
 4056
 4057        let entries = completions_menu.entries.borrow();
 4058        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4059        if self.show_edit_predictions_in_menu() {
 4060            self.discard_inline_completion(true, cx);
 4061        }
 4062        let candidate_id = mat.candidate_id;
 4063        drop(entries);
 4064
 4065        let buffer_handle = completions_menu.buffer;
 4066        let completion = completions_menu
 4067            .completions
 4068            .borrow()
 4069            .get(candidate_id)?
 4070            .clone();
 4071        cx.stop_propagation();
 4072
 4073        let snippet;
 4074        let text;
 4075
 4076        if completion.is_snippet() {
 4077            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4078            text = snippet.as_ref().unwrap().text.clone();
 4079        } else {
 4080            snippet = None;
 4081            text = completion.new_text.clone();
 4082        };
 4083        let selections = self.selections.all::<usize>(cx);
 4084        let buffer = buffer_handle.read(cx);
 4085        let old_range = completion.old_range.to_offset(buffer);
 4086        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4087
 4088        let newest_selection = self.selections.newest_anchor();
 4089        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4090            return None;
 4091        }
 4092
 4093        let lookbehind = newest_selection
 4094            .start
 4095            .text_anchor
 4096            .to_offset(buffer)
 4097            .saturating_sub(old_range.start);
 4098        let lookahead = old_range
 4099            .end
 4100            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4101        let mut common_prefix_len = old_text
 4102            .bytes()
 4103            .zip(text.bytes())
 4104            .take_while(|(a, b)| a == b)
 4105            .count();
 4106
 4107        let snapshot = self.buffer.read(cx).snapshot(cx);
 4108        let mut range_to_replace: Option<Range<isize>> = None;
 4109        let mut ranges = Vec::new();
 4110        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4111        for selection in &selections {
 4112            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4113                let start = selection.start.saturating_sub(lookbehind);
 4114                let end = selection.end + lookahead;
 4115                if selection.id == newest_selection.id {
 4116                    range_to_replace = Some(
 4117                        ((start + common_prefix_len) as isize - selection.start as isize)
 4118                            ..(end as isize - selection.start as isize),
 4119                    );
 4120                }
 4121                ranges.push(start + common_prefix_len..end);
 4122            } else {
 4123                common_prefix_len = 0;
 4124                ranges.clear();
 4125                ranges.extend(selections.iter().map(|s| {
 4126                    if s.id == newest_selection.id {
 4127                        range_to_replace = Some(
 4128                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4129                                - selection.start as isize
 4130                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4131                                    - selection.start as isize,
 4132                        );
 4133                        old_range.clone()
 4134                    } else {
 4135                        s.start..s.end
 4136                    }
 4137                }));
 4138                break;
 4139            }
 4140            if !self.linked_edit_ranges.is_empty() {
 4141                let start_anchor = snapshot.anchor_before(selection.head());
 4142                let end_anchor = snapshot.anchor_after(selection.tail());
 4143                if let Some(ranges) = self
 4144                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4145                {
 4146                    for (buffer, edits) in ranges {
 4147                        linked_edits.entry(buffer.clone()).or_default().extend(
 4148                            edits
 4149                                .into_iter()
 4150                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4151                        );
 4152                    }
 4153                }
 4154            }
 4155        }
 4156        let text = &text[common_prefix_len..];
 4157
 4158        cx.emit(EditorEvent::InputHandled {
 4159            utf16_range_to_replace: range_to_replace,
 4160            text: text.into(),
 4161        });
 4162
 4163        self.transact(window, cx, |this, window, cx| {
 4164            if let Some(mut snippet) = snippet {
 4165                snippet.text = text.to_string();
 4166                for tabstop in snippet
 4167                    .tabstops
 4168                    .iter_mut()
 4169                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4170                {
 4171                    tabstop.start -= common_prefix_len as isize;
 4172                    tabstop.end -= common_prefix_len as isize;
 4173                }
 4174
 4175                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4176            } else {
 4177                this.buffer.update(cx, |buffer, cx| {
 4178                    buffer.edit(
 4179                        ranges.iter().map(|range| (range.clone(), text)),
 4180                        this.autoindent_mode.clone(),
 4181                        cx,
 4182                    );
 4183                });
 4184            }
 4185            for (buffer, edits) in linked_edits {
 4186                buffer.update(cx, |buffer, cx| {
 4187                    let snapshot = buffer.snapshot();
 4188                    let edits = edits
 4189                        .into_iter()
 4190                        .map(|(range, text)| {
 4191                            use text::ToPoint as TP;
 4192                            let end_point = TP::to_point(&range.end, &snapshot);
 4193                            let start_point = TP::to_point(&range.start, &snapshot);
 4194                            (start_point..end_point, text)
 4195                        })
 4196                        .sorted_by_key(|(range, _)| range.start)
 4197                        .collect::<Vec<_>>();
 4198                    buffer.edit(edits, None, cx);
 4199                })
 4200            }
 4201
 4202            this.refresh_inline_completion(true, false, window, cx);
 4203        });
 4204
 4205        let show_new_completions_on_confirm = completion
 4206            .confirm
 4207            .as_ref()
 4208            .map_or(false, |confirm| confirm(intent, window, cx));
 4209        if show_new_completions_on_confirm {
 4210            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4211        }
 4212
 4213        let provider = self.completion_provider.as_ref()?;
 4214        drop(completion);
 4215        let apply_edits = provider.apply_additional_edits_for_completion(
 4216            buffer_handle,
 4217            completions_menu.completions.clone(),
 4218            candidate_id,
 4219            true,
 4220            cx,
 4221        );
 4222
 4223        let editor_settings = EditorSettings::get_global(cx);
 4224        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4225            // After the code completion is finished, users often want to know what signatures are needed.
 4226            // so we should automatically call signature_help
 4227            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4228        }
 4229
 4230        Some(cx.foreground_executor().spawn(async move {
 4231            apply_edits.await?;
 4232            Ok(())
 4233        }))
 4234    }
 4235
 4236    pub fn toggle_code_actions(
 4237        &mut self,
 4238        action: &ToggleCodeActions,
 4239        window: &mut Window,
 4240        cx: &mut Context<Self>,
 4241    ) {
 4242        let mut context_menu = self.context_menu.borrow_mut();
 4243        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4244            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4245                // Toggle if we're selecting the same one
 4246                *context_menu = None;
 4247                cx.notify();
 4248                return;
 4249            } else {
 4250                // Otherwise, clear it and start a new one
 4251                *context_menu = None;
 4252                cx.notify();
 4253            }
 4254        }
 4255        drop(context_menu);
 4256        let snapshot = self.snapshot(window, cx);
 4257        let deployed_from_indicator = action.deployed_from_indicator;
 4258        let mut task = self.code_actions_task.take();
 4259        let action = action.clone();
 4260        cx.spawn_in(window, |editor, mut cx| async move {
 4261            while let Some(prev_task) = task {
 4262                prev_task.await.log_err();
 4263                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4264            }
 4265
 4266            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4267                if editor.focus_handle.is_focused(window) {
 4268                    let multibuffer_point = action
 4269                        .deployed_from_indicator
 4270                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4271                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4272                    let (buffer, buffer_row) = snapshot
 4273                        .buffer_snapshot
 4274                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4275                        .and_then(|(buffer_snapshot, range)| {
 4276                            editor
 4277                                .buffer
 4278                                .read(cx)
 4279                                .buffer(buffer_snapshot.remote_id())
 4280                                .map(|buffer| (buffer, range.start.row))
 4281                        })?;
 4282                    let (_, code_actions) = editor
 4283                        .available_code_actions
 4284                        .clone()
 4285                        .and_then(|(location, code_actions)| {
 4286                            let snapshot = location.buffer.read(cx).snapshot();
 4287                            let point_range = location.range.to_point(&snapshot);
 4288                            let point_range = point_range.start.row..=point_range.end.row;
 4289                            if point_range.contains(&buffer_row) {
 4290                                Some((location, code_actions))
 4291                            } else {
 4292                                None
 4293                            }
 4294                        })
 4295                        .unzip();
 4296                    let buffer_id = buffer.read(cx).remote_id();
 4297                    let tasks = editor
 4298                        .tasks
 4299                        .get(&(buffer_id, buffer_row))
 4300                        .map(|t| Arc::new(t.to_owned()));
 4301                    if tasks.is_none() && code_actions.is_none() {
 4302                        return None;
 4303                    }
 4304
 4305                    editor.completion_tasks.clear();
 4306                    editor.discard_inline_completion(false, cx);
 4307                    let task_context =
 4308                        tasks
 4309                            .as_ref()
 4310                            .zip(editor.project.clone())
 4311                            .map(|(tasks, project)| {
 4312                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4313                            });
 4314
 4315                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4316                        let task_context = match task_context {
 4317                            Some(task_context) => task_context.await,
 4318                            None => None,
 4319                        };
 4320                        let resolved_tasks =
 4321                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4322                                Rc::new(ResolvedTasks {
 4323                                    templates: tasks.resolve(&task_context).collect(),
 4324                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4325                                        multibuffer_point.row,
 4326                                        tasks.column,
 4327                                    )),
 4328                                })
 4329                            });
 4330                        let spawn_straight_away = resolved_tasks
 4331                            .as_ref()
 4332                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4333                            && code_actions
 4334                                .as_ref()
 4335                                .map_or(true, |actions| actions.is_empty());
 4336                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4337                            *editor.context_menu.borrow_mut() =
 4338                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4339                                    buffer,
 4340                                    actions: CodeActionContents {
 4341                                        tasks: resolved_tasks,
 4342                                        actions: code_actions,
 4343                                    },
 4344                                    selected_item: Default::default(),
 4345                                    scroll_handle: UniformListScrollHandle::default(),
 4346                                    deployed_from_indicator,
 4347                                }));
 4348                            if spawn_straight_away {
 4349                                if let Some(task) = editor.confirm_code_action(
 4350                                    &ConfirmCodeAction { item_ix: Some(0) },
 4351                                    window,
 4352                                    cx,
 4353                                ) {
 4354                                    cx.notify();
 4355                                    return task;
 4356                                }
 4357                            }
 4358                            cx.notify();
 4359                            Task::ready(Ok(()))
 4360                        }) {
 4361                            task.await
 4362                        } else {
 4363                            Ok(())
 4364                        }
 4365                    }))
 4366                } else {
 4367                    Some(Task::ready(Ok(())))
 4368                }
 4369            })?;
 4370            if let Some(task) = spawned_test_task {
 4371                task.await?;
 4372            }
 4373
 4374            Ok::<_, anyhow::Error>(())
 4375        })
 4376        .detach_and_log_err(cx);
 4377    }
 4378
 4379    pub fn confirm_code_action(
 4380        &mut self,
 4381        action: &ConfirmCodeAction,
 4382        window: &mut Window,
 4383        cx: &mut Context<Self>,
 4384    ) -> Option<Task<Result<()>>> {
 4385        let actions_menu =
 4386            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4387                menu
 4388            } else {
 4389                return None;
 4390            };
 4391        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4392        let action = actions_menu.actions.get(action_ix)?;
 4393        let title = action.label();
 4394        let buffer = actions_menu.buffer;
 4395        let workspace = self.workspace()?;
 4396
 4397        match action {
 4398            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4399                workspace.update(cx, |workspace, cx| {
 4400                    workspace::tasks::schedule_resolved_task(
 4401                        workspace,
 4402                        task_source_kind,
 4403                        resolved_task,
 4404                        false,
 4405                        cx,
 4406                    );
 4407
 4408                    Some(Task::ready(Ok(())))
 4409                })
 4410            }
 4411            CodeActionsItem::CodeAction {
 4412                excerpt_id,
 4413                action,
 4414                provider,
 4415            } => {
 4416                let apply_code_action =
 4417                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4418                let workspace = workspace.downgrade();
 4419                Some(cx.spawn_in(window, |editor, cx| async move {
 4420                    let project_transaction = apply_code_action.await?;
 4421                    Self::open_project_transaction(
 4422                        &editor,
 4423                        workspace,
 4424                        project_transaction,
 4425                        title,
 4426                        cx,
 4427                    )
 4428                    .await
 4429                }))
 4430            }
 4431        }
 4432    }
 4433
 4434    pub async fn open_project_transaction(
 4435        this: &WeakEntity<Editor>,
 4436        workspace: WeakEntity<Workspace>,
 4437        transaction: ProjectTransaction,
 4438        title: String,
 4439        mut cx: AsyncWindowContext,
 4440    ) -> Result<()> {
 4441        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4442        cx.update(|_, cx| {
 4443            entries.sort_unstable_by_key(|(buffer, _)| {
 4444                buffer.read(cx).file().map(|f| f.path().clone())
 4445            });
 4446        })?;
 4447
 4448        // If the project transaction's edits are all contained within this editor, then
 4449        // avoid opening a new editor to display them.
 4450
 4451        if let Some((buffer, transaction)) = entries.first() {
 4452            if entries.len() == 1 {
 4453                let excerpt = this.update(&mut cx, |editor, cx| {
 4454                    editor
 4455                        .buffer()
 4456                        .read(cx)
 4457                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4458                })?;
 4459                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4460                    if excerpted_buffer == *buffer {
 4461                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4462                            let excerpt_range = excerpt_range.to_offset(buffer);
 4463                            buffer
 4464                                .edited_ranges_for_transaction::<usize>(transaction)
 4465                                .all(|range| {
 4466                                    excerpt_range.start <= range.start
 4467                                        && excerpt_range.end >= range.end
 4468                                })
 4469                        })?;
 4470
 4471                        if all_edits_within_excerpt {
 4472                            return Ok(());
 4473                        }
 4474                    }
 4475                }
 4476            }
 4477        } else {
 4478            return Ok(());
 4479        }
 4480
 4481        let mut ranges_to_highlight = Vec::new();
 4482        let excerpt_buffer = cx.new(|cx| {
 4483            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4484            for (buffer_handle, transaction) in &entries {
 4485                let buffer = buffer_handle.read(cx);
 4486                ranges_to_highlight.extend(
 4487                    multibuffer.push_excerpts_with_context_lines(
 4488                        buffer_handle.clone(),
 4489                        buffer
 4490                            .edited_ranges_for_transaction::<usize>(transaction)
 4491                            .collect(),
 4492                        DEFAULT_MULTIBUFFER_CONTEXT,
 4493                        cx,
 4494                    ),
 4495                );
 4496            }
 4497            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4498            multibuffer
 4499        })?;
 4500
 4501        workspace.update_in(&mut cx, |workspace, window, cx| {
 4502            let project = workspace.project().clone();
 4503            let editor = cx
 4504                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4505            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4506            editor.update(cx, |editor, cx| {
 4507                editor.highlight_background::<Self>(
 4508                    &ranges_to_highlight,
 4509                    |theme| theme.editor_highlighted_line_background,
 4510                    cx,
 4511                );
 4512            });
 4513        })?;
 4514
 4515        Ok(())
 4516    }
 4517
 4518    pub fn clear_code_action_providers(&mut self) {
 4519        self.code_action_providers.clear();
 4520        self.available_code_actions.take();
 4521    }
 4522
 4523    pub fn add_code_action_provider(
 4524        &mut self,
 4525        provider: Rc<dyn CodeActionProvider>,
 4526        window: &mut Window,
 4527        cx: &mut Context<Self>,
 4528    ) {
 4529        if self
 4530            .code_action_providers
 4531            .iter()
 4532            .any(|existing_provider| existing_provider.id() == provider.id())
 4533        {
 4534            return;
 4535        }
 4536
 4537        self.code_action_providers.push(provider);
 4538        self.refresh_code_actions(window, cx);
 4539    }
 4540
 4541    pub fn remove_code_action_provider(
 4542        &mut self,
 4543        id: Arc<str>,
 4544        window: &mut Window,
 4545        cx: &mut Context<Self>,
 4546    ) {
 4547        self.code_action_providers
 4548            .retain(|provider| provider.id() != id);
 4549        self.refresh_code_actions(window, cx);
 4550    }
 4551
 4552    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4553        let buffer = self.buffer.read(cx);
 4554        let newest_selection = self.selections.newest_anchor().clone();
 4555        if newest_selection.head().diff_base_anchor.is_some() {
 4556            return None;
 4557        }
 4558        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4559        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4560        if start_buffer != end_buffer {
 4561            return None;
 4562        }
 4563
 4564        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4565            cx.background_executor()
 4566                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4567                .await;
 4568
 4569            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4570                let providers = this.code_action_providers.clone();
 4571                let tasks = this
 4572                    .code_action_providers
 4573                    .iter()
 4574                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4575                    .collect::<Vec<_>>();
 4576                (providers, tasks)
 4577            })?;
 4578
 4579            let mut actions = Vec::new();
 4580            for (provider, provider_actions) in
 4581                providers.into_iter().zip(future::join_all(tasks).await)
 4582            {
 4583                if let Some(provider_actions) = provider_actions.log_err() {
 4584                    actions.extend(provider_actions.into_iter().map(|action| {
 4585                        AvailableCodeAction {
 4586                            excerpt_id: newest_selection.start.excerpt_id,
 4587                            action,
 4588                            provider: provider.clone(),
 4589                        }
 4590                    }));
 4591                }
 4592            }
 4593
 4594            this.update(&mut cx, |this, cx| {
 4595                this.available_code_actions = if actions.is_empty() {
 4596                    None
 4597                } else {
 4598                    Some((
 4599                        Location {
 4600                            buffer: start_buffer,
 4601                            range: start..end,
 4602                        },
 4603                        actions.into(),
 4604                    ))
 4605                };
 4606                cx.notify();
 4607            })
 4608        }));
 4609        None
 4610    }
 4611
 4612    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4613        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4614            self.show_git_blame_inline = false;
 4615
 4616            self.show_git_blame_inline_delay_task =
 4617                Some(cx.spawn_in(window, |this, mut cx| async move {
 4618                    cx.background_executor().timer(delay).await;
 4619
 4620                    this.update(&mut cx, |this, cx| {
 4621                        this.show_git_blame_inline = true;
 4622                        cx.notify();
 4623                    })
 4624                    .log_err();
 4625                }));
 4626        }
 4627    }
 4628
 4629    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4630        if self.pending_rename.is_some() {
 4631            return None;
 4632        }
 4633
 4634        let provider = self.semantics_provider.clone()?;
 4635        let buffer = self.buffer.read(cx);
 4636        let newest_selection = self.selections.newest_anchor().clone();
 4637        let cursor_position = newest_selection.head();
 4638        let (cursor_buffer, cursor_buffer_position) =
 4639            buffer.text_anchor_for_position(cursor_position, cx)?;
 4640        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4641        if cursor_buffer != tail_buffer {
 4642            return None;
 4643        }
 4644        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4645        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4646            cx.background_executor()
 4647                .timer(Duration::from_millis(debounce))
 4648                .await;
 4649
 4650            let highlights = if let Some(highlights) = cx
 4651                .update(|cx| {
 4652                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4653                })
 4654                .ok()
 4655                .flatten()
 4656            {
 4657                highlights.await.log_err()
 4658            } else {
 4659                None
 4660            };
 4661
 4662            if let Some(highlights) = highlights {
 4663                this.update(&mut cx, |this, cx| {
 4664                    if this.pending_rename.is_some() {
 4665                        return;
 4666                    }
 4667
 4668                    let buffer_id = cursor_position.buffer_id;
 4669                    let buffer = this.buffer.read(cx);
 4670                    if !buffer
 4671                        .text_anchor_for_position(cursor_position, cx)
 4672                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4673                    {
 4674                        return;
 4675                    }
 4676
 4677                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4678                    let mut write_ranges = Vec::new();
 4679                    let mut read_ranges = Vec::new();
 4680                    for highlight in highlights {
 4681                        for (excerpt_id, excerpt_range) in
 4682                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4683                        {
 4684                            let start = highlight
 4685                                .range
 4686                                .start
 4687                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4688                            let end = highlight
 4689                                .range
 4690                                .end
 4691                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4692                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4693                                continue;
 4694                            }
 4695
 4696                            let range = Anchor {
 4697                                buffer_id,
 4698                                excerpt_id,
 4699                                text_anchor: start,
 4700                                diff_base_anchor: None,
 4701                            }..Anchor {
 4702                                buffer_id,
 4703                                excerpt_id,
 4704                                text_anchor: end,
 4705                                diff_base_anchor: None,
 4706                            };
 4707                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4708                                write_ranges.push(range);
 4709                            } else {
 4710                                read_ranges.push(range);
 4711                            }
 4712                        }
 4713                    }
 4714
 4715                    this.highlight_background::<DocumentHighlightRead>(
 4716                        &read_ranges,
 4717                        |theme| theme.editor_document_highlight_read_background,
 4718                        cx,
 4719                    );
 4720                    this.highlight_background::<DocumentHighlightWrite>(
 4721                        &write_ranges,
 4722                        |theme| theme.editor_document_highlight_write_background,
 4723                        cx,
 4724                    );
 4725                    cx.notify();
 4726                })
 4727                .log_err();
 4728            }
 4729        }));
 4730        None
 4731    }
 4732
 4733    pub fn refresh_inline_completion(
 4734        &mut self,
 4735        debounce: bool,
 4736        user_requested: bool,
 4737        window: &mut Window,
 4738        cx: &mut Context<Self>,
 4739    ) -> Option<()> {
 4740        let provider = self.edit_prediction_provider()?;
 4741        let cursor = self.selections.newest_anchor().head();
 4742        let (buffer, cursor_buffer_position) =
 4743            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4744
 4745        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4746            self.discard_inline_completion(false, cx);
 4747            return None;
 4748        }
 4749
 4750        if !user_requested
 4751            && (!self.should_show_edit_predictions()
 4752                || !self.is_focused(window)
 4753                || buffer.read(cx).is_empty())
 4754        {
 4755            self.discard_inline_completion(false, cx);
 4756            return None;
 4757        }
 4758
 4759        self.update_visible_inline_completion(window, cx);
 4760        provider.refresh(
 4761            self.project.clone(),
 4762            buffer,
 4763            cursor_buffer_position,
 4764            debounce,
 4765            cx,
 4766        );
 4767        Some(())
 4768    }
 4769
 4770    fn show_edit_predictions_in_menu(&self) -> bool {
 4771        match self.edit_prediction_settings {
 4772            EditPredictionSettings::Disabled => false,
 4773            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4774        }
 4775    }
 4776
 4777    pub fn edit_predictions_enabled(&self) -> bool {
 4778        match self.edit_prediction_settings {
 4779            EditPredictionSettings::Disabled => false,
 4780            EditPredictionSettings::Enabled { .. } => true,
 4781        }
 4782    }
 4783
 4784    fn edit_prediction_requires_modifier(&self) -> bool {
 4785        match self.edit_prediction_settings {
 4786            EditPredictionSettings::Disabled => false,
 4787            EditPredictionSettings::Enabled {
 4788                preview_requires_modifier,
 4789                ..
 4790            } => preview_requires_modifier,
 4791        }
 4792    }
 4793
 4794    fn edit_prediction_settings_at_position(
 4795        &self,
 4796        buffer: &Entity<Buffer>,
 4797        buffer_position: language::Anchor,
 4798        cx: &App,
 4799    ) -> EditPredictionSettings {
 4800        if self.mode != EditorMode::Full
 4801            || !self.show_inline_completions_override.unwrap_or(true)
 4802            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4803        {
 4804            return EditPredictionSettings::Disabled;
 4805        }
 4806
 4807        let buffer = buffer.read(cx);
 4808
 4809        let file = buffer.file();
 4810
 4811        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4812            return EditPredictionSettings::Disabled;
 4813        };
 4814
 4815        let by_provider = matches!(
 4816            self.menu_inline_completions_policy,
 4817            MenuInlineCompletionsPolicy::ByProvider
 4818        );
 4819
 4820        let show_in_menu = by_provider
 4821            && self
 4822                .edit_prediction_provider
 4823                .as_ref()
 4824                .map_or(false, |provider| {
 4825                    provider.provider.show_completions_in_menu()
 4826                });
 4827
 4828        let preview_requires_modifier =
 4829            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4830
 4831        EditPredictionSettings::Enabled {
 4832            show_in_menu,
 4833            preview_requires_modifier,
 4834        }
 4835    }
 4836
 4837    fn should_show_edit_predictions(&self) -> bool {
 4838        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4839    }
 4840
 4841    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4842        matches!(
 4843            self.edit_prediction_preview,
 4844            EditPredictionPreview::Active { .. }
 4845        )
 4846    }
 4847
 4848    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4849        let cursor = self.selections.newest_anchor().head();
 4850        if let Some((buffer, cursor_position)) =
 4851            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4852        {
 4853            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4854        } else {
 4855            false
 4856        }
 4857    }
 4858
 4859    fn inline_completions_enabled_in_buffer(
 4860        &self,
 4861        buffer: &Entity<Buffer>,
 4862        buffer_position: language::Anchor,
 4863        cx: &App,
 4864    ) -> bool {
 4865        maybe!({
 4866            let provider = self.edit_prediction_provider()?;
 4867            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4868                return Some(false);
 4869            }
 4870            let buffer = buffer.read(cx);
 4871            let Some(file) = buffer.file() else {
 4872                return Some(true);
 4873            };
 4874            let settings = all_language_settings(Some(file), cx);
 4875            Some(settings.inline_completions_enabled_for_path(file.path()))
 4876        })
 4877        .unwrap_or(false)
 4878    }
 4879
 4880    fn cycle_inline_completion(
 4881        &mut self,
 4882        direction: Direction,
 4883        window: &mut Window,
 4884        cx: &mut Context<Self>,
 4885    ) -> Option<()> {
 4886        let provider = self.edit_prediction_provider()?;
 4887        let cursor = self.selections.newest_anchor().head();
 4888        let (buffer, cursor_buffer_position) =
 4889            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4890        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4891            return None;
 4892        }
 4893
 4894        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4895        self.update_visible_inline_completion(window, cx);
 4896
 4897        Some(())
 4898    }
 4899
 4900    pub fn show_inline_completion(
 4901        &mut self,
 4902        _: &ShowEditPrediction,
 4903        window: &mut Window,
 4904        cx: &mut Context<Self>,
 4905    ) {
 4906        if !self.has_active_inline_completion() {
 4907            self.refresh_inline_completion(false, true, window, cx);
 4908            return;
 4909        }
 4910
 4911        self.update_visible_inline_completion(window, cx);
 4912    }
 4913
 4914    pub fn display_cursor_names(
 4915        &mut self,
 4916        _: &DisplayCursorNames,
 4917        window: &mut Window,
 4918        cx: &mut Context<Self>,
 4919    ) {
 4920        self.show_cursor_names(window, cx);
 4921    }
 4922
 4923    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4924        self.show_cursor_names = true;
 4925        cx.notify();
 4926        cx.spawn_in(window, |this, mut cx| async move {
 4927            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4928            this.update(&mut cx, |this, cx| {
 4929                this.show_cursor_names = false;
 4930                cx.notify()
 4931            })
 4932            .ok()
 4933        })
 4934        .detach();
 4935    }
 4936
 4937    pub fn next_edit_prediction(
 4938        &mut self,
 4939        _: &NextEditPrediction,
 4940        window: &mut Window,
 4941        cx: &mut Context<Self>,
 4942    ) {
 4943        if self.has_active_inline_completion() {
 4944            self.cycle_inline_completion(Direction::Next, window, cx);
 4945        } else {
 4946            let is_copilot_disabled = self
 4947                .refresh_inline_completion(false, true, window, cx)
 4948                .is_none();
 4949            if is_copilot_disabled {
 4950                cx.propagate();
 4951            }
 4952        }
 4953    }
 4954
 4955    pub fn previous_edit_prediction(
 4956        &mut self,
 4957        _: &PreviousEditPrediction,
 4958        window: &mut Window,
 4959        cx: &mut Context<Self>,
 4960    ) {
 4961        if self.has_active_inline_completion() {
 4962            self.cycle_inline_completion(Direction::Prev, window, cx);
 4963        } else {
 4964            let is_copilot_disabled = self
 4965                .refresh_inline_completion(false, true, window, cx)
 4966                .is_none();
 4967            if is_copilot_disabled {
 4968                cx.propagate();
 4969            }
 4970        }
 4971    }
 4972
 4973    pub fn accept_edit_prediction(
 4974        &mut self,
 4975        _: &AcceptEditPrediction,
 4976        window: &mut Window,
 4977        cx: &mut Context<Self>,
 4978    ) {
 4979        if self.show_edit_predictions_in_menu() {
 4980            self.hide_context_menu(window, cx);
 4981        }
 4982
 4983        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4984            return;
 4985        };
 4986
 4987        self.report_inline_completion_event(
 4988            active_inline_completion.completion_id.clone(),
 4989            true,
 4990            cx,
 4991        );
 4992
 4993        match &active_inline_completion.completion {
 4994            InlineCompletion::Move { target, .. } => {
 4995                let target = *target;
 4996
 4997                if let Some(position_map) = &self.last_position_map {
 4998                    if position_map
 4999                        .visible_row_range
 5000                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5001                        || !self.edit_prediction_requires_modifier()
 5002                    {
 5003                        // Note that this is also done in vim's handler of the Tab action.
 5004                        self.change_selections(
 5005                            Some(Autoscroll::newest()),
 5006                            window,
 5007                            cx,
 5008                            |selections| {
 5009                                selections.select_anchor_ranges([target..target]);
 5010                            },
 5011                        );
 5012                        self.clear_row_highlights::<EditPredictionPreview>();
 5013
 5014                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5015                            previous_scroll_position: None,
 5016                        };
 5017                    } else {
 5018                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5019                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5020                        };
 5021                        self.highlight_rows::<EditPredictionPreview>(
 5022                            target..target,
 5023                            cx.theme().colors().editor_highlighted_line_background,
 5024                            true,
 5025                            cx,
 5026                        );
 5027                        self.request_autoscroll(Autoscroll::fit(), cx);
 5028                    }
 5029                }
 5030            }
 5031            InlineCompletion::Edit { edits, .. } => {
 5032                if let Some(provider) = self.edit_prediction_provider() {
 5033                    provider.accept(cx);
 5034                }
 5035
 5036                let snapshot = self.buffer.read(cx).snapshot(cx);
 5037                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5038
 5039                self.buffer.update(cx, |buffer, cx| {
 5040                    buffer.edit(edits.iter().cloned(), None, cx)
 5041                });
 5042
 5043                self.change_selections(None, window, cx, |s| {
 5044                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5045                });
 5046
 5047                self.update_visible_inline_completion(window, cx);
 5048                if self.active_inline_completion.is_none() {
 5049                    self.refresh_inline_completion(true, true, window, cx);
 5050                }
 5051
 5052                cx.notify();
 5053            }
 5054        }
 5055
 5056        self.edit_prediction_requires_modifier_in_leading_space = false;
 5057    }
 5058
 5059    pub fn accept_partial_inline_completion(
 5060        &mut self,
 5061        _: &AcceptPartialEditPrediction,
 5062        window: &mut Window,
 5063        cx: &mut Context<Self>,
 5064    ) {
 5065        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5066            return;
 5067        };
 5068        if self.selections.count() != 1 {
 5069            return;
 5070        }
 5071
 5072        self.report_inline_completion_event(
 5073            active_inline_completion.completion_id.clone(),
 5074            true,
 5075            cx,
 5076        );
 5077
 5078        match &active_inline_completion.completion {
 5079            InlineCompletion::Move { target, .. } => {
 5080                let target = *target;
 5081                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5082                    selections.select_anchor_ranges([target..target]);
 5083                });
 5084            }
 5085            InlineCompletion::Edit { edits, .. } => {
 5086                // Find an insertion that starts at the cursor position.
 5087                let snapshot = self.buffer.read(cx).snapshot(cx);
 5088                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5089                let insertion = edits.iter().find_map(|(range, text)| {
 5090                    let range = range.to_offset(&snapshot);
 5091                    if range.is_empty() && range.start == cursor_offset {
 5092                        Some(text)
 5093                    } else {
 5094                        None
 5095                    }
 5096                });
 5097
 5098                if let Some(text) = insertion {
 5099                    let mut partial_completion = text
 5100                        .chars()
 5101                        .by_ref()
 5102                        .take_while(|c| c.is_alphabetic())
 5103                        .collect::<String>();
 5104                    if partial_completion.is_empty() {
 5105                        partial_completion = text
 5106                            .chars()
 5107                            .by_ref()
 5108                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5109                            .collect::<String>();
 5110                    }
 5111
 5112                    cx.emit(EditorEvent::InputHandled {
 5113                        utf16_range_to_replace: None,
 5114                        text: partial_completion.clone().into(),
 5115                    });
 5116
 5117                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5118
 5119                    self.refresh_inline_completion(true, true, window, cx);
 5120                    cx.notify();
 5121                } else {
 5122                    self.accept_edit_prediction(&Default::default(), window, cx);
 5123                }
 5124            }
 5125        }
 5126    }
 5127
 5128    fn discard_inline_completion(
 5129        &mut self,
 5130        should_report_inline_completion_event: bool,
 5131        cx: &mut Context<Self>,
 5132    ) -> bool {
 5133        if should_report_inline_completion_event {
 5134            let completion_id = self
 5135                .active_inline_completion
 5136                .as_ref()
 5137                .and_then(|active_completion| active_completion.completion_id.clone());
 5138
 5139            self.report_inline_completion_event(completion_id, false, cx);
 5140        }
 5141
 5142        if let Some(provider) = self.edit_prediction_provider() {
 5143            provider.discard(cx);
 5144        }
 5145
 5146        self.take_active_inline_completion(cx)
 5147    }
 5148
 5149    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5150        let Some(provider) = self.edit_prediction_provider() else {
 5151            return;
 5152        };
 5153
 5154        let Some((_, buffer, _)) = self
 5155            .buffer
 5156            .read(cx)
 5157            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5158        else {
 5159            return;
 5160        };
 5161
 5162        let extension = buffer
 5163            .read(cx)
 5164            .file()
 5165            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5166
 5167        let event_type = match accepted {
 5168            true => "Edit Prediction Accepted",
 5169            false => "Edit Prediction Discarded",
 5170        };
 5171        telemetry::event!(
 5172            event_type,
 5173            provider = provider.name(),
 5174            prediction_id = id,
 5175            suggestion_accepted = accepted,
 5176            file_extension = extension,
 5177        );
 5178    }
 5179
 5180    pub fn has_active_inline_completion(&self) -> bool {
 5181        self.active_inline_completion.is_some()
 5182    }
 5183
 5184    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5185        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5186            return false;
 5187        };
 5188
 5189        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5190        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5191        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5192        true
 5193    }
 5194
 5195    /// Returns true when we're displaying the edit prediction popover below the cursor
 5196    /// like we are not previewing and the LSP autocomplete menu is visible
 5197    /// or we are in `when_holding_modifier` mode.
 5198    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5199        if self.edit_prediction_preview_is_active()
 5200            || !self.show_edit_predictions_in_menu()
 5201            || !self.edit_predictions_enabled()
 5202        {
 5203            return false;
 5204        }
 5205
 5206        if self.has_visible_completions_menu() {
 5207            return true;
 5208        }
 5209
 5210        has_completion && self.edit_prediction_requires_modifier()
 5211    }
 5212
 5213    fn handle_modifiers_changed(
 5214        &mut self,
 5215        modifiers: Modifiers,
 5216        position_map: &PositionMap,
 5217        window: &mut Window,
 5218        cx: &mut Context<Self>,
 5219    ) {
 5220        if self.show_edit_predictions_in_menu() {
 5221            self.update_edit_prediction_preview(&modifiers, window, cx);
 5222        }
 5223
 5224        let mouse_position = window.mouse_position();
 5225        if !position_map.text_hitbox.is_hovered(window) {
 5226            return;
 5227        }
 5228
 5229        self.update_hovered_link(
 5230            position_map.point_for_position(mouse_position),
 5231            &position_map.snapshot,
 5232            modifiers,
 5233            window,
 5234            cx,
 5235        )
 5236    }
 5237
 5238    fn update_edit_prediction_preview(
 5239        &mut self,
 5240        modifiers: &Modifiers,
 5241        window: &mut Window,
 5242        cx: &mut Context<Self>,
 5243    ) {
 5244        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5245        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5246            return;
 5247        };
 5248
 5249        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5250            if matches!(
 5251                self.edit_prediction_preview,
 5252                EditPredictionPreview::Inactive
 5253            ) {
 5254                self.edit_prediction_preview = EditPredictionPreview::Active {
 5255                    previous_scroll_position: None,
 5256                };
 5257
 5258                self.update_visible_inline_completion(window, cx);
 5259                cx.notify();
 5260            }
 5261        } else if let EditPredictionPreview::Active {
 5262            previous_scroll_position,
 5263        } = self.edit_prediction_preview
 5264        {
 5265            if let (Some(previous_scroll_position), Some(position_map)) =
 5266                (previous_scroll_position, self.last_position_map.as_ref())
 5267            {
 5268                self.set_scroll_position(
 5269                    previous_scroll_position
 5270                        .scroll_position(&position_map.snapshot.display_snapshot),
 5271                    window,
 5272                    cx,
 5273                );
 5274            }
 5275
 5276            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5277            self.clear_row_highlights::<EditPredictionPreview>();
 5278            self.update_visible_inline_completion(window, cx);
 5279            cx.notify();
 5280        }
 5281    }
 5282
 5283    fn update_visible_inline_completion(
 5284        &mut self,
 5285        _window: &mut Window,
 5286        cx: &mut Context<Self>,
 5287    ) -> Option<()> {
 5288        let selection = self.selections.newest_anchor();
 5289        let cursor = selection.head();
 5290        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5291        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5292        let excerpt_id = cursor.excerpt_id;
 5293
 5294        let show_in_menu = self.show_edit_predictions_in_menu();
 5295        let completions_menu_has_precedence = !show_in_menu
 5296            && (self.context_menu.borrow().is_some()
 5297                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5298
 5299        if completions_menu_has_precedence
 5300            || !offset_selection.is_empty()
 5301            || self
 5302                .active_inline_completion
 5303                .as_ref()
 5304                .map_or(false, |completion| {
 5305                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5306                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5307                    !invalidation_range.contains(&offset_selection.head())
 5308                })
 5309        {
 5310            self.discard_inline_completion(false, cx);
 5311            return None;
 5312        }
 5313
 5314        self.take_active_inline_completion(cx);
 5315        let Some(provider) = self.edit_prediction_provider() else {
 5316            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5317            return None;
 5318        };
 5319
 5320        let (buffer, cursor_buffer_position) =
 5321            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5322
 5323        self.edit_prediction_settings =
 5324            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5325
 5326        if !self.edit_prediction_settings.is_enabled() {
 5327            self.discard_inline_completion(false, cx);
 5328            return None;
 5329        }
 5330
 5331        self.edit_prediction_cursor_on_leading_whitespace =
 5332            multibuffer.is_line_whitespace_upto(cursor);
 5333
 5334        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5335        let edits = inline_completion
 5336            .edits
 5337            .into_iter()
 5338            .flat_map(|(range, new_text)| {
 5339                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5340                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5341                Some((start..end, new_text))
 5342            })
 5343            .collect::<Vec<_>>();
 5344        if edits.is_empty() {
 5345            return None;
 5346        }
 5347
 5348        let first_edit_start = edits.first().unwrap().0.start;
 5349        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5350        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5351
 5352        let last_edit_end = edits.last().unwrap().0.end;
 5353        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5354        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5355
 5356        let cursor_row = cursor.to_point(&multibuffer).row;
 5357
 5358        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5359
 5360        let mut inlay_ids = Vec::new();
 5361        let invalidation_row_range;
 5362        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5363            Some(cursor_row..edit_end_row)
 5364        } else if cursor_row > edit_end_row {
 5365            Some(edit_start_row..cursor_row)
 5366        } else {
 5367            None
 5368        };
 5369        let is_move =
 5370            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5371        let completion = if is_move {
 5372            invalidation_row_range =
 5373                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5374            let target = first_edit_start;
 5375            InlineCompletion::Move { target, snapshot }
 5376        } else {
 5377            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5378                && !self.inline_completions_hidden_for_vim_mode;
 5379
 5380            if show_completions_in_buffer {
 5381                if edits
 5382                    .iter()
 5383                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5384                {
 5385                    let mut inlays = Vec::new();
 5386                    for (range, new_text) in &edits {
 5387                        let inlay = Inlay::inline_completion(
 5388                            post_inc(&mut self.next_inlay_id),
 5389                            range.start,
 5390                            new_text.as_str(),
 5391                        );
 5392                        inlay_ids.push(inlay.id);
 5393                        inlays.push(inlay);
 5394                    }
 5395
 5396                    self.splice_inlays(&[], inlays, cx);
 5397                } else {
 5398                    let background_color = cx.theme().status().deleted_background;
 5399                    self.highlight_text::<InlineCompletionHighlight>(
 5400                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5401                        HighlightStyle {
 5402                            background_color: Some(background_color),
 5403                            ..Default::default()
 5404                        },
 5405                        cx,
 5406                    );
 5407                }
 5408            }
 5409
 5410            invalidation_row_range = edit_start_row..edit_end_row;
 5411
 5412            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5413                if provider.show_tab_accept_marker() {
 5414                    EditDisplayMode::TabAccept
 5415                } else {
 5416                    EditDisplayMode::Inline
 5417                }
 5418            } else {
 5419                EditDisplayMode::DiffPopover
 5420            };
 5421
 5422            InlineCompletion::Edit {
 5423                edits,
 5424                edit_preview: inline_completion.edit_preview,
 5425                display_mode,
 5426                snapshot,
 5427            }
 5428        };
 5429
 5430        let invalidation_range = multibuffer
 5431            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5432            ..multibuffer.anchor_after(Point::new(
 5433                invalidation_row_range.end,
 5434                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5435            ));
 5436
 5437        self.stale_inline_completion_in_menu = None;
 5438        self.active_inline_completion = Some(InlineCompletionState {
 5439            inlay_ids,
 5440            completion,
 5441            completion_id: inline_completion.id,
 5442            invalidation_range,
 5443        });
 5444
 5445        cx.notify();
 5446
 5447        Some(())
 5448    }
 5449
 5450    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5451        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5452    }
 5453
 5454    fn render_code_actions_indicator(
 5455        &self,
 5456        _style: &EditorStyle,
 5457        row: DisplayRow,
 5458        is_active: bool,
 5459        cx: &mut Context<Self>,
 5460    ) -> Option<IconButton> {
 5461        if self.available_code_actions.is_some() {
 5462            Some(
 5463                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5464                    .shape(ui::IconButtonShape::Square)
 5465                    .icon_size(IconSize::XSmall)
 5466                    .icon_color(Color::Muted)
 5467                    .toggle_state(is_active)
 5468                    .tooltip({
 5469                        let focus_handle = self.focus_handle.clone();
 5470                        move |window, cx| {
 5471                            Tooltip::for_action_in(
 5472                                "Toggle Code Actions",
 5473                                &ToggleCodeActions {
 5474                                    deployed_from_indicator: None,
 5475                                },
 5476                                &focus_handle,
 5477                                window,
 5478                                cx,
 5479                            )
 5480                        }
 5481                    })
 5482                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5483                        window.focus(&editor.focus_handle(cx));
 5484                        editor.toggle_code_actions(
 5485                            &ToggleCodeActions {
 5486                                deployed_from_indicator: Some(row),
 5487                            },
 5488                            window,
 5489                            cx,
 5490                        );
 5491                    })),
 5492            )
 5493        } else {
 5494            None
 5495        }
 5496    }
 5497
 5498    fn clear_tasks(&mut self) {
 5499        self.tasks.clear()
 5500    }
 5501
 5502    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5503        if self.tasks.insert(key, value).is_some() {
 5504            // This case should hopefully be rare, but just in case...
 5505            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5506        }
 5507    }
 5508
 5509    fn build_tasks_context(
 5510        project: &Entity<Project>,
 5511        buffer: &Entity<Buffer>,
 5512        buffer_row: u32,
 5513        tasks: &Arc<RunnableTasks>,
 5514        cx: &mut Context<Self>,
 5515    ) -> Task<Option<task::TaskContext>> {
 5516        let position = Point::new(buffer_row, tasks.column);
 5517        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5518        let location = Location {
 5519            buffer: buffer.clone(),
 5520            range: range_start..range_start,
 5521        };
 5522        // Fill in the environmental variables from the tree-sitter captures
 5523        let mut captured_task_variables = TaskVariables::default();
 5524        for (capture_name, value) in tasks.extra_variables.clone() {
 5525            captured_task_variables.insert(
 5526                task::VariableName::Custom(capture_name.into()),
 5527                value.clone(),
 5528            );
 5529        }
 5530        project.update(cx, |project, cx| {
 5531            project.task_store().update(cx, |task_store, cx| {
 5532                task_store.task_context_for_location(captured_task_variables, location, cx)
 5533            })
 5534        })
 5535    }
 5536
 5537    pub fn spawn_nearest_task(
 5538        &mut self,
 5539        action: &SpawnNearestTask,
 5540        window: &mut Window,
 5541        cx: &mut Context<Self>,
 5542    ) {
 5543        let Some((workspace, _)) = self.workspace.clone() else {
 5544            return;
 5545        };
 5546        let Some(project) = self.project.clone() else {
 5547            return;
 5548        };
 5549
 5550        // Try to find a closest, enclosing node using tree-sitter that has a
 5551        // task
 5552        let Some((buffer, buffer_row, tasks)) = self
 5553            .find_enclosing_node_task(cx)
 5554            // Or find the task that's closest in row-distance.
 5555            .or_else(|| self.find_closest_task(cx))
 5556        else {
 5557            return;
 5558        };
 5559
 5560        let reveal_strategy = action.reveal;
 5561        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5562        cx.spawn_in(window, |_, mut cx| async move {
 5563            let context = task_context.await?;
 5564            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5565
 5566            let resolved = resolved_task.resolved.as_mut()?;
 5567            resolved.reveal = reveal_strategy;
 5568
 5569            workspace
 5570                .update(&mut cx, |workspace, cx| {
 5571                    workspace::tasks::schedule_resolved_task(
 5572                        workspace,
 5573                        task_source_kind,
 5574                        resolved_task,
 5575                        false,
 5576                        cx,
 5577                    );
 5578                })
 5579                .ok()
 5580        })
 5581        .detach();
 5582    }
 5583
 5584    fn find_closest_task(
 5585        &mut self,
 5586        cx: &mut Context<Self>,
 5587    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5588        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5589
 5590        let ((buffer_id, row), tasks) = self
 5591            .tasks
 5592            .iter()
 5593            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5594
 5595        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5596        let tasks = Arc::new(tasks.to_owned());
 5597        Some((buffer, *row, tasks))
 5598    }
 5599
 5600    fn find_enclosing_node_task(
 5601        &mut self,
 5602        cx: &mut Context<Self>,
 5603    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5604        let snapshot = self.buffer.read(cx).snapshot(cx);
 5605        let offset = self.selections.newest::<usize>(cx).head();
 5606        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5607        let buffer_id = excerpt.buffer().remote_id();
 5608
 5609        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5610        let mut cursor = layer.node().walk();
 5611
 5612        while cursor.goto_first_child_for_byte(offset).is_some() {
 5613            if cursor.node().end_byte() == offset {
 5614                cursor.goto_next_sibling();
 5615            }
 5616        }
 5617
 5618        // Ascend to the smallest ancestor that contains the range and has a task.
 5619        loop {
 5620            let node = cursor.node();
 5621            let node_range = node.byte_range();
 5622            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5623
 5624            // Check if this node contains our offset
 5625            if node_range.start <= offset && node_range.end >= offset {
 5626                // If it contains offset, check for task
 5627                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5628                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5629                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5630                }
 5631            }
 5632
 5633            if !cursor.goto_parent() {
 5634                break;
 5635            }
 5636        }
 5637        None
 5638    }
 5639
 5640    fn render_run_indicator(
 5641        &self,
 5642        _style: &EditorStyle,
 5643        is_active: bool,
 5644        row: DisplayRow,
 5645        cx: &mut Context<Self>,
 5646    ) -> IconButton {
 5647        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5648            .shape(ui::IconButtonShape::Square)
 5649            .icon_size(IconSize::XSmall)
 5650            .icon_color(Color::Muted)
 5651            .toggle_state(is_active)
 5652            .on_click(cx.listener(move |editor, _e, window, cx| {
 5653                window.focus(&editor.focus_handle(cx));
 5654                editor.toggle_code_actions(
 5655                    &ToggleCodeActions {
 5656                        deployed_from_indicator: Some(row),
 5657                    },
 5658                    window,
 5659                    cx,
 5660                );
 5661            }))
 5662    }
 5663
 5664    pub fn context_menu_visible(&self) -> bool {
 5665        !self.edit_prediction_preview_is_active()
 5666            && self
 5667                .context_menu
 5668                .borrow()
 5669                .as_ref()
 5670                .map_or(false, |menu| menu.visible())
 5671    }
 5672
 5673    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5674        self.context_menu
 5675            .borrow()
 5676            .as_ref()
 5677            .map(|menu| menu.origin())
 5678    }
 5679
 5680    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5681        px(30.)
 5682    }
 5683
 5684    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5685        if self.read_only(cx) {
 5686            cx.theme().players().read_only()
 5687        } else {
 5688            self.style.as_ref().unwrap().local_player
 5689        }
 5690    }
 5691
 5692    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5693        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5694        let accept_keystroke = accept_binding.keystroke()?;
 5695
 5696        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5697
 5698        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5699            Color::Accent
 5700        } else {
 5701            Color::Muted
 5702        };
 5703
 5704        h_flex()
 5705            .px_0p5()
 5706            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5707            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5708            .text_size(TextSize::XSmall.rems(cx))
 5709            .child(h_flex().children(ui::render_modifiers(
 5710                &accept_keystroke.modifiers,
 5711                PlatformStyle::platform(),
 5712                Some(modifiers_color),
 5713                Some(IconSize::XSmall.rems().into()),
 5714                true,
 5715            )))
 5716            .when(is_platform_style_mac, |parent| {
 5717                parent.child(accept_keystroke.key.clone())
 5718            })
 5719            .when(!is_platform_style_mac, |parent| {
 5720                parent.child(
 5721                    Key::new(
 5722                        util::capitalize(&accept_keystroke.key),
 5723                        Some(Color::Default),
 5724                    )
 5725                    .size(Some(IconSize::XSmall.rems().into())),
 5726                )
 5727            })
 5728            .into()
 5729    }
 5730
 5731    fn render_edit_prediction_line_popover(
 5732        &self,
 5733        label: impl Into<SharedString>,
 5734        icon: Option<IconName>,
 5735        window: &mut Window,
 5736        cx: &App,
 5737    ) -> Option<Div> {
 5738        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5739
 5740        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5741
 5742        let result = h_flex()
 5743            .gap_1()
 5744            .border_1()
 5745            .rounded_lg()
 5746            .shadow_sm()
 5747            .bg(bg_color)
 5748            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5749            .py_0p5()
 5750            .pl_1()
 5751            .pr(padding_right)
 5752            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5753            .child(Label::new(label).size(LabelSize::Small))
 5754            .when_some(icon, |element, icon| {
 5755                element.child(
 5756                    div()
 5757                        .mt(px(1.5))
 5758                        .child(Icon::new(icon).size(IconSize::Small)),
 5759                )
 5760            });
 5761
 5762        Some(result)
 5763    }
 5764
 5765    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5766        let accent_color = cx.theme().colors().text_accent;
 5767        let editor_bg_color = cx.theme().colors().editor_background;
 5768        editor_bg_color.blend(accent_color.opacity(0.1))
 5769    }
 5770
 5771    #[allow(clippy::too_many_arguments)]
 5772    fn render_edit_prediction_cursor_popover(
 5773        &self,
 5774        min_width: Pixels,
 5775        max_width: Pixels,
 5776        cursor_point: Point,
 5777        style: &EditorStyle,
 5778        accept_keystroke: &gpui::Keystroke,
 5779        _window: &Window,
 5780        cx: &mut Context<Editor>,
 5781    ) -> Option<AnyElement> {
 5782        let provider = self.edit_prediction_provider.as_ref()?;
 5783
 5784        if provider.provider.needs_terms_acceptance(cx) {
 5785            return Some(
 5786                h_flex()
 5787                    .min_w(min_width)
 5788                    .flex_1()
 5789                    .px_2()
 5790                    .py_1()
 5791                    .gap_3()
 5792                    .elevation_2(cx)
 5793                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5794                    .id("accept-terms")
 5795                    .cursor_pointer()
 5796                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5797                    .on_click(cx.listener(|this, _event, window, cx| {
 5798                        cx.stop_propagation();
 5799                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5800                        window.dispatch_action(
 5801                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5802                            cx,
 5803                        );
 5804                    }))
 5805                    .child(
 5806                        h_flex()
 5807                            .flex_1()
 5808                            .gap_2()
 5809                            .child(Icon::new(IconName::ZedPredict))
 5810                            .child(Label::new("Accept Terms of Service"))
 5811                            .child(div().w_full())
 5812                            .child(
 5813                                Icon::new(IconName::ArrowUpRight)
 5814                                    .color(Color::Muted)
 5815                                    .size(IconSize::Small),
 5816                            )
 5817                            .into_any_element(),
 5818                    )
 5819                    .into_any(),
 5820            );
 5821        }
 5822
 5823        let is_refreshing = provider.provider.is_refreshing(cx);
 5824
 5825        fn pending_completion_container() -> Div {
 5826            h_flex()
 5827                .h_full()
 5828                .flex_1()
 5829                .gap_2()
 5830                .child(Icon::new(IconName::ZedPredict))
 5831        }
 5832
 5833        let completion = match &self.active_inline_completion {
 5834            Some(completion) => match &completion.completion {
 5835                InlineCompletion::Move {
 5836                    target, snapshot, ..
 5837                } if !self.has_visible_completions_menu() => {
 5838                    use text::ToPoint as _;
 5839
 5840                    return Some(
 5841                        h_flex()
 5842                            .px_2()
 5843                            .py_1()
 5844                            .elevation_2(cx)
 5845                            .border_color(cx.theme().colors().border)
 5846                            .rounded_tl(px(0.))
 5847                            .gap_2()
 5848                            .child(
 5849                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5850                                    Icon::new(IconName::ZedPredictDown)
 5851                                } else {
 5852                                    Icon::new(IconName::ZedPredictUp)
 5853                                },
 5854                            )
 5855                            .child(Label::new("Hold").size(LabelSize::Small))
 5856                            .child(h_flex().children(ui::render_modifiers(
 5857                                &accept_keystroke.modifiers,
 5858                                PlatformStyle::platform(),
 5859                                Some(Color::Default),
 5860                                Some(IconSize::Small.rems().into()),
 5861                                false,
 5862                            )))
 5863                            .into_any(),
 5864                    );
 5865                }
 5866                _ => self.render_edit_prediction_cursor_popover_preview(
 5867                    completion,
 5868                    cursor_point,
 5869                    style,
 5870                    cx,
 5871                )?,
 5872            },
 5873
 5874            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5875                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5876                    stale_completion,
 5877                    cursor_point,
 5878                    style,
 5879                    cx,
 5880                )?,
 5881
 5882                None => {
 5883                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5884                }
 5885            },
 5886
 5887            None => pending_completion_container().child(Label::new("No Prediction")),
 5888        };
 5889
 5890        let completion = if is_refreshing {
 5891            completion
 5892                .with_animation(
 5893                    "loading-completion",
 5894                    Animation::new(Duration::from_secs(2))
 5895                        .repeat()
 5896                        .with_easing(pulsating_between(0.4, 0.8)),
 5897                    |label, delta| label.opacity(delta),
 5898                )
 5899                .into_any_element()
 5900        } else {
 5901            completion.into_any_element()
 5902        };
 5903
 5904        let has_completion = self.active_inline_completion.is_some();
 5905
 5906        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5907        Some(
 5908            h_flex()
 5909                .min_w(min_width)
 5910                .max_w(max_width)
 5911                .flex_1()
 5912                .elevation_2(cx)
 5913                .border_color(cx.theme().colors().border)
 5914                .child(
 5915                    div()
 5916                        .flex_1()
 5917                        .py_1()
 5918                        .px_2()
 5919                        .overflow_hidden()
 5920                        .child(completion),
 5921                )
 5922                .child(
 5923                    h_flex()
 5924                        .h_full()
 5925                        .border_l_1()
 5926                        .rounded_r_lg()
 5927                        .border_color(cx.theme().colors().border)
 5928                        .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5929                        .gap_1()
 5930                        .py_1()
 5931                        .px_2()
 5932                        .child(
 5933                            h_flex()
 5934                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5935                                .when(is_platform_style_mac, |parent| parent.gap_1())
 5936                                .child(h_flex().children(ui::render_modifiers(
 5937                                    &accept_keystroke.modifiers,
 5938                                    PlatformStyle::platform(),
 5939                                    Some(if !has_completion {
 5940                                        Color::Muted
 5941                                    } else {
 5942                                        Color::Default
 5943                                    }),
 5944                                    None,
 5945                                    false,
 5946                                ))),
 5947                        )
 5948                        .child(Label::new("Preview").into_any_element())
 5949                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5950                )
 5951                .into_any(),
 5952        )
 5953    }
 5954
 5955    fn render_edit_prediction_cursor_popover_preview(
 5956        &self,
 5957        completion: &InlineCompletionState,
 5958        cursor_point: Point,
 5959        style: &EditorStyle,
 5960        cx: &mut Context<Editor>,
 5961    ) -> Option<Div> {
 5962        use text::ToPoint as _;
 5963
 5964        fn render_relative_row_jump(
 5965            prefix: impl Into<String>,
 5966            current_row: u32,
 5967            target_row: u32,
 5968        ) -> Div {
 5969            let (row_diff, arrow) = if target_row < current_row {
 5970                (current_row - target_row, IconName::ArrowUp)
 5971            } else {
 5972                (target_row - current_row, IconName::ArrowDown)
 5973            };
 5974
 5975            h_flex()
 5976                .child(
 5977                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5978                        .color(Color::Muted)
 5979                        .size(LabelSize::Small),
 5980                )
 5981                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5982        }
 5983
 5984        match &completion.completion {
 5985            InlineCompletion::Move {
 5986                target, snapshot, ..
 5987            } => Some(
 5988                h_flex()
 5989                    .px_2()
 5990                    .gap_2()
 5991                    .flex_1()
 5992                    .child(
 5993                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5994                            Icon::new(IconName::ZedPredictDown)
 5995                        } else {
 5996                            Icon::new(IconName::ZedPredictUp)
 5997                        },
 5998                    )
 5999                    .child(Label::new("Jump to Edit")),
 6000            ),
 6001
 6002            InlineCompletion::Edit {
 6003                edits,
 6004                edit_preview,
 6005                snapshot,
 6006                display_mode: _,
 6007            } => {
 6008                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6009
 6010                let highlighted_edits = crate::inline_completion_edit_text(
 6011                    &snapshot,
 6012                    &edits,
 6013                    edit_preview.as_ref()?,
 6014                    true,
 6015                    cx,
 6016                );
 6017
 6018                let len_total = highlighted_edits.text.len();
 6019                let first_line = &highlighted_edits.text
 6020                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 6021                let first_line_len = first_line.len();
 6022
 6023                let first_highlight_start = highlighted_edits
 6024                    .highlights
 6025                    .first()
 6026                    .map_or(0, |(range, _)| range.start);
 6027                let drop_prefix_len = first_line
 6028                    .char_indices()
 6029                    .find(|(_, c)| !c.is_whitespace())
 6030                    .map_or(first_highlight_start, |(ix, _)| {
 6031                        ix.min(first_highlight_start)
 6032                    });
 6033
 6034                let preview_text = &first_line[drop_prefix_len..];
 6035                let preview_len = preview_text.len();
 6036                let highlights = highlighted_edits
 6037                    .highlights
 6038                    .into_iter()
 6039                    .take_until(|(range, _)| range.start > first_line_len)
 6040                    .map(|(range, style)| {
 6041                        (
 6042                            range.start - drop_prefix_len
 6043                                ..(range.end - drop_prefix_len).min(preview_len),
 6044                            style,
 6045                        )
 6046                    });
 6047
 6048                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 6049                    .with_highlights(&style.text, highlights);
 6050
 6051                let preview = h_flex()
 6052                    .gap_1()
 6053                    .min_w_16()
 6054                    .child(styled_text)
 6055                    .when(len_total > first_line_len, |parent| parent.child(""));
 6056
 6057                let left = if first_edit_row != cursor_point.row {
 6058                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6059                        .into_any_element()
 6060                } else {
 6061                    Icon::new(IconName::ZedPredict).into_any_element()
 6062                };
 6063
 6064                Some(
 6065                    h_flex()
 6066                        .h_full()
 6067                        .flex_1()
 6068                        .gap_2()
 6069                        .pr_1()
 6070                        .overflow_x_hidden()
 6071                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6072                        .child(left)
 6073                        .child(preview),
 6074                )
 6075            }
 6076        }
 6077    }
 6078
 6079    fn render_context_menu(
 6080        &self,
 6081        style: &EditorStyle,
 6082        max_height_in_lines: u32,
 6083        y_flipped: bool,
 6084        window: &mut Window,
 6085        cx: &mut Context<Editor>,
 6086    ) -> Option<AnyElement> {
 6087        let menu = self.context_menu.borrow();
 6088        let menu = menu.as_ref()?;
 6089        if !menu.visible() {
 6090            return None;
 6091        };
 6092        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6093    }
 6094
 6095    fn render_context_menu_aside(
 6096        &self,
 6097        style: &EditorStyle,
 6098        max_size: Size<Pixels>,
 6099        cx: &mut Context<Editor>,
 6100    ) -> Option<AnyElement> {
 6101        self.context_menu.borrow().as_ref().and_then(|menu| {
 6102            if menu.visible() {
 6103                menu.render_aside(
 6104                    style,
 6105                    max_size,
 6106                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6107                    cx,
 6108                )
 6109            } else {
 6110                None
 6111            }
 6112        })
 6113    }
 6114
 6115    fn hide_context_menu(
 6116        &mut self,
 6117        window: &mut Window,
 6118        cx: &mut Context<Self>,
 6119    ) -> Option<CodeContextMenu> {
 6120        cx.notify();
 6121        self.completion_tasks.clear();
 6122        let context_menu = self.context_menu.borrow_mut().take();
 6123        self.stale_inline_completion_in_menu.take();
 6124        self.update_visible_inline_completion(window, cx);
 6125        context_menu
 6126    }
 6127
 6128    fn show_snippet_choices(
 6129        &mut self,
 6130        choices: &Vec<String>,
 6131        selection: Range<Anchor>,
 6132        cx: &mut Context<Self>,
 6133    ) {
 6134        if selection.start.buffer_id.is_none() {
 6135            return;
 6136        }
 6137        let buffer_id = selection.start.buffer_id.unwrap();
 6138        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6139        let id = post_inc(&mut self.next_completion_id);
 6140
 6141        if let Some(buffer) = buffer {
 6142            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6143                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6144            ));
 6145        }
 6146    }
 6147
 6148    pub fn insert_snippet(
 6149        &mut self,
 6150        insertion_ranges: &[Range<usize>],
 6151        snippet: Snippet,
 6152        window: &mut Window,
 6153        cx: &mut Context<Self>,
 6154    ) -> Result<()> {
 6155        struct Tabstop<T> {
 6156            is_end_tabstop: bool,
 6157            ranges: Vec<Range<T>>,
 6158            choices: Option<Vec<String>>,
 6159        }
 6160
 6161        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6162            let snippet_text: Arc<str> = snippet.text.clone().into();
 6163            buffer.edit(
 6164                insertion_ranges
 6165                    .iter()
 6166                    .cloned()
 6167                    .map(|range| (range, snippet_text.clone())),
 6168                Some(AutoindentMode::EachLine),
 6169                cx,
 6170            );
 6171
 6172            let snapshot = &*buffer.read(cx);
 6173            let snippet = &snippet;
 6174            snippet
 6175                .tabstops
 6176                .iter()
 6177                .map(|tabstop| {
 6178                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6179                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6180                    });
 6181                    let mut tabstop_ranges = tabstop
 6182                        .ranges
 6183                        .iter()
 6184                        .flat_map(|tabstop_range| {
 6185                            let mut delta = 0_isize;
 6186                            insertion_ranges.iter().map(move |insertion_range| {
 6187                                let insertion_start = insertion_range.start as isize + delta;
 6188                                delta +=
 6189                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6190
 6191                                let start = ((insertion_start + tabstop_range.start) as usize)
 6192                                    .min(snapshot.len());
 6193                                let end = ((insertion_start + tabstop_range.end) as usize)
 6194                                    .min(snapshot.len());
 6195                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6196                            })
 6197                        })
 6198                        .collect::<Vec<_>>();
 6199                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6200
 6201                    Tabstop {
 6202                        is_end_tabstop,
 6203                        ranges: tabstop_ranges,
 6204                        choices: tabstop.choices.clone(),
 6205                    }
 6206                })
 6207                .collect::<Vec<_>>()
 6208        });
 6209        if let Some(tabstop) = tabstops.first() {
 6210            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6211                s.select_ranges(tabstop.ranges.iter().cloned());
 6212            });
 6213
 6214            if let Some(choices) = &tabstop.choices {
 6215                if let Some(selection) = tabstop.ranges.first() {
 6216                    self.show_snippet_choices(choices, selection.clone(), cx)
 6217                }
 6218            }
 6219
 6220            // If we're already at the last tabstop and it's at the end of the snippet,
 6221            // we're done, we don't need to keep the state around.
 6222            if !tabstop.is_end_tabstop {
 6223                let choices = tabstops
 6224                    .iter()
 6225                    .map(|tabstop| tabstop.choices.clone())
 6226                    .collect();
 6227
 6228                let ranges = tabstops
 6229                    .into_iter()
 6230                    .map(|tabstop| tabstop.ranges)
 6231                    .collect::<Vec<_>>();
 6232
 6233                self.snippet_stack.push(SnippetState {
 6234                    active_index: 0,
 6235                    ranges,
 6236                    choices,
 6237                });
 6238            }
 6239
 6240            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6241            if self.autoclose_regions.is_empty() {
 6242                let snapshot = self.buffer.read(cx).snapshot(cx);
 6243                for selection in &mut self.selections.all::<Point>(cx) {
 6244                    let selection_head = selection.head();
 6245                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6246                        continue;
 6247                    };
 6248
 6249                    let mut bracket_pair = None;
 6250                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6251                    let prev_chars = snapshot
 6252                        .reversed_chars_at(selection_head)
 6253                        .collect::<String>();
 6254                    for (pair, enabled) in scope.brackets() {
 6255                        if enabled
 6256                            && pair.close
 6257                            && prev_chars.starts_with(pair.start.as_str())
 6258                            && next_chars.starts_with(pair.end.as_str())
 6259                        {
 6260                            bracket_pair = Some(pair.clone());
 6261                            break;
 6262                        }
 6263                    }
 6264                    if let Some(pair) = bracket_pair {
 6265                        let start = snapshot.anchor_after(selection_head);
 6266                        let end = snapshot.anchor_after(selection_head);
 6267                        self.autoclose_regions.push(AutocloseRegion {
 6268                            selection_id: selection.id,
 6269                            range: start..end,
 6270                            pair,
 6271                        });
 6272                    }
 6273                }
 6274            }
 6275        }
 6276        Ok(())
 6277    }
 6278
 6279    pub fn move_to_next_snippet_tabstop(
 6280        &mut self,
 6281        window: &mut Window,
 6282        cx: &mut Context<Self>,
 6283    ) -> bool {
 6284        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6285    }
 6286
 6287    pub fn move_to_prev_snippet_tabstop(
 6288        &mut self,
 6289        window: &mut Window,
 6290        cx: &mut Context<Self>,
 6291    ) -> bool {
 6292        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6293    }
 6294
 6295    pub fn move_to_snippet_tabstop(
 6296        &mut self,
 6297        bias: Bias,
 6298        window: &mut Window,
 6299        cx: &mut Context<Self>,
 6300    ) -> bool {
 6301        if let Some(mut snippet) = self.snippet_stack.pop() {
 6302            match bias {
 6303                Bias::Left => {
 6304                    if snippet.active_index > 0 {
 6305                        snippet.active_index -= 1;
 6306                    } else {
 6307                        self.snippet_stack.push(snippet);
 6308                        return false;
 6309                    }
 6310                }
 6311                Bias::Right => {
 6312                    if snippet.active_index + 1 < snippet.ranges.len() {
 6313                        snippet.active_index += 1;
 6314                    } else {
 6315                        self.snippet_stack.push(snippet);
 6316                        return false;
 6317                    }
 6318                }
 6319            }
 6320            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6321                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6322                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6323                });
 6324
 6325                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6326                    if let Some(selection) = current_ranges.first() {
 6327                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6328                    }
 6329                }
 6330
 6331                // If snippet state is not at the last tabstop, push it back on the stack
 6332                if snippet.active_index + 1 < snippet.ranges.len() {
 6333                    self.snippet_stack.push(snippet);
 6334                }
 6335                return true;
 6336            }
 6337        }
 6338
 6339        false
 6340    }
 6341
 6342    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6343        self.transact(window, cx, |this, window, cx| {
 6344            this.select_all(&SelectAll, window, cx);
 6345            this.insert("", window, cx);
 6346        });
 6347    }
 6348
 6349    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6350        self.transact(window, cx, |this, window, cx| {
 6351            this.select_autoclose_pair(window, cx);
 6352            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6353            if !this.linked_edit_ranges.is_empty() {
 6354                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6355                let snapshot = this.buffer.read(cx).snapshot(cx);
 6356
 6357                for selection in selections.iter() {
 6358                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6359                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6360                    if selection_start.buffer_id != selection_end.buffer_id {
 6361                        continue;
 6362                    }
 6363                    if let Some(ranges) =
 6364                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6365                    {
 6366                        for (buffer, entries) in ranges {
 6367                            linked_ranges.entry(buffer).or_default().extend(entries);
 6368                        }
 6369                    }
 6370                }
 6371            }
 6372
 6373            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6374            if !this.selections.line_mode {
 6375                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6376                for selection in &mut selections {
 6377                    if selection.is_empty() {
 6378                        let old_head = selection.head();
 6379                        let mut new_head =
 6380                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6381                                .to_point(&display_map);
 6382                        if let Some((buffer, line_buffer_range)) = display_map
 6383                            .buffer_snapshot
 6384                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6385                        {
 6386                            let indent_size =
 6387                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6388                            let indent_len = match indent_size.kind {
 6389                                IndentKind::Space => {
 6390                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6391                                }
 6392                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6393                            };
 6394                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6395                                let indent_len = indent_len.get();
 6396                                new_head = cmp::min(
 6397                                    new_head,
 6398                                    MultiBufferPoint::new(
 6399                                        old_head.row,
 6400                                        ((old_head.column - 1) / indent_len) * indent_len,
 6401                                    ),
 6402                                );
 6403                            }
 6404                        }
 6405
 6406                        selection.set_head(new_head, SelectionGoal::None);
 6407                    }
 6408                }
 6409            }
 6410
 6411            this.signature_help_state.set_backspace_pressed(true);
 6412            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6413                s.select(selections)
 6414            });
 6415            this.insert("", window, cx);
 6416            let empty_str: Arc<str> = Arc::from("");
 6417            for (buffer, edits) in linked_ranges {
 6418                let snapshot = buffer.read(cx).snapshot();
 6419                use text::ToPoint as TP;
 6420
 6421                let edits = edits
 6422                    .into_iter()
 6423                    .map(|range| {
 6424                        let end_point = TP::to_point(&range.end, &snapshot);
 6425                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6426
 6427                        if end_point == start_point {
 6428                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6429                                .saturating_sub(1);
 6430                            start_point =
 6431                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6432                        };
 6433
 6434                        (start_point..end_point, empty_str.clone())
 6435                    })
 6436                    .sorted_by_key(|(range, _)| range.start)
 6437                    .collect::<Vec<_>>();
 6438                buffer.update(cx, |this, cx| {
 6439                    this.edit(edits, None, cx);
 6440                })
 6441            }
 6442            this.refresh_inline_completion(true, false, window, cx);
 6443            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6444        });
 6445    }
 6446
 6447    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6448        self.transact(window, cx, |this, window, cx| {
 6449            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6450                let line_mode = s.line_mode;
 6451                s.move_with(|map, selection| {
 6452                    if selection.is_empty() && !line_mode {
 6453                        let cursor = movement::right(map, selection.head());
 6454                        selection.end = cursor;
 6455                        selection.reversed = true;
 6456                        selection.goal = SelectionGoal::None;
 6457                    }
 6458                })
 6459            });
 6460            this.insert("", window, cx);
 6461            this.refresh_inline_completion(true, false, window, cx);
 6462        });
 6463    }
 6464
 6465    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6466        if self.move_to_prev_snippet_tabstop(window, cx) {
 6467            return;
 6468        }
 6469
 6470        self.outdent(&Outdent, window, cx);
 6471    }
 6472
 6473    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6474        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6475            return;
 6476        }
 6477
 6478        let mut selections = self.selections.all_adjusted(cx);
 6479        let buffer = self.buffer.read(cx);
 6480        let snapshot = buffer.snapshot(cx);
 6481        let rows_iter = selections.iter().map(|s| s.head().row);
 6482        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6483
 6484        let mut edits = Vec::new();
 6485        let mut prev_edited_row = 0;
 6486        let mut row_delta = 0;
 6487        for selection in &mut selections {
 6488            if selection.start.row != prev_edited_row {
 6489                row_delta = 0;
 6490            }
 6491            prev_edited_row = selection.end.row;
 6492
 6493            // If the selection is non-empty, then increase the indentation of the selected lines.
 6494            if !selection.is_empty() {
 6495                row_delta =
 6496                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6497                continue;
 6498            }
 6499
 6500            // If the selection is empty and the cursor is in the leading whitespace before the
 6501            // suggested indentation, then auto-indent the line.
 6502            let cursor = selection.head();
 6503            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6504            if let Some(suggested_indent) =
 6505                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6506            {
 6507                if cursor.column < suggested_indent.len
 6508                    && cursor.column <= current_indent.len
 6509                    && current_indent.len <= suggested_indent.len
 6510                {
 6511                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6512                    selection.end = selection.start;
 6513                    if row_delta == 0 {
 6514                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6515                            cursor.row,
 6516                            current_indent,
 6517                            suggested_indent,
 6518                        ));
 6519                        row_delta = suggested_indent.len - current_indent.len;
 6520                    }
 6521                    continue;
 6522                }
 6523            }
 6524
 6525            // Otherwise, insert a hard or soft tab.
 6526            let settings = buffer.settings_at(cursor, cx);
 6527            let tab_size = if settings.hard_tabs {
 6528                IndentSize::tab()
 6529            } else {
 6530                let tab_size = settings.tab_size.get();
 6531                let char_column = snapshot
 6532                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6533                    .flat_map(str::chars)
 6534                    .count()
 6535                    + row_delta as usize;
 6536                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6537                IndentSize::spaces(chars_to_next_tab_stop)
 6538            };
 6539            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6540            selection.end = selection.start;
 6541            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6542            row_delta += tab_size.len;
 6543        }
 6544
 6545        self.transact(window, cx, |this, window, cx| {
 6546            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6547            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6548                s.select(selections)
 6549            });
 6550            this.refresh_inline_completion(true, false, window, cx);
 6551        });
 6552    }
 6553
 6554    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6555        if self.read_only(cx) {
 6556            return;
 6557        }
 6558        let mut selections = self.selections.all::<Point>(cx);
 6559        let mut prev_edited_row = 0;
 6560        let mut row_delta = 0;
 6561        let mut edits = Vec::new();
 6562        let buffer = self.buffer.read(cx);
 6563        let snapshot = buffer.snapshot(cx);
 6564        for selection in &mut selections {
 6565            if selection.start.row != prev_edited_row {
 6566                row_delta = 0;
 6567            }
 6568            prev_edited_row = selection.end.row;
 6569
 6570            row_delta =
 6571                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6572        }
 6573
 6574        self.transact(window, cx, |this, window, cx| {
 6575            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6576            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6577                s.select(selections)
 6578            });
 6579        });
 6580    }
 6581
 6582    fn indent_selection(
 6583        buffer: &MultiBuffer,
 6584        snapshot: &MultiBufferSnapshot,
 6585        selection: &mut Selection<Point>,
 6586        edits: &mut Vec<(Range<Point>, String)>,
 6587        delta_for_start_row: u32,
 6588        cx: &App,
 6589    ) -> u32 {
 6590        let settings = buffer.settings_at(selection.start, cx);
 6591        let tab_size = settings.tab_size.get();
 6592        let indent_kind = if settings.hard_tabs {
 6593            IndentKind::Tab
 6594        } else {
 6595            IndentKind::Space
 6596        };
 6597        let mut start_row = selection.start.row;
 6598        let mut end_row = selection.end.row + 1;
 6599
 6600        // If a selection ends at the beginning of a line, don't indent
 6601        // that last line.
 6602        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6603            end_row -= 1;
 6604        }
 6605
 6606        // Avoid re-indenting a row that has already been indented by a
 6607        // previous selection, but still update this selection's column
 6608        // to reflect that indentation.
 6609        if delta_for_start_row > 0 {
 6610            start_row += 1;
 6611            selection.start.column += delta_for_start_row;
 6612            if selection.end.row == selection.start.row {
 6613                selection.end.column += delta_for_start_row;
 6614            }
 6615        }
 6616
 6617        let mut delta_for_end_row = 0;
 6618        let has_multiple_rows = start_row + 1 != end_row;
 6619        for row in start_row..end_row {
 6620            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6621            let indent_delta = match (current_indent.kind, indent_kind) {
 6622                (IndentKind::Space, IndentKind::Space) => {
 6623                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6624                    IndentSize::spaces(columns_to_next_tab_stop)
 6625                }
 6626                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6627                (_, IndentKind::Tab) => IndentSize::tab(),
 6628            };
 6629
 6630            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6631                0
 6632            } else {
 6633                selection.start.column
 6634            };
 6635            let row_start = Point::new(row, start);
 6636            edits.push((
 6637                row_start..row_start,
 6638                indent_delta.chars().collect::<String>(),
 6639            ));
 6640
 6641            // Update this selection's endpoints to reflect the indentation.
 6642            if row == selection.start.row {
 6643                selection.start.column += indent_delta.len;
 6644            }
 6645            if row == selection.end.row {
 6646                selection.end.column += indent_delta.len;
 6647                delta_for_end_row = indent_delta.len;
 6648            }
 6649        }
 6650
 6651        if selection.start.row == selection.end.row {
 6652            delta_for_start_row + delta_for_end_row
 6653        } else {
 6654            delta_for_end_row
 6655        }
 6656    }
 6657
 6658    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6659        if self.read_only(cx) {
 6660            return;
 6661        }
 6662        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6663        let selections = self.selections.all::<Point>(cx);
 6664        let mut deletion_ranges = Vec::new();
 6665        let mut last_outdent = None;
 6666        {
 6667            let buffer = self.buffer.read(cx);
 6668            let snapshot = buffer.snapshot(cx);
 6669            for selection in &selections {
 6670                let settings = buffer.settings_at(selection.start, cx);
 6671                let tab_size = settings.tab_size.get();
 6672                let mut rows = selection.spanned_rows(false, &display_map);
 6673
 6674                // Avoid re-outdenting a row that has already been outdented by a
 6675                // previous selection.
 6676                if let Some(last_row) = last_outdent {
 6677                    if last_row == rows.start {
 6678                        rows.start = rows.start.next_row();
 6679                    }
 6680                }
 6681                let has_multiple_rows = rows.len() > 1;
 6682                for row in rows.iter_rows() {
 6683                    let indent_size = snapshot.indent_size_for_line(row);
 6684                    if indent_size.len > 0 {
 6685                        let deletion_len = match indent_size.kind {
 6686                            IndentKind::Space => {
 6687                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6688                                if columns_to_prev_tab_stop == 0 {
 6689                                    tab_size
 6690                                } else {
 6691                                    columns_to_prev_tab_stop
 6692                                }
 6693                            }
 6694                            IndentKind::Tab => 1,
 6695                        };
 6696                        let start = if has_multiple_rows
 6697                            || deletion_len > selection.start.column
 6698                            || indent_size.len < selection.start.column
 6699                        {
 6700                            0
 6701                        } else {
 6702                            selection.start.column - deletion_len
 6703                        };
 6704                        deletion_ranges.push(
 6705                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6706                        );
 6707                        last_outdent = Some(row);
 6708                    }
 6709                }
 6710            }
 6711        }
 6712
 6713        self.transact(window, cx, |this, window, cx| {
 6714            this.buffer.update(cx, |buffer, cx| {
 6715                let empty_str: Arc<str> = Arc::default();
 6716                buffer.edit(
 6717                    deletion_ranges
 6718                        .into_iter()
 6719                        .map(|range| (range, empty_str.clone())),
 6720                    None,
 6721                    cx,
 6722                );
 6723            });
 6724            let selections = this.selections.all::<usize>(cx);
 6725            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6726                s.select(selections)
 6727            });
 6728        });
 6729    }
 6730
 6731    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6732        if self.read_only(cx) {
 6733            return;
 6734        }
 6735        let selections = self
 6736            .selections
 6737            .all::<usize>(cx)
 6738            .into_iter()
 6739            .map(|s| s.range());
 6740
 6741        self.transact(window, cx, |this, window, cx| {
 6742            this.buffer.update(cx, |buffer, cx| {
 6743                buffer.autoindent_ranges(selections, cx);
 6744            });
 6745            let selections = this.selections.all::<usize>(cx);
 6746            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6747                s.select(selections)
 6748            });
 6749        });
 6750    }
 6751
 6752    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6753        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6754        let selections = self.selections.all::<Point>(cx);
 6755
 6756        let mut new_cursors = Vec::new();
 6757        let mut edit_ranges = Vec::new();
 6758        let mut selections = selections.iter().peekable();
 6759        while let Some(selection) = selections.next() {
 6760            let mut rows = selection.spanned_rows(false, &display_map);
 6761            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6762
 6763            // Accumulate contiguous regions of rows that we want to delete.
 6764            while let Some(next_selection) = selections.peek() {
 6765                let next_rows = next_selection.spanned_rows(false, &display_map);
 6766                if next_rows.start <= rows.end {
 6767                    rows.end = next_rows.end;
 6768                    selections.next().unwrap();
 6769                } else {
 6770                    break;
 6771                }
 6772            }
 6773
 6774            let buffer = &display_map.buffer_snapshot;
 6775            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6776            let edit_end;
 6777            let cursor_buffer_row;
 6778            if buffer.max_point().row >= rows.end.0 {
 6779                // If there's a line after the range, delete the \n from the end of the row range
 6780                // and position the cursor on the next line.
 6781                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6782                cursor_buffer_row = rows.end;
 6783            } else {
 6784                // If there isn't a line after the range, delete the \n from the line before the
 6785                // start of the row range and position the cursor there.
 6786                edit_start = edit_start.saturating_sub(1);
 6787                edit_end = buffer.len();
 6788                cursor_buffer_row = rows.start.previous_row();
 6789            }
 6790
 6791            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6792            *cursor.column_mut() =
 6793                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6794
 6795            new_cursors.push((
 6796                selection.id,
 6797                buffer.anchor_after(cursor.to_point(&display_map)),
 6798            ));
 6799            edit_ranges.push(edit_start..edit_end);
 6800        }
 6801
 6802        self.transact(window, cx, |this, window, cx| {
 6803            let buffer = this.buffer.update(cx, |buffer, cx| {
 6804                let empty_str: Arc<str> = Arc::default();
 6805                buffer.edit(
 6806                    edit_ranges
 6807                        .into_iter()
 6808                        .map(|range| (range, empty_str.clone())),
 6809                    None,
 6810                    cx,
 6811                );
 6812                buffer.snapshot(cx)
 6813            });
 6814            let new_selections = new_cursors
 6815                .into_iter()
 6816                .map(|(id, cursor)| {
 6817                    let cursor = cursor.to_point(&buffer);
 6818                    Selection {
 6819                        id,
 6820                        start: cursor,
 6821                        end: cursor,
 6822                        reversed: false,
 6823                        goal: SelectionGoal::None,
 6824                    }
 6825                })
 6826                .collect();
 6827
 6828            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6829                s.select(new_selections);
 6830            });
 6831        });
 6832    }
 6833
 6834    pub fn join_lines_impl(
 6835        &mut self,
 6836        insert_whitespace: bool,
 6837        window: &mut Window,
 6838        cx: &mut Context<Self>,
 6839    ) {
 6840        if self.read_only(cx) {
 6841            return;
 6842        }
 6843        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6844        for selection in self.selections.all::<Point>(cx) {
 6845            let start = MultiBufferRow(selection.start.row);
 6846            // Treat single line selections as if they include the next line. Otherwise this action
 6847            // would do nothing for single line selections individual cursors.
 6848            let end = if selection.start.row == selection.end.row {
 6849                MultiBufferRow(selection.start.row + 1)
 6850            } else {
 6851                MultiBufferRow(selection.end.row)
 6852            };
 6853
 6854            if let Some(last_row_range) = row_ranges.last_mut() {
 6855                if start <= last_row_range.end {
 6856                    last_row_range.end = end;
 6857                    continue;
 6858                }
 6859            }
 6860            row_ranges.push(start..end);
 6861        }
 6862
 6863        let snapshot = self.buffer.read(cx).snapshot(cx);
 6864        let mut cursor_positions = Vec::new();
 6865        for row_range in &row_ranges {
 6866            let anchor = snapshot.anchor_before(Point::new(
 6867                row_range.end.previous_row().0,
 6868                snapshot.line_len(row_range.end.previous_row()),
 6869            ));
 6870            cursor_positions.push(anchor..anchor);
 6871        }
 6872
 6873        self.transact(window, cx, |this, window, cx| {
 6874            for row_range in row_ranges.into_iter().rev() {
 6875                for row in row_range.iter_rows().rev() {
 6876                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6877                    let next_line_row = row.next_row();
 6878                    let indent = snapshot.indent_size_for_line(next_line_row);
 6879                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6880
 6881                    let replace =
 6882                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6883                            " "
 6884                        } else {
 6885                            ""
 6886                        };
 6887
 6888                    this.buffer.update(cx, |buffer, cx| {
 6889                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6890                    });
 6891                }
 6892            }
 6893
 6894            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6895                s.select_anchor_ranges(cursor_positions)
 6896            });
 6897        });
 6898    }
 6899
 6900    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6901        self.join_lines_impl(true, window, cx);
 6902    }
 6903
 6904    pub fn sort_lines_case_sensitive(
 6905        &mut self,
 6906        _: &SortLinesCaseSensitive,
 6907        window: &mut Window,
 6908        cx: &mut Context<Self>,
 6909    ) {
 6910        self.manipulate_lines(window, cx, |lines| lines.sort())
 6911    }
 6912
 6913    pub fn sort_lines_case_insensitive(
 6914        &mut self,
 6915        _: &SortLinesCaseInsensitive,
 6916        window: &mut Window,
 6917        cx: &mut Context<Self>,
 6918    ) {
 6919        self.manipulate_lines(window, cx, |lines| {
 6920            lines.sort_by_key(|line| line.to_lowercase())
 6921        })
 6922    }
 6923
 6924    pub fn unique_lines_case_insensitive(
 6925        &mut self,
 6926        _: &UniqueLinesCaseInsensitive,
 6927        window: &mut Window,
 6928        cx: &mut Context<Self>,
 6929    ) {
 6930        self.manipulate_lines(window, cx, |lines| {
 6931            let mut seen = HashSet::default();
 6932            lines.retain(|line| seen.insert(line.to_lowercase()));
 6933        })
 6934    }
 6935
 6936    pub fn unique_lines_case_sensitive(
 6937        &mut self,
 6938        _: &UniqueLinesCaseSensitive,
 6939        window: &mut Window,
 6940        cx: &mut Context<Self>,
 6941    ) {
 6942        self.manipulate_lines(window, cx, |lines| {
 6943            let mut seen = HashSet::default();
 6944            lines.retain(|line| seen.insert(*line));
 6945        })
 6946    }
 6947
 6948    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6949        let mut revert_changes = HashMap::default();
 6950        let snapshot = self.snapshot(window, cx);
 6951        for hunk in snapshot
 6952            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6953        {
 6954            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6955        }
 6956        if !revert_changes.is_empty() {
 6957            self.transact(window, cx, |editor, window, cx| {
 6958                editor.revert(revert_changes, window, cx);
 6959            });
 6960        }
 6961    }
 6962
 6963    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6964        let Some(project) = self.project.clone() else {
 6965            return;
 6966        };
 6967        self.reload(project, window, cx)
 6968            .detach_and_notify_err(window, cx);
 6969    }
 6970
 6971    pub fn revert_selected_hunks(
 6972        &mut self,
 6973        _: &RevertSelectedHunks,
 6974        window: &mut Window,
 6975        cx: &mut Context<Self>,
 6976    ) {
 6977        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6978        self.discard_hunks_in_ranges(selections, window, cx);
 6979    }
 6980
 6981    fn discard_hunks_in_ranges(
 6982        &mut self,
 6983        ranges: impl Iterator<Item = Range<Point>>,
 6984        window: &mut Window,
 6985        cx: &mut Context<Editor>,
 6986    ) {
 6987        let mut revert_changes = HashMap::default();
 6988        let snapshot = self.snapshot(window, cx);
 6989        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6990            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6991        }
 6992        if !revert_changes.is_empty() {
 6993            self.transact(window, cx, |editor, window, cx| {
 6994                editor.revert(revert_changes, window, cx);
 6995            });
 6996        }
 6997    }
 6998
 6999    pub fn open_active_item_in_terminal(
 7000        &mut self,
 7001        _: &OpenInTerminal,
 7002        window: &mut Window,
 7003        cx: &mut Context<Self>,
 7004    ) {
 7005        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7006            let project_path = buffer.read(cx).project_path(cx)?;
 7007            let project = self.project.as_ref()?.read(cx);
 7008            let entry = project.entry_for_path(&project_path, cx)?;
 7009            let parent = match &entry.canonical_path {
 7010                Some(canonical_path) => canonical_path.to_path_buf(),
 7011                None => project.absolute_path(&project_path, cx)?,
 7012            }
 7013            .parent()?
 7014            .to_path_buf();
 7015            Some(parent)
 7016        }) {
 7017            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7018        }
 7019    }
 7020
 7021    pub fn prepare_revert_change(
 7022        &self,
 7023        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7024        hunk: &MultiBufferDiffHunk,
 7025        cx: &mut App,
 7026    ) -> Option<()> {
 7027        let buffer = self.buffer.read(cx);
 7028        let diff = buffer.diff_for(hunk.buffer_id)?;
 7029        let buffer = buffer.buffer(hunk.buffer_id)?;
 7030        let buffer = buffer.read(cx);
 7031        let original_text = diff
 7032            .read(cx)
 7033            .base_text()
 7034            .as_ref()?
 7035            .as_rope()
 7036            .slice(hunk.diff_base_byte_range.clone());
 7037        let buffer_snapshot = buffer.snapshot();
 7038        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7039        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7040            probe
 7041                .0
 7042                .start
 7043                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7044                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7045        }) {
 7046            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7047            Some(())
 7048        } else {
 7049            None
 7050        }
 7051    }
 7052
 7053    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7054        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7055    }
 7056
 7057    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7058        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7059    }
 7060
 7061    fn manipulate_lines<Fn>(
 7062        &mut self,
 7063        window: &mut Window,
 7064        cx: &mut Context<Self>,
 7065        mut callback: Fn,
 7066    ) where
 7067        Fn: FnMut(&mut Vec<&str>),
 7068    {
 7069        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7070        let buffer = self.buffer.read(cx).snapshot(cx);
 7071
 7072        let mut edits = Vec::new();
 7073
 7074        let selections = self.selections.all::<Point>(cx);
 7075        let mut selections = selections.iter().peekable();
 7076        let mut contiguous_row_selections = Vec::new();
 7077        let mut new_selections = Vec::new();
 7078        let mut added_lines = 0;
 7079        let mut removed_lines = 0;
 7080
 7081        while let Some(selection) = selections.next() {
 7082            let (start_row, end_row) = consume_contiguous_rows(
 7083                &mut contiguous_row_selections,
 7084                selection,
 7085                &display_map,
 7086                &mut selections,
 7087            );
 7088
 7089            let start_point = Point::new(start_row.0, 0);
 7090            let end_point = Point::new(
 7091                end_row.previous_row().0,
 7092                buffer.line_len(end_row.previous_row()),
 7093            );
 7094            let text = buffer
 7095                .text_for_range(start_point..end_point)
 7096                .collect::<String>();
 7097
 7098            let mut lines = text.split('\n').collect_vec();
 7099
 7100            let lines_before = lines.len();
 7101            callback(&mut lines);
 7102            let lines_after = lines.len();
 7103
 7104            edits.push((start_point..end_point, lines.join("\n")));
 7105
 7106            // Selections must change based on added and removed line count
 7107            let start_row =
 7108                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7109            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7110            new_selections.push(Selection {
 7111                id: selection.id,
 7112                start: start_row,
 7113                end: end_row,
 7114                goal: SelectionGoal::None,
 7115                reversed: selection.reversed,
 7116            });
 7117
 7118            if lines_after > lines_before {
 7119                added_lines += lines_after - lines_before;
 7120            } else if lines_before > lines_after {
 7121                removed_lines += lines_before - lines_after;
 7122            }
 7123        }
 7124
 7125        self.transact(window, cx, |this, window, cx| {
 7126            let buffer = this.buffer.update(cx, |buffer, cx| {
 7127                buffer.edit(edits, None, cx);
 7128                buffer.snapshot(cx)
 7129            });
 7130
 7131            // Recalculate offsets on newly edited buffer
 7132            let new_selections = new_selections
 7133                .iter()
 7134                .map(|s| {
 7135                    let start_point = Point::new(s.start.0, 0);
 7136                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7137                    Selection {
 7138                        id: s.id,
 7139                        start: buffer.point_to_offset(start_point),
 7140                        end: buffer.point_to_offset(end_point),
 7141                        goal: s.goal,
 7142                        reversed: s.reversed,
 7143                    }
 7144                })
 7145                .collect();
 7146
 7147            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7148                s.select(new_selections);
 7149            });
 7150
 7151            this.request_autoscroll(Autoscroll::fit(), cx);
 7152        });
 7153    }
 7154
 7155    pub fn convert_to_upper_case(
 7156        &mut self,
 7157        _: &ConvertToUpperCase,
 7158        window: &mut Window,
 7159        cx: &mut Context<Self>,
 7160    ) {
 7161        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7162    }
 7163
 7164    pub fn convert_to_lower_case(
 7165        &mut self,
 7166        _: &ConvertToLowerCase,
 7167        window: &mut Window,
 7168        cx: &mut Context<Self>,
 7169    ) {
 7170        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7171    }
 7172
 7173    pub fn convert_to_title_case(
 7174        &mut self,
 7175        _: &ConvertToTitleCase,
 7176        window: &mut Window,
 7177        cx: &mut Context<Self>,
 7178    ) {
 7179        self.manipulate_text(window, cx, |text| {
 7180            text.split('\n')
 7181                .map(|line| line.to_case(Case::Title))
 7182                .join("\n")
 7183        })
 7184    }
 7185
 7186    pub fn convert_to_snake_case(
 7187        &mut self,
 7188        _: &ConvertToSnakeCase,
 7189        window: &mut Window,
 7190        cx: &mut Context<Self>,
 7191    ) {
 7192        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7193    }
 7194
 7195    pub fn convert_to_kebab_case(
 7196        &mut self,
 7197        _: &ConvertToKebabCase,
 7198        window: &mut Window,
 7199        cx: &mut Context<Self>,
 7200    ) {
 7201        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7202    }
 7203
 7204    pub fn convert_to_upper_camel_case(
 7205        &mut self,
 7206        _: &ConvertToUpperCamelCase,
 7207        window: &mut Window,
 7208        cx: &mut Context<Self>,
 7209    ) {
 7210        self.manipulate_text(window, cx, |text| {
 7211            text.split('\n')
 7212                .map(|line| line.to_case(Case::UpperCamel))
 7213                .join("\n")
 7214        })
 7215    }
 7216
 7217    pub fn convert_to_lower_camel_case(
 7218        &mut self,
 7219        _: &ConvertToLowerCamelCase,
 7220        window: &mut Window,
 7221        cx: &mut Context<Self>,
 7222    ) {
 7223        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7224    }
 7225
 7226    pub fn convert_to_opposite_case(
 7227        &mut self,
 7228        _: &ConvertToOppositeCase,
 7229        window: &mut Window,
 7230        cx: &mut Context<Self>,
 7231    ) {
 7232        self.manipulate_text(window, cx, |text| {
 7233            text.chars()
 7234                .fold(String::with_capacity(text.len()), |mut t, c| {
 7235                    if c.is_uppercase() {
 7236                        t.extend(c.to_lowercase());
 7237                    } else {
 7238                        t.extend(c.to_uppercase());
 7239                    }
 7240                    t
 7241                })
 7242        })
 7243    }
 7244
 7245    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7246    where
 7247        Fn: FnMut(&str) -> String,
 7248    {
 7249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7250        let buffer = self.buffer.read(cx).snapshot(cx);
 7251
 7252        let mut new_selections = Vec::new();
 7253        let mut edits = Vec::new();
 7254        let mut selection_adjustment = 0i32;
 7255
 7256        for selection in self.selections.all::<usize>(cx) {
 7257            let selection_is_empty = selection.is_empty();
 7258
 7259            let (start, end) = if selection_is_empty {
 7260                let word_range = movement::surrounding_word(
 7261                    &display_map,
 7262                    selection.start.to_display_point(&display_map),
 7263                );
 7264                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7265                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7266                (start, end)
 7267            } else {
 7268                (selection.start, selection.end)
 7269            };
 7270
 7271            let text = buffer.text_for_range(start..end).collect::<String>();
 7272            let old_length = text.len() as i32;
 7273            let text = callback(&text);
 7274
 7275            new_selections.push(Selection {
 7276                start: (start as i32 - selection_adjustment) as usize,
 7277                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7278                goal: SelectionGoal::None,
 7279                ..selection
 7280            });
 7281
 7282            selection_adjustment += old_length - text.len() as i32;
 7283
 7284            edits.push((start..end, text));
 7285        }
 7286
 7287        self.transact(window, cx, |this, window, cx| {
 7288            this.buffer.update(cx, |buffer, cx| {
 7289                buffer.edit(edits, None, cx);
 7290            });
 7291
 7292            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7293                s.select(new_selections);
 7294            });
 7295
 7296            this.request_autoscroll(Autoscroll::fit(), cx);
 7297        });
 7298    }
 7299
 7300    pub fn duplicate(
 7301        &mut self,
 7302        upwards: bool,
 7303        whole_lines: bool,
 7304        window: &mut Window,
 7305        cx: &mut Context<Self>,
 7306    ) {
 7307        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7308        let buffer = &display_map.buffer_snapshot;
 7309        let selections = self.selections.all::<Point>(cx);
 7310
 7311        let mut edits = Vec::new();
 7312        let mut selections_iter = selections.iter().peekable();
 7313        while let Some(selection) = selections_iter.next() {
 7314            let mut rows = selection.spanned_rows(false, &display_map);
 7315            // duplicate line-wise
 7316            if whole_lines || selection.start == selection.end {
 7317                // Avoid duplicating the same lines twice.
 7318                while let Some(next_selection) = selections_iter.peek() {
 7319                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7320                    if next_rows.start < rows.end {
 7321                        rows.end = next_rows.end;
 7322                        selections_iter.next().unwrap();
 7323                    } else {
 7324                        break;
 7325                    }
 7326                }
 7327
 7328                // Copy the text from the selected row region and splice it either at the start
 7329                // or end of the region.
 7330                let start = Point::new(rows.start.0, 0);
 7331                let end = Point::new(
 7332                    rows.end.previous_row().0,
 7333                    buffer.line_len(rows.end.previous_row()),
 7334                );
 7335                let text = buffer
 7336                    .text_for_range(start..end)
 7337                    .chain(Some("\n"))
 7338                    .collect::<String>();
 7339                let insert_location = if upwards {
 7340                    Point::new(rows.end.0, 0)
 7341                } else {
 7342                    start
 7343                };
 7344                edits.push((insert_location..insert_location, text));
 7345            } else {
 7346                // duplicate character-wise
 7347                let start = selection.start;
 7348                let end = selection.end;
 7349                let text = buffer.text_for_range(start..end).collect::<String>();
 7350                edits.push((selection.end..selection.end, text));
 7351            }
 7352        }
 7353
 7354        self.transact(window, cx, |this, _, cx| {
 7355            this.buffer.update(cx, |buffer, cx| {
 7356                buffer.edit(edits, None, cx);
 7357            });
 7358
 7359            this.request_autoscroll(Autoscroll::fit(), cx);
 7360        });
 7361    }
 7362
 7363    pub fn duplicate_line_up(
 7364        &mut self,
 7365        _: &DuplicateLineUp,
 7366        window: &mut Window,
 7367        cx: &mut Context<Self>,
 7368    ) {
 7369        self.duplicate(true, true, window, cx);
 7370    }
 7371
 7372    pub fn duplicate_line_down(
 7373        &mut self,
 7374        _: &DuplicateLineDown,
 7375        window: &mut Window,
 7376        cx: &mut Context<Self>,
 7377    ) {
 7378        self.duplicate(false, true, window, cx);
 7379    }
 7380
 7381    pub fn duplicate_selection(
 7382        &mut self,
 7383        _: &DuplicateSelection,
 7384        window: &mut Window,
 7385        cx: &mut Context<Self>,
 7386    ) {
 7387        self.duplicate(false, false, window, cx);
 7388    }
 7389
 7390    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7391        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7392        let buffer = self.buffer.read(cx).snapshot(cx);
 7393
 7394        let mut edits = Vec::new();
 7395        let mut unfold_ranges = Vec::new();
 7396        let mut refold_creases = Vec::new();
 7397
 7398        let selections = self.selections.all::<Point>(cx);
 7399        let mut selections = selections.iter().peekable();
 7400        let mut contiguous_row_selections = Vec::new();
 7401        let mut new_selections = Vec::new();
 7402
 7403        while let Some(selection) = selections.next() {
 7404            // Find all the selections that span a contiguous row range
 7405            let (start_row, end_row) = consume_contiguous_rows(
 7406                &mut contiguous_row_selections,
 7407                selection,
 7408                &display_map,
 7409                &mut selections,
 7410            );
 7411
 7412            // Move the text spanned by the row range to be before the line preceding the row range
 7413            if start_row.0 > 0 {
 7414                let range_to_move = Point::new(
 7415                    start_row.previous_row().0,
 7416                    buffer.line_len(start_row.previous_row()),
 7417                )
 7418                    ..Point::new(
 7419                        end_row.previous_row().0,
 7420                        buffer.line_len(end_row.previous_row()),
 7421                    );
 7422                let insertion_point = display_map
 7423                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7424                    .0;
 7425
 7426                // Don't move lines across excerpts
 7427                if buffer
 7428                    .excerpt_containing(insertion_point..range_to_move.end)
 7429                    .is_some()
 7430                {
 7431                    let text = buffer
 7432                        .text_for_range(range_to_move.clone())
 7433                        .flat_map(|s| s.chars())
 7434                        .skip(1)
 7435                        .chain(['\n'])
 7436                        .collect::<String>();
 7437
 7438                    edits.push((
 7439                        buffer.anchor_after(range_to_move.start)
 7440                            ..buffer.anchor_before(range_to_move.end),
 7441                        String::new(),
 7442                    ));
 7443                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7444                    edits.push((insertion_anchor..insertion_anchor, text));
 7445
 7446                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7447
 7448                    // Move selections up
 7449                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7450                        |mut selection| {
 7451                            selection.start.row -= row_delta;
 7452                            selection.end.row -= row_delta;
 7453                            selection
 7454                        },
 7455                    ));
 7456
 7457                    // Move folds up
 7458                    unfold_ranges.push(range_to_move.clone());
 7459                    for fold in display_map.folds_in_range(
 7460                        buffer.anchor_before(range_to_move.start)
 7461                            ..buffer.anchor_after(range_to_move.end),
 7462                    ) {
 7463                        let mut start = fold.range.start.to_point(&buffer);
 7464                        let mut end = fold.range.end.to_point(&buffer);
 7465                        start.row -= row_delta;
 7466                        end.row -= row_delta;
 7467                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7468                    }
 7469                }
 7470            }
 7471
 7472            // If we didn't move line(s), preserve the existing selections
 7473            new_selections.append(&mut contiguous_row_selections);
 7474        }
 7475
 7476        self.transact(window, cx, |this, window, cx| {
 7477            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7478            this.buffer.update(cx, |buffer, cx| {
 7479                for (range, text) in edits {
 7480                    buffer.edit([(range, text)], None, cx);
 7481                }
 7482            });
 7483            this.fold_creases(refold_creases, true, window, cx);
 7484            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7485                s.select(new_selections);
 7486            })
 7487        });
 7488    }
 7489
 7490    pub fn move_line_down(
 7491        &mut self,
 7492        _: &MoveLineDown,
 7493        window: &mut Window,
 7494        cx: &mut Context<Self>,
 7495    ) {
 7496        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7497        let buffer = self.buffer.read(cx).snapshot(cx);
 7498
 7499        let mut edits = Vec::new();
 7500        let mut unfold_ranges = Vec::new();
 7501        let mut refold_creases = Vec::new();
 7502
 7503        let selections = self.selections.all::<Point>(cx);
 7504        let mut selections = selections.iter().peekable();
 7505        let mut contiguous_row_selections = Vec::new();
 7506        let mut new_selections = Vec::new();
 7507
 7508        while let Some(selection) = selections.next() {
 7509            // Find all the selections that span a contiguous row range
 7510            let (start_row, end_row) = consume_contiguous_rows(
 7511                &mut contiguous_row_selections,
 7512                selection,
 7513                &display_map,
 7514                &mut selections,
 7515            );
 7516
 7517            // Move the text spanned by the row range to be after the last line of the row range
 7518            if end_row.0 <= buffer.max_point().row {
 7519                let range_to_move =
 7520                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7521                let insertion_point = display_map
 7522                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7523                    .0;
 7524
 7525                // Don't move lines across excerpt boundaries
 7526                if buffer
 7527                    .excerpt_containing(range_to_move.start..insertion_point)
 7528                    .is_some()
 7529                {
 7530                    let mut text = String::from("\n");
 7531                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7532                    text.pop(); // Drop trailing newline
 7533                    edits.push((
 7534                        buffer.anchor_after(range_to_move.start)
 7535                            ..buffer.anchor_before(range_to_move.end),
 7536                        String::new(),
 7537                    ));
 7538                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7539                    edits.push((insertion_anchor..insertion_anchor, text));
 7540
 7541                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7542
 7543                    // Move selections down
 7544                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7545                        |mut selection| {
 7546                            selection.start.row += row_delta;
 7547                            selection.end.row += row_delta;
 7548                            selection
 7549                        },
 7550                    ));
 7551
 7552                    // Move folds down
 7553                    unfold_ranges.push(range_to_move.clone());
 7554                    for fold in display_map.folds_in_range(
 7555                        buffer.anchor_before(range_to_move.start)
 7556                            ..buffer.anchor_after(range_to_move.end),
 7557                    ) {
 7558                        let mut start = fold.range.start.to_point(&buffer);
 7559                        let mut end = fold.range.end.to_point(&buffer);
 7560                        start.row += row_delta;
 7561                        end.row += row_delta;
 7562                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7563                    }
 7564                }
 7565            }
 7566
 7567            // If we didn't move line(s), preserve the existing selections
 7568            new_selections.append(&mut contiguous_row_selections);
 7569        }
 7570
 7571        self.transact(window, cx, |this, window, cx| {
 7572            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7573            this.buffer.update(cx, |buffer, cx| {
 7574                for (range, text) in edits {
 7575                    buffer.edit([(range, text)], None, cx);
 7576                }
 7577            });
 7578            this.fold_creases(refold_creases, true, window, cx);
 7579            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7580                s.select(new_selections)
 7581            });
 7582        });
 7583    }
 7584
 7585    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7586        let text_layout_details = &self.text_layout_details(window);
 7587        self.transact(window, cx, |this, window, cx| {
 7588            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7589                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7590                let line_mode = s.line_mode;
 7591                s.move_with(|display_map, selection| {
 7592                    if !selection.is_empty() || line_mode {
 7593                        return;
 7594                    }
 7595
 7596                    let mut head = selection.head();
 7597                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7598                    if head.column() == display_map.line_len(head.row()) {
 7599                        transpose_offset = display_map
 7600                            .buffer_snapshot
 7601                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7602                    }
 7603
 7604                    if transpose_offset == 0 {
 7605                        return;
 7606                    }
 7607
 7608                    *head.column_mut() += 1;
 7609                    head = display_map.clip_point(head, Bias::Right);
 7610                    let goal = SelectionGoal::HorizontalPosition(
 7611                        display_map
 7612                            .x_for_display_point(head, text_layout_details)
 7613                            .into(),
 7614                    );
 7615                    selection.collapse_to(head, goal);
 7616
 7617                    let transpose_start = display_map
 7618                        .buffer_snapshot
 7619                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7620                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7621                        let transpose_end = display_map
 7622                            .buffer_snapshot
 7623                            .clip_offset(transpose_offset + 1, Bias::Right);
 7624                        if let Some(ch) =
 7625                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7626                        {
 7627                            edits.push((transpose_start..transpose_offset, String::new()));
 7628                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7629                        }
 7630                    }
 7631                });
 7632                edits
 7633            });
 7634            this.buffer
 7635                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7636            let selections = this.selections.all::<usize>(cx);
 7637            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7638                s.select(selections);
 7639            });
 7640        });
 7641    }
 7642
 7643    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7644        self.rewrap_impl(IsVimMode::No, cx)
 7645    }
 7646
 7647    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7648        let buffer = self.buffer.read(cx).snapshot(cx);
 7649        let selections = self.selections.all::<Point>(cx);
 7650        let mut selections = selections.iter().peekable();
 7651
 7652        let mut edits = Vec::new();
 7653        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7654
 7655        while let Some(selection) = selections.next() {
 7656            let mut start_row = selection.start.row;
 7657            let mut end_row = selection.end.row;
 7658
 7659            // Skip selections that overlap with a range that has already been rewrapped.
 7660            let selection_range = start_row..end_row;
 7661            if rewrapped_row_ranges
 7662                .iter()
 7663                .any(|range| range.overlaps(&selection_range))
 7664            {
 7665                continue;
 7666            }
 7667
 7668            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7669
 7670            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7671                match language_scope.language_name().as_ref() {
 7672                    "Markdown" | "Plain Text" => {
 7673                        should_rewrap = true;
 7674                    }
 7675                    _ => {}
 7676                }
 7677            }
 7678
 7679            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7680
 7681            // Since not all lines in the selection may be at the same indent
 7682            // level, choose the indent size that is the most common between all
 7683            // of the lines.
 7684            //
 7685            // If there is a tie, we use the deepest indent.
 7686            let (indent_size, indent_end) = {
 7687                let mut indent_size_occurrences = HashMap::default();
 7688                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7689
 7690                for row in start_row..=end_row {
 7691                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7692                    rows_by_indent_size.entry(indent).or_default().push(row);
 7693                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7694                }
 7695
 7696                let indent_size = indent_size_occurrences
 7697                    .into_iter()
 7698                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7699                    .map(|(indent, _)| indent)
 7700                    .unwrap_or_default();
 7701                let row = rows_by_indent_size[&indent_size][0];
 7702                let indent_end = Point::new(row, indent_size.len);
 7703
 7704                (indent_size, indent_end)
 7705            };
 7706
 7707            let mut line_prefix = indent_size.chars().collect::<String>();
 7708
 7709            if let Some(comment_prefix) =
 7710                buffer
 7711                    .language_scope_at(selection.head())
 7712                    .and_then(|language| {
 7713                        language
 7714                            .line_comment_prefixes()
 7715                            .iter()
 7716                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7717                            .cloned()
 7718                    })
 7719            {
 7720                line_prefix.push_str(&comment_prefix);
 7721                should_rewrap = true;
 7722            }
 7723
 7724            if !should_rewrap {
 7725                continue;
 7726            }
 7727
 7728            if selection.is_empty() {
 7729                'expand_upwards: while start_row > 0 {
 7730                    let prev_row = start_row - 1;
 7731                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7732                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7733                    {
 7734                        start_row = prev_row;
 7735                    } else {
 7736                        break 'expand_upwards;
 7737                    }
 7738                }
 7739
 7740                'expand_downwards: while end_row < buffer.max_point().row {
 7741                    let next_row = end_row + 1;
 7742                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7743                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7744                    {
 7745                        end_row = next_row;
 7746                    } else {
 7747                        break 'expand_downwards;
 7748                    }
 7749                }
 7750            }
 7751
 7752            let start = Point::new(start_row, 0);
 7753            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7754            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7755            let Some(lines_without_prefixes) = selection_text
 7756                .lines()
 7757                .map(|line| {
 7758                    line.strip_prefix(&line_prefix)
 7759                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7760                        .ok_or_else(|| {
 7761                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7762                        })
 7763                })
 7764                .collect::<Result<Vec<_>, _>>()
 7765                .log_err()
 7766            else {
 7767                continue;
 7768            };
 7769
 7770            let wrap_column = buffer
 7771                .settings_at(Point::new(start_row, 0), cx)
 7772                .preferred_line_length as usize;
 7773            let wrapped_text = wrap_with_prefix(
 7774                line_prefix,
 7775                lines_without_prefixes.join(" "),
 7776                wrap_column,
 7777                tab_size,
 7778            );
 7779
 7780            // TODO: should always use char-based diff while still supporting cursor behavior that
 7781            // matches vim.
 7782            let diff = match is_vim_mode {
 7783                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7784                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7785            };
 7786            let mut offset = start.to_offset(&buffer);
 7787            let mut moved_since_edit = true;
 7788
 7789            for change in diff.iter_all_changes() {
 7790                let value = change.value();
 7791                match change.tag() {
 7792                    ChangeTag::Equal => {
 7793                        offset += value.len();
 7794                        moved_since_edit = true;
 7795                    }
 7796                    ChangeTag::Delete => {
 7797                        let start = buffer.anchor_after(offset);
 7798                        let end = buffer.anchor_before(offset + value.len());
 7799
 7800                        if moved_since_edit {
 7801                            edits.push((start..end, String::new()));
 7802                        } else {
 7803                            edits.last_mut().unwrap().0.end = end;
 7804                        }
 7805
 7806                        offset += value.len();
 7807                        moved_since_edit = false;
 7808                    }
 7809                    ChangeTag::Insert => {
 7810                        if moved_since_edit {
 7811                            let anchor = buffer.anchor_after(offset);
 7812                            edits.push((anchor..anchor, value.to_string()));
 7813                        } else {
 7814                            edits.last_mut().unwrap().1.push_str(value);
 7815                        }
 7816
 7817                        moved_since_edit = false;
 7818                    }
 7819                }
 7820            }
 7821
 7822            rewrapped_row_ranges.push(start_row..=end_row);
 7823        }
 7824
 7825        self.buffer
 7826            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7827    }
 7828
 7829    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7830        let mut text = String::new();
 7831        let buffer = self.buffer.read(cx).snapshot(cx);
 7832        let mut selections = self.selections.all::<Point>(cx);
 7833        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7834        {
 7835            let max_point = buffer.max_point();
 7836            let mut is_first = true;
 7837            for selection in &mut selections {
 7838                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7839                if is_entire_line {
 7840                    selection.start = Point::new(selection.start.row, 0);
 7841                    if !selection.is_empty() && selection.end.column == 0 {
 7842                        selection.end = cmp::min(max_point, selection.end);
 7843                    } else {
 7844                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7845                    }
 7846                    selection.goal = SelectionGoal::None;
 7847                }
 7848                if is_first {
 7849                    is_first = false;
 7850                } else {
 7851                    text += "\n";
 7852                }
 7853                let mut len = 0;
 7854                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7855                    text.push_str(chunk);
 7856                    len += chunk.len();
 7857                }
 7858                clipboard_selections.push(ClipboardSelection {
 7859                    len,
 7860                    is_entire_line,
 7861                    first_line_indent: buffer
 7862                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7863                        .len,
 7864                });
 7865            }
 7866        }
 7867
 7868        self.transact(window, cx, |this, window, cx| {
 7869            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7870                s.select(selections);
 7871            });
 7872            this.insert("", window, cx);
 7873        });
 7874        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7875    }
 7876
 7877    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7878        let item = self.cut_common(window, cx);
 7879        cx.write_to_clipboard(item);
 7880    }
 7881
 7882    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7883        self.change_selections(None, window, cx, |s| {
 7884            s.move_with(|snapshot, sel| {
 7885                if sel.is_empty() {
 7886                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7887                }
 7888            });
 7889        });
 7890        let item = self.cut_common(window, cx);
 7891        cx.set_global(KillRing(item))
 7892    }
 7893
 7894    pub fn kill_ring_yank(
 7895        &mut self,
 7896        _: &KillRingYank,
 7897        window: &mut Window,
 7898        cx: &mut Context<Self>,
 7899    ) {
 7900        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7901            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7902                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7903            } else {
 7904                return;
 7905            }
 7906        } else {
 7907            return;
 7908        };
 7909        self.do_paste(&text, metadata, false, window, cx);
 7910    }
 7911
 7912    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7913        let selections = self.selections.all::<Point>(cx);
 7914        let buffer = self.buffer.read(cx).read(cx);
 7915        let mut text = String::new();
 7916
 7917        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7918        {
 7919            let max_point = buffer.max_point();
 7920            let mut is_first = true;
 7921            for selection in selections.iter() {
 7922                let mut start = selection.start;
 7923                let mut end = selection.end;
 7924                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7925                if is_entire_line {
 7926                    start = Point::new(start.row, 0);
 7927                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7928                }
 7929                if is_first {
 7930                    is_first = false;
 7931                } else {
 7932                    text += "\n";
 7933                }
 7934                let mut len = 0;
 7935                for chunk in buffer.text_for_range(start..end) {
 7936                    text.push_str(chunk);
 7937                    len += chunk.len();
 7938                }
 7939                clipboard_selections.push(ClipboardSelection {
 7940                    len,
 7941                    is_entire_line,
 7942                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7943                });
 7944            }
 7945        }
 7946
 7947        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7948            text,
 7949            clipboard_selections,
 7950        ));
 7951    }
 7952
 7953    pub fn do_paste(
 7954        &mut self,
 7955        text: &String,
 7956        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7957        handle_entire_lines: bool,
 7958        window: &mut Window,
 7959        cx: &mut Context<Self>,
 7960    ) {
 7961        if self.read_only(cx) {
 7962            return;
 7963        }
 7964
 7965        let clipboard_text = Cow::Borrowed(text);
 7966
 7967        self.transact(window, cx, |this, window, cx| {
 7968            if let Some(mut clipboard_selections) = clipboard_selections {
 7969                let old_selections = this.selections.all::<usize>(cx);
 7970                let all_selections_were_entire_line =
 7971                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7972                let first_selection_indent_column =
 7973                    clipboard_selections.first().map(|s| s.first_line_indent);
 7974                if clipboard_selections.len() != old_selections.len() {
 7975                    clipboard_selections.drain(..);
 7976                }
 7977                let cursor_offset = this.selections.last::<usize>(cx).head();
 7978                let mut auto_indent_on_paste = true;
 7979
 7980                this.buffer.update(cx, |buffer, cx| {
 7981                    let snapshot = buffer.read(cx);
 7982                    auto_indent_on_paste =
 7983                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7984
 7985                    let mut start_offset = 0;
 7986                    let mut edits = Vec::new();
 7987                    let mut original_indent_columns = Vec::new();
 7988                    for (ix, selection) in old_selections.iter().enumerate() {
 7989                        let to_insert;
 7990                        let entire_line;
 7991                        let original_indent_column;
 7992                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7993                            let end_offset = start_offset + clipboard_selection.len;
 7994                            to_insert = &clipboard_text[start_offset..end_offset];
 7995                            entire_line = clipboard_selection.is_entire_line;
 7996                            start_offset = end_offset + 1;
 7997                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7998                        } else {
 7999                            to_insert = clipboard_text.as_str();
 8000                            entire_line = all_selections_were_entire_line;
 8001                            original_indent_column = first_selection_indent_column
 8002                        }
 8003
 8004                        // If the corresponding selection was empty when this slice of the
 8005                        // clipboard text was written, then the entire line containing the
 8006                        // selection was copied. If this selection is also currently empty,
 8007                        // then paste the line before the current line of the buffer.
 8008                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8009                            let column = selection.start.to_point(&snapshot).column as usize;
 8010                            let line_start = selection.start - column;
 8011                            line_start..line_start
 8012                        } else {
 8013                            selection.range()
 8014                        };
 8015
 8016                        edits.push((range, to_insert));
 8017                        original_indent_columns.extend(original_indent_column);
 8018                    }
 8019                    drop(snapshot);
 8020
 8021                    buffer.edit(
 8022                        edits,
 8023                        if auto_indent_on_paste {
 8024                            Some(AutoindentMode::Block {
 8025                                original_indent_columns,
 8026                            })
 8027                        } else {
 8028                            None
 8029                        },
 8030                        cx,
 8031                    );
 8032                });
 8033
 8034                let selections = this.selections.all::<usize>(cx);
 8035                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8036                    s.select(selections)
 8037                });
 8038            } else {
 8039                this.insert(&clipboard_text, window, cx);
 8040            }
 8041        });
 8042    }
 8043
 8044    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8045        if let Some(item) = cx.read_from_clipboard() {
 8046            let entries = item.entries();
 8047
 8048            match entries.first() {
 8049                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8050                // of all the pasted entries.
 8051                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8052                    .do_paste(
 8053                        clipboard_string.text(),
 8054                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8055                        true,
 8056                        window,
 8057                        cx,
 8058                    ),
 8059                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8060            }
 8061        }
 8062    }
 8063
 8064    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8065        if self.read_only(cx) {
 8066            return;
 8067        }
 8068
 8069        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8070            if let Some((selections, _)) =
 8071                self.selection_history.transaction(transaction_id).cloned()
 8072            {
 8073                self.change_selections(None, window, cx, |s| {
 8074                    s.select_anchors(selections.to_vec());
 8075                });
 8076            }
 8077            self.request_autoscroll(Autoscroll::fit(), cx);
 8078            self.unmark_text(window, cx);
 8079            self.refresh_inline_completion(true, false, window, cx);
 8080            cx.emit(EditorEvent::Edited { transaction_id });
 8081            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8082        }
 8083    }
 8084
 8085    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8086        if self.read_only(cx) {
 8087            return;
 8088        }
 8089
 8090        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8091            if let Some((_, Some(selections))) =
 8092                self.selection_history.transaction(transaction_id).cloned()
 8093            {
 8094                self.change_selections(None, window, cx, |s| {
 8095                    s.select_anchors(selections.to_vec());
 8096                });
 8097            }
 8098            self.request_autoscroll(Autoscroll::fit(), cx);
 8099            self.unmark_text(window, cx);
 8100            self.refresh_inline_completion(true, false, window, cx);
 8101            cx.emit(EditorEvent::Edited { transaction_id });
 8102        }
 8103    }
 8104
 8105    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8106        self.buffer
 8107            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8108    }
 8109
 8110    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8111        self.buffer
 8112            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8113    }
 8114
 8115    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8116        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8117            let line_mode = s.line_mode;
 8118            s.move_with(|map, selection| {
 8119                let cursor = if selection.is_empty() && !line_mode {
 8120                    movement::left(map, selection.start)
 8121                } else {
 8122                    selection.start
 8123                };
 8124                selection.collapse_to(cursor, SelectionGoal::None);
 8125            });
 8126        })
 8127    }
 8128
 8129    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8130        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8131            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8132        })
 8133    }
 8134
 8135    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8136        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8137            let line_mode = s.line_mode;
 8138            s.move_with(|map, selection| {
 8139                let cursor = if selection.is_empty() && !line_mode {
 8140                    movement::right(map, selection.end)
 8141                } else {
 8142                    selection.end
 8143                };
 8144                selection.collapse_to(cursor, SelectionGoal::None)
 8145            });
 8146        })
 8147    }
 8148
 8149    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8150        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8151            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8152        })
 8153    }
 8154
 8155    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8156        if self.take_rename(true, window, cx).is_some() {
 8157            return;
 8158        }
 8159
 8160        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8161            cx.propagate();
 8162            return;
 8163        }
 8164
 8165        let text_layout_details = &self.text_layout_details(window);
 8166        let selection_count = self.selections.count();
 8167        let first_selection = self.selections.first_anchor();
 8168
 8169        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8170            let line_mode = s.line_mode;
 8171            s.move_with(|map, selection| {
 8172                if !selection.is_empty() && !line_mode {
 8173                    selection.goal = SelectionGoal::None;
 8174                }
 8175                let (cursor, goal) = movement::up(
 8176                    map,
 8177                    selection.start,
 8178                    selection.goal,
 8179                    false,
 8180                    text_layout_details,
 8181                );
 8182                selection.collapse_to(cursor, goal);
 8183            });
 8184        });
 8185
 8186        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8187        {
 8188            cx.propagate();
 8189        }
 8190    }
 8191
 8192    pub fn move_up_by_lines(
 8193        &mut self,
 8194        action: &MoveUpByLines,
 8195        window: &mut Window,
 8196        cx: &mut Context<Self>,
 8197    ) {
 8198        if self.take_rename(true, window, cx).is_some() {
 8199            return;
 8200        }
 8201
 8202        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8203            cx.propagate();
 8204            return;
 8205        }
 8206
 8207        let text_layout_details = &self.text_layout_details(window);
 8208
 8209        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8210            let line_mode = s.line_mode;
 8211            s.move_with(|map, selection| {
 8212                if !selection.is_empty() && !line_mode {
 8213                    selection.goal = SelectionGoal::None;
 8214                }
 8215                let (cursor, goal) = movement::up_by_rows(
 8216                    map,
 8217                    selection.start,
 8218                    action.lines,
 8219                    selection.goal,
 8220                    false,
 8221                    text_layout_details,
 8222                );
 8223                selection.collapse_to(cursor, goal);
 8224            });
 8225        })
 8226    }
 8227
 8228    pub fn move_down_by_lines(
 8229        &mut self,
 8230        action: &MoveDownByLines,
 8231        window: &mut Window,
 8232        cx: &mut Context<Self>,
 8233    ) {
 8234        if self.take_rename(true, window, cx).is_some() {
 8235            return;
 8236        }
 8237
 8238        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8239            cx.propagate();
 8240            return;
 8241        }
 8242
 8243        let text_layout_details = &self.text_layout_details(window);
 8244
 8245        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8246            let line_mode = s.line_mode;
 8247            s.move_with(|map, selection| {
 8248                if !selection.is_empty() && !line_mode {
 8249                    selection.goal = SelectionGoal::None;
 8250                }
 8251                let (cursor, goal) = movement::down_by_rows(
 8252                    map,
 8253                    selection.start,
 8254                    action.lines,
 8255                    selection.goal,
 8256                    false,
 8257                    text_layout_details,
 8258                );
 8259                selection.collapse_to(cursor, goal);
 8260            });
 8261        })
 8262    }
 8263
 8264    pub fn select_down_by_lines(
 8265        &mut self,
 8266        action: &SelectDownByLines,
 8267        window: &mut Window,
 8268        cx: &mut Context<Self>,
 8269    ) {
 8270        let text_layout_details = &self.text_layout_details(window);
 8271        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8272            s.move_heads_with(|map, head, goal| {
 8273                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8274            })
 8275        })
 8276    }
 8277
 8278    pub fn select_up_by_lines(
 8279        &mut self,
 8280        action: &SelectUpByLines,
 8281        window: &mut Window,
 8282        cx: &mut Context<Self>,
 8283    ) {
 8284        let text_layout_details = &self.text_layout_details(window);
 8285        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8286            s.move_heads_with(|map, head, goal| {
 8287                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8288            })
 8289        })
 8290    }
 8291
 8292    pub fn select_page_up(
 8293        &mut self,
 8294        _: &SelectPageUp,
 8295        window: &mut Window,
 8296        cx: &mut Context<Self>,
 8297    ) {
 8298        let Some(row_count) = self.visible_row_count() else {
 8299            return;
 8300        };
 8301
 8302        let text_layout_details = &self.text_layout_details(window);
 8303
 8304        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8305            s.move_heads_with(|map, head, goal| {
 8306                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8307            })
 8308        })
 8309    }
 8310
 8311    pub fn move_page_up(
 8312        &mut self,
 8313        action: &MovePageUp,
 8314        window: &mut Window,
 8315        cx: &mut Context<Self>,
 8316    ) {
 8317        if self.take_rename(true, window, cx).is_some() {
 8318            return;
 8319        }
 8320
 8321        if self
 8322            .context_menu
 8323            .borrow_mut()
 8324            .as_mut()
 8325            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8326            .unwrap_or(false)
 8327        {
 8328            return;
 8329        }
 8330
 8331        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8332            cx.propagate();
 8333            return;
 8334        }
 8335
 8336        let Some(row_count) = self.visible_row_count() else {
 8337            return;
 8338        };
 8339
 8340        let autoscroll = if action.center_cursor {
 8341            Autoscroll::center()
 8342        } else {
 8343            Autoscroll::fit()
 8344        };
 8345
 8346        let text_layout_details = &self.text_layout_details(window);
 8347
 8348        self.change_selections(Some(autoscroll), window, cx, |s| {
 8349            let line_mode = s.line_mode;
 8350            s.move_with(|map, selection| {
 8351                if !selection.is_empty() && !line_mode {
 8352                    selection.goal = SelectionGoal::None;
 8353                }
 8354                let (cursor, goal) = movement::up_by_rows(
 8355                    map,
 8356                    selection.end,
 8357                    row_count,
 8358                    selection.goal,
 8359                    false,
 8360                    text_layout_details,
 8361                );
 8362                selection.collapse_to(cursor, goal);
 8363            });
 8364        });
 8365    }
 8366
 8367    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8368        let text_layout_details = &self.text_layout_details(window);
 8369        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8370            s.move_heads_with(|map, head, goal| {
 8371                movement::up(map, head, goal, false, text_layout_details)
 8372            })
 8373        })
 8374    }
 8375
 8376    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8377        self.take_rename(true, window, cx);
 8378
 8379        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8380            cx.propagate();
 8381            return;
 8382        }
 8383
 8384        let text_layout_details = &self.text_layout_details(window);
 8385        let selection_count = self.selections.count();
 8386        let first_selection = self.selections.first_anchor();
 8387
 8388        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8389            let line_mode = s.line_mode;
 8390            s.move_with(|map, selection| {
 8391                if !selection.is_empty() && !line_mode {
 8392                    selection.goal = SelectionGoal::None;
 8393                }
 8394                let (cursor, goal) = movement::down(
 8395                    map,
 8396                    selection.end,
 8397                    selection.goal,
 8398                    false,
 8399                    text_layout_details,
 8400                );
 8401                selection.collapse_to(cursor, goal);
 8402            });
 8403        });
 8404
 8405        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8406        {
 8407            cx.propagate();
 8408        }
 8409    }
 8410
 8411    pub fn select_page_down(
 8412        &mut self,
 8413        _: &SelectPageDown,
 8414        window: &mut Window,
 8415        cx: &mut Context<Self>,
 8416    ) {
 8417        let Some(row_count) = self.visible_row_count() else {
 8418            return;
 8419        };
 8420
 8421        let text_layout_details = &self.text_layout_details(window);
 8422
 8423        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8424            s.move_heads_with(|map, head, goal| {
 8425                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8426            })
 8427        })
 8428    }
 8429
 8430    pub fn move_page_down(
 8431        &mut self,
 8432        action: &MovePageDown,
 8433        window: &mut Window,
 8434        cx: &mut Context<Self>,
 8435    ) {
 8436        if self.take_rename(true, window, cx).is_some() {
 8437            return;
 8438        }
 8439
 8440        if self
 8441            .context_menu
 8442            .borrow_mut()
 8443            .as_mut()
 8444            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8445            .unwrap_or(false)
 8446        {
 8447            return;
 8448        }
 8449
 8450        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8451            cx.propagate();
 8452            return;
 8453        }
 8454
 8455        let Some(row_count) = self.visible_row_count() else {
 8456            return;
 8457        };
 8458
 8459        let autoscroll = if action.center_cursor {
 8460            Autoscroll::center()
 8461        } else {
 8462            Autoscroll::fit()
 8463        };
 8464
 8465        let text_layout_details = &self.text_layout_details(window);
 8466        self.change_selections(Some(autoscroll), window, cx, |s| {
 8467            let line_mode = s.line_mode;
 8468            s.move_with(|map, selection| {
 8469                if !selection.is_empty() && !line_mode {
 8470                    selection.goal = SelectionGoal::None;
 8471                }
 8472                let (cursor, goal) = movement::down_by_rows(
 8473                    map,
 8474                    selection.end,
 8475                    row_count,
 8476                    selection.goal,
 8477                    false,
 8478                    text_layout_details,
 8479                );
 8480                selection.collapse_to(cursor, goal);
 8481            });
 8482        });
 8483    }
 8484
 8485    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8486        let text_layout_details = &self.text_layout_details(window);
 8487        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8488            s.move_heads_with(|map, head, goal| {
 8489                movement::down(map, head, goal, false, text_layout_details)
 8490            })
 8491        });
 8492    }
 8493
 8494    pub fn context_menu_first(
 8495        &mut self,
 8496        _: &ContextMenuFirst,
 8497        _window: &mut Window,
 8498        cx: &mut Context<Self>,
 8499    ) {
 8500        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8501            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8502        }
 8503    }
 8504
 8505    pub fn context_menu_prev(
 8506        &mut self,
 8507        _: &ContextMenuPrev,
 8508        _window: &mut Window,
 8509        cx: &mut Context<Self>,
 8510    ) {
 8511        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8512            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8513        }
 8514    }
 8515
 8516    pub fn context_menu_next(
 8517        &mut self,
 8518        _: &ContextMenuNext,
 8519        _window: &mut Window,
 8520        cx: &mut Context<Self>,
 8521    ) {
 8522        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8523            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8524        }
 8525    }
 8526
 8527    pub fn context_menu_last(
 8528        &mut self,
 8529        _: &ContextMenuLast,
 8530        _window: &mut Window,
 8531        cx: &mut Context<Self>,
 8532    ) {
 8533        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8534            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8535        }
 8536    }
 8537
 8538    pub fn move_to_previous_word_start(
 8539        &mut self,
 8540        _: &MoveToPreviousWordStart,
 8541        window: &mut Window,
 8542        cx: &mut Context<Self>,
 8543    ) {
 8544        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8545            s.move_cursors_with(|map, head, _| {
 8546                (
 8547                    movement::previous_word_start(map, head),
 8548                    SelectionGoal::None,
 8549                )
 8550            });
 8551        })
 8552    }
 8553
 8554    pub fn move_to_previous_subword_start(
 8555        &mut self,
 8556        _: &MoveToPreviousSubwordStart,
 8557        window: &mut Window,
 8558        cx: &mut Context<Self>,
 8559    ) {
 8560        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8561            s.move_cursors_with(|map, head, _| {
 8562                (
 8563                    movement::previous_subword_start(map, head),
 8564                    SelectionGoal::None,
 8565                )
 8566            });
 8567        })
 8568    }
 8569
 8570    pub fn select_to_previous_word_start(
 8571        &mut self,
 8572        _: &SelectToPreviousWordStart,
 8573        window: &mut Window,
 8574        cx: &mut Context<Self>,
 8575    ) {
 8576        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8577            s.move_heads_with(|map, head, _| {
 8578                (
 8579                    movement::previous_word_start(map, head),
 8580                    SelectionGoal::None,
 8581                )
 8582            });
 8583        })
 8584    }
 8585
 8586    pub fn select_to_previous_subword_start(
 8587        &mut self,
 8588        _: &SelectToPreviousSubwordStart,
 8589        window: &mut Window,
 8590        cx: &mut Context<Self>,
 8591    ) {
 8592        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8593            s.move_heads_with(|map, head, _| {
 8594                (
 8595                    movement::previous_subword_start(map, head),
 8596                    SelectionGoal::None,
 8597                )
 8598            });
 8599        })
 8600    }
 8601
 8602    pub fn delete_to_previous_word_start(
 8603        &mut self,
 8604        action: &DeleteToPreviousWordStart,
 8605        window: &mut Window,
 8606        cx: &mut Context<Self>,
 8607    ) {
 8608        self.transact(window, cx, |this, window, cx| {
 8609            this.select_autoclose_pair(window, cx);
 8610            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8611                let line_mode = s.line_mode;
 8612                s.move_with(|map, selection| {
 8613                    if selection.is_empty() && !line_mode {
 8614                        let cursor = if action.ignore_newlines {
 8615                            movement::previous_word_start(map, selection.head())
 8616                        } else {
 8617                            movement::previous_word_start_or_newline(map, selection.head())
 8618                        };
 8619                        selection.set_head(cursor, SelectionGoal::None);
 8620                    }
 8621                });
 8622            });
 8623            this.insert("", window, cx);
 8624        });
 8625    }
 8626
 8627    pub fn delete_to_previous_subword_start(
 8628        &mut self,
 8629        _: &DeleteToPreviousSubwordStart,
 8630        window: &mut Window,
 8631        cx: &mut Context<Self>,
 8632    ) {
 8633        self.transact(window, cx, |this, window, cx| {
 8634            this.select_autoclose_pair(window, cx);
 8635            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8636                let line_mode = s.line_mode;
 8637                s.move_with(|map, selection| {
 8638                    if selection.is_empty() && !line_mode {
 8639                        let cursor = movement::previous_subword_start(map, selection.head());
 8640                        selection.set_head(cursor, SelectionGoal::None);
 8641                    }
 8642                });
 8643            });
 8644            this.insert("", window, cx);
 8645        });
 8646    }
 8647
 8648    pub fn move_to_next_word_end(
 8649        &mut self,
 8650        _: &MoveToNextWordEnd,
 8651        window: &mut Window,
 8652        cx: &mut Context<Self>,
 8653    ) {
 8654        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8655            s.move_cursors_with(|map, head, _| {
 8656                (movement::next_word_end(map, head), SelectionGoal::None)
 8657            });
 8658        })
 8659    }
 8660
 8661    pub fn move_to_next_subword_end(
 8662        &mut self,
 8663        _: &MoveToNextSubwordEnd,
 8664        window: &mut Window,
 8665        cx: &mut Context<Self>,
 8666    ) {
 8667        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8668            s.move_cursors_with(|map, head, _| {
 8669                (movement::next_subword_end(map, head), SelectionGoal::None)
 8670            });
 8671        })
 8672    }
 8673
 8674    pub fn select_to_next_word_end(
 8675        &mut self,
 8676        _: &SelectToNextWordEnd,
 8677        window: &mut Window,
 8678        cx: &mut Context<Self>,
 8679    ) {
 8680        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8681            s.move_heads_with(|map, head, _| {
 8682                (movement::next_word_end(map, head), SelectionGoal::None)
 8683            });
 8684        })
 8685    }
 8686
 8687    pub fn select_to_next_subword_end(
 8688        &mut self,
 8689        _: &SelectToNextSubwordEnd,
 8690        window: &mut Window,
 8691        cx: &mut Context<Self>,
 8692    ) {
 8693        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8694            s.move_heads_with(|map, head, _| {
 8695                (movement::next_subword_end(map, head), SelectionGoal::None)
 8696            });
 8697        })
 8698    }
 8699
 8700    pub fn delete_to_next_word_end(
 8701        &mut self,
 8702        action: &DeleteToNextWordEnd,
 8703        window: &mut Window,
 8704        cx: &mut Context<Self>,
 8705    ) {
 8706        self.transact(window, cx, |this, window, cx| {
 8707            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8708                let line_mode = s.line_mode;
 8709                s.move_with(|map, selection| {
 8710                    if selection.is_empty() && !line_mode {
 8711                        let cursor = if action.ignore_newlines {
 8712                            movement::next_word_end(map, selection.head())
 8713                        } else {
 8714                            movement::next_word_end_or_newline(map, selection.head())
 8715                        };
 8716                        selection.set_head(cursor, SelectionGoal::None);
 8717                    }
 8718                });
 8719            });
 8720            this.insert("", window, cx);
 8721        });
 8722    }
 8723
 8724    pub fn delete_to_next_subword_end(
 8725        &mut self,
 8726        _: &DeleteToNextSubwordEnd,
 8727        window: &mut Window,
 8728        cx: &mut Context<Self>,
 8729    ) {
 8730        self.transact(window, cx, |this, window, cx| {
 8731            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8732                s.move_with(|map, selection| {
 8733                    if selection.is_empty() {
 8734                        let cursor = movement::next_subword_end(map, selection.head());
 8735                        selection.set_head(cursor, SelectionGoal::None);
 8736                    }
 8737                });
 8738            });
 8739            this.insert("", window, cx);
 8740        });
 8741    }
 8742
 8743    pub fn move_to_beginning_of_line(
 8744        &mut self,
 8745        action: &MoveToBeginningOfLine,
 8746        window: &mut Window,
 8747        cx: &mut Context<Self>,
 8748    ) {
 8749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8750            s.move_cursors_with(|map, head, _| {
 8751                (
 8752                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8753                    SelectionGoal::None,
 8754                )
 8755            });
 8756        })
 8757    }
 8758
 8759    pub fn select_to_beginning_of_line(
 8760        &mut self,
 8761        action: &SelectToBeginningOfLine,
 8762        window: &mut Window,
 8763        cx: &mut Context<Self>,
 8764    ) {
 8765        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8766            s.move_heads_with(|map, head, _| {
 8767                (
 8768                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8769                    SelectionGoal::None,
 8770                )
 8771            });
 8772        });
 8773    }
 8774
 8775    pub fn delete_to_beginning_of_line(
 8776        &mut self,
 8777        _: &DeleteToBeginningOfLine,
 8778        window: &mut Window,
 8779        cx: &mut Context<Self>,
 8780    ) {
 8781        self.transact(window, cx, |this, window, cx| {
 8782            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8783                s.move_with(|_, selection| {
 8784                    selection.reversed = true;
 8785                });
 8786            });
 8787
 8788            this.select_to_beginning_of_line(
 8789                &SelectToBeginningOfLine {
 8790                    stop_at_soft_wraps: false,
 8791                },
 8792                window,
 8793                cx,
 8794            );
 8795            this.backspace(&Backspace, window, cx);
 8796        });
 8797    }
 8798
 8799    pub fn move_to_end_of_line(
 8800        &mut self,
 8801        action: &MoveToEndOfLine,
 8802        window: &mut Window,
 8803        cx: &mut Context<Self>,
 8804    ) {
 8805        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8806            s.move_cursors_with(|map, head, _| {
 8807                (
 8808                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8809                    SelectionGoal::None,
 8810                )
 8811            });
 8812        })
 8813    }
 8814
 8815    pub fn select_to_end_of_line(
 8816        &mut self,
 8817        action: &SelectToEndOfLine,
 8818        window: &mut Window,
 8819        cx: &mut Context<Self>,
 8820    ) {
 8821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8822            s.move_heads_with(|map, head, _| {
 8823                (
 8824                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8825                    SelectionGoal::None,
 8826                )
 8827            });
 8828        })
 8829    }
 8830
 8831    pub fn delete_to_end_of_line(
 8832        &mut self,
 8833        _: &DeleteToEndOfLine,
 8834        window: &mut Window,
 8835        cx: &mut Context<Self>,
 8836    ) {
 8837        self.transact(window, cx, |this, window, cx| {
 8838            this.select_to_end_of_line(
 8839                &SelectToEndOfLine {
 8840                    stop_at_soft_wraps: false,
 8841                },
 8842                window,
 8843                cx,
 8844            );
 8845            this.delete(&Delete, window, cx);
 8846        });
 8847    }
 8848
 8849    pub fn cut_to_end_of_line(
 8850        &mut self,
 8851        _: &CutToEndOfLine,
 8852        window: &mut Window,
 8853        cx: &mut Context<Self>,
 8854    ) {
 8855        self.transact(window, cx, |this, window, cx| {
 8856            this.select_to_end_of_line(
 8857                &SelectToEndOfLine {
 8858                    stop_at_soft_wraps: false,
 8859                },
 8860                window,
 8861                cx,
 8862            );
 8863            this.cut(&Cut, window, cx);
 8864        });
 8865    }
 8866
 8867    pub fn move_to_start_of_paragraph(
 8868        &mut self,
 8869        _: &MoveToStartOfParagraph,
 8870        window: &mut Window,
 8871        cx: &mut Context<Self>,
 8872    ) {
 8873        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8874            cx.propagate();
 8875            return;
 8876        }
 8877
 8878        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8879            s.move_with(|map, selection| {
 8880                selection.collapse_to(
 8881                    movement::start_of_paragraph(map, selection.head(), 1),
 8882                    SelectionGoal::None,
 8883                )
 8884            });
 8885        })
 8886    }
 8887
 8888    pub fn move_to_end_of_paragraph(
 8889        &mut self,
 8890        _: &MoveToEndOfParagraph,
 8891        window: &mut Window,
 8892        cx: &mut Context<Self>,
 8893    ) {
 8894        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8895            cx.propagate();
 8896            return;
 8897        }
 8898
 8899        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8900            s.move_with(|map, selection| {
 8901                selection.collapse_to(
 8902                    movement::end_of_paragraph(map, selection.head(), 1),
 8903                    SelectionGoal::None,
 8904                )
 8905            });
 8906        })
 8907    }
 8908
 8909    pub fn select_to_start_of_paragraph(
 8910        &mut self,
 8911        _: &SelectToStartOfParagraph,
 8912        window: &mut Window,
 8913        cx: &mut Context<Self>,
 8914    ) {
 8915        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8916            cx.propagate();
 8917            return;
 8918        }
 8919
 8920        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8921            s.move_heads_with(|map, head, _| {
 8922                (
 8923                    movement::start_of_paragraph(map, head, 1),
 8924                    SelectionGoal::None,
 8925                )
 8926            });
 8927        })
 8928    }
 8929
 8930    pub fn select_to_end_of_paragraph(
 8931        &mut self,
 8932        _: &SelectToEndOfParagraph,
 8933        window: &mut Window,
 8934        cx: &mut Context<Self>,
 8935    ) {
 8936        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8937            cx.propagate();
 8938            return;
 8939        }
 8940
 8941        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8942            s.move_heads_with(|map, head, _| {
 8943                (
 8944                    movement::end_of_paragraph(map, head, 1),
 8945                    SelectionGoal::None,
 8946                )
 8947            });
 8948        })
 8949    }
 8950
 8951    pub fn move_to_beginning(
 8952        &mut self,
 8953        _: &MoveToBeginning,
 8954        window: &mut Window,
 8955        cx: &mut Context<Self>,
 8956    ) {
 8957        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8958            cx.propagate();
 8959            return;
 8960        }
 8961
 8962        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8963            s.select_ranges(vec![0..0]);
 8964        });
 8965    }
 8966
 8967    pub fn select_to_beginning(
 8968        &mut self,
 8969        _: &SelectToBeginning,
 8970        window: &mut Window,
 8971        cx: &mut Context<Self>,
 8972    ) {
 8973        let mut selection = self.selections.last::<Point>(cx);
 8974        selection.set_head(Point::zero(), SelectionGoal::None);
 8975
 8976        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8977            s.select(vec![selection]);
 8978        });
 8979    }
 8980
 8981    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8982        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8983            cx.propagate();
 8984            return;
 8985        }
 8986
 8987        let cursor = self.buffer.read(cx).read(cx).len();
 8988        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8989            s.select_ranges(vec![cursor..cursor])
 8990        });
 8991    }
 8992
 8993    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8994        self.nav_history = nav_history;
 8995    }
 8996
 8997    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8998        self.nav_history.as_ref()
 8999    }
 9000
 9001    fn push_to_nav_history(
 9002        &mut self,
 9003        cursor_anchor: Anchor,
 9004        new_position: Option<Point>,
 9005        cx: &mut Context<Self>,
 9006    ) {
 9007        if let Some(nav_history) = self.nav_history.as_mut() {
 9008            let buffer = self.buffer.read(cx).read(cx);
 9009            let cursor_position = cursor_anchor.to_point(&buffer);
 9010            let scroll_state = self.scroll_manager.anchor();
 9011            let scroll_top_row = scroll_state.top_row(&buffer);
 9012            drop(buffer);
 9013
 9014            if let Some(new_position) = new_position {
 9015                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9016                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9017                    return;
 9018                }
 9019            }
 9020
 9021            nav_history.push(
 9022                Some(NavigationData {
 9023                    cursor_anchor,
 9024                    cursor_position,
 9025                    scroll_anchor: scroll_state,
 9026                    scroll_top_row,
 9027                }),
 9028                cx,
 9029            );
 9030        }
 9031    }
 9032
 9033    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9034        let buffer = self.buffer.read(cx).snapshot(cx);
 9035        let mut selection = self.selections.first::<usize>(cx);
 9036        selection.set_head(buffer.len(), SelectionGoal::None);
 9037        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9038            s.select(vec![selection]);
 9039        });
 9040    }
 9041
 9042    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9043        let end = self.buffer.read(cx).read(cx).len();
 9044        self.change_selections(None, window, cx, |s| {
 9045            s.select_ranges(vec![0..end]);
 9046        });
 9047    }
 9048
 9049    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9050        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9051        let mut selections = self.selections.all::<Point>(cx);
 9052        let max_point = display_map.buffer_snapshot.max_point();
 9053        for selection in &mut selections {
 9054            let rows = selection.spanned_rows(true, &display_map);
 9055            selection.start = Point::new(rows.start.0, 0);
 9056            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9057            selection.reversed = false;
 9058        }
 9059        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9060            s.select(selections);
 9061        });
 9062    }
 9063
 9064    pub fn split_selection_into_lines(
 9065        &mut self,
 9066        _: &SplitSelectionIntoLines,
 9067        window: &mut Window,
 9068        cx: &mut Context<Self>,
 9069    ) {
 9070        let mut to_unfold = Vec::new();
 9071        let mut new_selection_ranges = Vec::new();
 9072        {
 9073            let selections = self.selections.all::<Point>(cx);
 9074            let buffer = self.buffer.read(cx).read(cx);
 9075            for selection in selections {
 9076                for row in selection.start.row..selection.end.row {
 9077                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9078                    new_selection_ranges.push(cursor..cursor);
 9079                }
 9080                new_selection_ranges.push(selection.end..selection.end);
 9081                to_unfold.push(selection.start..selection.end);
 9082            }
 9083        }
 9084        self.unfold_ranges(&to_unfold, true, true, cx);
 9085        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9086            s.select_ranges(new_selection_ranges);
 9087        });
 9088    }
 9089
 9090    pub fn add_selection_above(
 9091        &mut self,
 9092        _: &AddSelectionAbove,
 9093        window: &mut Window,
 9094        cx: &mut Context<Self>,
 9095    ) {
 9096        self.add_selection(true, window, cx);
 9097    }
 9098
 9099    pub fn add_selection_below(
 9100        &mut self,
 9101        _: &AddSelectionBelow,
 9102        window: &mut Window,
 9103        cx: &mut Context<Self>,
 9104    ) {
 9105        self.add_selection(false, window, cx);
 9106    }
 9107
 9108    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9109        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9110        let mut selections = self.selections.all::<Point>(cx);
 9111        let text_layout_details = self.text_layout_details(window);
 9112        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9113            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9114            let range = oldest_selection.display_range(&display_map).sorted();
 9115
 9116            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9117            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9118            let positions = start_x.min(end_x)..start_x.max(end_x);
 9119
 9120            selections.clear();
 9121            let mut stack = Vec::new();
 9122            for row in range.start.row().0..=range.end.row().0 {
 9123                if let Some(selection) = self.selections.build_columnar_selection(
 9124                    &display_map,
 9125                    DisplayRow(row),
 9126                    &positions,
 9127                    oldest_selection.reversed,
 9128                    &text_layout_details,
 9129                ) {
 9130                    stack.push(selection.id);
 9131                    selections.push(selection);
 9132                }
 9133            }
 9134
 9135            if above {
 9136                stack.reverse();
 9137            }
 9138
 9139            AddSelectionsState { above, stack }
 9140        });
 9141
 9142        let last_added_selection = *state.stack.last().unwrap();
 9143        let mut new_selections = Vec::new();
 9144        if above == state.above {
 9145            let end_row = if above {
 9146                DisplayRow(0)
 9147            } else {
 9148                display_map.max_point().row()
 9149            };
 9150
 9151            'outer: for selection in selections {
 9152                if selection.id == last_added_selection {
 9153                    let range = selection.display_range(&display_map).sorted();
 9154                    debug_assert_eq!(range.start.row(), range.end.row());
 9155                    let mut row = range.start.row();
 9156                    let positions =
 9157                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9158                            px(start)..px(end)
 9159                        } else {
 9160                            let start_x =
 9161                                display_map.x_for_display_point(range.start, &text_layout_details);
 9162                            let end_x =
 9163                                display_map.x_for_display_point(range.end, &text_layout_details);
 9164                            start_x.min(end_x)..start_x.max(end_x)
 9165                        };
 9166
 9167                    while row != end_row {
 9168                        if above {
 9169                            row.0 -= 1;
 9170                        } else {
 9171                            row.0 += 1;
 9172                        }
 9173
 9174                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9175                            &display_map,
 9176                            row,
 9177                            &positions,
 9178                            selection.reversed,
 9179                            &text_layout_details,
 9180                        ) {
 9181                            state.stack.push(new_selection.id);
 9182                            if above {
 9183                                new_selections.push(new_selection);
 9184                                new_selections.push(selection);
 9185                            } else {
 9186                                new_selections.push(selection);
 9187                                new_selections.push(new_selection);
 9188                            }
 9189
 9190                            continue 'outer;
 9191                        }
 9192                    }
 9193                }
 9194
 9195                new_selections.push(selection);
 9196            }
 9197        } else {
 9198            new_selections = selections;
 9199            new_selections.retain(|s| s.id != last_added_selection);
 9200            state.stack.pop();
 9201        }
 9202
 9203        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9204            s.select(new_selections);
 9205        });
 9206        if state.stack.len() > 1 {
 9207            self.add_selections_state = Some(state);
 9208        }
 9209    }
 9210
 9211    pub fn select_next_match_internal(
 9212        &mut self,
 9213        display_map: &DisplaySnapshot,
 9214        replace_newest: bool,
 9215        autoscroll: Option<Autoscroll>,
 9216        window: &mut Window,
 9217        cx: &mut Context<Self>,
 9218    ) -> Result<()> {
 9219        fn select_next_match_ranges(
 9220            this: &mut Editor,
 9221            range: Range<usize>,
 9222            replace_newest: bool,
 9223            auto_scroll: Option<Autoscroll>,
 9224            window: &mut Window,
 9225            cx: &mut Context<Editor>,
 9226        ) {
 9227            this.unfold_ranges(&[range.clone()], false, true, cx);
 9228            this.change_selections(auto_scroll, window, cx, |s| {
 9229                if replace_newest {
 9230                    s.delete(s.newest_anchor().id);
 9231                }
 9232                s.insert_range(range.clone());
 9233            });
 9234        }
 9235
 9236        let buffer = &display_map.buffer_snapshot;
 9237        let mut selections = self.selections.all::<usize>(cx);
 9238        if let Some(mut select_next_state) = self.select_next_state.take() {
 9239            let query = &select_next_state.query;
 9240            if !select_next_state.done {
 9241                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9242                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9243                let mut next_selected_range = None;
 9244
 9245                let bytes_after_last_selection =
 9246                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9247                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9248                let query_matches = query
 9249                    .stream_find_iter(bytes_after_last_selection)
 9250                    .map(|result| (last_selection.end, result))
 9251                    .chain(
 9252                        query
 9253                            .stream_find_iter(bytes_before_first_selection)
 9254                            .map(|result| (0, result)),
 9255                    );
 9256
 9257                for (start_offset, query_match) in query_matches {
 9258                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9259                    let offset_range =
 9260                        start_offset + query_match.start()..start_offset + query_match.end();
 9261                    let display_range = offset_range.start.to_display_point(display_map)
 9262                        ..offset_range.end.to_display_point(display_map);
 9263
 9264                    if !select_next_state.wordwise
 9265                        || (!movement::is_inside_word(display_map, display_range.start)
 9266                            && !movement::is_inside_word(display_map, display_range.end))
 9267                    {
 9268                        // TODO: This is n^2, because we might check all the selections
 9269                        if !selections
 9270                            .iter()
 9271                            .any(|selection| selection.range().overlaps(&offset_range))
 9272                        {
 9273                            next_selected_range = Some(offset_range);
 9274                            break;
 9275                        }
 9276                    }
 9277                }
 9278
 9279                if let Some(next_selected_range) = next_selected_range {
 9280                    select_next_match_ranges(
 9281                        self,
 9282                        next_selected_range,
 9283                        replace_newest,
 9284                        autoscroll,
 9285                        window,
 9286                        cx,
 9287                    );
 9288                } else {
 9289                    select_next_state.done = true;
 9290                }
 9291            }
 9292
 9293            self.select_next_state = Some(select_next_state);
 9294        } else {
 9295            let mut only_carets = true;
 9296            let mut same_text_selected = true;
 9297            let mut selected_text = None;
 9298
 9299            let mut selections_iter = selections.iter().peekable();
 9300            while let Some(selection) = selections_iter.next() {
 9301                if selection.start != selection.end {
 9302                    only_carets = false;
 9303                }
 9304
 9305                if same_text_selected {
 9306                    if selected_text.is_none() {
 9307                        selected_text =
 9308                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9309                    }
 9310
 9311                    if let Some(next_selection) = selections_iter.peek() {
 9312                        if next_selection.range().len() == selection.range().len() {
 9313                            let next_selected_text = buffer
 9314                                .text_for_range(next_selection.range())
 9315                                .collect::<String>();
 9316                            if Some(next_selected_text) != selected_text {
 9317                                same_text_selected = false;
 9318                                selected_text = None;
 9319                            }
 9320                        } else {
 9321                            same_text_selected = false;
 9322                            selected_text = None;
 9323                        }
 9324                    }
 9325                }
 9326            }
 9327
 9328            if only_carets {
 9329                for selection in &mut selections {
 9330                    let word_range = movement::surrounding_word(
 9331                        display_map,
 9332                        selection.start.to_display_point(display_map),
 9333                    );
 9334                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9335                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9336                    selection.goal = SelectionGoal::None;
 9337                    selection.reversed = false;
 9338                    select_next_match_ranges(
 9339                        self,
 9340                        selection.start..selection.end,
 9341                        replace_newest,
 9342                        autoscroll,
 9343                        window,
 9344                        cx,
 9345                    );
 9346                }
 9347
 9348                if selections.len() == 1 {
 9349                    let selection = selections
 9350                        .last()
 9351                        .expect("ensured that there's only one selection");
 9352                    let query = buffer
 9353                        .text_for_range(selection.start..selection.end)
 9354                        .collect::<String>();
 9355                    let is_empty = query.is_empty();
 9356                    let select_state = SelectNextState {
 9357                        query: AhoCorasick::new(&[query])?,
 9358                        wordwise: true,
 9359                        done: is_empty,
 9360                    };
 9361                    self.select_next_state = Some(select_state);
 9362                } else {
 9363                    self.select_next_state = None;
 9364                }
 9365            } else if let Some(selected_text) = selected_text {
 9366                self.select_next_state = Some(SelectNextState {
 9367                    query: AhoCorasick::new(&[selected_text])?,
 9368                    wordwise: false,
 9369                    done: false,
 9370                });
 9371                self.select_next_match_internal(
 9372                    display_map,
 9373                    replace_newest,
 9374                    autoscroll,
 9375                    window,
 9376                    cx,
 9377                )?;
 9378            }
 9379        }
 9380        Ok(())
 9381    }
 9382
 9383    pub fn select_all_matches(
 9384        &mut self,
 9385        _action: &SelectAllMatches,
 9386        window: &mut Window,
 9387        cx: &mut Context<Self>,
 9388    ) -> Result<()> {
 9389        self.push_to_selection_history();
 9390        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9391
 9392        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9393        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9394            return Ok(());
 9395        };
 9396        if select_next_state.done {
 9397            return Ok(());
 9398        }
 9399
 9400        let mut new_selections = self.selections.all::<usize>(cx);
 9401
 9402        let buffer = &display_map.buffer_snapshot;
 9403        let query_matches = select_next_state
 9404            .query
 9405            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9406
 9407        for query_match in query_matches {
 9408            let query_match = query_match.unwrap(); // can only fail due to I/O
 9409            let offset_range = query_match.start()..query_match.end();
 9410            let display_range = offset_range.start.to_display_point(&display_map)
 9411                ..offset_range.end.to_display_point(&display_map);
 9412
 9413            if !select_next_state.wordwise
 9414                || (!movement::is_inside_word(&display_map, display_range.start)
 9415                    && !movement::is_inside_word(&display_map, display_range.end))
 9416            {
 9417                self.selections.change_with(cx, |selections| {
 9418                    new_selections.push(Selection {
 9419                        id: selections.new_selection_id(),
 9420                        start: offset_range.start,
 9421                        end: offset_range.end,
 9422                        reversed: false,
 9423                        goal: SelectionGoal::None,
 9424                    });
 9425                });
 9426            }
 9427        }
 9428
 9429        new_selections.sort_by_key(|selection| selection.start);
 9430        let mut ix = 0;
 9431        while ix + 1 < new_selections.len() {
 9432            let current_selection = &new_selections[ix];
 9433            let next_selection = &new_selections[ix + 1];
 9434            if current_selection.range().overlaps(&next_selection.range()) {
 9435                if current_selection.id < next_selection.id {
 9436                    new_selections.remove(ix + 1);
 9437                } else {
 9438                    new_selections.remove(ix);
 9439                }
 9440            } else {
 9441                ix += 1;
 9442            }
 9443        }
 9444
 9445        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9446
 9447        for selection in new_selections.iter_mut() {
 9448            selection.reversed = reversed;
 9449        }
 9450
 9451        select_next_state.done = true;
 9452        self.unfold_ranges(
 9453            &new_selections
 9454                .iter()
 9455                .map(|selection| selection.range())
 9456                .collect::<Vec<_>>(),
 9457            false,
 9458            false,
 9459            cx,
 9460        );
 9461        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9462            selections.select(new_selections)
 9463        });
 9464
 9465        Ok(())
 9466    }
 9467
 9468    pub fn select_next(
 9469        &mut self,
 9470        action: &SelectNext,
 9471        window: &mut Window,
 9472        cx: &mut Context<Self>,
 9473    ) -> Result<()> {
 9474        self.push_to_selection_history();
 9475        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9476        self.select_next_match_internal(
 9477            &display_map,
 9478            action.replace_newest,
 9479            Some(Autoscroll::newest()),
 9480            window,
 9481            cx,
 9482        )?;
 9483        Ok(())
 9484    }
 9485
 9486    pub fn select_previous(
 9487        &mut self,
 9488        action: &SelectPrevious,
 9489        window: &mut Window,
 9490        cx: &mut Context<Self>,
 9491    ) -> Result<()> {
 9492        self.push_to_selection_history();
 9493        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9494        let buffer = &display_map.buffer_snapshot;
 9495        let mut selections = self.selections.all::<usize>(cx);
 9496        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9497            let query = &select_prev_state.query;
 9498            if !select_prev_state.done {
 9499                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9500                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9501                let mut next_selected_range = None;
 9502                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9503                let bytes_before_last_selection =
 9504                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9505                let bytes_after_first_selection =
 9506                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9507                let query_matches = query
 9508                    .stream_find_iter(bytes_before_last_selection)
 9509                    .map(|result| (last_selection.start, result))
 9510                    .chain(
 9511                        query
 9512                            .stream_find_iter(bytes_after_first_selection)
 9513                            .map(|result| (buffer.len(), result)),
 9514                    );
 9515                for (end_offset, query_match) in query_matches {
 9516                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9517                    let offset_range =
 9518                        end_offset - query_match.end()..end_offset - query_match.start();
 9519                    let display_range = offset_range.start.to_display_point(&display_map)
 9520                        ..offset_range.end.to_display_point(&display_map);
 9521
 9522                    if !select_prev_state.wordwise
 9523                        || (!movement::is_inside_word(&display_map, display_range.start)
 9524                            && !movement::is_inside_word(&display_map, display_range.end))
 9525                    {
 9526                        next_selected_range = Some(offset_range);
 9527                        break;
 9528                    }
 9529                }
 9530
 9531                if let Some(next_selected_range) = next_selected_range {
 9532                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9533                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9534                        if action.replace_newest {
 9535                            s.delete(s.newest_anchor().id);
 9536                        }
 9537                        s.insert_range(next_selected_range);
 9538                    });
 9539                } else {
 9540                    select_prev_state.done = true;
 9541                }
 9542            }
 9543
 9544            self.select_prev_state = Some(select_prev_state);
 9545        } else {
 9546            let mut only_carets = true;
 9547            let mut same_text_selected = true;
 9548            let mut selected_text = None;
 9549
 9550            let mut selections_iter = selections.iter().peekable();
 9551            while let Some(selection) = selections_iter.next() {
 9552                if selection.start != selection.end {
 9553                    only_carets = false;
 9554                }
 9555
 9556                if same_text_selected {
 9557                    if selected_text.is_none() {
 9558                        selected_text =
 9559                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9560                    }
 9561
 9562                    if let Some(next_selection) = selections_iter.peek() {
 9563                        if next_selection.range().len() == selection.range().len() {
 9564                            let next_selected_text = buffer
 9565                                .text_for_range(next_selection.range())
 9566                                .collect::<String>();
 9567                            if Some(next_selected_text) != selected_text {
 9568                                same_text_selected = false;
 9569                                selected_text = None;
 9570                            }
 9571                        } else {
 9572                            same_text_selected = false;
 9573                            selected_text = None;
 9574                        }
 9575                    }
 9576                }
 9577            }
 9578
 9579            if only_carets {
 9580                for selection in &mut selections {
 9581                    let word_range = movement::surrounding_word(
 9582                        &display_map,
 9583                        selection.start.to_display_point(&display_map),
 9584                    );
 9585                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9586                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9587                    selection.goal = SelectionGoal::None;
 9588                    selection.reversed = false;
 9589                }
 9590                if selections.len() == 1 {
 9591                    let selection = selections
 9592                        .last()
 9593                        .expect("ensured that there's only one selection");
 9594                    let query = buffer
 9595                        .text_for_range(selection.start..selection.end)
 9596                        .collect::<String>();
 9597                    let is_empty = query.is_empty();
 9598                    let select_state = SelectNextState {
 9599                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9600                        wordwise: true,
 9601                        done: is_empty,
 9602                    };
 9603                    self.select_prev_state = Some(select_state);
 9604                } else {
 9605                    self.select_prev_state = None;
 9606                }
 9607
 9608                self.unfold_ranges(
 9609                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9610                    false,
 9611                    true,
 9612                    cx,
 9613                );
 9614                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9615                    s.select(selections);
 9616                });
 9617            } else if let Some(selected_text) = selected_text {
 9618                self.select_prev_state = Some(SelectNextState {
 9619                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9620                    wordwise: false,
 9621                    done: false,
 9622                });
 9623                self.select_previous(action, window, cx)?;
 9624            }
 9625        }
 9626        Ok(())
 9627    }
 9628
 9629    pub fn toggle_comments(
 9630        &mut self,
 9631        action: &ToggleComments,
 9632        window: &mut Window,
 9633        cx: &mut Context<Self>,
 9634    ) {
 9635        if self.read_only(cx) {
 9636            return;
 9637        }
 9638        let text_layout_details = &self.text_layout_details(window);
 9639        self.transact(window, cx, |this, window, cx| {
 9640            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9641            let mut edits = Vec::new();
 9642            let mut selection_edit_ranges = Vec::new();
 9643            let mut last_toggled_row = None;
 9644            let snapshot = this.buffer.read(cx).read(cx);
 9645            let empty_str: Arc<str> = Arc::default();
 9646            let mut suffixes_inserted = Vec::new();
 9647            let ignore_indent = action.ignore_indent;
 9648
 9649            fn comment_prefix_range(
 9650                snapshot: &MultiBufferSnapshot,
 9651                row: MultiBufferRow,
 9652                comment_prefix: &str,
 9653                comment_prefix_whitespace: &str,
 9654                ignore_indent: bool,
 9655            ) -> Range<Point> {
 9656                let indent_size = if ignore_indent {
 9657                    0
 9658                } else {
 9659                    snapshot.indent_size_for_line(row).len
 9660                };
 9661
 9662                let start = Point::new(row.0, indent_size);
 9663
 9664                let mut line_bytes = snapshot
 9665                    .bytes_in_range(start..snapshot.max_point())
 9666                    .flatten()
 9667                    .copied();
 9668
 9669                // If this line currently begins with the line comment prefix, then record
 9670                // the range containing the prefix.
 9671                if line_bytes
 9672                    .by_ref()
 9673                    .take(comment_prefix.len())
 9674                    .eq(comment_prefix.bytes())
 9675                {
 9676                    // Include any whitespace that matches the comment prefix.
 9677                    let matching_whitespace_len = line_bytes
 9678                        .zip(comment_prefix_whitespace.bytes())
 9679                        .take_while(|(a, b)| a == b)
 9680                        .count() as u32;
 9681                    let end = Point::new(
 9682                        start.row,
 9683                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9684                    );
 9685                    start..end
 9686                } else {
 9687                    start..start
 9688                }
 9689            }
 9690
 9691            fn comment_suffix_range(
 9692                snapshot: &MultiBufferSnapshot,
 9693                row: MultiBufferRow,
 9694                comment_suffix: &str,
 9695                comment_suffix_has_leading_space: bool,
 9696            ) -> Range<Point> {
 9697                let end = Point::new(row.0, snapshot.line_len(row));
 9698                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9699
 9700                let mut line_end_bytes = snapshot
 9701                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9702                    .flatten()
 9703                    .copied();
 9704
 9705                let leading_space_len = if suffix_start_column > 0
 9706                    && line_end_bytes.next() == Some(b' ')
 9707                    && comment_suffix_has_leading_space
 9708                {
 9709                    1
 9710                } else {
 9711                    0
 9712                };
 9713
 9714                // If this line currently begins with the line comment prefix, then record
 9715                // the range containing the prefix.
 9716                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9717                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9718                    start..end
 9719                } else {
 9720                    end..end
 9721                }
 9722            }
 9723
 9724            // TODO: Handle selections that cross excerpts
 9725            for selection in &mut selections {
 9726                let start_column = snapshot
 9727                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9728                    .len;
 9729                let language = if let Some(language) =
 9730                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9731                {
 9732                    language
 9733                } else {
 9734                    continue;
 9735                };
 9736
 9737                selection_edit_ranges.clear();
 9738
 9739                // If multiple selections contain a given row, avoid processing that
 9740                // row more than once.
 9741                let mut start_row = MultiBufferRow(selection.start.row);
 9742                if last_toggled_row == Some(start_row) {
 9743                    start_row = start_row.next_row();
 9744                }
 9745                let end_row =
 9746                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9747                        MultiBufferRow(selection.end.row - 1)
 9748                    } else {
 9749                        MultiBufferRow(selection.end.row)
 9750                    };
 9751                last_toggled_row = Some(end_row);
 9752
 9753                if start_row > end_row {
 9754                    continue;
 9755                }
 9756
 9757                // If the language has line comments, toggle those.
 9758                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9759
 9760                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9761                if ignore_indent {
 9762                    full_comment_prefixes = full_comment_prefixes
 9763                        .into_iter()
 9764                        .map(|s| Arc::from(s.trim_end()))
 9765                        .collect();
 9766                }
 9767
 9768                if !full_comment_prefixes.is_empty() {
 9769                    let first_prefix = full_comment_prefixes
 9770                        .first()
 9771                        .expect("prefixes is non-empty");
 9772                    let prefix_trimmed_lengths = full_comment_prefixes
 9773                        .iter()
 9774                        .map(|p| p.trim_end_matches(' ').len())
 9775                        .collect::<SmallVec<[usize; 4]>>();
 9776
 9777                    let mut all_selection_lines_are_comments = true;
 9778
 9779                    for row in start_row.0..=end_row.0 {
 9780                        let row = MultiBufferRow(row);
 9781                        if start_row < end_row && snapshot.is_line_blank(row) {
 9782                            continue;
 9783                        }
 9784
 9785                        let prefix_range = full_comment_prefixes
 9786                            .iter()
 9787                            .zip(prefix_trimmed_lengths.iter().copied())
 9788                            .map(|(prefix, trimmed_prefix_len)| {
 9789                                comment_prefix_range(
 9790                                    snapshot.deref(),
 9791                                    row,
 9792                                    &prefix[..trimmed_prefix_len],
 9793                                    &prefix[trimmed_prefix_len..],
 9794                                    ignore_indent,
 9795                                )
 9796                            })
 9797                            .max_by_key(|range| range.end.column - range.start.column)
 9798                            .expect("prefixes is non-empty");
 9799
 9800                        if prefix_range.is_empty() {
 9801                            all_selection_lines_are_comments = false;
 9802                        }
 9803
 9804                        selection_edit_ranges.push(prefix_range);
 9805                    }
 9806
 9807                    if all_selection_lines_are_comments {
 9808                        edits.extend(
 9809                            selection_edit_ranges
 9810                                .iter()
 9811                                .cloned()
 9812                                .map(|range| (range, empty_str.clone())),
 9813                        );
 9814                    } else {
 9815                        let min_column = selection_edit_ranges
 9816                            .iter()
 9817                            .map(|range| range.start.column)
 9818                            .min()
 9819                            .unwrap_or(0);
 9820                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9821                            let position = Point::new(range.start.row, min_column);
 9822                            (position..position, first_prefix.clone())
 9823                        }));
 9824                    }
 9825                } else if let Some((full_comment_prefix, comment_suffix)) =
 9826                    language.block_comment_delimiters()
 9827                {
 9828                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9829                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9830                    let prefix_range = comment_prefix_range(
 9831                        snapshot.deref(),
 9832                        start_row,
 9833                        comment_prefix,
 9834                        comment_prefix_whitespace,
 9835                        ignore_indent,
 9836                    );
 9837                    let suffix_range = comment_suffix_range(
 9838                        snapshot.deref(),
 9839                        end_row,
 9840                        comment_suffix.trim_start_matches(' '),
 9841                        comment_suffix.starts_with(' '),
 9842                    );
 9843
 9844                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9845                        edits.push((
 9846                            prefix_range.start..prefix_range.start,
 9847                            full_comment_prefix.clone(),
 9848                        ));
 9849                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9850                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9851                    } else {
 9852                        edits.push((prefix_range, empty_str.clone()));
 9853                        edits.push((suffix_range, empty_str.clone()));
 9854                    }
 9855                } else {
 9856                    continue;
 9857                }
 9858            }
 9859
 9860            drop(snapshot);
 9861            this.buffer.update(cx, |buffer, cx| {
 9862                buffer.edit(edits, None, cx);
 9863            });
 9864
 9865            // Adjust selections so that they end before any comment suffixes that
 9866            // were inserted.
 9867            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9868            let mut selections = this.selections.all::<Point>(cx);
 9869            let snapshot = this.buffer.read(cx).read(cx);
 9870            for selection in &mut selections {
 9871                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9872                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9873                        Ordering::Less => {
 9874                            suffixes_inserted.next();
 9875                            continue;
 9876                        }
 9877                        Ordering::Greater => break,
 9878                        Ordering::Equal => {
 9879                            if selection.end.column == snapshot.line_len(row) {
 9880                                if selection.is_empty() {
 9881                                    selection.start.column -= suffix_len as u32;
 9882                                }
 9883                                selection.end.column -= suffix_len as u32;
 9884                            }
 9885                            break;
 9886                        }
 9887                    }
 9888                }
 9889            }
 9890
 9891            drop(snapshot);
 9892            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9893                s.select(selections)
 9894            });
 9895
 9896            let selections = this.selections.all::<Point>(cx);
 9897            let selections_on_single_row = selections.windows(2).all(|selections| {
 9898                selections[0].start.row == selections[1].start.row
 9899                    && selections[0].end.row == selections[1].end.row
 9900                    && selections[0].start.row == selections[0].end.row
 9901            });
 9902            let selections_selecting = selections
 9903                .iter()
 9904                .any(|selection| selection.start != selection.end);
 9905            let advance_downwards = action.advance_downwards
 9906                && selections_on_single_row
 9907                && !selections_selecting
 9908                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9909
 9910            if advance_downwards {
 9911                let snapshot = this.buffer.read(cx).snapshot(cx);
 9912
 9913                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9914                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9915                        let mut point = display_point.to_point(display_snapshot);
 9916                        point.row += 1;
 9917                        point = snapshot.clip_point(point, Bias::Left);
 9918                        let display_point = point.to_display_point(display_snapshot);
 9919                        let goal = SelectionGoal::HorizontalPosition(
 9920                            display_snapshot
 9921                                .x_for_display_point(display_point, text_layout_details)
 9922                                .into(),
 9923                        );
 9924                        (display_point, goal)
 9925                    })
 9926                });
 9927            }
 9928        });
 9929    }
 9930
 9931    pub fn select_enclosing_symbol(
 9932        &mut self,
 9933        _: &SelectEnclosingSymbol,
 9934        window: &mut Window,
 9935        cx: &mut Context<Self>,
 9936    ) {
 9937        let buffer = self.buffer.read(cx).snapshot(cx);
 9938        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9939
 9940        fn update_selection(
 9941            selection: &Selection<usize>,
 9942            buffer_snap: &MultiBufferSnapshot,
 9943        ) -> Option<Selection<usize>> {
 9944            let cursor = selection.head();
 9945            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9946            for symbol in symbols.iter().rev() {
 9947                let start = symbol.range.start.to_offset(buffer_snap);
 9948                let end = symbol.range.end.to_offset(buffer_snap);
 9949                let new_range = start..end;
 9950                if start < selection.start || end > selection.end {
 9951                    return Some(Selection {
 9952                        id: selection.id,
 9953                        start: new_range.start,
 9954                        end: new_range.end,
 9955                        goal: SelectionGoal::None,
 9956                        reversed: selection.reversed,
 9957                    });
 9958                }
 9959            }
 9960            None
 9961        }
 9962
 9963        let mut selected_larger_symbol = false;
 9964        let new_selections = old_selections
 9965            .iter()
 9966            .map(|selection| match update_selection(selection, &buffer) {
 9967                Some(new_selection) => {
 9968                    if new_selection.range() != selection.range() {
 9969                        selected_larger_symbol = true;
 9970                    }
 9971                    new_selection
 9972                }
 9973                None => selection.clone(),
 9974            })
 9975            .collect::<Vec<_>>();
 9976
 9977        if selected_larger_symbol {
 9978            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9979                s.select(new_selections);
 9980            });
 9981        }
 9982    }
 9983
 9984    pub fn select_larger_syntax_node(
 9985        &mut self,
 9986        _: &SelectLargerSyntaxNode,
 9987        window: &mut Window,
 9988        cx: &mut Context<Self>,
 9989    ) {
 9990        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9991        let buffer = self.buffer.read(cx).snapshot(cx);
 9992        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9993
 9994        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9995        let mut selected_larger_node = false;
 9996        let new_selections = old_selections
 9997            .iter()
 9998            .map(|selection| {
 9999                let old_range = selection.start..selection.end;
10000                let mut new_range = old_range.clone();
10001                let mut new_node = None;
10002                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10003                {
10004                    new_node = Some(node);
10005                    new_range = containing_range;
10006                    if !display_map.intersects_fold(new_range.start)
10007                        && !display_map.intersects_fold(new_range.end)
10008                    {
10009                        break;
10010                    }
10011                }
10012
10013                if let Some(node) = new_node {
10014                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10015                    // nodes. Parent and grandparent are also logged because this operation will not
10016                    // visit nodes that have the same range as their parent.
10017                    log::info!("Node: {node:?}");
10018                    let parent = node.parent();
10019                    log::info!("Parent: {parent:?}");
10020                    let grandparent = parent.and_then(|x| x.parent());
10021                    log::info!("Grandparent: {grandparent:?}");
10022                }
10023
10024                selected_larger_node |= new_range != old_range;
10025                Selection {
10026                    id: selection.id,
10027                    start: new_range.start,
10028                    end: new_range.end,
10029                    goal: SelectionGoal::None,
10030                    reversed: selection.reversed,
10031                }
10032            })
10033            .collect::<Vec<_>>();
10034
10035        if selected_larger_node {
10036            stack.push(old_selections);
10037            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10038                s.select(new_selections);
10039            });
10040        }
10041        self.select_larger_syntax_node_stack = stack;
10042    }
10043
10044    pub fn select_smaller_syntax_node(
10045        &mut self,
10046        _: &SelectSmallerSyntaxNode,
10047        window: &mut Window,
10048        cx: &mut Context<Self>,
10049    ) {
10050        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10051        if let Some(selections) = stack.pop() {
10052            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10053                s.select(selections.to_vec());
10054            });
10055        }
10056        self.select_larger_syntax_node_stack = stack;
10057    }
10058
10059    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10060        if !EditorSettings::get_global(cx).gutter.runnables {
10061            self.clear_tasks();
10062            return Task::ready(());
10063        }
10064        let project = self.project.as_ref().map(Entity::downgrade);
10065        cx.spawn_in(window, |this, mut cx| async move {
10066            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10067            let Some(project) = project.and_then(|p| p.upgrade()) else {
10068                return;
10069            };
10070            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10071                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10072            }) else {
10073                return;
10074            };
10075
10076            let hide_runnables = project
10077                .update(&mut cx, |project, cx| {
10078                    // Do not display any test indicators in non-dev server remote projects.
10079                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10080                })
10081                .unwrap_or(true);
10082            if hide_runnables {
10083                return;
10084            }
10085            let new_rows =
10086                cx.background_executor()
10087                    .spawn({
10088                        let snapshot = display_snapshot.clone();
10089                        async move {
10090                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10091                        }
10092                    })
10093                    .await;
10094
10095            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10096            this.update(&mut cx, |this, _| {
10097                this.clear_tasks();
10098                for (key, value) in rows {
10099                    this.insert_tasks(key, value);
10100                }
10101            })
10102            .ok();
10103        })
10104    }
10105    fn fetch_runnable_ranges(
10106        snapshot: &DisplaySnapshot,
10107        range: Range<Anchor>,
10108    ) -> Vec<language::RunnableRange> {
10109        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10110    }
10111
10112    fn runnable_rows(
10113        project: Entity<Project>,
10114        snapshot: DisplaySnapshot,
10115        runnable_ranges: Vec<RunnableRange>,
10116        mut cx: AsyncWindowContext,
10117    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10118        runnable_ranges
10119            .into_iter()
10120            .filter_map(|mut runnable| {
10121                let tasks = cx
10122                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10123                    .ok()?;
10124                if tasks.is_empty() {
10125                    return None;
10126                }
10127
10128                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10129
10130                let row = snapshot
10131                    .buffer_snapshot
10132                    .buffer_line_for_row(MultiBufferRow(point.row))?
10133                    .1
10134                    .start
10135                    .row;
10136
10137                let context_range =
10138                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10139                Some((
10140                    (runnable.buffer_id, row),
10141                    RunnableTasks {
10142                        templates: tasks,
10143                        offset: MultiBufferOffset(runnable.run_range.start),
10144                        context_range,
10145                        column: point.column,
10146                        extra_variables: runnable.extra_captures,
10147                    },
10148                ))
10149            })
10150            .collect()
10151    }
10152
10153    fn templates_with_tags(
10154        project: &Entity<Project>,
10155        runnable: &mut Runnable,
10156        cx: &mut App,
10157    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10158        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10159            let (worktree_id, file) = project
10160                .buffer_for_id(runnable.buffer, cx)
10161                .and_then(|buffer| buffer.read(cx).file())
10162                .map(|file| (file.worktree_id(cx), file.clone()))
10163                .unzip();
10164
10165            (
10166                project.task_store().read(cx).task_inventory().cloned(),
10167                worktree_id,
10168                file,
10169            )
10170        });
10171
10172        let tags = mem::take(&mut runnable.tags);
10173        let mut tags: Vec<_> = tags
10174            .into_iter()
10175            .flat_map(|tag| {
10176                let tag = tag.0.clone();
10177                inventory
10178                    .as_ref()
10179                    .into_iter()
10180                    .flat_map(|inventory| {
10181                        inventory.read(cx).list_tasks(
10182                            file.clone(),
10183                            Some(runnable.language.clone()),
10184                            worktree_id,
10185                            cx,
10186                        )
10187                    })
10188                    .filter(move |(_, template)| {
10189                        template.tags.iter().any(|source_tag| source_tag == &tag)
10190                    })
10191            })
10192            .sorted_by_key(|(kind, _)| kind.to_owned())
10193            .collect();
10194        if let Some((leading_tag_source, _)) = tags.first() {
10195            // Strongest source wins; if we have worktree tag binding, prefer that to
10196            // global and language bindings;
10197            // if we have a global binding, prefer that to language binding.
10198            let first_mismatch = tags
10199                .iter()
10200                .position(|(tag_source, _)| tag_source != leading_tag_source);
10201            if let Some(index) = first_mismatch {
10202                tags.truncate(index);
10203            }
10204        }
10205
10206        tags
10207    }
10208
10209    pub fn move_to_enclosing_bracket(
10210        &mut self,
10211        _: &MoveToEnclosingBracket,
10212        window: &mut Window,
10213        cx: &mut Context<Self>,
10214    ) {
10215        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10216            s.move_offsets_with(|snapshot, selection| {
10217                let Some(enclosing_bracket_ranges) =
10218                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10219                else {
10220                    return;
10221                };
10222
10223                let mut best_length = usize::MAX;
10224                let mut best_inside = false;
10225                let mut best_in_bracket_range = false;
10226                let mut best_destination = None;
10227                for (open, close) in enclosing_bracket_ranges {
10228                    let close = close.to_inclusive();
10229                    let length = close.end() - open.start;
10230                    let inside = selection.start >= open.end && selection.end <= *close.start();
10231                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10232                        || close.contains(&selection.head());
10233
10234                    // If best is next to a bracket and current isn't, skip
10235                    if !in_bracket_range && best_in_bracket_range {
10236                        continue;
10237                    }
10238
10239                    // Prefer smaller lengths unless best is inside and current isn't
10240                    if length > best_length && (best_inside || !inside) {
10241                        continue;
10242                    }
10243
10244                    best_length = length;
10245                    best_inside = inside;
10246                    best_in_bracket_range = in_bracket_range;
10247                    best_destination = Some(
10248                        if close.contains(&selection.start) && close.contains(&selection.end) {
10249                            if inside {
10250                                open.end
10251                            } else {
10252                                open.start
10253                            }
10254                        } else if inside {
10255                            *close.start()
10256                        } else {
10257                            *close.end()
10258                        },
10259                    );
10260                }
10261
10262                if let Some(destination) = best_destination {
10263                    selection.collapse_to(destination, SelectionGoal::None);
10264                }
10265            })
10266        });
10267    }
10268
10269    pub fn undo_selection(
10270        &mut self,
10271        _: &UndoSelection,
10272        window: &mut Window,
10273        cx: &mut Context<Self>,
10274    ) {
10275        self.end_selection(window, cx);
10276        self.selection_history.mode = SelectionHistoryMode::Undoing;
10277        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10278            self.change_selections(None, window, cx, |s| {
10279                s.select_anchors(entry.selections.to_vec())
10280            });
10281            self.select_next_state = entry.select_next_state;
10282            self.select_prev_state = entry.select_prev_state;
10283            self.add_selections_state = entry.add_selections_state;
10284            self.request_autoscroll(Autoscroll::newest(), cx);
10285        }
10286        self.selection_history.mode = SelectionHistoryMode::Normal;
10287    }
10288
10289    pub fn redo_selection(
10290        &mut self,
10291        _: &RedoSelection,
10292        window: &mut Window,
10293        cx: &mut Context<Self>,
10294    ) {
10295        self.end_selection(window, cx);
10296        self.selection_history.mode = SelectionHistoryMode::Redoing;
10297        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10298            self.change_selections(None, window, cx, |s| {
10299                s.select_anchors(entry.selections.to_vec())
10300            });
10301            self.select_next_state = entry.select_next_state;
10302            self.select_prev_state = entry.select_prev_state;
10303            self.add_selections_state = entry.add_selections_state;
10304            self.request_autoscroll(Autoscroll::newest(), cx);
10305        }
10306        self.selection_history.mode = SelectionHistoryMode::Normal;
10307    }
10308
10309    pub fn expand_excerpts(
10310        &mut self,
10311        action: &ExpandExcerpts,
10312        _: &mut Window,
10313        cx: &mut Context<Self>,
10314    ) {
10315        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10316    }
10317
10318    pub fn expand_excerpts_down(
10319        &mut self,
10320        action: &ExpandExcerptsDown,
10321        _: &mut Window,
10322        cx: &mut Context<Self>,
10323    ) {
10324        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10325    }
10326
10327    pub fn expand_excerpts_up(
10328        &mut self,
10329        action: &ExpandExcerptsUp,
10330        _: &mut Window,
10331        cx: &mut Context<Self>,
10332    ) {
10333        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10334    }
10335
10336    pub fn expand_excerpts_for_direction(
10337        &mut self,
10338        lines: u32,
10339        direction: ExpandExcerptDirection,
10340
10341        cx: &mut Context<Self>,
10342    ) {
10343        let selections = self.selections.disjoint_anchors();
10344
10345        let lines = if lines == 0 {
10346            EditorSettings::get_global(cx).expand_excerpt_lines
10347        } else {
10348            lines
10349        };
10350
10351        self.buffer.update(cx, |buffer, cx| {
10352            let snapshot = buffer.snapshot(cx);
10353            let mut excerpt_ids = selections
10354                .iter()
10355                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10356                .collect::<Vec<_>>();
10357            excerpt_ids.sort();
10358            excerpt_ids.dedup();
10359            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10360        })
10361    }
10362
10363    pub fn expand_excerpt(
10364        &mut self,
10365        excerpt: ExcerptId,
10366        direction: ExpandExcerptDirection,
10367        cx: &mut Context<Self>,
10368    ) {
10369        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10370        self.buffer.update(cx, |buffer, cx| {
10371            buffer.expand_excerpts([excerpt], lines, direction, cx)
10372        })
10373    }
10374
10375    pub fn go_to_singleton_buffer_point(
10376        &mut self,
10377        point: Point,
10378        window: &mut Window,
10379        cx: &mut Context<Self>,
10380    ) {
10381        self.go_to_singleton_buffer_range(point..point, window, cx);
10382    }
10383
10384    pub fn go_to_singleton_buffer_range(
10385        &mut self,
10386        range: Range<Point>,
10387        window: &mut Window,
10388        cx: &mut Context<Self>,
10389    ) {
10390        let multibuffer = self.buffer().read(cx);
10391        let Some(buffer) = multibuffer.as_singleton() else {
10392            return;
10393        };
10394        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10395            return;
10396        };
10397        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10398            return;
10399        };
10400        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10401            s.select_anchor_ranges([start..end])
10402        });
10403    }
10404
10405    fn go_to_diagnostic(
10406        &mut self,
10407        _: &GoToDiagnostic,
10408        window: &mut Window,
10409        cx: &mut Context<Self>,
10410    ) {
10411        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10412    }
10413
10414    fn go_to_prev_diagnostic(
10415        &mut self,
10416        _: &GoToPrevDiagnostic,
10417        window: &mut Window,
10418        cx: &mut Context<Self>,
10419    ) {
10420        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10421    }
10422
10423    pub fn go_to_diagnostic_impl(
10424        &mut self,
10425        direction: Direction,
10426        window: &mut Window,
10427        cx: &mut Context<Self>,
10428    ) {
10429        let buffer = self.buffer.read(cx).snapshot(cx);
10430        let selection = self.selections.newest::<usize>(cx);
10431
10432        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10433        if direction == Direction::Next {
10434            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10435                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10436                    return;
10437                };
10438                self.activate_diagnostics(
10439                    buffer_id,
10440                    popover.local_diagnostic.diagnostic.group_id,
10441                    window,
10442                    cx,
10443                );
10444                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10445                    let primary_range_start = active_diagnostics.primary_range.start;
10446                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10447                        let mut new_selection = s.newest_anchor().clone();
10448                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10449                        s.select_anchors(vec![new_selection.clone()]);
10450                    });
10451                    self.refresh_inline_completion(false, true, window, cx);
10452                }
10453                return;
10454            }
10455        }
10456
10457        let active_group_id = self
10458            .active_diagnostics
10459            .as_ref()
10460            .map(|active_group| active_group.group_id);
10461        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10462            active_diagnostics
10463                .primary_range
10464                .to_offset(&buffer)
10465                .to_inclusive()
10466        });
10467        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10468            if active_primary_range.contains(&selection.head()) {
10469                *active_primary_range.start()
10470            } else {
10471                selection.head()
10472            }
10473        } else {
10474            selection.head()
10475        };
10476
10477        let snapshot = self.snapshot(window, cx);
10478        let primary_diagnostics_before = buffer
10479            .diagnostics_in_range::<usize>(0..search_start)
10480            .filter(|entry| entry.diagnostic.is_primary)
10481            .filter(|entry| entry.range.start != entry.range.end)
10482            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10483            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10484            .collect::<Vec<_>>();
10485        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10486            primary_diagnostics_before
10487                .iter()
10488                .position(|entry| entry.diagnostic.group_id == active_group_id)
10489        });
10490
10491        let primary_diagnostics_after = buffer
10492            .diagnostics_in_range::<usize>(search_start..buffer.len())
10493            .filter(|entry| entry.diagnostic.is_primary)
10494            .filter(|entry| entry.range.start != entry.range.end)
10495            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10496            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10497            .collect::<Vec<_>>();
10498        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10499            primary_diagnostics_after
10500                .iter()
10501                .enumerate()
10502                .rev()
10503                .find_map(|(i, entry)| {
10504                    if entry.diagnostic.group_id == active_group_id {
10505                        Some(i)
10506                    } else {
10507                        None
10508                    }
10509                })
10510        });
10511
10512        let next_primary_diagnostic = match direction {
10513            Direction::Prev => primary_diagnostics_before
10514                .iter()
10515                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10516                .rev()
10517                .next(),
10518            Direction::Next => primary_diagnostics_after
10519                .iter()
10520                .skip(
10521                    last_same_group_diagnostic_after
10522                        .map(|index| index + 1)
10523                        .unwrap_or(0),
10524                )
10525                .next(),
10526        };
10527
10528        // Cycle around to the start of the buffer, potentially moving back to the start of
10529        // the currently active diagnostic.
10530        let cycle_around = || match direction {
10531            Direction::Prev => primary_diagnostics_after
10532                .iter()
10533                .rev()
10534                .chain(primary_diagnostics_before.iter().rev())
10535                .next(),
10536            Direction::Next => primary_diagnostics_before
10537                .iter()
10538                .chain(primary_diagnostics_after.iter())
10539                .next(),
10540        };
10541
10542        if let Some((primary_range, group_id)) = next_primary_diagnostic
10543            .or_else(cycle_around)
10544            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10545        {
10546            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10547                return;
10548            };
10549            self.activate_diagnostics(buffer_id, group_id, window, cx);
10550            if self.active_diagnostics.is_some() {
10551                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10552                    s.select(vec![Selection {
10553                        id: selection.id,
10554                        start: primary_range.start,
10555                        end: primary_range.start,
10556                        reversed: false,
10557                        goal: SelectionGoal::None,
10558                    }]);
10559                });
10560                self.refresh_inline_completion(false, true, window, cx);
10561            }
10562        }
10563    }
10564
10565    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10566        let snapshot = self.snapshot(window, cx);
10567        let selection = self.selections.newest::<Point>(cx);
10568        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10569    }
10570
10571    fn go_to_hunk_after_position(
10572        &mut self,
10573        snapshot: &EditorSnapshot,
10574        position: Point,
10575        window: &mut Window,
10576        cx: &mut Context<Editor>,
10577    ) -> Option<MultiBufferDiffHunk> {
10578        let mut hunk = snapshot
10579            .buffer_snapshot
10580            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10581            .find(|hunk| hunk.row_range.start.0 > position.row);
10582        if hunk.is_none() {
10583            hunk = snapshot
10584                .buffer_snapshot
10585                .diff_hunks_in_range(Point::zero()..position)
10586                .find(|hunk| hunk.row_range.end.0 < position.row)
10587        }
10588        if let Some(hunk) = &hunk {
10589            let destination = Point::new(hunk.row_range.start.0, 0);
10590            self.unfold_ranges(&[destination..destination], false, false, cx);
10591            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10592                s.select_ranges(vec![destination..destination]);
10593            });
10594        }
10595
10596        hunk
10597    }
10598
10599    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10600        let snapshot = self.snapshot(window, cx);
10601        let selection = self.selections.newest::<Point>(cx);
10602        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10603    }
10604
10605    fn go_to_hunk_before_position(
10606        &mut self,
10607        snapshot: &EditorSnapshot,
10608        position: Point,
10609        window: &mut Window,
10610        cx: &mut Context<Editor>,
10611    ) -> Option<MultiBufferDiffHunk> {
10612        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10613        if hunk.is_none() {
10614            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10615        }
10616        if let Some(hunk) = &hunk {
10617            let destination = Point::new(hunk.row_range.start.0, 0);
10618            self.unfold_ranges(&[destination..destination], false, false, cx);
10619            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10620                s.select_ranges(vec![destination..destination]);
10621            });
10622        }
10623
10624        hunk
10625    }
10626
10627    pub fn go_to_definition(
10628        &mut self,
10629        _: &GoToDefinition,
10630        window: &mut Window,
10631        cx: &mut Context<Self>,
10632    ) -> Task<Result<Navigated>> {
10633        let definition =
10634            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10635        cx.spawn_in(window, |editor, mut cx| async move {
10636            if definition.await? == Navigated::Yes {
10637                return Ok(Navigated::Yes);
10638            }
10639            match editor.update_in(&mut cx, |editor, window, cx| {
10640                editor.find_all_references(&FindAllReferences, window, cx)
10641            })? {
10642                Some(references) => references.await,
10643                None => Ok(Navigated::No),
10644            }
10645        })
10646    }
10647
10648    pub fn go_to_declaration(
10649        &mut self,
10650        _: &GoToDeclaration,
10651        window: &mut Window,
10652        cx: &mut Context<Self>,
10653    ) -> Task<Result<Navigated>> {
10654        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10655    }
10656
10657    pub fn go_to_declaration_split(
10658        &mut self,
10659        _: &GoToDeclaration,
10660        window: &mut Window,
10661        cx: &mut Context<Self>,
10662    ) -> Task<Result<Navigated>> {
10663        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10664    }
10665
10666    pub fn go_to_implementation(
10667        &mut self,
10668        _: &GoToImplementation,
10669        window: &mut Window,
10670        cx: &mut Context<Self>,
10671    ) -> Task<Result<Navigated>> {
10672        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10673    }
10674
10675    pub fn go_to_implementation_split(
10676        &mut self,
10677        _: &GoToImplementationSplit,
10678        window: &mut Window,
10679        cx: &mut Context<Self>,
10680    ) -> Task<Result<Navigated>> {
10681        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10682    }
10683
10684    pub fn go_to_type_definition(
10685        &mut self,
10686        _: &GoToTypeDefinition,
10687        window: &mut Window,
10688        cx: &mut Context<Self>,
10689    ) -> Task<Result<Navigated>> {
10690        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10691    }
10692
10693    pub fn go_to_definition_split(
10694        &mut self,
10695        _: &GoToDefinitionSplit,
10696        window: &mut Window,
10697        cx: &mut Context<Self>,
10698    ) -> Task<Result<Navigated>> {
10699        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10700    }
10701
10702    pub fn go_to_type_definition_split(
10703        &mut self,
10704        _: &GoToTypeDefinitionSplit,
10705        window: &mut Window,
10706        cx: &mut Context<Self>,
10707    ) -> Task<Result<Navigated>> {
10708        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10709    }
10710
10711    fn go_to_definition_of_kind(
10712        &mut self,
10713        kind: GotoDefinitionKind,
10714        split: bool,
10715        window: &mut Window,
10716        cx: &mut Context<Self>,
10717    ) -> Task<Result<Navigated>> {
10718        let Some(provider) = self.semantics_provider.clone() else {
10719            return Task::ready(Ok(Navigated::No));
10720        };
10721        let head = self.selections.newest::<usize>(cx).head();
10722        let buffer = self.buffer.read(cx);
10723        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10724            text_anchor
10725        } else {
10726            return Task::ready(Ok(Navigated::No));
10727        };
10728
10729        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10730            return Task::ready(Ok(Navigated::No));
10731        };
10732
10733        cx.spawn_in(window, |editor, mut cx| async move {
10734            let definitions = definitions.await?;
10735            let navigated = editor
10736                .update_in(&mut cx, |editor, window, cx| {
10737                    editor.navigate_to_hover_links(
10738                        Some(kind),
10739                        definitions
10740                            .into_iter()
10741                            .filter(|location| {
10742                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10743                            })
10744                            .map(HoverLink::Text)
10745                            .collect::<Vec<_>>(),
10746                        split,
10747                        window,
10748                        cx,
10749                    )
10750                })?
10751                .await?;
10752            anyhow::Ok(navigated)
10753        })
10754    }
10755
10756    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10757        let selection = self.selections.newest_anchor();
10758        let head = selection.head();
10759        let tail = selection.tail();
10760
10761        let Some((buffer, start_position)) =
10762            self.buffer.read(cx).text_anchor_for_position(head, cx)
10763        else {
10764            return;
10765        };
10766
10767        let end_position = if head != tail {
10768            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10769                return;
10770            };
10771            Some(pos)
10772        } else {
10773            None
10774        };
10775
10776        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10777            let url = if let Some(end_pos) = end_position {
10778                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10779            } else {
10780                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10781            };
10782
10783            if let Some(url) = url {
10784                editor.update(&mut cx, |_, cx| {
10785                    cx.open_url(&url);
10786                })
10787            } else {
10788                Ok(())
10789            }
10790        });
10791
10792        url_finder.detach();
10793    }
10794
10795    pub fn open_selected_filename(
10796        &mut self,
10797        _: &OpenSelectedFilename,
10798        window: &mut Window,
10799        cx: &mut Context<Self>,
10800    ) {
10801        let Some(workspace) = self.workspace() else {
10802            return;
10803        };
10804
10805        let position = self.selections.newest_anchor().head();
10806
10807        let Some((buffer, buffer_position)) =
10808            self.buffer.read(cx).text_anchor_for_position(position, cx)
10809        else {
10810            return;
10811        };
10812
10813        let project = self.project.clone();
10814
10815        cx.spawn_in(window, |_, mut cx| async move {
10816            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10817
10818            if let Some((_, path)) = result {
10819                workspace
10820                    .update_in(&mut cx, |workspace, window, cx| {
10821                        workspace.open_resolved_path(path, window, cx)
10822                    })?
10823                    .await?;
10824            }
10825            anyhow::Ok(())
10826        })
10827        .detach();
10828    }
10829
10830    pub(crate) fn navigate_to_hover_links(
10831        &mut self,
10832        kind: Option<GotoDefinitionKind>,
10833        mut definitions: Vec<HoverLink>,
10834        split: bool,
10835        window: &mut Window,
10836        cx: &mut Context<Editor>,
10837    ) -> Task<Result<Navigated>> {
10838        // If there is one definition, just open it directly
10839        if definitions.len() == 1 {
10840            let definition = definitions.pop().unwrap();
10841
10842            enum TargetTaskResult {
10843                Location(Option<Location>),
10844                AlreadyNavigated,
10845            }
10846
10847            let target_task = match definition {
10848                HoverLink::Text(link) => {
10849                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10850                }
10851                HoverLink::InlayHint(lsp_location, server_id) => {
10852                    let computation =
10853                        self.compute_target_location(lsp_location, server_id, window, cx);
10854                    cx.background_executor().spawn(async move {
10855                        let location = computation.await?;
10856                        Ok(TargetTaskResult::Location(location))
10857                    })
10858                }
10859                HoverLink::Url(url) => {
10860                    cx.open_url(&url);
10861                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10862                }
10863                HoverLink::File(path) => {
10864                    if let Some(workspace) = self.workspace() {
10865                        cx.spawn_in(window, |_, mut cx| async move {
10866                            workspace
10867                                .update_in(&mut cx, |workspace, window, cx| {
10868                                    workspace.open_resolved_path(path, window, cx)
10869                                })?
10870                                .await
10871                                .map(|_| TargetTaskResult::AlreadyNavigated)
10872                        })
10873                    } else {
10874                        Task::ready(Ok(TargetTaskResult::Location(None)))
10875                    }
10876                }
10877            };
10878            cx.spawn_in(window, |editor, mut cx| async move {
10879                let target = match target_task.await.context("target resolution task")? {
10880                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10881                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10882                    TargetTaskResult::Location(Some(target)) => target,
10883                };
10884
10885                editor.update_in(&mut cx, |editor, window, cx| {
10886                    let Some(workspace) = editor.workspace() else {
10887                        return Navigated::No;
10888                    };
10889                    let pane = workspace.read(cx).active_pane().clone();
10890
10891                    let range = target.range.to_point(target.buffer.read(cx));
10892                    let range = editor.range_for_match(&range);
10893                    let range = collapse_multiline_range(range);
10894
10895                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10896                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10897                    } else {
10898                        window.defer(cx, move |window, cx| {
10899                            let target_editor: Entity<Self> =
10900                                workspace.update(cx, |workspace, cx| {
10901                                    let pane = if split {
10902                                        workspace.adjacent_pane(window, cx)
10903                                    } else {
10904                                        workspace.active_pane().clone()
10905                                    };
10906
10907                                    workspace.open_project_item(
10908                                        pane,
10909                                        target.buffer.clone(),
10910                                        true,
10911                                        true,
10912                                        window,
10913                                        cx,
10914                                    )
10915                                });
10916                            target_editor.update(cx, |target_editor, cx| {
10917                                // When selecting a definition in a different buffer, disable the nav history
10918                                // to avoid creating a history entry at the previous cursor location.
10919                                pane.update(cx, |pane, _| pane.disable_history());
10920                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10921                                pane.update(cx, |pane, _| pane.enable_history());
10922                            });
10923                        });
10924                    }
10925                    Navigated::Yes
10926                })
10927            })
10928        } else if !definitions.is_empty() {
10929            cx.spawn_in(window, |editor, mut cx| async move {
10930                let (title, location_tasks, workspace) = editor
10931                    .update_in(&mut cx, |editor, window, cx| {
10932                        let tab_kind = match kind {
10933                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10934                            _ => "Definitions",
10935                        };
10936                        let title = definitions
10937                            .iter()
10938                            .find_map(|definition| match definition {
10939                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10940                                    let buffer = origin.buffer.read(cx);
10941                                    format!(
10942                                        "{} for {}",
10943                                        tab_kind,
10944                                        buffer
10945                                            .text_for_range(origin.range.clone())
10946                                            .collect::<String>()
10947                                    )
10948                                }),
10949                                HoverLink::InlayHint(_, _) => None,
10950                                HoverLink::Url(_) => None,
10951                                HoverLink::File(_) => None,
10952                            })
10953                            .unwrap_or(tab_kind.to_string());
10954                        let location_tasks = definitions
10955                            .into_iter()
10956                            .map(|definition| match definition {
10957                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10958                                HoverLink::InlayHint(lsp_location, server_id) => editor
10959                                    .compute_target_location(lsp_location, server_id, window, cx),
10960                                HoverLink::Url(_) => Task::ready(Ok(None)),
10961                                HoverLink::File(_) => Task::ready(Ok(None)),
10962                            })
10963                            .collect::<Vec<_>>();
10964                        (title, location_tasks, editor.workspace().clone())
10965                    })
10966                    .context("location tasks preparation")?;
10967
10968                let locations = future::join_all(location_tasks)
10969                    .await
10970                    .into_iter()
10971                    .filter_map(|location| location.transpose())
10972                    .collect::<Result<_>>()
10973                    .context("location tasks")?;
10974
10975                let Some(workspace) = workspace else {
10976                    return Ok(Navigated::No);
10977                };
10978                let opened = workspace
10979                    .update_in(&mut cx, |workspace, window, cx| {
10980                        Self::open_locations_in_multibuffer(
10981                            workspace,
10982                            locations,
10983                            title,
10984                            split,
10985                            MultibufferSelectionMode::First,
10986                            window,
10987                            cx,
10988                        )
10989                    })
10990                    .ok();
10991
10992                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10993            })
10994        } else {
10995            Task::ready(Ok(Navigated::No))
10996        }
10997    }
10998
10999    fn compute_target_location(
11000        &self,
11001        lsp_location: lsp::Location,
11002        server_id: LanguageServerId,
11003        window: &mut Window,
11004        cx: &mut Context<Self>,
11005    ) -> Task<anyhow::Result<Option<Location>>> {
11006        let Some(project) = self.project.clone() else {
11007            return Task::ready(Ok(None));
11008        };
11009
11010        cx.spawn_in(window, move |editor, mut cx| async move {
11011            let location_task = editor.update(&mut cx, |_, cx| {
11012                project.update(cx, |project, cx| {
11013                    let language_server_name = project
11014                        .language_server_statuses(cx)
11015                        .find(|(id, _)| server_id == *id)
11016                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11017                    language_server_name.map(|language_server_name| {
11018                        project.open_local_buffer_via_lsp(
11019                            lsp_location.uri.clone(),
11020                            server_id,
11021                            language_server_name,
11022                            cx,
11023                        )
11024                    })
11025                })
11026            })?;
11027            let location = match location_task {
11028                Some(task) => Some({
11029                    let target_buffer_handle = task.await.context("open local buffer")?;
11030                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11031                        let target_start = target_buffer
11032                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11033                        let target_end = target_buffer
11034                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11035                        target_buffer.anchor_after(target_start)
11036                            ..target_buffer.anchor_before(target_end)
11037                    })?;
11038                    Location {
11039                        buffer: target_buffer_handle,
11040                        range,
11041                    }
11042                }),
11043                None => None,
11044            };
11045            Ok(location)
11046        })
11047    }
11048
11049    pub fn find_all_references(
11050        &mut self,
11051        _: &FindAllReferences,
11052        window: &mut Window,
11053        cx: &mut Context<Self>,
11054    ) -> Option<Task<Result<Navigated>>> {
11055        let selection = self.selections.newest::<usize>(cx);
11056        let multi_buffer = self.buffer.read(cx);
11057        let head = selection.head();
11058
11059        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11060        let head_anchor = multi_buffer_snapshot.anchor_at(
11061            head,
11062            if head < selection.tail() {
11063                Bias::Right
11064            } else {
11065                Bias::Left
11066            },
11067        );
11068
11069        match self
11070            .find_all_references_task_sources
11071            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11072        {
11073            Ok(_) => {
11074                log::info!(
11075                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11076                );
11077                return None;
11078            }
11079            Err(i) => {
11080                self.find_all_references_task_sources.insert(i, head_anchor);
11081            }
11082        }
11083
11084        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11085        let workspace = self.workspace()?;
11086        let project = workspace.read(cx).project().clone();
11087        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11088        Some(cx.spawn_in(window, |editor, mut cx| async move {
11089            let _cleanup = defer({
11090                let mut cx = cx.clone();
11091                move || {
11092                    let _ = editor.update(&mut cx, |editor, _| {
11093                        if let Ok(i) =
11094                            editor
11095                                .find_all_references_task_sources
11096                                .binary_search_by(|anchor| {
11097                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11098                                })
11099                        {
11100                            editor.find_all_references_task_sources.remove(i);
11101                        }
11102                    });
11103                }
11104            });
11105
11106            let locations = references.await?;
11107            if locations.is_empty() {
11108                return anyhow::Ok(Navigated::No);
11109            }
11110
11111            workspace.update_in(&mut cx, |workspace, window, cx| {
11112                let title = locations
11113                    .first()
11114                    .as_ref()
11115                    .map(|location| {
11116                        let buffer = location.buffer.read(cx);
11117                        format!(
11118                            "References to `{}`",
11119                            buffer
11120                                .text_for_range(location.range.clone())
11121                                .collect::<String>()
11122                        )
11123                    })
11124                    .unwrap();
11125                Self::open_locations_in_multibuffer(
11126                    workspace,
11127                    locations,
11128                    title,
11129                    false,
11130                    MultibufferSelectionMode::First,
11131                    window,
11132                    cx,
11133                );
11134                Navigated::Yes
11135            })
11136        }))
11137    }
11138
11139    /// Opens a multibuffer with the given project locations in it
11140    pub fn open_locations_in_multibuffer(
11141        workspace: &mut Workspace,
11142        mut locations: Vec<Location>,
11143        title: String,
11144        split: bool,
11145        multibuffer_selection_mode: MultibufferSelectionMode,
11146        window: &mut Window,
11147        cx: &mut Context<Workspace>,
11148    ) {
11149        // If there are multiple definitions, open them in a multibuffer
11150        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11151        let mut locations = locations.into_iter().peekable();
11152        let mut ranges = Vec::new();
11153        let capability = workspace.project().read(cx).capability();
11154
11155        let excerpt_buffer = cx.new(|cx| {
11156            let mut multibuffer = MultiBuffer::new(capability);
11157            while let Some(location) = locations.next() {
11158                let buffer = location.buffer.read(cx);
11159                let mut ranges_for_buffer = Vec::new();
11160                let range = location.range.to_offset(buffer);
11161                ranges_for_buffer.push(range.clone());
11162
11163                while let Some(next_location) = locations.peek() {
11164                    if next_location.buffer == location.buffer {
11165                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11166                        locations.next();
11167                    } else {
11168                        break;
11169                    }
11170                }
11171
11172                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11173                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11174                    location.buffer.clone(),
11175                    ranges_for_buffer,
11176                    DEFAULT_MULTIBUFFER_CONTEXT,
11177                    cx,
11178                ))
11179            }
11180
11181            multibuffer.with_title(title)
11182        });
11183
11184        let editor = cx.new(|cx| {
11185            Editor::for_multibuffer(
11186                excerpt_buffer,
11187                Some(workspace.project().clone()),
11188                true,
11189                window,
11190                cx,
11191            )
11192        });
11193        editor.update(cx, |editor, cx| {
11194            match multibuffer_selection_mode {
11195                MultibufferSelectionMode::First => {
11196                    if let Some(first_range) = ranges.first() {
11197                        editor.change_selections(None, window, cx, |selections| {
11198                            selections.clear_disjoint();
11199                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11200                        });
11201                    }
11202                    editor.highlight_background::<Self>(
11203                        &ranges,
11204                        |theme| theme.editor_highlighted_line_background,
11205                        cx,
11206                    );
11207                }
11208                MultibufferSelectionMode::All => {
11209                    editor.change_selections(None, window, cx, |selections| {
11210                        selections.clear_disjoint();
11211                        selections.select_anchor_ranges(ranges);
11212                    });
11213                }
11214            }
11215            editor.register_buffers_with_language_servers(cx);
11216        });
11217
11218        let item = Box::new(editor);
11219        let item_id = item.item_id();
11220
11221        if split {
11222            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11223        } else {
11224            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11225                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11226                    pane.close_current_preview_item(window, cx)
11227                } else {
11228                    None
11229                }
11230            });
11231            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11232        }
11233        workspace.active_pane().update(cx, |pane, cx| {
11234            pane.set_preview_item_id(Some(item_id), cx);
11235        });
11236    }
11237
11238    pub fn rename(
11239        &mut self,
11240        _: &Rename,
11241        window: &mut Window,
11242        cx: &mut Context<Self>,
11243    ) -> Option<Task<Result<()>>> {
11244        use language::ToOffset as _;
11245
11246        let provider = self.semantics_provider.clone()?;
11247        let selection = self.selections.newest_anchor().clone();
11248        let (cursor_buffer, cursor_buffer_position) = self
11249            .buffer
11250            .read(cx)
11251            .text_anchor_for_position(selection.head(), cx)?;
11252        let (tail_buffer, cursor_buffer_position_end) = self
11253            .buffer
11254            .read(cx)
11255            .text_anchor_for_position(selection.tail(), cx)?;
11256        if tail_buffer != cursor_buffer {
11257            return None;
11258        }
11259
11260        let snapshot = cursor_buffer.read(cx).snapshot();
11261        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11262        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11263        let prepare_rename = provider
11264            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11265            .unwrap_or_else(|| Task::ready(Ok(None)));
11266        drop(snapshot);
11267
11268        Some(cx.spawn_in(window, |this, mut cx| async move {
11269            let rename_range = if let Some(range) = prepare_rename.await? {
11270                Some(range)
11271            } else {
11272                this.update(&mut cx, |this, cx| {
11273                    let buffer = this.buffer.read(cx).snapshot(cx);
11274                    let mut buffer_highlights = this
11275                        .document_highlights_for_position(selection.head(), &buffer)
11276                        .filter(|highlight| {
11277                            highlight.start.excerpt_id == selection.head().excerpt_id
11278                                && highlight.end.excerpt_id == selection.head().excerpt_id
11279                        });
11280                    buffer_highlights
11281                        .next()
11282                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11283                })?
11284            };
11285            if let Some(rename_range) = rename_range {
11286                this.update_in(&mut cx, |this, window, cx| {
11287                    let snapshot = cursor_buffer.read(cx).snapshot();
11288                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11289                    let cursor_offset_in_rename_range =
11290                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11291                    let cursor_offset_in_rename_range_end =
11292                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11293
11294                    this.take_rename(false, window, cx);
11295                    let buffer = this.buffer.read(cx).read(cx);
11296                    let cursor_offset = selection.head().to_offset(&buffer);
11297                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11298                    let rename_end = rename_start + rename_buffer_range.len();
11299                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11300                    let mut old_highlight_id = None;
11301                    let old_name: Arc<str> = buffer
11302                        .chunks(rename_start..rename_end, true)
11303                        .map(|chunk| {
11304                            if old_highlight_id.is_none() {
11305                                old_highlight_id = chunk.syntax_highlight_id;
11306                            }
11307                            chunk.text
11308                        })
11309                        .collect::<String>()
11310                        .into();
11311
11312                    drop(buffer);
11313
11314                    // Position the selection in the rename editor so that it matches the current selection.
11315                    this.show_local_selections = false;
11316                    let rename_editor = cx.new(|cx| {
11317                        let mut editor = Editor::single_line(window, cx);
11318                        editor.buffer.update(cx, |buffer, cx| {
11319                            buffer.edit([(0..0, old_name.clone())], None, cx)
11320                        });
11321                        let rename_selection_range = match cursor_offset_in_rename_range
11322                            .cmp(&cursor_offset_in_rename_range_end)
11323                        {
11324                            Ordering::Equal => {
11325                                editor.select_all(&SelectAll, window, cx);
11326                                return editor;
11327                            }
11328                            Ordering::Less => {
11329                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11330                            }
11331                            Ordering::Greater => {
11332                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11333                            }
11334                        };
11335                        if rename_selection_range.end > old_name.len() {
11336                            editor.select_all(&SelectAll, window, cx);
11337                        } else {
11338                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11339                                s.select_ranges([rename_selection_range]);
11340                            });
11341                        }
11342                        editor
11343                    });
11344                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11345                        if e == &EditorEvent::Focused {
11346                            cx.emit(EditorEvent::FocusedIn)
11347                        }
11348                    })
11349                    .detach();
11350
11351                    let write_highlights =
11352                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11353                    let read_highlights =
11354                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11355                    let ranges = write_highlights
11356                        .iter()
11357                        .flat_map(|(_, ranges)| ranges.iter())
11358                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11359                        .cloned()
11360                        .collect();
11361
11362                    this.highlight_text::<Rename>(
11363                        ranges,
11364                        HighlightStyle {
11365                            fade_out: Some(0.6),
11366                            ..Default::default()
11367                        },
11368                        cx,
11369                    );
11370                    let rename_focus_handle = rename_editor.focus_handle(cx);
11371                    window.focus(&rename_focus_handle);
11372                    let block_id = this.insert_blocks(
11373                        [BlockProperties {
11374                            style: BlockStyle::Flex,
11375                            placement: BlockPlacement::Below(range.start),
11376                            height: 1,
11377                            render: Arc::new({
11378                                let rename_editor = rename_editor.clone();
11379                                move |cx: &mut BlockContext| {
11380                                    let mut text_style = cx.editor_style.text.clone();
11381                                    if let Some(highlight_style) = old_highlight_id
11382                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11383                                    {
11384                                        text_style = text_style.highlight(highlight_style);
11385                                    }
11386                                    div()
11387                                        .block_mouse_down()
11388                                        .pl(cx.anchor_x)
11389                                        .child(EditorElement::new(
11390                                            &rename_editor,
11391                                            EditorStyle {
11392                                                background: cx.theme().system().transparent,
11393                                                local_player: cx.editor_style.local_player,
11394                                                text: text_style,
11395                                                scrollbar_width: cx.editor_style.scrollbar_width,
11396                                                syntax: cx.editor_style.syntax.clone(),
11397                                                status: cx.editor_style.status.clone(),
11398                                                inlay_hints_style: HighlightStyle {
11399                                                    font_weight: Some(FontWeight::BOLD),
11400                                                    ..make_inlay_hints_style(cx.app)
11401                                                },
11402                                                inline_completion_styles: make_suggestion_styles(
11403                                                    cx.app,
11404                                                ),
11405                                                ..EditorStyle::default()
11406                                            },
11407                                        ))
11408                                        .into_any_element()
11409                                }
11410                            }),
11411                            priority: 0,
11412                        }],
11413                        Some(Autoscroll::fit()),
11414                        cx,
11415                    )[0];
11416                    this.pending_rename = Some(RenameState {
11417                        range,
11418                        old_name,
11419                        editor: rename_editor,
11420                        block_id,
11421                    });
11422                })?;
11423            }
11424
11425            Ok(())
11426        }))
11427    }
11428
11429    pub fn confirm_rename(
11430        &mut self,
11431        _: &ConfirmRename,
11432        window: &mut Window,
11433        cx: &mut Context<Self>,
11434    ) -> Option<Task<Result<()>>> {
11435        let rename = self.take_rename(false, window, cx)?;
11436        let workspace = self.workspace()?.downgrade();
11437        let (buffer, start) = self
11438            .buffer
11439            .read(cx)
11440            .text_anchor_for_position(rename.range.start, cx)?;
11441        let (end_buffer, _) = self
11442            .buffer
11443            .read(cx)
11444            .text_anchor_for_position(rename.range.end, cx)?;
11445        if buffer != end_buffer {
11446            return None;
11447        }
11448
11449        let old_name = rename.old_name;
11450        let new_name = rename.editor.read(cx).text(cx);
11451
11452        let rename = self.semantics_provider.as_ref()?.perform_rename(
11453            &buffer,
11454            start,
11455            new_name.clone(),
11456            cx,
11457        )?;
11458
11459        Some(cx.spawn_in(window, |editor, mut cx| async move {
11460            let project_transaction = rename.await?;
11461            Self::open_project_transaction(
11462                &editor,
11463                workspace,
11464                project_transaction,
11465                format!("Rename: {}{}", old_name, new_name),
11466                cx.clone(),
11467            )
11468            .await?;
11469
11470            editor.update(&mut cx, |editor, cx| {
11471                editor.refresh_document_highlights(cx);
11472            })?;
11473            Ok(())
11474        }))
11475    }
11476
11477    fn take_rename(
11478        &mut self,
11479        moving_cursor: bool,
11480        window: &mut Window,
11481        cx: &mut Context<Self>,
11482    ) -> Option<RenameState> {
11483        let rename = self.pending_rename.take()?;
11484        if rename.editor.focus_handle(cx).is_focused(window) {
11485            window.focus(&self.focus_handle);
11486        }
11487
11488        self.remove_blocks(
11489            [rename.block_id].into_iter().collect(),
11490            Some(Autoscroll::fit()),
11491            cx,
11492        );
11493        self.clear_highlights::<Rename>(cx);
11494        self.show_local_selections = true;
11495
11496        if moving_cursor {
11497            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11498                editor.selections.newest::<usize>(cx).head()
11499            });
11500
11501            // Update the selection to match the position of the selection inside
11502            // the rename editor.
11503            let snapshot = self.buffer.read(cx).read(cx);
11504            let rename_range = rename.range.to_offset(&snapshot);
11505            let cursor_in_editor = snapshot
11506                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11507                .min(rename_range.end);
11508            drop(snapshot);
11509
11510            self.change_selections(None, window, cx, |s| {
11511                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11512            });
11513        } else {
11514            self.refresh_document_highlights(cx);
11515        }
11516
11517        Some(rename)
11518    }
11519
11520    pub fn pending_rename(&self) -> Option<&RenameState> {
11521        self.pending_rename.as_ref()
11522    }
11523
11524    fn format(
11525        &mut self,
11526        _: &Format,
11527        window: &mut Window,
11528        cx: &mut Context<Self>,
11529    ) -> Option<Task<Result<()>>> {
11530        let project = match &self.project {
11531            Some(project) => project.clone(),
11532            None => return None,
11533        };
11534
11535        Some(self.perform_format(
11536            project,
11537            FormatTrigger::Manual,
11538            FormatTarget::Buffers,
11539            window,
11540            cx,
11541        ))
11542    }
11543
11544    fn format_selections(
11545        &mut self,
11546        _: &FormatSelections,
11547        window: &mut Window,
11548        cx: &mut Context<Self>,
11549    ) -> Option<Task<Result<()>>> {
11550        let project = match &self.project {
11551            Some(project) => project.clone(),
11552            None => return None,
11553        };
11554
11555        let ranges = self
11556            .selections
11557            .all_adjusted(cx)
11558            .into_iter()
11559            .map(|selection| selection.range())
11560            .collect_vec();
11561
11562        Some(self.perform_format(
11563            project,
11564            FormatTrigger::Manual,
11565            FormatTarget::Ranges(ranges),
11566            window,
11567            cx,
11568        ))
11569    }
11570
11571    fn perform_format(
11572        &mut self,
11573        project: Entity<Project>,
11574        trigger: FormatTrigger,
11575        target: FormatTarget,
11576        window: &mut Window,
11577        cx: &mut Context<Self>,
11578    ) -> Task<Result<()>> {
11579        let buffer = self.buffer.clone();
11580        let (buffers, target) = match target {
11581            FormatTarget::Buffers => {
11582                let mut buffers = buffer.read(cx).all_buffers();
11583                if trigger == FormatTrigger::Save {
11584                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11585                }
11586                (buffers, LspFormatTarget::Buffers)
11587            }
11588            FormatTarget::Ranges(selection_ranges) => {
11589                let multi_buffer = buffer.read(cx);
11590                let snapshot = multi_buffer.read(cx);
11591                let mut buffers = HashSet::default();
11592                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11593                    BTreeMap::new();
11594                for selection_range in selection_ranges {
11595                    for (buffer, buffer_range, _) in
11596                        snapshot.range_to_buffer_ranges(selection_range)
11597                    {
11598                        let buffer_id = buffer.remote_id();
11599                        let start = buffer.anchor_before(buffer_range.start);
11600                        let end = buffer.anchor_after(buffer_range.end);
11601                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11602                        buffer_id_to_ranges
11603                            .entry(buffer_id)
11604                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11605                            .or_insert_with(|| vec![start..end]);
11606                    }
11607                }
11608                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11609            }
11610        };
11611
11612        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11613        let format = project.update(cx, |project, cx| {
11614            project.format(buffers, target, true, trigger, cx)
11615        });
11616
11617        cx.spawn_in(window, |_, mut cx| async move {
11618            let transaction = futures::select_biased! {
11619                () = timeout => {
11620                    log::warn!("timed out waiting for formatting");
11621                    None
11622                }
11623                transaction = format.log_err().fuse() => transaction,
11624            };
11625
11626            buffer
11627                .update(&mut cx, |buffer, cx| {
11628                    if let Some(transaction) = transaction {
11629                        if !buffer.is_singleton() {
11630                            buffer.push_transaction(&transaction.0, cx);
11631                        }
11632                    }
11633
11634                    cx.notify();
11635                })
11636                .ok();
11637
11638            Ok(())
11639        })
11640    }
11641
11642    fn restart_language_server(
11643        &mut self,
11644        _: &RestartLanguageServer,
11645        _: &mut Window,
11646        cx: &mut Context<Self>,
11647    ) {
11648        if let Some(project) = self.project.clone() {
11649            self.buffer.update(cx, |multi_buffer, cx| {
11650                project.update(cx, |project, cx| {
11651                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11652                });
11653            })
11654        }
11655    }
11656
11657    fn cancel_language_server_work(
11658        workspace: &mut Workspace,
11659        _: &actions::CancelLanguageServerWork,
11660        _: &mut Window,
11661        cx: &mut Context<Workspace>,
11662    ) {
11663        let project = workspace.project();
11664        let buffers = workspace
11665            .active_item(cx)
11666            .and_then(|item| item.act_as::<Editor>(cx))
11667            .map_or(HashSet::default(), |editor| {
11668                editor.read(cx).buffer.read(cx).all_buffers()
11669            });
11670        project.update(cx, |project, cx| {
11671            project.cancel_language_server_work_for_buffers(buffers, cx);
11672        });
11673    }
11674
11675    fn show_character_palette(
11676        &mut self,
11677        _: &ShowCharacterPalette,
11678        window: &mut Window,
11679        _: &mut Context<Self>,
11680    ) {
11681        window.show_character_palette();
11682    }
11683
11684    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11685        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11686            let buffer = self.buffer.read(cx).snapshot(cx);
11687            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11688            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11689            let is_valid = buffer
11690                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11691                .any(|entry| {
11692                    entry.diagnostic.is_primary
11693                        && !entry.range.is_empty()
11694                        && entry.range.start == primary_range_start
11695                        && entry.diagnostic.message == active_diagnostics.primary_message
11696                });
11697
11698            if is_valid != active_diagnostics.is_valid {
11699                active_diagnostics.is_valid = is_valid;
11700                let mut new_styles = HashMap::default();
11701                for (block_id, diagnostic) in &active_diagnostics.blocks {
11702                    new_styles.insert(
11703                        *block_id,
11704                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11705                    );
11706                }
11707                self.display_map.update(cx, |display_map, _cx| {
11708                    display_map.replace_blocks(new_styles)
11709                });
11710            }
11711        }
11712    }
11713
11714    fn activate_diagnostics(
11715        &mut self,
11716        buffer_id: BufferId,
11717        group_id: usize,
11718        window: &mut Window,
11719        cx: &mut Context<Self>,
11720    ) {
11721        self.dismiss_diagnostics(cx);
11722        let snapshot = self.snapshot(window, cx);
11723        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11724            let buffer = self.buffer.read(cx).snapshot(cx);
11725
11726            let mut primary_range = None;
11727            let mut primary_message = None;
11728            let diagnostic_group = buffer
11729                .diagnostic_group(buffer_id, group_id)
11730                .filter_map(|entry| {
11731                    let start = entry.range.start;
11732                    let end = entry.range.end;
11733                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11734                        && (start.row == end.row
11735                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11736                    {
11737                        return None;
11738                    }
11739                    if entry.diagnostic.is_primary {
11740                        primary_range = Some(entry.range.clone());
11741                        primary_message = Some(entry.diagnostic.message.clone());
11742                    }
11743                    Some(entry)
11744                })
11745                .collect::<Vec<_>>();
11746            let primary_range = primary_range?;
11747            let primary_message = primary_message?;
11748
11749            let blocks = display_map
11750                .insert_blocks(
11751                    diagnostic_group.iter().map(|entry| {
11752                        let diagnostic = entry.diagnostic.clone();
11753                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11754                        BlockProperties {
11755                            style: BlockStyle::Fixed,
11756                            placement: BlockPlacement::Below(
11757                                buffer.anchor_after(entry.range.start),
11758                            ),
11759                            height: message_height,
11760                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11761                            priority: 0,
11762                        }
11763                    }),
11764                    cx,
11765                )
11766                .into_iter()
11767                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11768                .collect();
11769
11770            Some(ActiveDiagnosticGroup {
11771                primary_range: buffer.anchor_before(primary_range.start)
11772                    ..buffer.anchor_after(primary_range.end),
11773                primary_message,
11774                group_id,
11775                blocks,
11776                is_valid: true,
11777            })
11778        });
11779    }
11780
11781    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11782        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11783            self.display_map.update(cx, |display_map, cx| {
11784                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11785            });
11786            cx.notify();
11787        }
11788    }
11789
11790    pub fn set_selections_from_remote(
11791        &mut self,
11792        selections: Vec<Selection<Anchor>>,
11793        pending_selection: Option<Selection<Anchor>>,
11794        window: &mut Window,
11795        cx: &mut Context<Self>,
11796    ) {
11797        let old_cursor_position = self.selections.newest_anchor().head();
11798        self.selections.change_with(cx, |s| {
11799            s.select_anchors(selections);
11800            if let Some(pending_selection) = pending_selection {
11801                s.set_pending(pending_selection, SelectMode::Character);
11802            } else {
11803                s.clear_pending();
11804            }
11805        });
11806        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11807    }
11808
11809    fn push_to_selection_history(&mut self) {
11810        self.selection_history.push(SelectionHistoryEntry {
11811            selections: self.selections.disjoint_anchors(),
11812            select_next_state: self.select_next_state.clone(),
11813            select_prev_state: self.select_prev_state.clone(),
11814            add_selections_state: self.add_selections_state.clone(),
11815        });
11816    }
11817
11818    pub fn transact(
11819        &mut self,
11820        window: &mut Window,
11821        cx: &mut Context<Self>,
11822        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11823    ) -> Option<TransactionId> {
11824        self.start_transaction_at(Instant::now(), window, cx);
11825        update(self, window, cx);
11826        self.end_transaction_at(Instant::now(), cx)
11827    }
11828
11829    pub fn start_transaction_at(
11830        &mut self,
11831        now: Instant,
11832        window: &mut Window,
11833        cx: &mut Context<Self>,
11834    ) {
11835        self.end_selection(window, cx);
11836        if let Some(tx_id) = self
11837            .buffer
11838            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11839        {
11840            self.selection_history
11841                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11842            cx.emit(EditorEvent::TransactionBegun {
11843                transaction_id: tx_id,
11844            })
11845        }
11846    }
11847
11848    pub fn end_transaction_at(
11849        &mut self,
11850        now: Instant,
11851        cx: &mut Context<Self>,
11852    ) -> Option<TransactionId> {
11853        if let Some(transaction_id) = self
11854            .buffer
11855            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11856        {
11857            if let Some((_, end_selections)) =
11858                self.selection_history.transaction_mut(transaction_id)
11859            {
11860                *end_selections = Some(self.selections.disjoint_anchors());
11861            } else {
11862                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11863            }
11864
11865            cx.emit(EditorEvent::Edited { transaction_id });
11866            Some(transaction_id)
11867        } else {
11868            None
11869        }
11870    }
11871
11872    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11873        if self.selection_mark_mode {
11874            self.change_selections(None, window, cx, |s| {
11875                s.move_with(|_, sel| {
11876                    sel.collapse_to(sel.head(), SelectionGoal::None);
11877                });
11878            })
11879        }
11880        self.selection_mark_mode = true;
11881        cx.notify();
11882    }
11883
11884    pub fn swap_selection_ends(
11885        &mut self,
11886        _: &actions::SwapSelectionEnds,
11887        window: &mut Window,
11888        cx: &mut Context<Self>,
11889    ) {
11890        self.change_selections(None, window, cx, |s| {
11891            s.move_with(|_, sel| {
11892                if sel.start != sel.end {
11893                    sel.reversed = !sel.reversed
11894                }
11895            });
11896        });
11897        self.request_autoscroll(Autoscroll::newest(), cx);
11898        cx.notify();
11899    }
11900
11901    pub fn toggle_fold(
11902        &mut self,
11903        _: &actions::ToggleFold,
11904        window: &mut Window,
11905        cx: &mut Context<Self>,
11906    ) {
11907        if self.is_singleton(cx) {
11908            let selection = self.selections.newest::<Point>(cx);
11909
11910            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11911            let range = if selection.is_empty() {
11912                let point = selection.head().to_display_point(&display_map);
11913                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11914                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11915                    .to_point(&display_map);
11916                start..end
11917            } else {
11918                selection.range()
11919            };
11920            if display_map.folds_in_range(range).next().is_some() {
11921                self.unfold_lines(&Default::default(), window, cx)
11922            } else {
11923                self.fold(&Default::default(), window, cx)
11924            }
11925        } else {
11926            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11927            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11928                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11929                .map(|(snapshot, _, _)| snapshot.remote_id())
11930                .collect();
11931
11932            for buffer_id in buffer_ids {
11933                if self.is_buffer_folded(buffer_id, cx) {
11934                    self.unfold_buffer(buffer_id, cx);
11935                } else {
11936                    self.fold_buffer(buffer_id, cx);
11937                }
11938            }
11939        }
11940    }
11941
11942    pub fn toggle_fold_recursive(
11943        &mut self,
11944        _: &actions::ToggleFoldRecursive,
11945        window: &mut Window,
11946        cx: &mut Context<Self>,
11947    ) {
11948        let selection = self.selections.newest::<Point>(cx);
11949
11950        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11951        let range = if selection.is_empty() {
11952            let point = selection.head().to_display_point(&display_map);
11953            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11954            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11955                .to_point(&display_map);
11956            start..end
11957        } else {
11958            selection.range()
11959        };
11960        if display_map.folds_in_range(range).next().is_some() {
11961            self.unfold_recursive(&Default::default(), window, cx)
11962        } else {
11963            self.fold_recursive(&Default::default(), window, cx)
11964        }
11965    }
11966
11967    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11968        if self.is_singleton(cx) {
11969            let mut to_fold = Vec::new();
11970            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11971            let selections = self.selections.all_adjusted(cx);
11972
11973            for selection in selections {
11974                let range = selection.range().sorted();
11975                let buffer_start_row = range.start.row;
11976
11977                if range.start.row != range.end.row {
11978                    let mut found = false;
11979                    let mut row = range.start.row;
11980                    while row <= range.end.row {
11981                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11982                        {
11983                            found = true;
11984                            row = crease.range().end.row + 1;
11985                            to_fold.push(crease);
11986                        } else {
11987                            row += 1
11988                        }
11989                    }
11990                    if found {
11991                        continue;
11992                    }
11993                }
11994
11995                for row in (0..=range.start.row).rev() {
11996                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11997                        if crease.range().end.row >= buffer_start_row {
11998                            to_fold.push(crease);
11999                            if row <= range.start.row {
12000                                break;
12001                            }
12002                        }
12003                    }
12004                }
12005            }
12006
12007            self.fold_creases(to_fold, true, window, cx);
12008        } else {
12009            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12010
12011            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12012                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12013                .map(|(snapshot, _, _)| snapshot.remote_id())
12014                .collect();
12015            for buffer_id in buffer_ids {
12016                self.fold_buffer(buffer_id, cx);
12017            }
12018        }
12019    }
12020
12021    fn fold_at_level(
12022        &mut self,
12023        fold_at: &FoldAtLevel,
12024        window: &mut Window,
12025        cx: &mut Context<Self>,
12026    ) {
12027        if !self.buffer.read(cx).is_singleton() {
12028            return;
12029        }
12030
12031        let fold_at_level = fold_at.0;
12032        let snapshot = self.buffer.read(cx).snapshot(cx);
12033        let mut to_fold = Vec::new();
12034        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12035
12036        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12037            while start_row < end_row {
12038                match self
12039                    .snapshot(window, cx)
12040                    .crease_for_buffer_row(MultiBufferRow(start_row))
12041                {
12042                    Some(crease) => {
12043                        let nested_start_row = crease.range().start.row + 1;
12044                        let nested_end_row = crease.range().end.row;
12045
12046                        if current_level < fold_at_level {
12047                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12048                        } else if current_level == fold_at_level {
12049                            to_fold.push(crease);
12050                        }
12051
12052                        start_row = nested_end_row + 1;
12053                    }
12054                    None => start_row += 1,
12055                }
12056            }
12057        }
12058
12059        self.fold_creases(to_fold, true, window, cx);
12060    }
12061
12062    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12063        if self.buffer.read(cx).is_singleton() {
12064            let mut fold_ranges = Vec::new();
12065            let snapshot = self.buffer.read(cx).snapshot(cx);
12066
12067            for row in 0..snapshot.max_row().0 {
12068                if let Some(foldable_range) = self
12069                    .snapshot(window, cx)
12070                    .crease_for_buffer_row(MultiBufferRow(row))
12071                {
12072                    fold_ranges.push(foldable_range);
12073                }
12074            }
12075
12076            self.fold_creases(fold_ranges, true, window, cx);
12077        } else {
12078            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12079                editor
12080                    .update_in(&mut cx, |editor, _, cx| {
12081                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12082                            editor.fold_buffer(buffer_id, cx);
12083                        }
12084                    })
12085                    .ok();
12086            });
12087        }
12088    }
12089
12090    pub fn fold_function_bodies(
12091        &mut self,
12092        _: &actions::FoldFunctionBodies,
12093        window: &mut Window,
12094        cx: &mut Context<Self>,
12095    ) {
12096        let snapshot = self.buffer.read(cx).snapshot(cx);
12097
12098        let ranges = snapshot
12099            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12100            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12101            .collect::<Vec<_>>();
12102
12103        let creases = ranges
12104            .into_iter()
12105            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12106            .collect();
12107
12108        self.fold_creases(creases, true, window, cx);
12109    }
12110
12111    pub fn fold_recursive(
12112        &mut self,
12113        _: &actions::FoldRecursive,
12114        window: &mut Window,
12115        cx: &mut Context<Self>,
12116    ) {
12117        let mut to_fold = Vec::new();
12118        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12119        let selections = self.selections.all_adjusted(cx);
12120
12121        for selection in selections {
12122            let range = selection.range().sorted();
12123            let buffer_start_row = range.start.row;
12124
12125            if range.start.row != range.end.row {
12126                let mut found = false;
12127                for row in range.start.row..=range.end.row {
12128                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12129                        found = true;
12130                        to_fold.push(crease);
12131                    }
12132                }
12133                if found {
12134                    continue;
12135                }
12136            }
12137
12138            for row in (0..=range.start.row).rev() {
12139                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12140                    if crease.range().end.row >= buffer_start_row {
12141                        to_fold.push(crease);
12142                    } else {
12143                        break;
12144                    }
12145                }
12146            }
12147        }
12148
12149        self.fold_creases(to_fold, true, window, cx);
12150    }
12151
12152    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12153        let buffer_row = fold_at.buffer_row;
12154        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12155
12156        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12157            let autoscroll = self
12158                .selections
12159                .all::<Point>(cx)
12160                .iter()
12161                .any(|selection| crease.range().overlaps(&selection.range()));
12162
12163            self.fold_creases(vec![crease], autoscroll, window, cx);
12164        }
12165    }
12166
12167    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12168        if self.is_singleton(cx) {
12169            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12170            let buffer = &display_map.buffer_snapshot;
12171            let selections = self.selections.all::<Point>(cx);
12172            let ranges = selections
12173                .iter()
12174                .map(|s| {
12175                    let range = s.display_range(&display_map).sorted();
12176                    let mut start = range.start.to_point(&display_map);
12177                    let mut end = range.end.to_point(&display_map);
12178                    start.column = 0;
12179                    end.column = buffer.line_len(MultiBufferRow(end.row));
12180                    start..end
12181                })
12182                .collect::<Vec<_>>();
12183
12184            self.unfold_ranges(&ranges, true, true, cx);
12185        } else {
12186            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12187            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12188                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12189                .map(|(snapshot, _, _)| snapshot.remote_id())
12190                .collect();
12191            for buffer_id in buffer_ids {
12192                self.unfold_buffer(buffer_id, cx);
12193            }
12194        }
12195    }
12196
12197    pub fn unfold_recursive(
12198        &mut self,
12199        _: &UnfoldRecursive,
12200        _window: &mut Window,
12201        cx: &mut Context<Self>,
12202    ) {
12203        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12204        let selections = self.selections.all::<Point>(cx);
12205        let ranges = selections
12206            .iter()
12207            .map(|s| {
12208                let mut range = s.display_range(&display_map).sorted();
12209                *range.start.column_mut() = 0;
12210                *range.end.column_mut() = display_map.line_len(range.end.row());
12211                let start = range.start.to_point(&display_map);
12212                let end = range.end.to_point(&display_map);
12213                start..end
12214            })
12215            .collect::<Vec<_>>();
12216
12217        self.unfold_ranges(&ranges, true, true, cx);
12218    }
12219
12220    pub fn unfold_at(
12221        &mut self,
12222        unfold_at: &UnfoldAt,
12223        _window: &mut Window,
12224        cx: &mut Context<Self>,
12225    ) {
12226        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12227
12228        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12229            ..Point::new(
12230                unfold_at.buffer_row.0,
12231                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12232            );
12233
12234        let autoscroll = self
12235            .selections
12236            .all::<Point>(cx)
12237            .iter()
12238            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12239
12240        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12241    }
12242
12243    pub fn unfold_all(
12244        &mut self,
12245        _: &actions::UnfoldAll,
12246        _window: &mut Window,
12247        cx: &mut Context<Self>,
12248    ) {
12249        if self.buffer.read(cx).is_singleton() {
12250            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12251            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12252        } else {
12253            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12254                editor
12255                    .update(&mut cx, |editor, cx| {
12256                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12257                            editor.unfold_buffer(buffer_id, cx);
12258                        }
12259                    })
12260                    .ok();
12261            });
12262        }
12263    }
12264
12265    pub fn fold_selected_ranges(
12266        &mut self,
12267        _: &FoldSelectedRanges,
12268        window: &mut Window,
12269        cx: &mut Context<Self>,
12270    ) {
12271        let selections = self.selections.all::<Point>(cx);
12272        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12273        let line_mode = self.selections.line_mode;
12274        let ranges = selections
12275            .into_iter()
12276            .map(|s| {
12277                if line_mode {
12278                    let start = Point::new(s.start.row, 0);
12279                    let end = Point::new(
12280                        s.end.row,
12281                        display_map
12282                            .buffer_snapshot
12283                            .line_len(MultiBufferRow(s.end.row)),
12284                    );
12285                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12286                } else {
12287                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12288                }
12289            })
12290            .collect::<Vec<_>>();
12291        self.fold_creases(ranges, true, window, cx);
12292    }
12293
12294    pub fn fold_ranges<T: ToOffset + Clone>(
12295        &mut self,
12296        ranges: Vec<Range<T>>,
12297        auto_scroll: bool,
12298        window: &mut Window,
12299        cx: &mut Context<Self>,
12300    ) {
12301        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12302        let ranges = ranges
12303            .into_iter()
12304            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12305            .collect::<Vec<_>>();
12306        self.fold_creases(ranges, auto_scroll, window, cx);
12307    }
12308
12309    pub fn fold_creases<T: ToOffset + Clone>(
12310        &mut self,
12311        creases: Vec<Crease<T>>,
12312        auto_scroll: bool,
12313        window: &mut Window,
12314        cx: &mut Context<Self>,
12315    ) {
12316        if creases.is_empty() {
12317            return;
12318        }
12319
12320        let mut buffers_affected = HashSet::default();
12321        let multi_buffer = self.buffer().read(cx);
12322        for crease in &creases {
12323            if let Some((_, buffer, _)) =
12324                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12325            {
12326                buffers_affected.insert(buffer.read(cx).remote_id());
12327            };
12328        }
12329
12330        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12331
12332        if auto_scroll {
12333            self.request_autoscroll(Autoscroll::fit(), cx);
12334        }
12335
12336        cx.notify();
12337
12338        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12339            // Clear diagnostics block when folding a range that contains it.
12340            let snapshot = self.snapshot(window, cx);
12341            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12342                drop(snapshot);
12343                self.active_diagnostics = Some(active_diagnostics);
12344                self.dismiss_diagnostics(cx);
12345            } else {
12346                self.active_diagnostics = Some(active_diagnostics);
12347            }
12348        }
12349
12350        self.scrollbar_marker_state.dirty = true;
12351    }
12352
12353    /// Removes any folds whose ranges intersect any of the given ranges.
12354    pub fn unfold_ranges<T: ToOffset + Clone>(
12355        &mut self,
12356        ranges: &[Range<T>],
12357        inclusive: bool,
12358        auto_scroll: bool,
12359        cx: &mut Context<Self>,
12360    ) {
12361        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12362            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12363        });
12364    }
12365
12366    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12367        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12368            return;
12369        }
12370        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12371        self.display_map
12372            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12373        cx.emit(EditorEvent::BufferFoldToggled {
12374            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12375            folded: true,
12376        });
12377        cx.notify();
12378    }
12379
12380    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12381        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12382            return;
12383        }
12384        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12385        self.display_map.update(cx, |display_map, cx| {
12386            display_map.unfold_buffer(buffer_id, cx);
12387        });
12388        cx.emit(EditorEvent::BufferFoldToggled {
12389            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12390            folded: false,
12391        });
12392        cx.notify();
12393    }
12394
12395    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12396        self.display_map.read(cx).is_buffer_folded(buffer)
12397    }
12398
12399    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12400        self.display_map.read(cx).folded_buffers()
12401    }
12402
12403    /// Removes any folds with the given ranges.
12404    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12405        &mut self,
12406        ranges: &[Range<T>],
12407        type_id: TypeId,
12408        auto_scroll: bool,
12409        cx: &mut Context<Self>,
12410    ) {
12411        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12412            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12413        });
12414    }
12415
12416    fn remove_folds_with<T: ToOffset + Clone>(
12417        &mut self,
12418        ranges: &[Range<T>],
12419        auto_scroll: bool,
12420        cx: &mut Context<Self>,
12421        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12422    ) {
12423        if ranges.is_empty() {
12424            return;
12425        }
12426
12427        let mut buffers_affected = HashSet::default();
12428        let multi_buffer = self.buffer().read(cx);
12429        for range in ranges {
12430            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12431                buffers_affected.insert(buffer.read(cx).remote_id());
12432            };
12433        }
12434
12435        self.display_map.update(cx, update);
12436
12437        if auto_scroll {
12438            self.request_autoscroll(Autoscroll::fit(), cx);
12439        }
12440
12441        cx.notify();
12442        self.scrollbar_marker_state.dirty = true;
12443        self.active_indent_guides_state.dirty = true;
12444    }
12445
12446    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12447        self.display_map.read(cx).fold_placeholder.clone()
12448    }
12449
12450    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12451        self.buffer.update(cx, |buffer, cx| {
12452            buffer.set_all_diff_hunks_expanded(cx);
12453        });
12454    }
12455
12456    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12457        self.distinguish_unstaged_diff_hunks = true;
12458    }
12459
12460    pub fn expand_all_diff_hunks(
12461        &mut self,
12462        _: &ExpandAllHunkDiffs,
12463        _window: &mut Window,
12464        cx: &mut Context<Self>,
12465    ) {
12466        self.buffer.update(cx, |buffer, cx| {
12467            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12468        });
12469    }
12470
12471    pub fn toggle_selected_diff_hunks(
12472        &mut self,
12473        _: &ToggleSelectedDiffHunks,
12474        _window: &mut Window,
12475        cx: &mut Context<Self>,
12476    ) {
12477        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12478        self.toggle_diff_hunks_in_ranges(ranges, cx);
12479    }
12480
12481    fn diff_hunks_in_ranges<'a>(
12482        &'a self,
12483        ranges: &'a [Range<Anchor>],
12484        buffer: &'a MultiBufferSnapshot,
12485    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12486        ranges.iter().flat_map(move |range| {
12487            let end_excerpt_id = range.end.excerpt_id;
12488            let range = range.to_point(buffer);
12489            let mut peek_end = range.end;
12490            if range.end.row < buffer.max_row().0 {
12491                peek_end = Point::new(range.end.row + 1, 0);
12492            }
12493            buffer
12494                .diff_hunks_in_range(range.start..peek_end)
12495                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12496        })
12497    }
12498
12499    pub fn has_stageable_diff_hunks_in_ranges(
12500        &self,
12501        ranges: &[Range<Anchor>],
12502        snapshot: &MultiBufferSnapshot,
12503    ) -> bool {
12504        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12505        hunks.any(|hunk| {
12506            log::debug!("considering {hunk:?}");
12507            hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12508        })
12509    }
12510
12511    pub fn toggle_staged_selected_diff_hunks(
12512        &mut self,
12513        _: &ToggleStagedSelectedDiffHunks,
12514        _window: &mut Window,
12515        cx: &mut Context<Self>,
12516    ) {
12517        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12518        self.stage_or_unstage_diff_hunks(&ranges, cx);
12519    }
12520
12521    pub fn stage_or_unstage_diff_hunks(
12522        &mut self,
12523        ranges: &[Range<Anchor>],
12524        cx: &mut Context<Self>,
12525    ) {
12526        let Some(project) = &self.project else {
12527            return;
12528        };
12529        let snapshot = self.buffer.read(cx).snapshot(cx);
12530        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12531
12532        let chunk_by = self
12533            .diff_hunks_in_ranges(&ranges, &snapshot)
12534            .chunk_by(|hunk| hunk.buffer_id);
12535        for (buffer_id, hunks) in &chunk_by {
12536            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12537                log::debug!("no buffer for id");
12538                continue;
12539            };
12540            let buffer = buffer.read(cx).snapshot();
12541            let Some((repo, path)) = project
12542                .read(cx)
12543                .repository_and_path_for_buffer_id(buffer_id, cx)
12544            else {
12545                log::debug!("no git repo for buffer id");
12546                continue;
12547            };
12548            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12549                log::debug!("no diff for buffer id");
12550                continue;
12551            };
12552            let Some(secondary_diff) = diff.secondary_diff() else {
12553                log::debug!("no secondary diff for buffer id");
12554                continue;
12555            };
12556
12557            let edits = diff.secondary_edits_for_stage_or_unstage(
12558                stage,
12559                hunks.map(|hunk| {
12560                    (
12561                        hunk.diff_base_byte_range.clone(),
12562                        hunk.secondary_diff_base_byte_range.clone(),
12563                        hunk.buffer_range.clone(),
12564                    )
12565                }),
12566                &buffer,
12567            );
12568
12569            let index_base = secondary_diff.base_text().map_or_else(
12570                || Rope::from(""),
12571                |snapshot| snapshot.text.as_rope().clone(),
12572            );
12573            let index_buffer = cx.new(|cx| {
12574                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12575            });
12576            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12577                index_buffer.edit(edits, None, cx);
12578                index_buffer.snapshot().as_rope().to_string()
12579            });
12580            let new_index_text = if new_index_text.is_empty()
12581                && (diff.is_single_insertion
12582                    || buffer
12583                        .file()
12584                        .map_or(false, |file| file.disk_state() == DiskState::New))
12585            {
12586                log::debug!("removing from index");
12587                None
12588            } else {
12589                Some(new_index_text)
12590            };
12591
12592            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12593        }
12594    }
12595
12596    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12597        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12598        self.buffer
12599            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12600    }
12601
12602    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12603        self.buffer.update(cx, |buffer, cx| {
12604            let ranges = vec![Anchor::min()..Anchor::max()];
12605            if !buffer.all_diff_hunks_expanded()
12606                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12607            {
12608                buffer.collapse_diff_hunks(ranges, cx);
12609                true
12610            } else {
12611                false
12612            }
12613        })
12614    }
12615
12616    fn toggle_diff_hunks_in_ranges(
12617        &mut self,
12618        ranges: Vec<Range<Anchor>>,
12619        cx: &mut Context<'_, Editor>,
12620    ) {
12621        self.buffer.update(cx, |buffer, cx| {
12622            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12623            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12624        })
12625    }
12626
12627    fn toggle_diff_hunks_in_ranges_narrow(
12628        &mut self,
12629        ranges: Vec<Range<Anchor>>,
12630        cx: &mut Context<'_, Editor>,
12631    ) {
12632        self.buffer.update(cx, |buffer, cx| {
12633            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12634            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12635        })
12636    }
12637
12638    pub(crate) fn apply_all_diff_hunks(
12639        &mut self,
12640        _: &ApplyAllDiffHunks,
12641        window: &mut Window,
12642        cx: &mut Context<Self>,
12643    ) {
12644        let buffers = self.buffer.read(cx).all_buffers();
12645        for branch_buffer in buffers {
12646            branch_buffer.update(cx, |branch_buffer, cx| {
12647                branch_buffer.merge_into_base(Vec::new(), cx);
12648            });
12649        }
12650
12651        if let Some(project) = self.project.clone() {
12652            self.save(true, project, window, cx).detach_and_log_err(cx);
12653        }
12654    }
12655
12656    pub(crate) fn apply_selected_diff_hunks(
12657        &mut self,
12658        _: &ApplyDiffHunk,
12659        window: &mut Window,
12660        cx: &mut Context<Self>,
12661    ) {
12662        let snapshot = self.snapshot(window, cx);
12663        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12664        let mut ranges_by_buffer = HashMap::default();
12665        self.transact(window, cx, |editor, _window, cx| {
12666            for hunk in hunks {
12667                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12668                    ranges_by_buffer
12669                        .entry(buffer.clone())
12670                        .or_insert_with(Vec::new)
12671                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12672                }
12673            }
12674
12675            for (buffer, ranges) in ranges_by_buffer {
12676                buffer.update(cx, |buffer, cx| {
12677                    buffer.merge_into_base(ranges, cx);
12678                });
12679            }
12680        });
12681
12682        if let Some(project) = self.project.clone() {
12683            self.save(true, project, window, cx).detach_and_log_err(cx);
12684        }
12685    }
12686
12687    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12688        if hovered != self.gutter_hovered {
12689            self.gutter_hovered = hovered;
12690            cx.notify();
12691        }
12692    }
12693
12694    pub fn insert_blocks(
12695        &mut self,
12696        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12697        autoscroll: Option<Autoscroll>,
12698        cx: &mut Context<Self>,
12699    ) -> Vec<CustomBlockId> {
12700        let blocks = self
12701            .display_map
12702            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12703        if let Some(autoscroll) = autoscroll {
12704            self.request_autoscroll(autoscroll, cx);
12705        }
12706        cx.notify();
12707        blocks
12708    }
12709
12710    pub fn resize_blocks(
12711        &mut self,
12712        heights: HashMap<CustomBlockId, u32>,
12713        autoscroll: Option<Autoscroll>,
12714        cx: &mut Context<Self>,
12715    ) {
12716        self.display_map
12717            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12718        if let Some(autoscroll) = autoscroll {
12719            self.request_autoscroll(autoscroll, cx);
12720        }
12721        cx.notify();
12722    }
12723
12724    pub fn replace_blocks(
12725        &mut self,
12726        renderers: HashMap<CustomBlockId, RenderBlock>,
12727        autoscroll: Option<Autoscroll>,
12728        cx: &mut Context<Self>,
12729    ) {
12730        self.display_map
12731            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12732        if let Some(autoscroll) = autoscroll {
12733            self.request_autoscroll(autoscroll, cx);
12734        }
12735        cx.notify();
12736    }
12737
12738    pub fn remove_blocks(
12739        &mut self,
12740        block_ids: HashSet<CustomBlockId>,
12741        autoscroll: Option<Autoscroll>,
12742        cx: &mut Context<Self>,
12743    ) {
12744        self.display_map.update(cx, |display_map, cx| {
12745            display_map.remove_blocks(block_ids, cx)
12746        });
12747        if let Some(autoscroll) = autoscroll {
12748            self.request_autoscroll(autoscroll, cx);
12749        }
12750        cx.notify();
12751    }
12752
12753    pub fn row_for_block(
12754        &self,
12755        block_id: CustomBlockId,
12756        cx: &mut Context<Self>,
12757    ) -> Option<DisplayRow> {
12758        self.display_map
12759            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12760    }
12761
12762    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12763        self.focused_block = Some(focused_block);
12764    }
12765
12766    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12767        self.focused_block.take()
12768    }
12769
12770    pub fn insert_creases(
12771        &mut self,
12772        creases: impl IntoIterator<Item = Crease<Anchor>>,
12773        cx: &mut Context<Self>,
12774    ) -> Vec<CreaseId> {
12775        self.display_map
12776            .update(cx, |map, cx| map.insert_creases(creases, cx))
12777    }
12778
12779    pub fn remove_creases(
12780        &mut self,
12781        ids: impl IntoIterator<Item = CreaseId>,
12782        cx: &mut Context<Self>,
12783    ) {
12784        self.display_map
12785            .update(cx, |map, cx| map.remove_creases(ids, cx));
12786    }
12787
12788    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12789        self.display_map
12790            .update(cx, |map, cx| map.snapshot(cx))
12791            .longest_row()
12792    }
12793
12794    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12795        self.display_map
12796            .update(cx, |map, cx| map.snapshot(cx))
12797            .max_point()
12798    }
12799
12800    pub fn text(&self, cx: &App) -> String {
12801        self.buffer.read(cx).read(cx).text()
12802    }
12803
12804    pub fn is_empty(&self, cx: &App) -> bool {
12805        self.buffer.read(cx).read(cx).is_empty()
12806    }
12807
12808    pub fn text_option(&self, cx: &App) -> Option<String> {
12809        let text = self.text(cx);
12810        let text = text.trim();
12811
12812        if text.is_empty() {
12813            return None;
12814        }
12815
12816        Some(text.to_string())
12817    }
12818
12819    pub fn set_text(
12820        &mut self,
12821        text: impl Into<Arc<str>>,
12822        window: &mut Window,
12823        cx: &mut Context<Self>,
12824    ) {
12825        self.transact(window, cx, |this, _, cx| {
12826            this.buffer
12827                .read(cx)
12828                .as_singleton()
12829                .expect("you can only call set_text on editors for singleton buffers")
12830                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12831        });
12832    }
12833
12834    pub fn display_text(&self, cx: &mut App) -> String {
12835        self.display_map
12836            .update(cx, |map, cx| map.snapshot(cx))
12837            .text()
12838    }
12839
12840    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12841        let mut wrap_guides = smallvec::smallvec![];
12842
12843        if self.show_wrap_guides == Some(false) {
12844            return wrap_guides;
12845        }
12846
12847        let settings = self.buffer.read(cx).settings_at(0, cx);
12848        if settings.show_wrap_guides {
12849            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12850                wrap_guides.push((soft_wrap as usize, true));
12851            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12852                wrap_guides.push((soft_wrap as usize, true));
12853            }
12854            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12855        }
12856
12857        wrap_guides
12858    }
12859
12860    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12861        let settings = self.buffer.read(cx).settings_at(0, cx);
12862        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12863        match mode {
12864            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12865                SoftWrap::None
12866            }
12867            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12868            language_settings::SoftWrap::PreferredLineLength => {
12869                SoftWrap::Column(settings.preferred_line_length)
12870            }
12871            language_settings::SoftWrap::Bounded => {
12872                SoftWrap::Bounded(settings.preferred_line_length)
12873            }
12874        }
12875    }
12876
12877    pub fn set_soft_wrap_mode(
12878        &mut self,
12879        mode: language_settings::SoftWrap,
12880
12881        cx: &mut Context<Self>,
12882    ) {
12883        self.soft_wrap_mode_override = Some(mode);
12884        cx.notify();
12885    }
12886
12887    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12888        self.text_style_refinement = Some(style);
12889    }
12890
12891    /// called by the Element so we know what style we were most recently rendered with.
12892    pub(crate) fn set_style(
12893        &mut self,
12894        style: EditorStyle,
12895        window: &mut Window,
12896        cx: &mut Context<Self>,
12897    ) {
12898        let rem_size = window.rem_size();
12899        self.display_map.update(cx, |map, cx| {
12900            map.set_font(
12901                style.text.font(),
12902                style.text.font_size.to_pixels(rem_size),
12903                cx,
12904            )
12905        });
12906        self.style = Some(style);
12907    }
12908
12909    pub fn style(&self) -> Option<&EditorStyle> {
12910        self.style.as_ref()
12911    }
12912
12913    // Called by the element. This method is not designed to be called outside of the editor
12914    // element's layout code because it does not notify when rewrapping is computed synchronously.
12915    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12916        self.display_map
12917            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12918    }
12919
12920    pub fn set_soft_wrap(&mut self) {
12921        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12922    }
12923
12924    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12925        if self.soft_wrap_mode_override.is_some() {
12926            self.soft_wrap_mode_override.take();
12927        } else {
12928            let soft_wrap = match self.soft_wrap_mode(cx) {
12929                SoftWrap::GitDiff => return,
12930                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12931                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12932                    language_settings::SoftWrap::None
12933                }
12934            };
12935            self.soft_wrap_mode_override = Some(soft_wrap);
12936        }
12937        cx.notify();
12938    }
12939
12940    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12941        let Some(workspace) = self.workspace() else {
12942            return;
12943        };
12944        let fs = workspace.read(cx).app_state().fs.clone();
12945        let current_show = TabBarSettings::get_global(cx).show;
12946        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12947            setting.show = Some(!current_show);
12948        });
12949    }
12950
12951    pub fn toggle_indent_guides(
12952        &mut self,
12953        _: &ToggleIndentGuides,
12954        _: &mut Window,
12955        cx: &mut Context<Self>,
12956    ) {
12957        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12958            self.buffer
12959                .read(cx)
12960                .settings_at(0, cx)
12961                .indent_guides
12962                .enabled
12963        });
12964        self.show_indent_guides = Some(!currently_enabled);
12965        cx.notify();
12966    }
12967
12968    fn should_show_indent_guides(&self) -> Option<bool> {
12969        self.show_indent_guides
12970    }
12971
12972    pub fn toggle_line_numbers(
12973        &mut self,
12974        _: &ToggleLineNumbers,
12975        _: &mut Window,
12976        cx: &mut Context<Self>,
12977    ) {
12978        let mut editor_settings = EditorSettings::get_global(cx).clone();
12979        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12980        EditorSettings::override_global(editor_settings, cx);
12981    }
12982
12983    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12984        self.use_relative_line_numbers
12985            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12986    }
12987
12988    pub fn toggle_relative_line_numbers(
12989        &mut self,
12990        _: &ToggleRelativeLineNumbers,
12991        _: &mut Window,
12992        cx: &mut Context<Self>,
12993    ) {
12994        let is_relative = self.should_use_relative_line_numbers(cx);
12995        self.set_relative_line_number(Some(!is_relative), cx)
12996    }
12997
12998    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12999        self.use_relative_line_numbers = is_relative;
13000        cx.notify();
13001    }
13002
13003    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13004        self.show_gutter = show_gutter;
13005        cx.notify();
13006    }
13007
13008    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13009        self.show_scrollbars = show_scrollbars;
13010        cx.notify();
13011    }
13012
13013    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13014        self.show_line_numbers = Some(show_line_numbers);
13015        cx.notify();
13016    }
13017
13018    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13019        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13020        cx.notify();
13021    }
13022
13023    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13024        self.show_code_actions = Some(show_code_actions);
13025        cx.notify();
13026    }
13027
13028    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13029        self.show_runnables = Some(show_runnables);
13030        cx.notify();
13031    }
13032
13033    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13034        if self.display_map.read(cx).masked != masked {
13035            self.display_map.update(cx, |map, _| map.masked = masked);
13036        }
13037        cx.notify()
13038    }
13039
13040    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13041        self.show_wrap_guides = Some(show_wrap_guides);
13042        cx.notify();
13043    }
13044
13045    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13046        self.show_indent_guides = Some(show_indent_guides);
13047        cx.notify();
13048    }
13049
13050    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13051        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13052            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13053                if let Some(dir) = file.abs_path(cx).parent() {
13054                    return Some(dir.to_owned());
13055                }
13056            }
13057
13058            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13059                return Some(project_path.path.to_path_buf());
13060            }
13061        }
13062
13063        None
13064    }
13065
13066    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13067        self.active_excerpt(cx)?
13068            .1
13069            .read(cx)
13070            .file()
13071            .and_then(|f| f.as_local())
13072    }
13073
13074    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13075        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13076            let buffer = buffer.read(cx);
13077            if let Some(project_path) = buffer.project_path(cx) {
13078                let project = self.project.as_ref()?.read(cx);
13079                project.absolute_path(&project_path, cx)
13080            } else {
13081                buffer
13082                    .file()
13083                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13084            }
13085        })
13086    }
13087
13088    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13089        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13090            let project_path = buffer.read(cx).project_path(cx)?;
13091            let project = self.project.as_ref()?.read(cx);
13092            let entry = project.entry_for_path(&project_path, cx)?;
13093            let path = entry.path.to_path_buf();
13094            Some(path)
13095        })
13096    }
13097
13098    pub fn reveal_in_finder(
13099        &mut self,
13100        _: &RevealInFileManager,
13101        _window: &mut Window,
13102        cx: &mut Context<Self>,
13103    ) {
13104        if let Some(target) = self.target_file(cx) {
13105            cx.reveal_path(&target.abs_path(cx));
13106        }
13107    }
13108
13109    pub fn copy_path(
13110        &mut self,
13111        _: &zed_actions::workspace::CopyPath,
13112        _window: &mut Window,
13113        cx: &mut Context<Self>,
13114    ) {
13115        if let Some(path) = self.target_file_abs_path(cx) {
13116            if let Some(path) = path.to_str() {
13117                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13118            }
13119        }
13120    }
13121
13122    pub fn copy_relative_path(
13123        &mut self,
13124        _: &zed_actions::workspace::CopyRelativePath,
13125        _window: &mut Window,
13126        cx: &mut Context<Self>,
13127    ) {
13128        if let Some(path) = self.target_file_path(cx) {
13129            if let Some(path) = path.to_str() {
13130                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13131            }
13132        }
13133    }
13134
13135    pub fn copy_file_name_without_extension(
13136        &mut self,
13137        _: &CopyFileNameWithoutExtension,
13138        _: &mut Window,
13139        cx: &mut Context<Self>,
13140    ) {
13141        if let Some(file) = self.target_file(cx) {
13142            if let Some(file_stem) = file.path().file_stem() {
13143                if let Some(name) = file_stem.to_str() {
13144                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13145                }
13146            }
13147        }
13148    }
13149
13150    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13151        if let Some(file) = self.target_file(cx) {
13152            if let Some(file_name) = file.path().file_name() {
13153                if let Some(name) = file_name.to_str() {
13154                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13155                }
13156            }
13157        }
13158    }
13159
13160    pub fn toggle_git_blame(
13161        &mut self,
13162        _: &ToggleGitBlame,
13163        window: &mut Window,
13164        cx: &mut Context<Self>,
13165    ) {
13166        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13167
13168        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13169            self.start_git_blame(true, window, cx);
13170        }
13171
13172        cx.notify();
13173    }
13174
13175    pub fn toggle_git_blame_inline(
13176        &mut self,
13177        _: &ToggleGitBlameInline,
13178        window: &mut Window,
13179        cx: &mut Context<Self>,
13180    ) {
13181        self.toggle_git_blame_inline_internal(true, window, cx);
13182        cx.notify();
13183    }
13184
13185    pub fn git_blame_inline_enabled(&self) -> bool {
13186        self.git_blame_inline_enabled
13187    }
13188
13189    pub fn toggle_selection_menu(
13190        &mut self,
13191        _: &ToggleSelectionMenu,
13192        _: &mut Window,
13193        cx: &mut Context<Self>,
13194    ) {
13195        self.show_selection_menu = self
13196            .show_selection_menu
13197            .map(|show_selections_menu| !show_selections_menu)
13198            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13199
13200        cx.notify();
13201    }
13202
13203    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13204        self.show_selection_menu
13205            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13206    }
13207
13208    fn start_git_blame(
13209        &mut self,
13210        user_triggered: bool,
13211        window: &mut Window,
13212        cx: &mut Context<Self>,
13213    ) {
13214        if let Some(project) = self.project.as_ref() {
13215            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13216                return;
13217            };
13218
13219            if buffer.read(cx).file().is_none() {
13220                return;
13221            }
13222
13223            let focused = self.focus_handle(cx).contains_focused(window, cx);
13224
13225            let project = project.clone();
13226            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13227            self.blame_subscription =
13228                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13229            self.blame = Some(blame);
13230        }
13231    }
13232
13233    fn toggle_git_blame_inline_internal(
13234        &mut self,
13235        user_triggered: bool,
13236        window: &mut Window,
13237        cx: &mut Context<Self>,
13238    ) {
13239        if self.git_blame_inline_enabled {
13240            self.git_blame_inline_enabled = false;
13241            self.show_git_blame_inline = false;
13242            self.show_git_blame_inline_delay_task.take();
13243        } else {
13244            self.git_blame_inline_enabled = true;
13245            self.start_git_blame_inline(user_triggered, window, cx);
13246        }
13247
13248        cx.notify();
13249    }
13250
13251    fn start_git_blame_inline(
13252        &mut self,
13253        user_triggered: bool,
13254        window: &mut Window,
13255        cx: &mut Context<Self>,
13256    ) {
13257        self.start_git_blame(user_triggered, window, cx);
13258
13259        if ProjectSettings::get_global(cx)
13260            .git
13261            .inline_blame_delay()
13262            .is_some()
13263        {
13264            self.start_inline_blame_timer(window, cx);
13265        } else {
13266            self.show_git_blame_inline = true
13267        }
13268    }
13269
13270    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13271        self.blame.as_ref()
13272    }
13273
13274    pub fn show_git_blame_gutter(&self) -> bool {
13275        self.show_git_blame_gutter
13276    }
13277
13278    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13279        self.show_git_blame_gutter && self.has_blame_entries(cx)
13280    }
13281
13282    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13283        self.show_git_blame_inline
13284            && self.focus_handle.is_focused(window)
13285            && !self.newest_selection_head_on_empty_line(cx)
13286            && self.has_blame_entries(cx)
13287    }
13288
13289    fn has_blame_entries(&self, cx: &App) -> bool {
13290        self.blame()
13291            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13292    }
13293
13294    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13295        let cursor_anchor = self.selections.newest_anchor().head();
13296
13297        let snapshot = self.buffer.read(cx).snapshot(cx);
13298        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13299
13300        snapshot.line_len(buffer_row) == 0
13301    }
13302
13303    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13304        let buffer_and_selection = maybe!({
13305            let selection = self.selections.newest::<Point>(cx);
13306            let selection_range = selection.range();
13307
13308            let multi_buffer = self.buffer().read(cx);
13309            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13310            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13311
13312            let (buffer, range, _) = if selection.reversed {
13313                buffer_ranges.first()
13314            } else {
13315                buffer_ranges.last()
13316            }?;
13317
13318            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13319                ..text::ToPoint::to_point(&range.end, &buffer).row;
13320            Some((
13321                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13322                selection,
13323            ))
13324        });
13325
13326        let Some((buffer, selection)) = buffer_and_selection else {
13327            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13328        };
13329
13330        let Some(project) = self.project.as_ref() else {
13331            return Task::ready(Err(anyhow!("editor does not have project")));
13332        };
13333
13334        project.update(cx, |project, cx| {
13335            project.get_permalink_to_line(&buffer, selection, cx)
13336        })
13337    }
13338
13339    pub fn copy_permalink_to_line(
13340        &mut self,
13341        _: &CopyPermalinkToLine,
13342        window: &mut Window,
13343        cx: &mut Context<Self>,
13344    ) {
13345        let permalink_task = self.get_permalink_to_line(cx);
13346        let workspace = self.workspace();
13347
13348        cx.spawn_in(window, |_, mut cx| async move {
13349            match permalink_task.await {
13350                Ok(permalink) => {
13351                    cx.update(|_, cx| {
13352                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13353                    })
13354                    .ok();
13355                }
13356                Err(err) => {
13357                    let message = format!("Failed to copy permalink: {err}");
13358
13359                    Err::<(), anyhow::Error>(err).log_err();
13360
13361                    if let Some(workspace) = workspace {
13362                        workspace
13363                            .update_in(&mut cx, |workspace, _, cx| {
13364                                struct CopyPermalinkToLine;
13365
13366                                workspace.show_toast(
13367                                    Toast::new(
13368                                        NotificationId::unique::<CopyPermalinkToLine>(),
13369                                        message,
13370                                    ),
13371                                    cx,
13372                                )
13373                            })
13374                            .ok();
13375                    }
13376                }
13377            }
13378        })
13379        .detach();
13380    }
13381
13382    pub fn copy_file_location(
13383        &mut self,
13384        _: &CopyFileLocation,
13385        _: &mut Window,
13386        cx: &mut Context<Self>,
13387    ) {
13388        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13389        if let Some(file) = self.target_file(cx) {
13390            if let Some(path) = file.path().to_str() {
13391                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13392            }
13393        }
13394    }
13395
13396    pub fn open_permalink_to_line(
13397        &mut self,
13398        _: &OpenPermalinkToLine,
13399        window: &mut Window,
13400        cx: &mut Context<Self>,
13401    ) {
13402        let permalink_task = self.get_permalink_to_line(cx);
13403        let workspace = self.workspace();
13404
13405        cx.spawn_in(window, |_, mut cx| async move {
13406            match permalink_task.await {
13407                Ok(permalink) => {
13408                    cx.update(|_, cx| {
13409                        cx.open_url(permalink.as_ref());
13410                    })
13411                    .ok();
13412                }
13413                Err(err) => {
13414                    let message = format!("Failed to open permalink: {err}");
13415
13416                    Err::<(), anyhow::Error>(err).log_err();
13417
13418                    if let Some(workspace) = workspace {
13419                        workspace
13420                            .update(&mut cx, |workspace, cx| {
13421                                struct OpenPermalinkToLine;
13422
13423                                workspace.show_toast(
13424                                    Toast::new(
13425                                        NotificationId::unique::<OpenPermalinkToLine>(),
13426                                        message,
13427                                    ),
13428                                    cx,
13429                                )
13430                            })
13431                            .ok();
13432                    }
13433                }
13434            }
13435        })
13436        .detach();
13437    }
13438
13439    pub fn insert_uuid_v4(
13440        &mut self,
13441        _: &InsertUuidV4,
13442        window: &mut Window,
13443        cx: &mut Context<Self>,
13444    ) {
13445        self.insert_uuid(UuidVersion::V4, window, cx);
13446    }
13447
13448    pub fn insert_uuid_v7(
13449        &mut self,
13450        _: &InsertUuidV7,
13451        window: &mut Window,
13452        cx: &mut Context<Self>,
13453    ) {
13454        self.insert_uuid(UuidVersion::V7, window, cx);
13455    }
13456
13457    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13458        self.transact(window, cx, |this, window, cx| {
13459            let edits = this
13460                .selections
13461                .all::<Point>(cx)
13462                .into_iter()
13463                .map(|selection| {
13464                    let uuid = match version {
13465                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13466                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13467                    };
13468
13469                    (selection.range(), uuid.to_string())
13470                });
13471            this.edit(edits, cx);
13472            this.refresh_inline_completion(true, false, window, cx);
13473        });
13474    }
13475
13476    pub fn open_selections_in_multibuffer(
13477        &mut self,
13478        _: &OpenSelectionsInMultibuffer,
13479        window: &mut Window,
13480        cx: &mut Context<Self>,
13481    ) {
13482        let multibuffer = self.buffer.read(cx);
13483
13484        let Some(buffer) = multibuffer.as_singleton() else {
13485            return;
13486        };
13487
13488        let Some(workspace) = self.workspace() else {
13489            return;
13490        };
13491
13492        let locations = self
13493            .selections
13494            .disjoint_anchors()
13495            .iter()
13496            .map(|range| Location {
13497                buffer: buffer.clone(),
13498                range: range.start.text_anchor..range.end.text_anchor,
13499            })
13500            .collect::<Vec<_>>();
13501
13502        let title = multibuffer.title(cx).to_string();
13503
13504        cx.spawn_in(window, |_, mut cx| async move {
13505            workspace.update_in(&mut cx, |workspace, window, cx| {
13506                Self::open_locations_in_multibuffer(
13507                    workspace,
13508                    locations,
13509                    format!("Selections for '{title}'"),
13510                    false,
13511                    MultibufferSelectionMode::All,
13512                    window,
13513                    cx,
13514                );
13515            })
13516        })
13517        .detach();
13518    }
13519
13520    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13521    /// last highlight added will be used.
13522    ///
13523    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13524    pub fn highlight_rows<T: 'static>(
13525        &mut self,
13526        range: Range<Anchor>,
13527        color: Hsla,
13528        should_autoscroll: bool,
13529        cx: &mut Context<Self>,
13530    ) {
13531        let snapshot = self.buffer().read(cx).snapshot(cx);
13532        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13533        let ix = row_highlights.binary_search_by(|highlight| {
13534            Ordering::Equal
13535                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13536                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13537        });
13538
13539        if let Err(mut ix) = ix {
13540            let index = post_inc(&mut self.highlight_order);
13541
13542            // If this range intersects with the preceding highlight, then merge it with
13543            // the preceding highlight. Otherwise insert a new highlight.
13544            let mut merged = false;
13545            if ix > 0 {
13546                let prev_highlight = &mut row_highlights[ix - 1];
13547                if prev_highlight
13548                    .range
13549                    .end
13550                    .cmp(&range.start, &snapshot)
13551                    .is_ge()
13552                {
13553                    ix -= 1;
13554                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13555                        prev_highlight.range.end = range.end;
13556                    }
13557                    merged = true;
13558                    prev_highlight.index = index;
13559                    prev_highlight.color = color;
13560                    prev_highlight.should_autoscroll = should_autoscroll;
13561                }
13562            }
13563
13564            if !merged {
13565                row_highlights.insert(
13566                    ix,
13567                    RowHighlight {
13568                        range: range.clone(),
13569                        index,
13570                        color,
13571                        should_autoscroll,
13572                    },
13573                );
13574            }
13575
13576            // If any of the following highlights intersect with this one, merge them.
13577            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13578                let highlight = &row_highlights[ix];
13579                if next_highlight
13580                    .range
13581                    .start
13582                    .cmp(&highlight.range.end, &snapshot)
13583                    .is_le()
13584                {
13585                    if next_highlight
13586                        .range
13587                        .end
13588                        .cmp(&highlight.range.end, &snapshot)
13589                        .is_gt()
13590                    {
13591                        row_highlights[ix].range.end = next_highlight.range.end;
13592                    }
13593                    row_highlights.remove(ix + 1);
13594                } else {
13595                    break;
13596                }
13597            }
13598        }
13599    }
13600
13601    /// Remove any highlighted row ranges of the given type that intersect the
13602    /// given ranges.
13603    pub fn remove_highlighted_rows<T: 'static>(
13604        &mut self,
13605        ranges_to_remove: Vec<Range<Anchor>>,
13606        cx: &mut Context<Self>,
13607    ) {
13608        let snapshot = self.buffer().read(cx).snapshot(cx);
13609        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13610        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13611        row_highlights.retain(|highlight| {
13612            while let Some(range_to_remove) = ranges_to_remove.peek() {
13613                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13614                    Ordering::Less | Ordering::Equal => {
13615                        ranges_to_remove.next();
13616                    }
13617                    Ordering::Greater => {
13618                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13619                            Ordering::Less | Ordering::Equal => {
13620                                return false;
13621                            }
13622                            Ordering::Greater => break,
13623                        }
13624                    }
13625                }
13626            }
13627
13628            true
13629        })
13630    }
13631
13632    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13633    pub fn clear_row_highlights<T: 'static>(&mut self) {
13634        self.highlighted_rows.remove(&TypeId::of::<T>());
13635    }
13636
13637    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13638    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13639        self.highlighted_rows
13640            .get(&TypeId::of::<T>())
13641            .map_or(&[] as &[_], |vec| vec.as_slice())
13642            .iter()
13643            .map(|highlight| (highlight.range.clone(), highlight.color))
13644    }
13645
13646    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13647    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13648    /// Allows to ignore certain kinds of highlights.
13649    pub fn highlighted_display_rows(
13650        &self,
13651        window: &mut Window,
13652        cx: &mut App,
13653    ) -> BTreeMap<DisplayRow, Hsla> {
13654        let snapshot = self.snapshot(window, cx);
13655        let mut used_highlight_orders = HashMap::default();
13656        self.highlighted_rows
13657            .iter()
13658            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13659            .fold(
13660                BTreeMap::<DisplayRow, Hsla>::new(),
13661                |mut unique_rows, highlight| {
13662                    let start = highlight.range.start.to_display_point(&snapshot);
13663                    let end = highlight.range.end.to_display_point(&snapshot);
13664                    let start_row = start.row().0;
13665                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13666                        && end.column() == 0
13667                    {
13668                        end.row().0.saturating_sub(1)
13669                    } else {
13670                        end.row().0
13671                    };
13672                    for row in start_row..=end_row {
13673                        let used_index =
13674                            used_highlight_orders.entry(row).or_insert(highlight.index);
13675                        if highlight.index >= *used_index {
13676                            *used_index = highlight.index;
13677                            unique_rows.insert(DisplayRow(row), highlight.color);
13678                        }
13679                    }
13680                    unique_rows
13681                },
13682            )
13683    }
13684
13685    pub fn highlighted_display_row_for_autoscroll(
13686        &self,
13687        snapshot: &DisplaySnapshot,
13688    ) -> Option<DisplayRow> {
13689        self.highlighted_rows
13690            .values()
13691            .flat_map(|highlighted_rows| highlighted_rows.iter())
13692            .filter_map(|highlight| {
13693                if highlight.should_autoscroll {
13694                    Some(highlight.range.start.to_display_point(snapshot).row())
13695                } else {
13696                    None
13697                }
13698            })
13699            .min()
13700    }
13701
13702    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13703        self.highlight_background::<SearchWithinRange>(
13704            ranges,
13705            |colors| colors.editor_document_highlight_read_background,
13706            cx,
13707        )
13708    }
13709
13710    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13711        self.breadcrumb_header = Some(new_header);
13712    }
13713
13714    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13715        self.clear_background_highlights::<SearchWithinRange>(cx);
13716    }
13717
13718    pub fn highlight_background<T: 'static>(
13719        &mut self,
13720        ranges: &[Range<Anchor>],
13721        color_fetcher: fn(&ThemeColors) -> Hsla,
13722        cx: &mut Context<Self>,
13723    ) {
13724        self.background_highlights
13725            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13726        self.scrollbar_marker_state.dirty = true;
13727        cx.notify();
13728    }
13729
13730    pub fn clear_background_highlights<T: 'static>(
13731        &mut self,
13732        cx: &mut Context<Self>,
13733    ) -> Option<BackgroundHighlight> {
13734        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13735        if !text_highlights.1.is_empty() {
13736            self.scrollbar_marker_state.dirty = true;
13737            cx.notify();
13738        }
13739        Some(text_highlights)
13740    }
13741
13742    pub fn highlight_gutter<T: 'static>(
13743        &mut self,
13744        ranges: &[Range<Anchor>],
13745        color_fetcher: fn(&App) -> Hsla,
13746        cx: &mut Context<Self>,
13747    ) {
13748        self.gutter_highlights
13749            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13750        cx.notify();
13751    }
13752
13753    pub fn clear_gutter_highlights<T: 'static>(
13754        &mut self,
13755        cx: &mut Context<Self>,
13756    ) -> Option<GutterHighlight> {
13757        cx.notify();
13758        self.gutter_highlights.remove(&TypeId::of::<T>())
13759    }
13760
13761    #[cfg(feature = "test-support")]
13762    pub fn all_text_background_highlights(
13763        &self,
13764        window: &mut Window,
13765        cx: &mut Context<Self>,
13766    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13767        let snapshot = self.snapshot(window, cx);
13768        let buffer = &snapshot.buffer_snapshot;
13769        let start = buffer.anchor_before(0);
13770        let end = buffer.anchor_after(buffer.len());
13771        let theme = cx.theme().colors();
13772        self.background_highlights_in_range(start..end, &snapshot, theme)
13773    }
13774
13775    #[cfg(feature = "test-support")]
13776    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13777        let snapshot = self.buffer().read(cx).snapshot(cx);
13778
13779        let highlights = self
13780            .background_highlights
13781            .get(&TypeId::of::<items::BufferSearchHighlights>());
13782
13783        if let Some((_color, ranges)) = highlights {
13784            ranges
13785                .iter()
13786                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13787                .collect_vec()
13788        } else {
13789            vec![]
13790        }
13791    }
13792
13793    fn document_highlights_for_position<'a>(
13794        &'a self,
13795        position: Anchor,
13796        buffer: &'a MultiBufferSnapshot,
13797    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13798        let read_highlights = self
13799            .background_highlights
13800            .get(&TypeId::of::<DocumentHighlightRead>())
13801            .map(|h| &h.1);
13802        let write_highlights = self
13803            .background_highlights
13804            .get(&TypeId::of::<DocumentHighlightWrite>())
13805            .map(|h| &h.1);
13806        let left_position = position.bias_left(buffer);
13807        let right_position = position.bias_right(buffer);
13808        read_highlights
13809            .into_iter()
13810            .chain(write_highlights)
13811            .flat_map(move |ranges| {
13812                let start_ix = match ranges.binary_search_by(|probe| {
13813                    let cmp = probe.end.cmp(&left_position, buffer);
13814                    if cmp.is_ge() {
13815                        Ordering::Greater
13816                    } else {
13817                        Ordering::Less
13818                    }
13819                }) {
13820                    Ok(i) | Err(i) => i,
13821                };
13822
13823                ranges[start_ix..]
13824                    .iter()
13825                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13826            })
13827    }
13828
13829    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13830        self.background_highlights
13831            .get(&TypeId::of::<T>())
13832            .map_or(false, |(_, highlights)| !highlights.is_empty())
13833    }
13834
13835    pub fn background_highlights_in_range(
13836        &self,
13837        search_range: Range<Anchor>,
13838        display_snapshot: &DisplaySnapshot,
13839        theme: &ThemeColors,
13840    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13841        let mut results = Vec::new();
13842        for (color_fetcher, ranges) in self.background_highlights.values() {
13843            let color = color_fetcher(theme);
13844            let start_ix = match ranges.binary_search_by(|probe| {
13845                let cmp = probe
13846                    .end
13847                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13848                if cmp.is_gt() {
13849                    Ordering::Greater
13850                } else {
13851                    Ordering::Less
13852                }
13853            }) {
13854                Ok(i) | Err(i) => i,
13855            };
13856            for range in &ranges[start_ix..] {
13857                if range
13858                    .start
13859                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13860                    .is_ge()
13861                {
13862                    break;
13863                }
13864
13865                let start = range.start.to_display_point(display_snapshot);
13866                let end = range.end.to_display_point(display_snapshot);
13867                results.push((start..end, color))
13868            }
13869        }
13870        results
13871    }
13872
13873    pub fn background_highlight_row_ranges<T: 'static>(
13874        &self,
13875        search_range: Range<Anchor>,
13876        display_snapshot: &DisplaySnapshot,
13877        count: usize,
13878    ) -> Vec<RangeInclusive<DisplayPoint>> {
13879        let mut results = Vec::new();
13880        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13881            return vec![];
13882        };
13883
13884        let start_ix = match ranges.binary_search_by(|probe| {
13885            let cmp = probe
13886                .end
13887                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13888            if cmp.is_gt() {
13889                Ordering::Greater
13890            } else {
13891                Ordering::Less
13892            }
13893        }) {
13894            Ok(i) | Err(i) => i,
13895        };
13896        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13897            if let (Some(start_display), Some(end_display)) = (start, end) {
13898                results.push(
13899                    start_display.to_display_point(display_snapshot)
13900                        ..=end_display.to_display_point(display_snapshot),
13901                );
13902            }
13903        };
13904        let mut start_row: Option<Point> = None;
13905        let mut end_row: Option<Point> = None;
13906        if ranges.len() > count {
13907            return Vec::new();
13908        }
13909        for range in &ranges[start_ix..] {
13910            if range
13911                .start
13912                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13913                .is_ge()
13914            {
13915                break;
13916            }
13917            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13918            if let Some(current_row) = &end_row {
13919                if end.row == current_row.row {
13920                    continue;
13921                }
13922            }
13923            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13924            if start_row.is_none() {
13925                assert_eq!(end_row, None);
13926                start_row = Some(start);
13927                end_row = Some(end);
13928                continue;
13929            }
13930            if let Some(current_end) = end_row.as_mut() {
13931                if start.row > current_end.row + 1 {
13932                    push_region(start_row, end_row);
13933                    start_row = Some(start);
13934                    end_row = Some(end);
13935                } else {
13936                    // Merge two hunks.
13937                    *current_end = end;
13938                }
13939            } else {
13940                unreachable!();
13941            }
13942        }
13943        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13944        push_region(start_row, end_row);
13945        results
13946    }
13947
13948    pub fn gutter_highlights_in_range(
13949        &self,
13950        search_range: Range<Anchor>,
13951        display_snapshot: &DisplaySnapshot,
13952        cx: &App,
13953    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13954        let mut results = Vec::new();
13955        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13956            let color = color_fetcher(cx);
13957            let start_ix = match ranges.binary_search_by(|probe| {
13958                let cmp = probe
13959                    .end
13960                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13961                if cmp.is_gt() {
13962                    Ordering::Greater
13963                } else {
13964                    Ordering::Less
13965                }
13966            }) {
13967                Ok(i) | Err(i) => i,
13968            };
13969            for range in &ranges[start_ix..] {
13970                if range
13971                    .start
13972                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13973                    .is_ge()
13974                {
13975                    break;
13976                }
13977
13978                let start = range.start.to_display_point(display_snapshot);
13979                let end = range.end.to_display_point(display_snapshot);
13980                results.push((start..end, color))
13981            }
13982        }
13983        results
13984    }
13985
13986    /// Get the text ranges corresponding to the redaction query
13987    pub fn redacted_ranges(
13988        &self,
13989        search_range: Range<Anchor>,
13990        display_snapshot: &DisplaySnapshot,
13991        cx: &App,
13992    ) -> Vec<Range<DisplayPoint>> {
13993        display_snapshot
13994            .buffer_snapshot
13995            .redacted_ranges(search_range, |file| {
13996                if let Some(file) = file {
13997                    file.is_private()
13998                        && EditorSettings::get(
13999                            Some(SettingsLocation {
14000                                worktree_id: file.worktree_id(cx),
14001                                path: file.path().as_ref(),
14002                            }),
14003                            cx,
14004                        )
14005                        .redact_private_values
14006                } else {
14007                    false
14008                }
14009            })
14010            .map(|range| {
14011                range.start.to_display_point(display_snapshot)
14012                    ..range.end.to_display_point(display_snapshot)
14013            })
14014            .collect()
14015    }
14016
14017    pub fn highlight_text<T: 'static>(
14018        &mut self,
14019        ranges: Vec<Range<Anchor>>,
14020        style: HighlightStyle,
14021        cx: &mut Context<Self>,
14022    ) {
14023        self.display_map.update(cx, |map, _| {
14024            map.highlight_text(TypeId::of::<T>(), ranges, style)
14025        });
14026        cx.notify();
14027    }
14028
14029    pub(crate) fn highlight_inlays<T: 'static>(
14030        &mut self,
14031        highlights: Vec<InlayHighlight>,
14032        style: HighlightStyle,
14033        cx: &mut Context<Self>,
14034    ) {
14035        self.display_map.update(cx, |map, _| {
14036            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14037        });
14038        cx.notify();
14039    }
14040
14041    pub fn text_highlights<'a, T: 'static>(
14042        &'a self,
14043        cx: &'a App,
14044    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14045        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14046    }
14047
14048    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14049        let cleared = self
14050            .display_map
14051            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14052        if cleared {
14053            cx.notify();
14054        }
14055    }
14056
14057    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14058        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14059            && self.focus_handle.is_focused(window)
14060    }
14061
14062    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14063        self.show_cursor_when_unfocused = is_enabled;
14064        cx.notify();
14065    }
14066
14067    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14068        self.project
14069            .as_ref()
14070            .map(|project| project.read(cx).lsp_store())
14071    }
14072
14073    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14074        cx.notify();
14075    }
14076
14077    fn on_buffer_event(
14078        &mut self,
14079        multibuffer: &Entity<MultiBuffer>,
14080        event: &multi_buffer::Event,
14081        window: &mut Window,
14082        cx: &mut Context<Self>,
14083    ) {
14084        match event {
14085            multi_buffer::Event::Edited {
14086                singleton_buffer_edited,
14087                edited_buffer: buffer_edited,
14088            } => {
14089                self.scrollbar_marker_state.dirty = true;
14090                self.active_indent_guides_state.dirty = true;
14091                self.refresh_active_diagnostics(cx);
14092                self.refresh_code_actions(window, cx);
14093                if self.has_active_inline_completion() {
14094                    self.update_visible_inline_completion(window, cx);
14095                }
14096                if let Some(buffer) = buffer_edited {
14097                    let buffer_id = buffer.read(cx).remote_id();
14098                    if !self.registered_buffers.contains_key(&buffer_id) {
14099                        if let Some(lsp_store) = self.lsp_store(cx) {
14100                            lsp_store.update(cx, |lsp_store, cx| {
14101                                self.registered_buffers.insert(
14102                                    buffer_id,
14103                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
14104                                );
14105                            })
14106                        }
14107                    }
14108                }
14109                cx.emit(EditorEvent::BufferEdited);
14110                cx.emit(SearchEvent::MatchesInvalidated);
14111                if *singleton_buffer_edited {
14112                    if let Some(project) = &self.project {
14113                        let project = project.read(cx);
14114                        #[allow(clippy::mutable_key_type)]
14115                        let languages_affected = multibuffer
14116                            .read(cx)
14117                            .all_buffers()
14118                            .into_iter()
14119                            .filter_map(|buffer| {
14120                                let buffer = buffer.read(cx);
14121                                let language = buffer.language()?;
14122                                if project.is_local()
14123                                    && project
14124                                        .language_servers_for_local_buffer(buffer, cx)
14125                                        .count()
14126                                        == 0
14127                                {
14128                                    None
14129                                } else {
14130                                    Some(language)
14131                                }
14132                            })
14133                            .cloned()
14134                            .collect::<HashSet<_>>();
14135                        if !languages_affected.is_empty() {
14136                            self.refresh_inlay_hints(
14137                                InlayHintRefreshReason::BufferEdited(languages_affected),
14138                                cx,
14139                            );
14140                        }
14141                    }
14142                }
14143
14144                let Some(project) = &self.project else { return };
14145                let (telemetry, is_via_ssh) = {
14146                    let project = project.read(cx);
14147                    let telemetry = project.client().telemetry().clone();
14148                    let is_via_ssh = project.is_via_ssh();
14149                    (telemetry, is_via_ssh)
14150                };
14151                refresh_linked_ranges(self, window, cx);
14152                telemetry.log_edit_event("editor", is_via_ssh);
14153            }
14154            multi_buffer::Event::ExcerptsAdded {
14155                buffer,
14156                predecessor,
14157                excerpts,
14158            } => {
14159                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14160                let buffer_id = buffer.read(cx).remote_id();
14161                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14162                    if let Some(project) = &self.project {
14163                        self.load_diff_task = Some(
14164                            get_uncommitted_diff_for_buffer(
14165                                project,
14166                                [buffer.clone()],
14167                                self.buffer.clone(),
14168                                cx,
14169                            )
14170                            .shared(),
14171                        );
14172                    }
14173                }
14174                cx.emit(EditorEvent::ExcerptsAdded {
14175                    buffer: buffer.clone(),
14176                    predecessor: *predecessor,
14177                    excerpts: excerpts.clone(),
14178                });
14179                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14180            }
14181            multi_buffer::Event::ExcerptsRemoved { ids } => {
14182                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14183                let buffer = self.buffer.read(cx);
14184                self.registered_buffers
14185                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14186                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14187            }
14188            multi_buffer::Event::ExcerptsEdited { ids } => {
14189                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14190            }
14191            multi_buffer::Event::ExcerptsExpanded { ids } => {
14192                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14193                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14194            }
14195            multi_buffer::Event::Reparsed(buffer_id) => {
14196                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14197
14198                cx.emit(EditorEvent::Reparsed(*buffer_id));
14199            }
14200            multi_buffer::Event::DiffHunksToggled => {
14201                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14202            }
14203            multi_buffer::Event::LanguageChanged(buffer_id) => {
14204                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14205                cx.emit(EditorEvent::Reparsed(*buffer_id));
14206                cx.notify();
14207            }
14208            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14209            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14210            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14211                cx.emit(EditorEvent::TitleChanged)
14212            }
14213            // multi_buffer::Event::DiffBaseChanged => {
14214            //     self.scrollbar_marker_state.dirty = true;
14215            //     cx.emit(EditorEvent::DiffBaseChanged);
14216            //     cx.notify();
14217            // }
14218            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14219            multi_buffer::Event::DiagnosticsUpdated => {
14220                self.refresh_active_diagnostics(cx);
14221                self.scrollbar_marker_state.dirty = true;
14222                cx.notify();
14223            }
14224            _ => {}
14225        };
14226    }
14227
14228    fn on_display_map_changed(
14229        &mut self,
14230        _: Entity<DisplayMap>,
14231        _: &mut Window,
14232        cx: &mut Context<Self>,
14233    ) {
14234        cx.notify();
14235    }
14236
14237    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14238        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14239        self.refresh_inline_completion(true, false, window, cx);
14240        self.refresh_inlay_hints(
14241            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14242                self.selections.newest_anchor().head(),
14243                &self.buffer.read(cx).snapshot(cx),
14244                cx,
14245            )),
14246            cx,
14247        );
14248
14249        let old_cursor_shape = self.cursor_shape;
14250
14251        {
14252            let editor_settings = EditorSettings::get_global(cx);
14253            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14254            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14255            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14256        }
14257
14258        if old_cursor_shape != self.cursor_shape {
14259            cx.emit(EditorEvent::CursorShapeChanged);
14260        }
14261
14262        let project_settings = ProjectSettings::get_global(cx);
14263        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14264
14265        if self.mode == EditorMode::Full {
14266            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14267            if self.git_blame_inline_enabled != inline_blame_enabled {
14268                self.toggle_git_blame_inline_internal(false, window, cx);
14269            }
14270        }
14271
14272        cx.notify();
14273    }
14274
14275    pub fn set_searchable(&mut self, searchable: bool) {
14276        self.searchable = searchable;
14277    }
14278
14279    pub fn searchable(&self) -> bool {
14280        self.searchable
14281    }
14282
14283    fn open_proposed_changes_editor(
14284        &mut self,
14285        _: &OpenProposedChangesEditor,
14286        window: &mut Window,
14287        cx: &mut Context<Self>,
14288    ) {
14289        let Some(workspace) = self.workspace() else {
14290            cx.propagate();
14291            return;
14292        };
14293
14294        let selections = self.selections.all::<usize>(cx);
14295        let multi_buffer = self.buffer.read(cx);
14296        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14297        let mut new_selections_by_buffer = HashMap::default();
14298        for selection in selections {
14299            for (buffer, range, _) in
14300                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14301            {
14302                let mut range = range.to_point(buffer);
14303                range.start.column = 0;
14304                range.end.column = buffer.line_len(range.end.row);
14305                new_selections_by_buffer
14306                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14307                    .or_insert(Vec::new())
14308                    .push(range)
14309            }
14310        }
14311
14312        let proposed_changes_buffers = new_selections_by_buffer
14313            .into_iter()
14314            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14315            .collect::<Vec<_>>();
14316        let proposed_changes_editor = cx.new(|cx| {
14317            ProposedChangesEditor::new(
14318                "Proposed changes",
14319                proposed_changes_buffers,
14320                self.project.clone(),
14321                window,
14322                cx,
14323            )
14324        });
14325
14326        window.defer(cx, move |window, cx| {
14327            workspace.update(cx, |workspace, cx| {
14328                workspace.active_pane().update(cx, |pane, cx| {
14329                    pane.add_item(
14330                        Box::new(proposed_changes_editor),
14331                        true,
14332                        true,
14333                        None,
14334                        window,
14335                        cx,
14336                    );
14337                });
14338            });
14339        });
14340    }
14341
14342    pub fn open_excerpts_in_split(
14343        &mut self,
14344        _: &OpenExcerptsSplit,
14345        window: &mut Window,
14346        cx: &mut Context<Self>,
14347    ) {
14348        self.open_excerpts_common(None, true, window, cx)
14349    }
14350
14351    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14352        self.open_excerpts_common(None, false, window, cx)
14353    }
14354
14355    fn open_excerpts_common(
14356        &mut self,
14357        jump_data: Option<JumpData>,
14358        split: bool,
14359        window: &mut Window,
14360        cx: &mut Context<Self>,
14361    ) {
14362        let Some(workspace) = self.workspace() else {
14363            cx.propagate();
14364            return;
14365        };
14366
14367        if self.buffer.read(cx).is_singleton() {
14368            cx.propagate();
14369            return;
14370        }
14371
14372        let mut new_selections_by_buffer = HashMap::default();
14373        match &jump_data {
14374            Some(JumpData::MultiBufferPoint {
14375                excerpt_id,
14376                position,
14377                anchor,
14378                line_offset_from_top,
14379            }) => {
14380                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14381                if let Some(buffer) = multi_buffer_snapshot
14382                    .buffer_id_for_excerpt(*excerpt_id)
14383                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14384                {
14385                    let buffer_snapshot = buffer.read(cx).snapshot();
14386                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14387                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14388                    } else {
14389                        buffer_snapshot.clip_point(*position, Bias::Left)
14390                    };
14391                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14392                    new_selections_by_buffer.insert(
14393                        buffer,
14394                        (
14395                            vec![jump_to_offset..jump_to_offset],
14396                            Some(*line_offset_from_top),
14397                        ),
14398                    );
14399                }
14400            }
14401            Some(JumpData::MultiBufferRow {
14402                row,
14403                line_offset_from_top,
14404            }) => {
14405                let point = MultiBufferPoint::new(row.0, 0);
14406                if let Some((buffer, buffer_point, _)) =
14407                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14408                {
14409                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14410                    new_selections_by_buffer
14411                        .entry(buffer)
14412                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14413                        .0
14414                        .push(buffer_offset..buffer_offset)
14415                }
14416            }
14417            None => {
14418                let selections = self.selections.all::<usize>(cx);
14419                let multi_buffer = self.buffer.read(cx);
14420                for selection in selections {
14421                    for (buffer, mut range, _) in multi_buffer
14422                        .snapshot(cx)
14423                        .range_to_buffer_ranges(selection.range())
14424                    {
14425                        // When editing branch buffers, jump to the corresponding location
14426                        // in their base buffer.
14427                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14428                        let buffer = buffer_handle.read(cx);
14429                        if let Some(base_buffer) = buffer.base_buffer() {
14430                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14431                            buffer_handle = base_buffer;
14432                        }
14433
14434                        if selection.reversed {
14435                            mem::swap(&mut range.start, &mut range.end);
14436                        }
14437                        new_selections_by_buffer
14438                            .entry(buffer_handle)
14439                            .or_insert((Vec::new(), None))
14440                            .0
14441                            .push(range)
14442                    }
14443                }
14444            }
14445        }
14446
14447        if new_selections_by_buffer.is_empty() {
14448            return;
14449        }
14450
14451        // We defer the pane interaction because we ourselves are a workspace item
14452        // and activating a new item causes the pane to call a method on us reentrantly,
14453        // which panics if we're on the stack.
14454        window.defer(cx, move |window, cx| {
14455            workspace.update(cx, |workspace, cx| {
14456                let pane = if split {
14457                    workspace.adjacent_pane(window, cx)
14458                } else {
14459                    workspace.active_pane().clone()
14460                };
14461
14462                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14463                    let editor = buffer
14464                        .read(cx)
14465                        .file()
14466                        .is_none()
14467                        .then(|| {
14468                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14469                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14470                            // Instead, we try to activate the existing editor in the pane first.
14471                            let (editor, pane_item_index) =
14472                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14473                                    let editor = item.downcast::<Editor>()?;
14474                                    let singleton_buffer =
14475                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14476                                    if singleton_buffer == buffer {
14477                                        Some((editor, i))
14478                                    } else {
14479                                        None
14480                                    }
14481                                })?;
14482                            pane.update(cx, |pane, cx| {
14483                                pane.activate_item(pane_item_index, true, true, window, cx)
14484                            });
14485                            Some(editor)
14486                        })
14487                        .flatten()
14488                        .unwrap_or_else(|| {
14489                            workspace.open_project_item::<Self>(
14490                                pane.clone(),
14491                                buffer,
14492                                true,
14493                                true,
14494                                window,
14495                                cx,
14496                            )
14497                        });
14498
14499                    editor.update(cx, |editor, cx| {
14500                        let autoscroll = match scroll_offset {
14501                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14502                            None => Autoscroll::newest(),
14503                        };
14504                        let nav_history = editor.nav_history.take();
14505                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14506                            s.select_ranges(ranges);
14507                        });
14508                        editor.nav_history = nav_history;
14509                    });
14510                }
14511            })
14512        });
14513    }
14514
14515    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14516        let snapshot = self.buffer.read(cx).read(cx);
14517        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14518        Some(
14519            ranges
14520                .iter()
14521                .map(move |range| {
14522                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14523                })
14524                .collect(),
14525        )
14526    }
14527
14528    fn selection_replacement_ranges(
14529        &self,
14530        range: Range<OffsetUtf16>,
14531        cx: &mut App,
14532    ) -> Vec<Range<OffsetUtf16>> {
14533        let selections = self.selections.all::<OffsetUtf16>(cx);
14534        let newest_selection = selections
14535            .iter()
14536            .max_by_key(|selection| selection.id)
14537            .unwrap();
14538        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14539        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14540        let snapshot = self.buffer.read(cx).read(cx);
14541        selections
14542            .into_iter()
14543            .map(|mut selection| {
14544                selection.start.0 =
14545                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14546                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14547                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14548                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14549            })
14550            .collect()
14551    }
14552
14553    fn report_editor_event(
14554        &self,
14555        event_type: &'static str,
14556        file_extension: Option<String>,
14557        cx: &App,
14558    ) {
14559        if cfg!(any(test, feature = "test-support")) {
14560            return;
14561        }
14562
14563        let Some(project) = &self.project else { return };
14564
14565        // If None, we are in a file without an extension
14566        let file = self
14567            .buffer
14568            .read(cx)
14569            .as_singleton()
14570            .and_then(|b| b.read(cx).file());
14571        let file_extension = file_extension.or(file
14572            .as_ref()
14573            .and_then(|file| Path::new(file.file_name(cx)).extension())
14574            .and_then(|e| e.to_str())
14575            .map(|a| a.to_string()));
14576
14577        let vim_mode = cx
14578            .global::<SettingsStore>()
14579            .raw_user_settings()
14580            .get("vim_mode")
14581            == Some(&serde_json::Value::Bool(true));
14582
14583        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14584        let copilot_enabled = edit_predictions_provider
14585            == language::language_settings::EditPredictionProvider::Copilot;
14586        let copilot_enabled_for_language = self
14587            .buffer
14588            .read(cx)
14589            .settings_at(0, cx)
14590            .show_edit_predictions;
14591
14592        let project = project.read(cx);
14593        telemetry::event!(
14594            event_type,
14595            file_extension,
14596            vim_mode,
14597            copilot_enabled,
14598            copilot_enabled_for_language,
14599            edit_predictions_provider,
14600            is_via_ssh = project.is_via_ssh(),
14601        );
14602    }
14603
14604    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14605    /// with each line being an array of {text, highlight} objects.
14606    fn copy_highlight_json(
14607        &mut self,
14608        _: &CopyHighlightJson,
14609        window: &mut Window,
14610        cx: &mut Context<Self>,
14611    ) {
14612        #[derive(Serialize)]
14613        struct Chunk<'a> {
14614            text: String,
14615            highlight: Option<&'a str>,
14616        }
14617
14618        let snapshot = self.buffer.read(cx).snapshot(cx);
14619        let range = self
14620            .selected_text_range(false, window, cx)
14621            .and_then(|selection| {
14622                if selection.range.is_empty() {
14623                    None
14624                } else {
14625                    Some(selection.range)
14626                }
14627            })
14628            .unwrap_or_else(|| 0..snapshot.len());
14629
14630        let chunks = snapshot.chunks(range, true);
14631        let mut lines = Vec::new();
14632        let mut line: VecDeque<Chunk> = VecDeque::new();
14633
14634        let Some(style) = self.style.as_ref() else {
14635            return;
14636        };
14637
14638        for chunk in chunks {
14639            let highlight = chunk
14640                .syntax_highlight_id
14641                .and_then(|id| id.name(&style.syntax));
14642            let mut chunk_lines = chunk.text.split('\n').peekable();
14643            while let Some(text) = chunk_lines.next() {
14644                let mut merged_with_last_token = false;
14645                if let Some(last_token) = line.back_mut() {
14646                    if last_token.highlight == highlight {
14647                        last_token.text.push_str(text);
14648                        merged_with_last_token = true;
14649                    }
14650                }
14651
14652                if !merged_with_last_token {
14653                    line.push_back(Chunk {
14654                        text: text.into(),
14655                        highlight,
14656                    });
14657                }
14658
14659                if chunk_lines.peek().is_some() {
14660                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14661                        line.pop_front();
14662                    }
14663                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14664                        line.pop_back();
14665                    }
14666
14667                    lines.push(mem::take(&mut line));
14668                }
14669            }
14670        }
14671
14672        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14673            return;
14674        };
14675        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14676    }
14677
14678    pub fn open_context_menu(
14679        &mut self,
14680        _: &OpenContextMenu,
14681        window: &mut Window,
14682        cx: &mut Context<Self>,
14683    ) {
14684        self.request_autoscroll(Autoscroll::newest(), cx);
14685        let position = self.selections.newest_display(cx).start;
14686        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14687    }
14688
14689    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14690        &self.inlay_hint_cache
14691    }
14692
14693    pub fn replay_insert_event(
14694        &mut self,
14695        text: &str,
14696        relative_utf16_range: Option<Range<isize>>,
14697        window: &mut Window,
14698        cx: &mut Context<Self>,
14699    ) {
14700        if !self.input_enabled {
14701            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14702            return;
14703        }
14704        if let Some(relative_utf16_range) = relative_utf16_range {
14705            let selections = self.selections.all::<OffsetUtf16>(cx);
14706            self.change_selections(None, window, cx, |s| {
14707                let new_ranges = selections.into_iter().map(|range| {
14708                    let start = OffsetUtf16(
14709                        range
14710                            .head()
14711                            .0
14712                            .saturating_add_signed(relative_utf16_range.start),
14713                    );
14714                    let end = OffsetUtf16(
14715                        range
14716                            .head()
14717                            .0
14718                            .saturating_add_signed(relative_utf16_range.end),
14719                    );
14720                    start..end
14721                });
14722                s.select_ranges(new_ranges);
14723            });
14724        }
14725
14726        self.handle_input(text, window, cx);
14727    }
14728
14729    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14730        let Some(provider) = self.semantics_provider.as_ref() else {
14731            return false;
14732        };
14733
14734        let mut supports = false;
14735        self.buffer().read(cx).for_each_buffer(|buffer| {
14736            supports |= provider.supports_inlay_hints(buffer, cx);
14737        });
14738        supports
14739    }
14740
14741    pub fn is_focused(&self, window: &Window) -> bool {
14742        self.focus_handle.is_focused(window)
14743    }
14744
14745    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14746        cx.emit(EditorEvent::Focused);
14747
14748        if let Some(descendant) = self
14749            .last_focused_descendant
14750            .take()
14751            .and_then(|descendant| descendant.upgrade())
14752        {
14753            window.focus(&descendant);
14754        } else {
14755            if let Some(blame) = self.blame.as_ref() {
14756                blame.update(cx, GitBlame::focus)
14757            }
14758
14759            self.blink_manager.update(cx, BlinkManager::enable);
14760            self.show_cursor_names(window, cx);
14761            self.buffer.update(cx, |buffer, cx| {
14762                buffer.finalize_last_transaction(cx);
14763                if self.leader_peer_id.is_none() {
14764                    buffer.set_active_selections(
14765                        &self.selections.disjoint_anchors(),
14766                        self.selections.line_mode,
14767                        self.cursor_shape,
14768                        cx,
14769                    );
14770                }
14771            });
14772        }
14773    }
14774
14775    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14776        cx.emit(EditorEvent::FocusedIn)
14777    }
14778
14779    fn handle_focus_out(
14780        &mut self,
14781        event: FocusOutEvent,
14782        _window: &mut Window,
14783        _cx: &mut Context<Self>,
14784    ) {
14785        if event.blurred != self.focus_handle {
14786            self.last_focused_descendant = Some(event.blurred);
14787        }
14788    }
14789
14790    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14791        self.blink_manager.update(cx, BlinkManager::disable);
14792        self.buffer
14793            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14794
14795        if let Some(blame) = self.blame.as_ref() {
14796            blame.update(cx, GitBlame::blur)
14797        }
14798        if !self.hover_state.focused(window, cx) {
14799            hide_hover(self, cx);
14800        }
14801
14802        self.hide_context_menu(window, cx);
14803        self.discard_inline_completion(false, cx);
14804        cx.emit(EditorEvent::Blurred);
14805        cx.notify();
14806    }
14807
14808    pub fn register_action<A: Action>(
14809        &mut self,
14810        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14811    ) -> Subscription {
14812        let id = self.next_editor_action_id.post_inc();
14813        let listener = Arc::new(listener);
14814        self.editor_actions.borrow_mut().insert(
14815            id,
14816            Box::new(move |window, _| {
14817                let listener = listener.clone();
14818                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14819                    let action = action.downcast_ref().unwrap();
14820                    if phase == DispatchPhase::Bubble {
14821                        listener(action, window, cx)
14822                    }
14823                })
14824            }),
14825        );
14826
14827        let editor_actions = self.editor_actions.clone();
14828        Subscription::new(move || {
14829            editor_actions.borrow_mut().remove(&id);
14830        })
14831    }
14832
14833    pub fn file_header_size(&self) -> u32 {
14834        FILE_HEADER_HEIGHT
14835    }
14836
14837    pub fn revert(
14838        &mut self,
14839        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14840        window: &mut Window,
14841        cx: &mut Context<Self>,
14842    ) {
14843        self.buffer().update(cx, |multi_buffer, cx| {
14844            for (buffer_id, changes) in revert_changes {
14845                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14846                    buffer.update(cx, |buffer, cx| {
14847                        buffer.edit(
14848                            changes.into_iter().map(|(range, text)| {
14849                                (range, text.to_string().map(Arc::<str>::from))
14850                            }),
14851                            None,
14852                            cx,
14853                        );
14854                    });
14855                }
14856            }
14857        });
14858        self.change_selections(None, window, cx, |selections| selections.refresh());
14859    }
14860
14861    pub fn to_pixel_point(
14862        &self,
14863        source: multi_buffer::Anchor,
14864        editor_snapshot: &EditorSnapshot,
14865        window: &mut Window,
14866    ) -> Option<gpui::Point<Pixels>> {
14867        let source_point = source.to_display_point(editor_snapshot);
14868        self.display_to_pixel_point(source_point, editor_snapshot, window)
14869    }
14870
14871    pub fn display_to_pixel_point(
14872        &self,
14873        source: DisplayPoint,
14874        editor_snapshot: &EditorSnapshot,
14875        window: &mut Window,
14876    ) -> Option<gpui::Point<Pixels>> {
14877        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14878        let text_layout_details = self.text_layout_details(window);
14879        let scroll_top = text_layout_details
14880            .scroll_anchor
14881            .scroll_position(editor_snapshot)
14882            .y;
14883
14884        if source.row().as_f32() < scroll_top.floor() {
14885            return None;
14886        }
14887        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14888        let source_y = line_height * (source.row().as_f32() - scroll_top);
14889        Some(gpui::Point::new(source_x, source_y))
14890    }
14891
14892    pub fn has_visible_completions_menu(&self) -> bool {
14893        !self.edit_prediction_preview_is_active()
14894            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14895                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14896            })
14897    }
14898
14899    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14900        self.addons
14901            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14902    }
14903
14904    pub fn unregister_addon<T: Addon>(&mut self) {
14905        self.addons.remove(&std::any::TypeId::of::<T>());
14906    }
14907
14908    pub fn addon<T: Addon>(&self) -> Option<&T> {
14909        let type_id = std::any::TypeId::of::<T>();
14910        self.addons
14911            .get(&type_id)
14912            .and_then(|item| item.to_any().downcast_ref::<T>())
14913    }
14914
14915    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14916        let text_layout_details = self.text_layout_details(window);
14917        let style = &text_layout_details.editor_style;
14918        let font_id = window.text_system().resolve_font(&style.text.font());
14919        let font_size = style.text.font_size.to_pixels(window.rem_size());
14920        let line_height = style.text.line_height_in_pixels(window.rem_size());
14921        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14922
14923        gpui::Size::new(em_width, line_height)
14924    }
14925
14926    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14927        self.load_diff_task.clone()
14928    }
14929}
14930
14931fn get_uncommitted_diff_for_buffer(
14932    project: &Entity<Project>,
14933    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14934    buffer: Entity<MultiBuffer>,
14935    cx: &mut App,
14936) -> Task<()> {
14937    let mut tasks = Vec::new();
14938    project.update(cx, |project, cx| {
14939        for buffer in buffers {
14940            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14941        }
14942    });
14943    cx.spawn(|mut cx| async move {
14944        let diffs = futures::future::join_all(tasks).await;
14945        buffer
14946            .update(&mut cx, |buffer, cx| {
14947                for diff in diffs.into_iter().flatten() {
14948                    buffer.add_diff(diff, cx);
14949                }
14950            })
14951            .ok();
14952    })
14953}
14954
14955fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14956    let tab_size = tab_size.get() as usize;
14957    let mut width = offset;
14958
14959    for ch in text.chars() {
14960        width += if ch == '\t' {
14961            tab_size - (width % tab_size)
14962        } else {
14963            1
14964        };
14965    }
14966
14967    width - offset
14968}
14969
14970#[cfg(test)]
14971mod tests {
14972    use super::*;
14973
14974    #[test]
14975    fn test_string_size_with_expanded_tabs() {
14976        let nz = |val| NonZeroU32::new(val).unwrap();
14977        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14978        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14979        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14980        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14981        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14982        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14983        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14984        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14985    }
14986}
14987
14988/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14989struct WordBreakingTokenizer<'a> {
14990    input: &'a str,
14991}
14992
14993impl<'a> WordBreakingTokenizer<'a> {
14994    fn new(input: &'a str) -> Self {
14995        Self { input }
14996    }
14997}
14998
14999fn is_char_ideographic(ch: char) -> bool {
15000    use unicode_script::Script::*;
15001    use unicode_script::UnicodeScript;
15002    matches!(ch.script(), Han | Tangut | Yi)
15003}
15004
15005fn is_grapheme_ideographic(text: &str) -> bool {
15006    text.chars().any(is_char_ideographic)
15007}
15008
15009fn is_grapheme_whitespace(text: &str) -> bool {
15010    text.chars().any(|x| x.is_whitespace())
15011}
15012
15013fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15014    text.chars().next().map_or(false, |ch| {
15015        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15016    })
15017}
15018
15019#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15020struct WordBreakToken<'a> {
15021    token: &'a str,
15022    grapheme_len: usize,
15023    is_whitespace: bool,
15024}
15025
15026impl<'a> Iterator for WordBreakingTokenizer<'a> {
15027    /// Yields a span, the count of graphemes in the token, and whether it was
15028    /// whitespace. Note that it also breaks at word boundaries.
15029    type Item = WordBreakToken<'a>;
15030
15031    fn next(&mut self) -> Option<Self::Item> {
15032        use unicode_segmentation::UnicodeSegmentation;
15033        if self.input.is_empty() {
15034            return None;
15035        }
15036
15037        let mut iter = self.input.graphemes(true).peekable();
15038        let mut offset = 0;
15039        let mut graphemes = 0;
15040        if let Some(first_grapheme) = iter.next() {
15041            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15042            offset += first_grapheme.len();
15043            graphemes += 1;
15044            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15045                if let Some(grapheme) = iter.peek().copied() {
15046                    if should_stay_with_preceding_ideograph(grapheme) {
15047                        offset += grapheme.len();
15048                        graphemes += 1;
15049                    }
15050                }
15051            } else {
15052                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15053                let mut next_word_bound = words.peek().copied();
15054                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15055                    next_word_bound = words.next();
15056                }
15057                while let Some(grapheme) = iter.peek().copied() {
15058                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15059                        break;
15060                    };
15061                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15062                        break;
15063                    };
15064                    offset += grapheme.len();
15065                    graphemes += 1;
15066                    iter.next();
15067                }
15068            }
15069            let token = &self.input[..offset];
15070            self.input = &self.input[offset..];
15071            if is_whitespace {
15072                Some(WordBreakToken {
15073                    token: " ",
15074                    grapheme_len: 1,
15075                    is_whitespace: true,
15076                })
15077            } else {
15078                Some(WordBreakToken {
15079                    token,
15080                    grapheme_len: graphemes,
15081                    is_whitespace: false,
15082                })
15083            }
15084        } else {
15085            None
15086        }
15087    }
15088}
15089
15090#[test]
15091fn test_word_breaking_tokenizer() {
15092    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15093        ("", &[]),
15094        ("  ", &[(" ", 1, true)]),
15095        ("Ʒ", &[("Ʒ", 1, false)]),
15096        ("Ǽ", &[("Ǽ", 1, false)]),
15097        ("", &[("", 1, false)]),
15098        ("⋑⋑", &[("⋑⋑", 2, false)]),
15099        (
15100            "原理,进而",
15101            &[
15102                ("", 1, false),
15103                ("理,", 2, false),
15104                ("", 1, false),
15105                ("", 1, false),
15106            ],
15107        ),
15108        (
15109            "hello world",
15110            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15111        ),
15112        (
15113            "hello, world",
15114            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15115        ),
15116        (
15117            "  hello world",
15118            &[
15119                (" ", 1, true),
15120                ("hello", 5, false),
15121                (" ", 1, true),
15122                ("world", 5, false),
15123            ],
15124        ),
15125        (
15126            "这是什么 \n 钢笔",
15127            &[
15128                ("", 1, false),
15129                ("", 1, false),
15130                ("", 1, false),
15131                ("", 1, false),
15132                (" ", 1, true),
15133                ("", 1, false),
15134                ("", 1, false),
15135            ],
15136        ),
15137        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15138    ];
15139
15140    for (input, result) in tests {
15141        assert_eq!(
15142            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15143            result
15144                .iter()
15145                .copied()
15146                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15147                    token,
15148                    grapheme_len,
15149                    is_whitespace,
15150                })
15151                .collect::<Vec<_>>()
15152        );
15153    }
15154}
15155
15156fn wrap_with_prefix(
15157    line_prefix: String,
15158    unwrapped_text: String,
15159    wrap_column: usize,
15160    tab_size: NonZeroU32,
15161) -> String {
15162    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15163    let mut wrapped_text = String::new();
15164    let mut current_line = line_prefix.clone();
15165
15166    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15167    let mut current_line_len = line_prefix_len;
15168    for WordBreakToken {
15169        token,
15170        grapheme_len,
15171        is_whitespace,
15172    } in tokenizer
15173    {
15174        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15175            wrapped_text.push_str(current_line.trim_end());
15176            wrapped_text.push('\n');
15177            current_line.truncate(line_prefix.len());
15178            current_line_len = line_prefix_len;
15179            if !is_whitespace {
15180                current_line.push_str(token);
15181                current_line_len += grapheme_len;
15182            }
15183        } else if !is_whitespace {
15184            current_line.push_str(token);
15185            current_line_len += grapheme_len;
15186        } else if current_line_len != line_prefix_len {
15187            current_line.push(' ');
15188            current_line_len += 1;
15189        }
15190    }
15191
15192    if !current_line.is_empty() {
15193        wrapped_text.push_str(&current_line);
15194    }
15195    wrapped_text
15196}
15197
15198#[test]
15199fn test_wrap_with_prefix() {
15200    assert_eq!(
15201        wrap_with_prefix(
15202            "# ".to_string(),
15203            "abcdefg".to_string(),
15204            4,
15205            NonZeroU32::new(4).unwrap()
15206        ),
15207        "# abcdefg"
15208    );
15209    assert_eq!(
15210        wrap_with_prefix(
15211            "".to_string(),
15212            "\thello world".to_string(),
15213            8,
15214            NonZeroU32::new(4).unwrap()
15215        ),
15216        "hello\nworld"
15217    );
15218    assert_eq!(
15219        wrap_with_prefix(
15220            "// ".to_string(),
15221            "xx \nyy zz aa bb cc".to_string(),
15222            12,
15223            NonZeroU32::new(4).unwrap()
15224        ),
15225        "// xx yy zz\n// aa bb cc"
15226    );
15227    assert_eq!(
15228        wrap_with_prefix(
15229            String::new(),
15230            "这是什么 \n 钢笔".to_string(),
15231            3,
15232            NonZeroU32::new(4).unwrap()
15233        ),
15234        "这是什\n么 钢\n"
15235    );
15236}
15237
15238pub trait CollaborationHub {
15239    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15240    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15241    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15242}
15243
15244impl CollaborationHub for Entity<Project> {
15245    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15246        self.read(cx).collaborators()
15247    }
15248
15249    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15250        self.read(cx).user_store().read(cx).participant_indices()
15251    }
15252
15253    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15254        let this = self.read(cx);
15255        let user_ids = this.collaborators().values().map(|c| c.user_id);
15256        this.user_store().read_with(cx, |user_store, cx| {
15257            user_store.participant_names(user_ids, cx)
15258        })
15259    }
15260}
15261
15262pub trait SemanticsProvider {
15263    fn hover(
15264        &self,
15265        buffer: &Entity<Buffer>,
15266        position: text::Anchor,
15267        cx: &mut App,
15268    ) -> Option<Task<Vec<project::Hover>>>;
15269
15270    fn inlay_hints(
15271        &self,
15272        buffer_handle: Entity<Buffer>,
15273        range: Range<text::Anchor>,
15274        cx: &mut App,
15275    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15276
15277    fn resolve_inlay_hint(
15278        &self,
15279        hint: InlayHint,
15280        buffer_handle: Entity<Buffer>,
15281        server_id: LanguageServerId,
15282        cx: &mut App,
15283    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15284
15285    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15286
15287    fn document_highlights(
15288        &self,
15289        buffer: &Entity<Buffer>,
15290        position: text::Anchor,
15291        cx: &mut App,
15292    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15293
15294    fn definitions(
15295        &self,
15296        buffer: &Entity<Buffer>,
15297        position: text::Anchor,
15298        kind: GotoDefinitionKind,
15299        cx: &mut App,
15300    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15301
15302    fn range_for_rename(
15303        &self,
15304        buffer: &Entity<Buffer>,
15305        position: text::Anchor,
15306        cx: &mut App,
15307    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15308
15309    fn perform_rename(
15310        &self,
15311        buffer: &Entity<Buffer>,
15312        position: text::Anchor,
15313        new_name: String,
15314        cx: &mut App,
15315    ) -> Option<Task<Result<ProjectTransaction>>>;
15316}
15317
15318pub trait CompletionProvider {
15319    fn completions(
15320        &self,
15321        buffer: &Entity<Buffer>,
15322        buffer_position: text::Anchor,
15323        trigger: CompletionContext,
15324        window: &mut Window,
15325        cx: &mut Context<Editor>,
15326    ) -> Task<Result<Vec<Completion>>>;
15327
15328    fn resolve_completions(
15329        &self,
15330        buffer: Entity<Buffer>,
15331        completion_indices: Vec<usize>,
15332        completions: Rc<RefCell<Box<[Completion]>>>,
15333        cx: &mut Context<Editor>,
15334    ) -> Task<Result<bool>>;
15335
15336    fn apply_additional_edits_for_completion(
15337        &self,
15338        _buffer: Entity<Buffer>,
15339        _completions: Rc<RefCell<Box<[Completion]>>>,
15340        _completion_index: usize,
15341        _push_to_history: bool,
15342        _cx: &mut Context<Editor>,
15343    ) -> Task<Result<Option<language::Transaction>>> {
15344        Task::ready(Ok(None))
15345    }
15346
15347    fn is_completion_trigger(
15348        &self,
15349        buffer: &Entity<Buffer>,
15350        position: language::Anchor,
15351        text: &str,
15352        trigger_in_words: bool,
15353        cx: &mut Context<Editor>,
15354    ) -> bool;
15355
15356    fn sort_completions(&self) -> bool {
15357        true
15358    }
15359}
15360
15361pub trait CodeActionProvider {
15362    fn id(&self) -> Arc<str>;
15363
15364    fn code_actions(
15365        &self,
15366        buffer: &Entity<Buffer>,
15367        range: Range<text::Anchor>,
15368        window: &mut Window,
15369        cx: &mut App,
15370    ) -> Task<Result<Vec<CodeAction>>>;
15371
15372    fn apply_code_action(
15373        &self,
15374        buffer_handle: Entity<Buffer>,
15375        action: CodeAction,
15376        excerpt_id: ExcerptId,
15377        push_to_history: bool,
15378        window: &mut Window,
15379        cx: &mut App,
15380    ) -> Task<Result<ProjectTransaction>>;
15381}
15382
15383impl CodeActionProvider for Entity<Project> {
15384    fn id(&self) -> Arc<str> {
15385        "project".into()
15386    }
15387
15388    fn code_actions(
15389        &self,
15390        buffer: &Entity<Buffer>,
15391        range: Range<text::Anchor>,
15392        _window: &mut Window,
15393        cx: &mut App,
15394    ) -> Task<Result<Vec<CodeAction>>> {
15395        self.update(cx, |project, cx| {
15396            project.code_actions(buffer, range, None, cx)
15397        })
15398    }
15399
15400    fn apply_code_action(
15401        &self,
15402        buffer_handle: Entity<Buffer>,
15403        action: CodeAction,
15404        _excerpt_id: ExcerptId,
15405        push_to_history: bool,
15406        _window: &mut Window,
15407        cx: &mut App,
15408    ) -> Task<Result<ProjectTransaction>> {
15409        self.update(cx, |project, cx| {
15410            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15411        })
15412    }
15413}
15414
15415fn snippet_completions(
15416    project: &Project,
15417    buffer: &Entity<Buffer>,
15418    buffer_position: text::Anchor,
15419    cx: &mut App,
15420) -> Task<Result<Vec<Completion>>> {
15421    let language = buffer.read(cx).language_at(buffer_position);
15422    let language_name = language.as_ref().map(|language| language.lsp_id());
15423    let snippet_store = project.snippets().read(cx);
15424    let snippets = snippet_store.snippets_for(language_name, cx);
15425
15426    if snippets.is_empty() {
15427        return Task::ready(Ok(vec![]));
15428    }
15429    let snapshot = buffer.read(cx).text_snapshot();
15430    let chars: String = snapshot
15431        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15432        .collect();
15433
15434    let scope = language.map(|language| language.default_scope());
15435    let executor = cx.background_executor().clone();
15436
15437    cx.background_executor().spawn(async move {
15438        let classifier = CharClassifier::new(scope).for_completion(true);
15439        let mut last_word = chars
15440            .chars()
15441            .take_while(|c| classifier.is_word(*c))
15442            .collect::<String>();
15443        last_word = last_word.chars().rev().collect();
15444
15445        if last_word.is_empty() {
15446            return Ok(vec![]);
15447        }
15448
15449        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15450        let to_lsp = |point: &text::Anchor| {
15451            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15452            point_to_lsp(end)
15453        };
15454        let lsp_end = to_lsp(&buffer_position);
15455
15456        let candidates = snippets
15457            .iter()
15458            .enumerate()
15459            .flat_map(|(ix, snippet)| {
15460                snippet
15461                    .prefix
15462                    .iter()
15463                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15464            })
15465            .collect::<Vec<StringMatchCandidate>>();
15466
15467        let mut matches = fuzzy::match_strings(
15468            &candidates,
15469            &last_word,
15470            last_word.chars().any(|c| c.is_uppercase()),
15471            100,
15472            &Default::default(),
15473            executor,
15474        )
15475        .await;
15476
15477        // Remove all candidates where the query's start does not match the start of any word in the candidate
15478        if let Some(query_start) = last_word.chars().next() {
15479            matches.retain(|string_match| {
15480                split_words(&string_match.string).any(|word| {
15481                    // Check that the first codepoint of the word as lowercase matches the first
15482                    // codepoint of the query as lowercase
15483                    word.chars()
15484                        .flat_map(|codepoint| codepoint.to_lowercase())
15485                        .zip(query_start.to_lowercase())
15486                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15487                })
15488            });
15489        }
15490
15491        let matched_strings = matches
15492            .into_iter()
15493            .map(|m| m.string)
15494            .collect::<HashSet<_>>();
15495
15496        let result: Vec<Completion> = snippets
15497            .into_iter()
15498            .filter_map(|snippet| {
15499                let matching_prefix = snippet
15500                    .prefix
15501                    .iter()
15502                    .find(|prefix| matched_strings.contains(*prefix))?;
15503                let start = as_offset - last_word.len();
15504                let start = snapshot.anchor_before(start);
15505                let range = start..buffer_position;
15506                let lsp_start = to_lsp(&start);
15507                let lsp_range = lsp::Range {
15508                    start: lsp_start,
15509                    end: lsp_end,
15510                };
15511                Some(Completion {
15512                    old_range: range,
15513                    new_text: snippet.body.clone(),
15514                    resolved: false,
15515                    label: CodeLabel {
15516                        text: matching_prefix.clone(),
15517                        runs: vec![],
15518                        filter_range: 0..matching_prefix.len(),
15519                    },
15520                    server_id: LanguageServerId(usize::MAX),
15521                    documentation: snippet
15522                        .description
15523                        .clone()
15524                        .map(CompletionDocumentation::SingleLine),
15525                    lsp_completion: lsp::CompletionItem {
15526                        label: snippet.prefix.first().unwrap().clone(),
15527                        kind: Some(CompletionItemKind::SNIPPET),
15528                        label_details: snippet.description.as_ref().map(|description| {
15529                            lsp::CompletionItemLabelDetails {
15530                                detail: Some(description.clone()),
15531                                description: None,
15532                            }
15533                        }),
15534                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15535                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15536                            lsp::InsertReplaceEdit {
15537                                new_text: snippet.body.clone(),
15538                                insert: lsp_range,
15539                                replace: lsp_range,
15540                            },
15541                        )),
15542                        filter_text: Some(snippet.body.clone()),
15543                        sort_text: Some(char::MAX.to_string()),
15544                        ..Default::default()
15545                    },
15546                    confirm: None,
15547                })
15548            })
15549            .collect();
15550
15551        Ok(result)
15552    })
15553}
15554
15555impl CompletionProvider for Entity<Project> {
15556    fn completions(
15557        &self,
15558        buffer: &Entity<Buffer>,
15559        buffer_position: text::Anchor,
15560        options: CompletionContext,
15561        _window: &mut Window,
15562        cx: &mut Context<Editor>,
15563    ) -> Task<Result<Vec<Completion>>> {
15564        self.update(cx, |project, cx| {
15565            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15566            let project_completions = project.completions(buffer, buffer_position, options, cx);
15567            cx.background_executor().spawn(async move {
15568                let mut completions = project_completions.await?;
15569                let snippets_completions = snippets.await?;
15570                completions.extend(snippets_completions);
15571                Ok(completions)
15572            })
15573        })
15574    }
15575
15576    fn resolve_completions(
15577        &self,
15578        buffer: Entity<Buffer>,
15579        completion_indices: Vec<usize>,
15580        completions: Rc<RefCell<Box<[Completion]>>>,
15581        cx: &mut Context<Editor>,
15582    ) -> Task<Result<bool>> {
15583        self.update(cx, |project, cx| {
15584            project.lsp_store().update(cx, |lsp_store, cx| {
15585                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15586            })
15587        })
15588    }
15589
15590    fn apply_additional_edits_for_completion(
15591        &self,
15592        buffer: Entity<Buffer>,
15593        completions: Rc<RefCell<Box<[Completion]>>>,
15594        completion_index: usize,
15595        push_to_history: bool,
15596        cx: &mut Context<Editor>,
15597    ) -> Task<Result<Option<language::Transaction>>> {
15598        self.update(cx, |project, cx| {
15599            project.lsp_store().update(cx, |lsp_store, cx| {
15600                lsp_store.apply_additional_edits_for_completion(
15601                    buffer,
15602                    completions,
15603                    completion_index,
15604                    push_to_history,
15605                    cx,
15606                )
15607            })
15608        })
15609    }
15610
15611    fn is_completion_trigger(
15612        &self,
15613        buffer: &Entity<Buffer>,
15614        position: language::Anchor,
15615        text: &str,
15616        trigger_in_words: bool,
15617        cx: &mut Context<Editor>,
15618    ) -> bool {
15619        let mut chars = text.chars();
15620        let char = if let Some(char) = chars.next() {
15621            char
15622        } else {
15623            return false;
15624        };
15625        if chars.next().is_some() {
15626            return false;
15627        }
15628
15629        let buffer = buffer.read(cx);
15630        let snapshot = buffer.snapshot();
15631        if !snapshot.settings_at(position, cx).show_completions_on_input {
15632            return false;
15633        }
15634        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15635        if trigger_in_words && classifier.is_word(char) {
15636            return true;
15637        }
15638
15639        buffer.completion_triggers().contains(text)
15640    }
15641}
15642
15643impl SemanticsProvider for Entity<Project> {
15644    fn hover(
15645        &self,
15646        buffer: &Entity<Buffer>,
15647        position: text::Anchor,
15648        cx: &mut App,
15649    ) -> Option<Task<Vec<project::Hover>>> {
15650        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15651    }
15652
15653    fn document_highlights(
15654        &self,
15655        buffer: &Entity<Buffer>,
15656        position: text::Anchor,
15657        cx: &mut App,
15658    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15659        Some(self.update(cx, |project, cx| {
15660            project.document_highlights(buffer, position, cx)
15661        }))
15662    }
15663
15664    fn definitions(
15665        &self,
15666        buffer: &Entity<Buffer>,
15667        position: text::Anchor,
15668        kind: GotoDefinitionKind,
15669        cx: &mut App,
15670    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15671        Some(self.update(cx, |project, cx| match kind {
15672            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15673            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15674            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15675            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15676        }))
15677    }
15678
15679    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15680        // TODO: make this work for remote projects
15681        self.read(cx)
15682            .language_servers_for_local_buffer(buffer.read(cx), cx)
15683            .any(
15684                |(_, server)| match server.capabilities().inlay_hint_provider {
15685                    Some(lsp::OneOf::Left(enabled)) => enabled,
15686                    Some(lsp::OneOf::Right(_)) => true,
15687                    None => false,
15688                },
15689            )
15690    }
15691
15692    fn inlay_hints(
15693        &self,
15694        buffer_handle: Entity<Buffer>,
15695        range: Range<text::Anchor>,
15696        cx: &mut App,
15697    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15698        Some(self.update(cx, |project, cx| {
15699            project.inlay_hints(buffer_handle, range, cx)
15700        }))
15701    }
15702
15703    fn resolve_inlay_hint(
15704        &self,
15705        hint: InlayHint,
15706        buffer_handle: Entity<Buffer>,
15707        server_id: LanguageServerId,
15708        cx: &mut App,
15709    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15710        Some(self.update(cx, |project, cx| {
15711            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15712        }))
15713    }
15714
15715    fn range_for_rename(
15716        &self,
15717        buffer: &Entity<Buffer>,
15718        position: text::Anchor,
15719        cx: &mut App,
15720    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15721        Some(self.update(cx, |project, cx| {
15722            let buffer = buffer.clone();
15723            let task = project.prepare_rename(buffer.clone(), position, cx);
15724            cx.spawn(|_, mut cx| async move {
15725                Ok(match task.await? {
15726                    PrepareRenameResponse::Success(range) => Some(range),
15727                    PrepareRenameResponse::InvalidPosition => None,
15728                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15729                        // Fallback on using TreeSitter info to determine identifier range
15730                        buffer.update(&mut cx, |buffer, _| {
15731                            let snapshot = buffer.snapshot();
15732                            let (range, kind) = snapshot.surrounding_word(position);
15733                            if kind != Some(CharKind::Word) {
15734                                return None;
15735                            }
15736                            Some(
15737                                snapshot.anchor_before(range.start)
15738                                    ..snapshot.anchor_after(range.end),
15739                            )
15740                        })?
15741                    }
15742                })
15743            })
15744        }))
15745    }
15746
15747    fn perform_rename(
15748        &self,
15749        buffer: &Entity<Buffer>,
15750        position: text::Anchor,
15751        new_name: String,
15752        cx: &mut App,
15753    ) -> Option<Task<Result<ProjectTransaction>>> {
15754        Some(self.update(cx, |project, cx| {
15755            project.perform_rename(buffer.clone(), position, new_name, cx)
15756        }))
15757    }
15758}
15759
15760fn inlay_hint_settings(
15761    location: Anchor,
15762    snapshot: &MultiBufferSnapshot,
15763    cx: &mut Context<Editor>,
15764) -> InlayHintSettings {
15765    let file = snapshot.file_at(location);
15766    let language = snapshot.language_at(location).map(|l| l.name());
15767    language_settings(language, file, cx).inlay_hints
15768}
15769
15770fn consume_contiguous_rows(
15771    contiguous_row_selections: &mut Vec<Selection<Point>>,
15772    selection: &Selection<Point>,
15773    display_map: &DisplaySnapshot,
15774    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15775) -> (MultiBufferRow, MultiBufferRow) {
15776    contiguous_row_selections.push(selection.clone());
15777    let start_row = MultiBufferRow(selection.start.row);
15778    let mut end_row = ending_row(selection, display_map);
15779
15780    while let Some(next_selection) = selections.peek() {
15781        if next_selection.start.row <= end_row.0 {
15782            end_row = ending_row(next_selection, display_map);
15783            contiguous_row_selections.push(selections.next().unwrap().clone());
15784        } else {
15785            break;
15786        }
15787    }
15788    (start_row, end_row)
15789}
15790
15791fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15792    if next_selection.end.column > 0 || next_selection.is_empty() {
15793        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15794    } else {
15795        MultiBufferRow(next_selection.end.row)
15796    }
15797}
15798
15799impl EditorSnapshot {
15800    pub fn remote_selections_in_range<'a>(
15801        &'a self,
15802        range: &'a Range<Anchor>,
15803        collaboration_hub: &dyn CollaborationHub,
15804        cx: &'a App,
15805    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15806        let participant_names = collaboration_hub.user_names(cx);
15807        let participant_indices = collaboration_hub.user_participant_indices(cx);
15808        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15809        let collaborators_by_replica_id = collaborators_by_peer_id
15810            .iter()
15811            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15812            .collect::<HashMap<_, _>>();
15813        self.buffer_snapshot
15814            .selections_in_range(range, false)
15815            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15816                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15817                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15818                let user_name = participant_names.get(&collaborator.user_id).cloned();
15819                Some(RemoteSelection {
15820                    replica_id,
15821                    selection,
15822                    cursor_shape,
15823                    line_mode,
15824                    participant_index,
15825                    peer_id: collaborator.peer_id,
15826                    user_name,
15827                })
15828            })
15829    }
15830
15831    pub fn hunks_for_ranges(
15832        &self,
15833        ranges: impl Iterator<Item = Range<Point>>,
15834    ) -> Vec<MultiBufferDiffHunk> {
15835        let mut hunks = Vec::new();
15836        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15837            HashMap::default();
15838        for query_range in ranges {
15839            let query_rows =
15840                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15841            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15842                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15843            ) {
15844                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15845                // when the caret is just above or just below the deleted hunk.
15846                let allow_adjacent = hunk.status().is_removed();
15847                let related_to_selection = if allow_adjacent {
15848                    hunk.row_range.overlaps(&query_rows)
15849                        || hunk.row_range.start == query_rows.end
15850                        || hunk.row_range.end == query_rows.start
15851                } else {
15852                    hunk.row_range.overlaps(&query_rows)
15853                };
15854                if related_to_selection {
15855                    if !processed_buffer_rows
15856                        .entry(hunk.buffer_id)
15857                        .or_default()
15858                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15859                    {
15860                        continue;
15861                    }
15862                    hunks.push(hunk);
15863                }
15864            }
15865        }
15866
15867        hunks
15868    }
15869
15870    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15871        self.display_snapshot.buffer_snapshot.language_at(position)
15872    }
15873
15874    pub fn is_focused(&self) -> bool {
15875        self.is_focused
15876    }
15877
15878    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15879        self.placeholder_text.as_ref()
15880    }
15881
15882    pub fn scroll_position(&self) -> gpui::Point<f32> {
15883        self.scroll_anchor.scroll_position(&self.display_snapshot)
15884    }
15885
15886    fn gutter_dimensions(
15887        &self,
15888        font_id: FontId,
15889        font_size: Pixels,
15890        max_line_number_width: Pixels,
15891        cx: &App,
15892    ) -> Option<GutterDimensions> {
15893        if !self.show_gutter {
15894            return None;
15895        }
15896
15897        let descent = cx.text_system().descent(font_id, font_size);
15898        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15899        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15900
15901        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15902            matches!(
15903                ProjectSettings::get_global(cx).git.git_gutter,
15904                Some(GitGutterSetting::TrackedFiles)
15905            )
15906        });
15907        let gutter_settings = EditorSettings::get_global(cx).gutter;
15908        let show_line_numbers = self
15909            .show_line_numbers
15910            .unwrap_or(gutter_settings.line_numbers);
15911        let line_gutter_width = if show_line_numbers {
15912            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15913            let min_width_for_number_on_gutter = em_advance * 4.0;
15914            max_line_number_width.max(min_width_for_number_on_gutter)
15915        } else {
15916            0.0.into()
15917        };
15918
15919        let show_code_actions = self
15920            .show_code_actions
15921            .unwrap_or(gutter_settings.code_actions);
15922
15923        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15924
15925        let git_blame_entries_width =
15926            self.git_blame_gutter_max_author_length
15927                .map(|max_author_length| {
15928                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15929
15930                    /// The number of characters to dedicate to gaps and margins.
15931                    const SPACING_WIDTH: usize = 4;
15932
15933                    let max_char_count = max_author_length
15934                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15935                        + ::git::SHORT_SHA_LENGTH
15936                        + MAX_RELATIVE_TIMESTAMP.len()
15937                        + SPACING_WIDTH;
15938
15939                    em_advance * max_char_count
15940                });
15941
15942        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15943        left_padding += if show_code_actions || show_runnables {
15944            em_width * 3.0
15945        } else if show_git_gutter && show_line_numbers {
15946            em_width * 2.0
15947        } else if show_git_gutter || show_line_numbers {
15948            em_width
15949        } else {
15950            px(0.)
15951        };
15952
15953        let right_padding = if gutter_settings.folds && show_line_numbers {
15954            em_width * 4.0
15955        } else if gutter_settings.folds {
15956            em_width * 3.0
15957        } else if show_line_numbers {
15958            em_width
15959        } else {
15960            px(0.)
15961        };
15962
15963        Some(GutterDimensions {
15964            left_padding,
15965            right_padding,
15966            width: line_gutter_width + left_padding + right_padding,
15967            margin: -descent,
15968            git_blame_entries_width,
15969        })
15970    }
15971
15972    pub fn render_crease_toggle(
15973        &self,
15974        buffer_row: MultiBufferRow,
15975        row_contains_cursor: bool,
15976        editor: Entity<Editor>,
15977        window: &mut Window,
15978        cx: &mut App,
15979    ) -> Option<AnyElement> {
15980        let folded = self.is_line_folded(buffer_row);
15981        let mut is_foldable = false;
15982
15983        if let Some(crease) = self
15984            .crease_snapshot
15985            .query_row(buffer_row, &self.buffer_snapshot)
15986        {
15987            is_foldable = true;
15988            match crease {
15989                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15990                    if let Some(render_toggle) = render_toggle {
15991                        let toggle_callback =
15992                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15993                                if folded {
15994                                    editor.update(cx, |editor, cx| {
15995                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15996                                    });
15997                                } else {
15998                                    editor.update(cx, |editor, cx| {
15999                                        editor.unfold_at(
16000                                            &crate::UnfoldAt { buffer_row },
16001                                            window,
16002                                            cx,
16003                                        )
16004                                    });
16005                                }
16006                            });
16007                        return Some((render_toggle)(
16008                            buffer_row,
16009                            folded,
16010                            toggle_callback,
16011                            window,
16012                            cx,
16013                        ));
16014                    }
16015                }
16016            }
16017        }
16018
16019        is_foldable |= self.starts_indent(buffer_row);
16020
16021        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16022            Some(
16023                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16024                    .toggle_state(folded)
16025                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16026                        if folded {
16027                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16028                        } else {
16029                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16030                        }
16031                    }))
16032                    .into_any_element(),
16033            )
16034        } else {
16035            None
16036        }
16037    }
16038
16039    pub fn render_crease_trailer(
16040        &self,
16041        buffer_row: MultiBufferRow,
16042        window: &mut Window,
16043        cx: &mut App,
16044    ) -> Option<AnyElement> {
16045        let folded = self.is_line_folded(buffer_row);
16046        if let Crease::Inline { render_trailer, .. } = self
16047            .crease_snapshot
16048            .query_row(buffer_row, &self.buffer_snapshot)?
16049        {
16050            let render_trailer = render_trailer.as_ref()?;
16051            Some(render_trailer(buffer_row, folded, window, cx))
16052        } else {
16053            None
16054        }
16055    }
16056}
16057
16058impl Deref for EditorSnapshot {
16059    type Target = DisplaySnapshot;
16060
16061    fn deref(&self) -> &Self::Target {
16062        &self.display_snapshot
16063    }
16064}
16065
16066#[derive(Clone, Debug, PartialEq, Eq)]
16067pub enum EditorEvent {
16068    InputIgnored {
16069        text: Arc<str>,
16070    },
16071    InputHandled {
16072        utf16_range_to_replace: Option<Range<isize>>,
16073        text: Arc<str>,
16074    },
16075    ExcerptsAdded {
16076        buffer: Entity<Buffer>,
16077        predecessor: ExcerptId,
16078        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16079    },
16080    ExcerptsRemoved {
16081        ids: Vec<ExcerptId>,
16082    },
16083    BufferFoldToggled {
16084        ids: Vec<ExcerptId>,
16085        folded: bool,
16086    },
16087    ExcerptsEdited {
16088        ids: Vec<ExcerptId>,
16089    },
16090    ExcerptsExpanded {
16091        ids: Vec<ExcerptId>,
16092    },
16093    BufferEdited,
16094    Edited {
16095        transaction_id: clock::Lamport,
16096    },
16097    Reparsed(BufferId),
16098    Focused,
16099    FocusedIn,
16100    Blurred,
16101    DirtyChanged,
16102    Saved,
16103    TitleChanged,
16104    DiffBaseChanged,
16105    SelectionsChanged {
16106        local: bool,
16107    },
16108    ScrollPositionChanged {
16109        local: bool,
16110        autoscroll: bool,
16111    },
16112    Closed,
16113    TransactionUndone {
16114        transaction_id: clock::Lamport,
16115    },
16116    TransactionBegun {
16117        transaction_id: clock::Lamport,
16118    },
16119    Reloaded,
16120    CursorShapeChanged,
16121}
16122
16123impl EventEmitter<EditorEvent> for Editor {}
16124
16125impl Focusable for Editor {
16126    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16127        self.focus_handle.clone()
16128    }
16129}
16130
16131impl Render for Editor {
16132    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16133        let settings = ThemeSettings::get_global(cx);
16134
16135        let mut text_style = match self.mode {
16136            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16137                color: cx.theme().colors().editor_foreground,
16138                font_family: settings.ui_font.family.clone(),
16139                font_features: settings.ui_font.features.clone(),
16140                font_fallbacks: settings.ui_font.fallbacks.clone(),
16141                font_size: rems(0.875).into(),
16142                font_weight: settings.ui_font.weight,
16143                line_height: relative(settings.buffer_line_height.value()),
16144                ..Default::default()
16145            },
16146            EditorMode::Full => TextStyle {
16147                color: cx.theme().colors().editor_foreground,
16148                font_family: settings.buffer_font.family.clone(),
16149                font_features: settings.buffer_font.features.clone(),
16150                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16151                font_size: settings.buffer_font_size().into(),
16152                font_weight: settings.buffer_font.weight,
16153                line_height: relative(settings.buffer_line_height.value()),
16154                ..Default::default()
16155            },
16156        };
16157        if let Some(text_style_refinement) = &self.text_style_refinement {
16158            text_style.refine(text_style_refinement)
16159        }
16160
16161        let background = match self.mode {
16162            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16163            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16164            EditorMode::Full => cx.theme().colors().editor_background,
16165        };
16166
16167        EditorElement::new(
16168            &cx.entity(),
16169            EditorStyle {
16170                background,
16171                local_player: cx.theme().players().local(),
16172                text: text_style,
16173                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16174                syntax: cx.theme().syntax().clone(),
16175                status: cx.theme().status().clone(),
16176                inlay_hints_style: make_inlay_hints_style(cx),
16177                inline_completion_styles: make_suggestion_styles(cx),
16178                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16179            },
16180        )
16181    }
16182}
16183
16184impl EntityInputHandler for Editor {
16185    fn text_for_range(
16186        &mut self,
16187        range_utf16: Range<usize>,
16188        adjusted_range: &mut Option<Range<usize>>,
16189        _: &mut Window,
16190        cx: &mut Context<Self>,
16191    ) -> Option<String> {
16192        let snapshot = self.buffer.read(cx).read(cx);
16193        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16194        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16195        if (start.0..end.0) != range_utf16 {
16196            adjusted_range.replace(start.0..end.0);
16197        }
16198        Some(snapshot.text_for_range(start..end).collect())
16199    }
16200
16201    fn selected_text_range(
16202        &mut self,
16203        ignore_disabled_input: bool,
16204        _: &mut Window,
16205        cx: &mut Context<Self>,
16206    ) -> Option<UTF16Selection> {
16207        // Prevent the IME menu from appearing when holding down an alphabetic key
16208        // while input is disabled.
16209        if !ignore_disabled_input && !self.input_enabled {
16210            return None;
16211        }
16212
16213        let selection = self.selections.newest::<OffsetUtf16>(cx);
16214        let range = selection.range();
16215
16216        Some(UTF16Selection {
16217            range: range.start.0..range.end.0,
16218            reversed: selection.reversed,
16219        })
16220    }
16221
16222    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16223        let snapshot = self.buffer.read(cx).read(cx);
16224        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16225        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16226    }
16227
16228    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16229        self.clear_highlights::<InputComposition>(cx);
16230        self.ime_transaction.take();
16231    }
16232
16233    fn replace_text_in_range(
16234        &mut self,
16235        range_utf16: Option<Range<usize>>,
16236        text: &str,
16237        window: &mut Window,
16238        cx: &mut Context<Self>,
16239    ) {
16240        if !self.input_enabled {
16241            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16242            return;
16243        }
16244
16245        self.transact(window, cx, |this, window, cx| {
16246            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16247                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16248                Some(this.selection_replacement_ranges(range_utf16, cx))
16249            } else {
16250                this.marked_text_ranges(cx)
16251            };
16252
16253            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16254                let newest_selection_id = this.selections.newest_anchor().id;
16255                this.selections
16256                    .all::<OffsetUtf16>(cx)
16257                    .iter()
16258                    .zip(ranges_to_replace.iter())
16259                    .find_map(|(selection, range)| {
16260                        if selection.id == newest_selection_id {
16261                            Some(
16262                                (range.start.0 as isize - selection.head().0 as isize)
16263                                    ..(range.end.0 as isize - selection.head().0 as isize),
16264                            )
16265                        } else {
16266                            None
16267                        }
16268                    })
16269            });
16270
16271            cx.emit(EditorEvent::InputHandled {
16272                utf16_range_to_replace: range_to_replace,
16273                text: text.into(),
16274            });
16275
16276            if let Some(new_selected_ranges) = new_selected_ranges {
16277                this.change_selections(None, window, cx, |selections| {
16278                    selections.select_ranges(new_selected_ranges)
16279                });
16280                this.backspace(&Default::default(), window, cx);
16281            }
16282
16283            this.handle_input(text, window, cx);
16284        });
16285
16286        if let Some(transaction) = self.ime_transaction {
16287            self.buffer.update(cx, |buffer, cx| {
16288                buffer.group_until_transaction(transaction, cx);
16289            });
16290        }
16291
16292        self.unmark_text(window, cx);
16293    }
16294
16295    fn replace_and_mark_text_in_range(
16296        &mut self,
16297        range_utf16: Option<Range<usize>>,
16298        text: &str,
16299        new_selected_range_utf16: Option<Range<usize>>,
16300        window: &mut Window,
16301        cx: &mut Context<Self>,
16302    ) {
16303        if !self.input_enabled {
16304            return;
16305        }
16306
16307        let transaction = self.transact(window, cx, |this, window, cx| {
16308            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16309                let snapshot = this.buffer.read(cx).read(cx);
16310                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16311                    for marked_range in &mut marked_ranges {
16312                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16313                        marked_range.start.0 += relative_range_utf16.start;
16314                        marked_range.start =
16315                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16316                        marked_range.end =
16317                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16318                    }
16319                }
16320                Some(marked_ranges)
16321            } else if let Some(range_utf16) = range_utf16 {
16322                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16323                Some(this.selection_replacement_ranges(range_utf16, cx))
16324            } else {
16325                None
16326            };
16327
16328            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16329                let newest_selection_id = this.selections.newest_anchor().id;
16330                this.selections
16331                    .all::<OffsetUtf16>(cx)
16332                    .iter()
16333                    .zip(ranges_to_replace.iter())
16334                    .find_map(|(selection, range)| {
16335                        if selection.id == newest_selection_id {
16336                            Some(
16337                                (range.start.0 as isize - selection.head().0 as isize)
16338                                    ..(range.end.0 as isize - selection.head().0 as isize),
16339                            )
16340                        } else {
16341                            None
16342                        }
16343                    })
16344            });
16345
16346            cx.emit(EditorEvent::InputHandled {
16347                utf16_range_to_replace: range_to_replace,
16348                text: text.into(),
16349            });
16350
16351            if let Some(ranges) = ranges_to_replace {
16352                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16353            }
16354
16355            let marked_ranges = {
16356                let snapshot = this.buffer.read(cx).read(cx);
16357                this.selections
16358                    .disjoint_anchors()
16359                    .iter()
16360                    .map(|selection| {
16361                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16362                    })
16363                    .collect::<Vec<_>>()
16364            };
16365
16366            if text.is_empty() {
16367                this.unmark_text(window, cx);
16368            } else {
16369                this.highlight_text::<InputComposition>(
16370                    marked_ranges.clone(),
16371                    HighlightStyle {
16372                        underline: Some(UnderlineStyle {
16373                            thickness: px(1.),
16374                            color: None,
16375                            wavy: false,
16376                        }),
16377                        ..Default::default()
16378                    },
16379                    cx,
16380                );
16381            }
16382
16383            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16384            let use_autoclose = this.use_autoclose;
16385            let use_auto_surround = this.use_auto_surround;
16386            this.set_use_autoclose(false);
16387            this.set_use_auto_surround(false);
16388            this.handle_input(text, window, cx);
16389            this.set_use_autoclose(use_autoclose);
16390            this.set_use_auto_surround(use_auto_surround);
16391
16392            if let Some(new_selected_range) = new_selected_range_utf16 {
16393                let snapshot = this.buffer.read(cx).read(cx);
16394                let new_selected_ranges = marked_ranges
16395                    .into_iter()
16396                    .map(|marked_range| {
16397                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16398                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16399                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16400                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16401                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16402                    })
16403                    .collect::<Vec<_>>();
16404
16405                drop(snapshot);
16406                this.change_selections(None, window, cx, |selections| {
16407                    selections.select_ranges(new_selected_ranges)
16408                });
16409            }
16410        });
16411
16412        self.ime_transaction = self.ime_transaction.or(transaction);
16413        if let Some(transaction) = self.ime_transaction {
16414            self.buffer.update(cx, |buffer, cx| {
16415                buffer.group_until_transaction(transaction, cx);
16416            });
16417        }
16418
16419        if self.text_highlights::<InputComposition>(cx).is_none() {
16420            self.ime_transaction.take();
16421        }
16422    }
16423
16424    fn bounds_for_range(
16425        &mut self,
16426        range_utf16: Range<usize>,
16427        element_bounds: gpui::Bounds<Pixels>,
16428        window: &mut Window,
16429        cx: &mut Context<Self>,
16430    ) -> Option<gpui::Bounds<Pixels>> {
16431        let text_layout_details = self.text_layout_details(window);
16432        let gpui::Size {
16433            width: em_width,
16434            height: line_height,
16435        } = self.character_size(window);
16436
16437        let snapshot = self.snapshot(window, cx);
16438        let scroll_position = snapshot.scroll_position();
16439        let scroll_left = scroll_position.x * em_width;
16440
16441        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16442        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16443            + self.gutter_dimensions.width
16444            + self.gutter_dimensions.margin;
16445        let y = line_height * (start.row().as_f32() - scroll_position.y);
16446
16447        Some(Bounds {
16448            origin: element_bounds.origin + point(x, y),
16449            size: size(em_width, line_height),
16450        })
16451    }
16452
16453    fn character_index_for_point(
16454        &mut self,
16455        point: gpui::Point<Pixels>,
16456        _window: &mut Window,
16457        _cx: &mut Context<Self>,
16458    ) -> Option<usize> {
16459        let position_map = self.last_position_map.as_ref()?;
16460        if !position_map.text_hitbox.contains(&point) {
16461            return None;
16462        }
16463        let display_point = position_map.point_for_position(point).previous_valid;
16464        let anchor = position_map
16465            .snapshot
16466            .display_point_to_anchor(display_point, Bias::Left);
16467        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16468        Some(utf16_offset.0)
16469    }
16470}
16471
16472trait SelectionExt {
16473    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16474    fn spanned_rows(
16475        &self,
16476        include_end_if_at_line_start: bool,
16477        map: &DisplaySnapshot,
16478    ) -> Range<MultiBufferRow>;
16479}
16480
16481impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16482    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16483        let start = self
16484            .start
16485            .to_point(&map.buffer_snapshot)
16486            .to_display_point(map);
16487        let end = self
16488            .end
16489            .to_point(&map.buffer_snapshot)
16490            .to_display_point(map);
16491        if self.reversed {
16492            end..start
16493        } else {
16494            start..end
16495        }
16496    }
16497
16498    fn spanned_rows(
16499        &self,
16500        include_end_if_at_line_start: bool,
16501        map: &DisplaySnapshot,
16502    ) -> Range<MultiBufferRow> {
16503        let start = self.start.to_point(&map.buffer_snapshot);
16504        let mut end = self.end.to_point(&map.buffer_snapshot);
16505        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16506            end.row -= 1;
16507        }
16508
16509        let buffer_start = map.prev_line_boundary(start).0;
16510        let buffer_end = map.next_line_boundary(end).0;
16511        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16512    }
16513}
16514
16515impl<T: InvalidationRegion> InvalidationStack<T> {
16516    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16517    where
16518        S: Clone + ToOffset,
16519    {
16520        while let Some(region) = self.last() {
16521            let all_selections_inside_invalidation_ranges =
16522                if selections.len() == region.ranges().len() {
16523                    selections
16524                        .iter()
16525                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16526                        .all(|(selection, invalidation_range)| {
16527                            let head = selection.head().to_offset(buffer);
16528                            invalidation_range.start <= head && invalidation_range.end >= head
16529                        })
16530                } else {
16531                    false
16532                };
16533
16534            if all_selections_inside_invalidation_ranges {
16535                break;
16536            } else {
16537                self.pop();
16538            }
16539        }
16540    }
16541}
16542
16543impl<T> Default for InvalidationStack<T> {
16544    fn default() -> Self {
16545        Self(Default::default())
16546    }
16547}
16548
16549impl<T> Deref for InvalidationStack<T> {
16550    type Target = Vec<T>;
16551
16552    fn deref(&self) -> &Self::Target {
16553        &self.0
16554    }
16555}
16556
16557impl<T> DerefMut for InvalidationStack<T> {
16558    fn deref_mut(&mut self) -> &mut Self::Target {
16559        &mut self.0
16560    }
16561}
16562
16563impl InvalidationRegion for SnippetState {
16564    fn ranges(&self) -> &[Range<Anchor>] {
16565        &self.ranges[self.active_index]
16566    }
16567}
16568
16569pub fn diagnostic_block_renderer(
16570    diagnostic: Diagnostic,
16571    max_message_rows: Option<u8>,
16572    allow_closing: bool,
16573    _is_valid: bool,
16574) -> RenderBlock {
16575    let (text_without_backticks, code_ranges) =
16576        highlight_diagnostic_message(&diagnostic, max_message_rows);
16577
16578    Arc::new(move |cx: &mut BlockContext| {
16579        let group_id: SharedString = cx.block_id.to_string().into();
16580
16581        let mut text_style = cx.window.text_style().clone();
16582        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16583        let theme_settings = ThemeSettings::get_global(cx);
16584        text_style.font_family = theme_settings.buffer_font.family.clone();
16585        text_style.font_style = theme_settings.buffer_font.style;
16586        text_style.font_features = theme_settings.buffer_font.features.clone();
16587        text_style.font_weight = theme_settings.buffer_font.weight;
16588
16589        let multi_line_diagnostic = diagnostic.message.contains('\n');
16590
16591        let buttons = |diagnostic: &Diagnostic| {
16592            if multi_line_diagnostic {
16593                v_flex()
16594            } else {
16595                h_flex()
16596            }
16597            .when(allow_closing, |div| {
16598                div.children(diagnostic.is_primary.then(|| {
16599                    IconButton::new("close-block", IconName::XCircle)
16600                        .icon_color(Color::Muted)
16601                        .size(ButtonSize::Compact)
16602                        .style(ButtonStyle::Transparent)
16603                        .visible_on_hover(group_id.clone())
16604                        .on_click(move |_click, window, cx| {
16605                            window.dispatch_action(Box::new(Cancel), cx)
16606                        })
16607                        .tooltip(|window, cx| {
16608                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16609                        })
16610                }))
16611            })
16612            .child(
16613                IconButton::new("copy-block", IconName::Copy)
16614                    .icon_color(Color::Muted)
16615                    .size(ButtonSize::Compact)
16616                    .style(ButtonStyle::Transparent)
16617                    .visible_on_hover(group_id.clone())
16618                    .on_click({
16619                        let message = diagnostic.message.clone();
16620                        move |_click, _, cx| {
16621                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16622                        }
16623                    })
16624                    .tooltip(Tooltip::text("Copy diagnostic message")),
16625            )
16626        };
16627
16628        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16629            AvailableSpace::min_size(),
16630            cx.window,
16631            cx.app,
16632        );
16633
16634        h_flex()
16635            .id(cx.block_id)
16636            .group(group_id.clone())
16637            .relative()
16638            .size_full()
16639            .block_mouse_down()
16640            .pl(cx.gutter_dimensions.width)
16641            .w(cx.max_width - cx.gutter_dimensions.full_width())
16642            .child(
16643                div()
16644                    .flex()
16645                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16646                    .flex_shrink(),
16647            )
16648            .child(buttons(&diagnostic))
16649            .child(div().flex().flex_shrink_0().child(
16650                StyledText::new(text_without_backticks.clone()).with_highlights(
16651                    &text_style,
16652                    code_ranges.iter().map(|range| {
16653                        (
16654                            range.clone(),
16655                            HighlightStyle {
16656                                font_weight: Some(FontWeight::BOLD),
16657                                ..Default::default()
16658                            },
16659                        )
16660                    }),
16661                ),
16662            ))
16663            .into_any_element()
16664    })
16665}
16666
16667fn inline_completion_edit_text(
16668    current_snapshot: &BufferSnapshot,
16669    edits: &[(Range<Anchor>, String)],
16670    edit_preview: &EditPreview,
16671    include_deletions: bool,
16672    cx: &App,
16673) -> HighlightedText {
16674    let edits = edits
16675        .iter()
16676        .map(|(anchor, text)| {
16677            (
16678                anchor.start.text_anchor..anchor.end.text_anchor,
16679                text.clone(),
16680            )
16681        })
16682        .collect::<Vec<_>>();
16683
16684    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16685}
16686
16687pub fn highlight_diagnostic_message(
16688    diagnostic: &Diagnostic,
16689    mut max_message_rows: Option<u8>,
16690) -> (SharedString, Vec<Range<usize>>) {
16691    let mut text_without_backticks = String::new();
16692    let mut code_ranges = Vec::new();
16693
16694    if let Some(source) = &diagnostic.source {
16695        text_without_backticks.push_str(source);
16696        code_ranges.push(0..source.len());
16697        text_without_backticks.push_str(": ");
16698    }
16699
16700    let mut prev_offset = 0;
16701    let mut in_code_block = false;
16702    let has_row_limit = max_message_rows.is_some();
16703    let mut newline_indices = diagnostic
16704        .message
16705        .match_indices('\n')
16706        .filter(|_| has_row_limit)
16707        .map(|(ix, _)| ix)
16708        .fuse()
16709        .peekable();
16710
16711    for (quote_ix, _) in diagnostic
16712        .message
16713        .match_indices('`')
16714        .chain([(diagnostic.message.len(), "")])
16715    {
16716        let mut first_newline_ix = None;
16717        let mut last_newline_ix = None;
16718        while let Some(newline_ix) = newline_indices.peek() {
16719            if *newline_ix < quote_ix {
16720                if first_newline_ix.is_none() {
16721                    first_newline_ix = Some(*newline_ix);
16722                }
16723                last_newline_ix = Some(*newline_ix);
16724
16725                if let Some(rows_left) = &mut max_message_rows {
16726                    if *rows_left == 0 {
16727                        break;
16728                    } else {
16729                        *rows_left -= 1;
16730                    }
16731                }
16732                let _ = newline_indices.next();
16733            } else {
16734                break;
16735            }
16736        }
16737        let prev_len = text_without_backticks.len();
16738        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16739        text_without_backticks.push_str(new_text);
16740        if in_code_block {
16741            code_ranges.push(prev_len..text_without_backticks.len());
16742        }
16743        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16744        in_code_block = !in_code_block;
16745        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16746            text_without_backticks.push_str("...");
16747            break;
16748        }
16749    }
16750
16751    (text_without_backticks.into(), code_ranges)
16752}
16753
16754fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16755    match severity {
16756        DiagnosticSeverity::ERROR => colors.error,
16757        DiagnosticSeverity::WARNING => colors.warning,
16758        DiagnosticSeverity::INFORMATION => colors.info,
16759        DiagnosticSeverity::HINT => colors.info,
16760        _ => colors.ignored,
16761    }
16762}
16763
16764pub fn styled_runs_for_code_label<'a>(
16765    label: &'a CodeLabel,
16766    syntax_theme: &'a theme::SyntaxTheme,
16767) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16768    let fade_out = HighlightStyle {
16769        fade_out: Some(0.35),
16770        ..Default::default()
16771    };
16772
16773    let mut prev_end = label.filter_range.end;
16774    label
16775        .runs
16776        .iter()
16777        .enumerate()
16778        .flat_map(move |(ix, (range, highlight_id))| {
16779            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16780                style
16781            } else {
16782                return Default::default();
16783            };
16784            let mut muted_style = style;
16785            muted_style.highlight(fade_out);
16786
16787            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16788            if range.start >= label.filter_range.end {
16789                if range.start > prev_end {
16790                    runs.push((prev_end..range.start, fade_out));
16791                }
16792                runs.push((range.clone(), muted_style));
16793            } else if range.end <= label.filter_range.end {
16794                runs.push((range.clone(), style));
16795            } else {
16796                runs.push((range.start..label.filter_range.end, style));
16797                runs.push((label.filter_range.end..range.end, muted_style));
16798            }
16799            prev_end = cmp::max(prev_end, range.end);
16800
16801            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16802                runs.push((prev_end..label.text.len(), fade_out));
16803            }
16804
16805            runs
16806        })
16807}
16808
16809pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16810    let mut prev_index = 0;
16811    let mut prev_codepoint: Option<char> = None;
16812    text.char_indices()
16813        .chain([(text.len(), '\0')])
16814        .filter_map(move |(index, codepoint)| {
16815            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16816            let is_boundary = index == text.len()
16817                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16818                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16819            if is_boundary {
16820                let chunk = &text[prev_index..index];
16821                prev_index = index;
16822                Some(chunk)
16823            } else {
16824                None
16825            }
16826        })
16827}
16828
16829pub trait RangeToAnchorExt: Sized {
16830    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16831
16832    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16833        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16834        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16835    }
16836}
16837
16838impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16839    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16840        let start_offset = self.start.to_offset(snapshot);
16841        let end_offset = self.end.to_offset(snapshot);
16842        if start_offset == end_offset {
16843            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16844        } else {
16845            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16846        }
16847    }
16848}
16849
16850pub trait RowExt {
16851    fn as_f32(&self) -> f32;
16852
16853    fn next_row(&self) -> Self;
16854
16855    fn previous_row(&self) -> Self;
16856
16857    fn minus(&self, other: Self) -> u32;
16858}
16859
16860impl RowExt for DisplayRow {
16861    fn as_f32(&self) -> f32 {
16862        self.0 as f32
16863    }
16864
16865    fn next_row(&self) -> Self {
16866        Self(self.0 + 1)
16867    }
16868
16869    fn previous_row(&self) -> Self {
16870        Self(self.0.saturating_sub(1))
16871    }
16872
16873    fn minus(&self, other: Self) -> u32 {
16874        self.0 - other.0
16875    }
16876}
16877
16878impl RowExt for MultiBufferRow {
16879    fn as_f32(&self) -> f32 {
16880        self.0 as f32
16881    }
16882
16883    fn next_row(&self) -> Self {
16884        Self(self.0 + 1)
16885    }
16886
16887    fn previous_row(&self) -> Self {
16888        Self(self.0.saturating_sub(1))
16889    }
16890
16891    fn minus(&self, other: Self) -> u32 {
16892        self.0 - other.0
16893    }
16894}
16895
16896trait RowRangeExt {
16897    type Row;
16898
16899    fn len(&self) -> usize;
16900
16901    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16902}
16903
16904impl RowRangeExt for Range<MultiBufferRow> {
16905    type Row = MultiBufferRow;
16906
16907    fn len(&self) -> usize {
16908        (self.end.0 - self.start.0) as usize
16909    }
16910
16911    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16912        (self.start.0..self.end.0).map(MultiBufferRow)
16913    }
16914}
16915
16916impl RowRangeExt for Range<DisplayRow> {
16917    type Row = DisplayRow;
16918
16919    fn len(&self) -> usize {
16920        (self.end.0 - self.start.0) as usize
16921    }
16922
16923    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16924        (self.start.0..self.end.0).map(DisplayRow)
16925    }
16926}
16927
16928/// If select range has more than one line, we
16929/// just point the cursor to range.start.
16930fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16931    if range.start.row == range.end.row {
16932        range
16933    } else {
16934        range.start..range.start
16935    }
16936}
16937pub struct KillRing(ClipboardItem);
16938impl Global for KillRing {}
16939
16940const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16941
16942fn all_edits_insertions_or_deletions(
16943    edits: &Vec<(Range<Anchor>, String)>,
16944    snapshot: &MultiBufferSnapshot,
16945) -> bool {
16946    let mut all_insertions = true;
16947    let mut all_deletions = true;
16948
16949    for (range, new_text) in edits.iter() {
16950        let range_is_empty = range.to_offset(&snapshot).is_empty();
16951        let text_is_empty = new_text.is_empty();
16952
16953        if range_is_empty != text_is_empty {
16954            if range_is_empty {
16955                all_deletions = false;
16956            } else {
16957                all_insertions = false;
16958            }
16959        } else {
16960            return false;
16961        }
16962
16963        if !all_insertions && !all_deletions {
16964            return false;
16965        }
16966    }
16967    all_insertions || all_deletions
16968}