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 blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   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 client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use display_map::*;
   60pub use display_map::{DisplayPoint, FoldPlaceholder};
   61pub use editor_settings::{
   62    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   63};
   64pub use editor_settings_controls::*;
   65use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   66pub use element::{
   67    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   68};
   69use futures::{future, FutureExt};
   70use fuzzy::StringMatchCandidate;
   71
   72use code_context_menus::{
   73    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   74    CompletionsMenu, ContextMenuOrigin,
   75};
   76use git::blame::GitBlame;
   77use gpui::{
   78    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   79    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   80    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   81    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   82    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   83    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   84    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   85    WeakEntity, WeakFocusHandle, Window,
   86};
   87use highlight_matching_bracket::refresh_matching_bracket_highlights;
   88use hover_popover::{hide_hover, HoverState};
   89use indent_guides::ActiveIndentGuidesState;
   90use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   91pub use inline_completion::Direction;
   92use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   93pub use items::MAX_TAB_TITLE_LEN;
   94use itertools::Itertools;
   95use language::{
   96    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   97    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   98    CompletionDocumentation, CursorShape, Diagnostic, EditPredictionsMode, EditPreview,
   99    HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
  100    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  101};
  102use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  103use linked_editing_ranges::refresh_linked_ranges;
  104use mouse_context_menu::MouseContextMenu;
  105pub use proposed_changes_editor::{
  106    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  107};
  108use similar::{ChangeTag, TextDiff};
  109use std::iter::Peekable;
  110use task::{ResolvedTask, TaskTemplate, TaskVariables};
  111
  112use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  113pub use lsp::CompletionContext;
  114use lsp::{
  115    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  116    LanguageServerId, LanguageServerName,
  117};
  118
  119use language::BufferSnapshot;
  120use movement::TextLayoutDetails;
  121pub use multi_buffer::{
  122    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  123    ToOffset, ToPoint,
  124};
  125use multi_buffer::{
  126    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  127    ToOffsetUtf16,
  128};
  129use project::{
  130    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  131    project_settings::{GitGutterSetting, ProjectSettings},
  132    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  133    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  134};
  135use rand::prelude::*;
  136use rpc::{proto::*, ErrorExt};
  137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  138use selections_collection::{
  139    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  140};
  141use serde::{Deserialize, Serialize};
  142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  143use smallvec::SmallVec;
  144use snippet::Snippet;
  145use std::{
  146    any::TypeId,
  147    borrow::Cow,
  148    cell::RefCell,
  149    cmp::{self, Ordering, Reverse},
  150    mem,
  151    num::NonZeroU32,
  152    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  153    path::{Path, PathBuf},
  154    rc::Rc,
  155    sync::Arc,
  156    time::{Duration, Instant},
  157};
  158pub use sum_tree::Bias;
  159use sum_tree::TreeMap;
  160use text::{BufferId, OffsetUtf16, Rope};
  161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  167use workspace::item::{ItemHandle, PreviewTabsSettings};
  168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  169use workspace::{
  170    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  171};
  172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  173
  174use crate::hover_links::{find_url, find_url_from_range};
  175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  176
  177pub const FILE_HEADER_HEIGHT: u32 = 2;
  178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  182const MAX_LINE_LEN: usize = 1024;
  183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  186#[doc(hidden)]
  187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  188
  189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  191
  192pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  193pub(crate) const EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
  194    "edit_prediction_requires_modifier";
  195
  196pub fn render_parsed_markdown(
  197    element_id: impl Into<ElementId>,
  198    parsed: &language::ParsedMarkdown,
  199    editor_style: &EditorStyle,
  200    workspace: Option<WeakEntity<Workspace>>,
  201    cx: &mut App,
  202) -> InteractiveText {
  203    let code_span_background_color = cx
  204        .theme()
  205        .colors()
  206        .editor_document_highlight_read_background;
  207
  208    let highlights = gpui::combine_highlights(
  209        parsed.highlights.iter().filter_map(|(range, highlight)| {
  210            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  211            Some((range.clone(), highlight))
  212        }),
  213        parsed
  214            .regions
  215            .iter()
  216            .zip(&parsed.region_ranges)
  217            .filter_map(|(region, range)| {
  218                if region.code {
  219                    Some((
  220                        range.clone(),
  221                        HighlightStyle {
  222                            background_color: Some(code_span_background_color),
  223                            ..Default::default()
  224                        },
  225                    ))
  226                } else {
  227                    None
  228                }
  229            }),
  230    );
  231
  232    let mut links = Vec::new();
  233    let mut link_ranges = Vec::new();
  234    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  235        if let Some(link) = region.link.clone() {
  236            links.push(link);
  237            link_ranges.push(range.clone());
  238        }
  239    }
  240
  241    InteractiveText::new(
  242        element_id,
  243        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  244    )
  245    .on_click(
  246        link_ranges,
  247        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace
  253                            .open_abs_path(path.clone(), false, window, cx)
  254                            .detach();
  255                    });
  256                }
  257            }
  258        },
  259    )
  260}
  261
  262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  263pub enum InlayId {
  264    InlineCompletion(usize),
  265    Hint(usize),
  266}
  267
  268impl InlayId {
  269    fn id(&self) -> usize {
  270        match self {
  271            Self::InlineCompletion(id) => *id,
  272            Self::Hint(id) => *id,
  273        }
  274    }
  275}
  276
  277enum DocumentHighlightRead {}
  278enum DocumentHighlightWrite {}
  279enum InputComposition {}
  280
  281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  282pub enum Navigated {
  283    Yes,
  284    No,
  285}
  286
  287impl Navigated {
  288    pub fn from_bool(yes: bool) -> Navigated {
  289        if yes {
  290            Navigated::Yes
  291        } else {
  292            Navigated::No
  293        }
  294    }
  295}
  296
  297pub fn init_settings(cx: &mut App) {
  298    EditorSettings::register(cx);
  299}
  300
  301pub fn init(cx: &mut App) {
  302    init_settings(cx);
  303
  304    workspace::register_project_item::<Editor>(cx);
  305    workspace::FollowableViewRegistry::register::<Editor>(cx);
  306    workspace::register_serializable_item::<Editor>(cx);
  307
  308    cx.observe_new(
  309        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  310            workspace.register_action(Editor::new_file);
  311            workspace.register_action(Editor::new_file_vertical);
  312            workspace.register_action(Editor::new_file_horizontal);
  313            workspace.register_action(Editor::cancel_language_server_work);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(
  322                Default::default(),
  323                app_state,
  324                cx,
  325                |workspace, window, cx| {
  326                    Editor::new_file(workspace, &Default::default(), window, cx)
  327                },
  328            )
  329            .detach();
  330        }
  331    });
  332    cx.on_action(move |_: &workspace::NewWindow, cx| {
  333        let app_state = workspace::AppState::global(cx);
  334        if let Some(app_state) = app_state.upgrade() {
  335            workspace::open_new(
  336                Default::default(),
  337                app_state,
  338                cx,
  339                |workspace, window, cx| {
  340                    cx.activate(true);
  341                    Editor::new_file(workspace, &Default::default(), window, cx)
  342                },
  343            )
  344            .detach();
  345        }
  346    });
  347}
  348
  349pub struct SearchWithinRange;
  350
  351trait InvalidationRegion {
  352    fn ranges(&self) -> &[Range<Anchor>];
  353}
  354
  355#[derive(Clone, Debug, PartialEq)]
  356pub enum SelectPhase {
  357    Begin {
  358        position: DisplayPoint,
  359        add: bool,
  360        click_count: usize,
  361    },
  362    BeginColumnar {
  363        position: DisplayPoint,
  364        reset: bool,
  365        goal_column: u32,
  366    },
  367    Extend {
  368        position: DisplayPoint,
  369        click_count: usize,
  370    },
  371    Update {
  372        position: DisplayPoint,
  373        goal_column: u32,
  374        scroll_delta: gpui::Point<f32>,
  375    },
  376    End,
  377}
  378
  379#[derive(Clone, Debug)]
  380pub enum SelectMode {
  381    Character,
  382    Word(Range<Anchor>),
  383    Line(Range<Anchor>),
  384    All,
  385}
  386
  387#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  388pub enum EditorMode {
  389    SingleLine { auto_width: bool },
  390    AutoHeight { max_lines: usize },
  391    Full,
  392}
  393
  394#[derive(Copy, Clone, Debug)]
  395pub enum SoftWrap {
  396    /// Prefer not to wrap at all.
  397    ///
  398    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  399    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  400    GitDiff,
  401    /// Prefer a single line generally, unless an overly long line is encountered.
  402    None,
  403    /// Soft wrap lines that exceed the editor width.
  404    EditorWidth,
  405    /// Soft wrap lines at the preferred line length.
  406    Column(u32),
  407    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  408    Bounded(u32),
  409}
  410
  411#[derive(Clone)]
  412pub struct EditorStyle {
  413    pub background: Hsla,
  414    pub local_player: PlayerColor,
  415    pub text: TextStyle,
  416    pub scrollbar_width: Pixels,
  417    pub syntax: Arc<SyntaxTheme>,
  418    pub status: StatusColors,
  419    pub inlay_hints_style: HighlightStyle,
  420    pub inline_completion_styles: InlineCompletionStyles,
  421    pub unnecessary_code_fade: f32,
  422}
  423
  424impl Default for EditorStyle {
  425    fn default() -> Self {
  426        Self {
  427            background: Hsla::default(),
  428            local_player: PlayerColor::default(),
  429            text: TextStyle::default(),
  430            scrollbar_width: Pixels::default(),
  431            syntax: Default::default(),
  432            // HACK: Status colors don't have a real default.
  433            // We should look into removing the status colors from the editor
  434            // style and retrieve them directly from the theme.
  435            status: StatusColors::dark(),
  436            inlay_hints_style: HighlightStyle::default(),
  437            inline_completion_styles: InlineCompletionStyles {
  438                insertion: HighlightStyle::default(),
  439                whitespace: HighlightStyle::default(),
  440            },
  441            unnecessary_code_fade: Default::default(),
  442        }
  443    }
  444}
  445
  446pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  447    let show_background = language_settings::language_settings(None, None, cx)
  448        .inlay_hints
  449        .show_background;
  450
  451    HighlightStyle {
  452        color: Some(cx.theme().status().hint),
  453        background_color: show_background.then(|| cx.theme().status().hint_background),
  454        ..HighlightStyle::default()
  455    }
  456}
  457
  458pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  459    InlineCompletionStyles {
  460        insertion: HighlightStyle {
  461            color: Some(cx.theme().status().predictive),
  462            ..HighlightStyle::default()
  463        },
  464        whitespace: HighlightStyle {
  465            background_color: Some(cx.theme().status().created_background),
  466            ..HighlightStyle::default()
  467        },
  468    }
  469}
  470
  471type CompletionId = usize;
  472
  473pub(crate) enum EditDisplayMode {
  474    TabAccept,
  475    DiffPopover,
  476    Inline,
  477}
  478
  479enum InlineCompletion {
  480    Edit {
  481        edits: Vec<(Range<Anchor>, String)>,
  482        edit_preview: Option<EditPreview>,
  483        display_mode: EditDisplayMode,
  484        snapshot: BufferSnapshot,
  485    },
  486    Move {
  487        target: Anchor,
  488        snapshot: BufferSnapshot,
  489    },
  490}
  491
  492struct InlineCompletionState {
  493    inlay_ids: Vec<InlayId>,
  494    completion: InlineCompletion,
  495    completion_id: Option<SharedString>,
  496    invalidation_range: Range<Anchor>,
  497}
  498
  499enum EditPredictionSettings {
  500    Disabled,
  501    Enabled {
  502        show_in_menu: bool,
  503        preview_requires_modifier: bool,
  504    },
  505}
  506
  507impl EditPredictionSettings {
  508    pub fn is_enabled(&self) -> bool {
  509        match self {
  510            EditPredictionSettings::Disabled => false,
  511            EditPredictionSettings::Enabled { .. } => true,
  512        }
  513    }
  514}
  515
  516enum InlineCompletionHighlight {}
  517
  518pub enum MenuInlineCompletionsPolicy {
  519    Never,
  520    ByProvider,
  521}
  522
  523pub enum EditPredictionPreview {
  524    /// Modifier is not pressed
  525    Inactive,
  526    /// Modifier pressed
  527    Active {
  528        previous_scroll_position: Option<ScrollAnchor>,
  529    },
  530}
  531
  532#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  533struct EditorActionId(usize);
  534
  535impl EditorActionId {
  536    pub fn post_inc(&mut self) -> Self {
  537        let answer = self.0;
  538
  539        *self = Self(answer + 1);
  540
  541        Self(answer)
  542    }
  543}
  544
  545// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  546// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  547
  548type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  549type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  550
  551#[derive(Default)]
  552struct ScrollbarMarkerState {
  553    scrollbar_size: Size<Pixels>,
  554    dirty: bool,
  555    markers: Arc<[PaintQuad]>,
  556    pending_refresh: Option<Task<Result<()>>>,
  557}
  558
  559impl ScrollbarMarkerState {
  560    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  561        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  562    }
  563}
  564
  565#[derive(Clone, Debug)]
  566struct RunnableTasks {
  567    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  568    offset: MultiBufferOffset,
  569    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  570    column: u32,
  571    // Values of all named captures, including those starting with '_'
  572    extra_variables: HashMap<String, String>,
  573    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  574    context_range: Range<BufferOffset>,
  575}
  576
  577impl RunnableTasks {
  578    fn resolve<'a>(
  579        &'a self,
  580        cx: &'a task::TaskContext,
  581    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  582        self.templates.iter().filter_map(|(kind, template)| {
  583            template
  584                .resolve_task(&kind.to_id_base(), cx)
  585                .map(|task| (kind.clone(), task))
  586        })
  587    }
  588}
  589
  590#[derive(Clone)]
  591struct ResolvedTasks {
  592    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  593    position: Anchor,
  594}
  595#[derive(Copy, Clone, Debug)]
  596struct MultiBufferOffset(usize);
  597#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  598struct BufferOffset(usize);
  599
  600// Addons allow storing per-editor state in other crates (e.g. Vim)
  601pub trait Addon: 'static {
  602    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  603
  604    fn render_buffer_header_controls(
  605        &self,
  606        _: &ExcerptInfo,
  607        _: &Window,
  608        _: &App,
  609    ) -> Option<AnyElement> {
  610        None
  611    }
  612
  613    fn to_any(&self) -> &dyn std::any::Any;
  614}
  615
  616#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  617pub enum IsVimMode {
  618    Yes,
  619    No,
  620}
  621
  622/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  623///
  624/// See the [module level documentation](self) for more information.
  625pub struct Editor {
  626    focus_handle: FocusHandle,
  627    last_focused_descendant: Option<WeakFocusHandle>,
  628    /// The text buffer being edited
  629    buffer: Entity<MultiBuffer>,
  630    /// Map of how text in the buffer should be displayed.
  631    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  632    pub display_map: Entity<DisplayMap>,
  633    pub selections: SelectionsCollection,
  634    pub scroll_manager: ScrollManager,
  635    /// When inline assist editors are linked, they all render cursors because
  636    /// typing enters text into each of them, even the ones that aren't focused.
  637    pub(crate) show_cursor_when_unfocused: bool,
  638    columnar_selection_tail: Option<Anchor>,
  639    add_selections_state: Option<AddSelectionsState>,
  640    select_next_state: Option<SelectNextState>,
  641    select_prev_state: Option<SelectNextState>,
  642    selection_history: SelectionHistory,
  643    autoclose_regions: Vec<AutocloseRegion>,
  644    snippet_stack: InvalidationStack<SnippetState>,
  645    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  646    ime_transaction: Option<TransactionId>,
  647    active_diagnostics: Option<ActiveDiagnosticGroup>,
  648    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  649
  650    // TODO: make this a access method
  651    pub project: Option<Entity<Project>>,
  652    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  653    completion_provider: Option<Box<dyn CompletionProvider>>,
  654    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  655    blink_manager: Entity<BlinkManager>,
  656    show_cursor_names: bool,
  657    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  658    pub show_local_selections: bool,
  659    mode: EditorMode,
  660    show_breadcrumbs: bool,
  661    show_gutter: bool,
  662    show_scrollbars: bool,
  663    show_line_numbers: Option<bool>,
  664    use_relative_line_numbers: Option<bool>,
  665    show_git_diff_gutter: Option<bool>,
  666    show_code_actions: Option<bool>,
  667    show_runnables: Option<bool>,
  668    show_wrap_guides: Option<bool>,
  669    show_indent_guides: Option<bool>,
  670    placeholder_text: Option<Arc<str>>,
  671    highlight_order: usize,
  672    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  673    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  674    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  675    scrollbar_marker_state: ScrollbarMarkerState,
  676    active_indent_guides_state: ActiveIndentGuidesState,
  677    nav_history: Option<ItemNavHistory>,
  678    context_menu: RefCell<Option<CodeContextMenu>>,
  679    mouse_context_menu: Option<MouseContextMenu>,
  680    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  681    signature_help_state: SignatureHelpState,
  682    auto_signature_help: Option<bool>,
  683    find_all_references_task_sources: Vec<Anchor>,
  684    next_completion_id: CompletionId,
  685    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  686    code_actions_task: Option<Task<Result<()>>>,
  687    document_highlights_task: Option<Task<()>>,
  688    linked_editing_range_task: Option<Task<Option<()>>>,
  689    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  690    pending_rename: Option<RenameState>,
  691    searchable: bool,
  692    cursor_shape: CursorShape,
  693    current_line_highlight: Option<CurrentLineHighlight>,
  694    collapse_matches: bool,
  695    autoindent_mode: Option<AutoindentMode>,
  696    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  697    input_enabled: bool,
  698    use_modal_editing: bool,
  699    read_only: bool,
  700    leader_peer_id: Option<PeerId>,
  701    remote_id: Option<ViewId>,
  702    hover_state: HoverState,
  703    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  704    gutter_hovered: bool,
  705    hovered_link_state: Option<HoveredLinkState>,
  706    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  707    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  708    active_inline_completion: Option<InlineCompletionState>,
  709    /// Used to prevent flickering as the user types while the menu is open
  710    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  711    edit_prediction_settings: EditPredictionSettings,
  712    inline_completions_hidden_for_vim_mode: bool,
  713    show_inline_completions_override: Option<bool>,
  714    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  715    edit_prediction_preview: EditPredictionPreview,
  716    inlay_hint_cache: InlayHintCache,
  717    next_inlay_id: usize,
  718    _subscriptions: Vec<Subscription>,
  719    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  720    gutter_dimensions: GutterDimensions,
  721    style: Option<EditorStyle>,
  722    text_style_refinement: Option<TextStyleRefinement>,
  723    next_editor_action_id: EditorActionId,
  724    editor_actions:
  725        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  726    use_autoclose: bool,
  727    use_auto_surround: bool,
  728    auto_replace_emoji_shortcode: bool,
  729    show_git_blame_gutter: bool,
  730    show_git_blame_inline: bool,
  731    show_git_blame_inline_delay_task: Option<Task<()>>,
  732    distinguish_unstaged_diff_hunks: bool,
  733    git_blame_inline_enabled: bool,
  734    serialize_dirty_buffers: bool,
  735    show_selection_menu: Option<bool>,
  736    blame: Option<Entity<GitBlame>>,
  737    blame_subscription: Option<Subscription>,
  738    custom_context_menu: Option<
  739        Box<
  740            dyn 'static
  741                + Fn(
  742                    &mut Self,
  743                    DisplayPoint,
  744                    &mut Window,
  745                    &mut Context<Self>,
  746                ) -> Option<Entity<ui::ContextMenu>>,
  747        >,
  748    >,
  749    last_bounds: Option<Bounds<Pixels>>,
  750    last_position_map: Option<Rc<PositionMap>>,
  751    expect_bounds_change: Option<Bounds<Pixels>>,
  752    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  753    tasks_update_task: Option<Task<()>>,
  754    in_project_search: bool,
  755    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  756    breadcrumb_header: Option<String>,
  757    focused_block: Option<FocusedBlock>,
  758    next_scroll_position: NextScrollCursorCenterTopBottom,
  759    addons: HashMap<TypeId, Box<dyn Addon>>,
  760    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  761    selection_mark_mode: bool,
  762    toggle_fold_multiple_buffers: Task<()>,
  763    _scroll_cursor_center_top_bottom_task: Task<()>,
  764}
  765
  766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  767enum NextScrollCursorCenterTopBottom {
  768    #[default]
  769    Center,
  770    Top,
  771    Bottom,
  772}
  773
  774impl NextScrollCursorCenterTopBottom {
  775    fn next(&self) -> Self {
  776        match self {
  777            Self::Center => Self::Top,
  778            Self::Top => Self::Bottom,
  779            Self::Bottom => Self::Center,
  780        }
  781    }
  782}
  783
  784#[derive(Clone)]
  785pub struct EditorSnapshot {
  786    pub mode: EditorMode,
  787    show_gutter: bool,
  788    show_line_numbers: Option<bool>,
  789    show_git_diff_gutter: Option<bool>,
  790    show_code_actions: Option<bool>,
  791    show_runnables: Option<bool>,
  792    git_blame_gutter_max_author_length: Option<usize>,
  793    pub display_snapshot: DisplaySnapshot,
  794    pub placeholder_text: Option<Arc<str>>,
  795    is_focused: bool,
  796    scroll_anchor: ScrollAnchor,
  797    ongoing_scroll: OngoingScroll,
  798    current_line_highlight: CurrentLineHighlight,
  799    gutter_hovered: bool,
  800}
  801
  802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  803
  804#[derive(Default, Debug, Clone, Copy)]
  805pub struct GutterDimensions {
  806    pub left_padding: Pixels,
  807    pub right_padding: Pixels,
  808    pub width: Pixels,
  809    pub margin: Pixels,
  810    pub git_blame_entries_width: Option<Pixels>,
  811}
  812
  813impl GutterDimensions {
  814    /// The full width of the space taken up by the gutter.
  815    pub fn full_width(&self) -> Pixels {
  816        self.margin + self.width
  817    }
  818
  819    /// The width of the space reserved for the fold indicators,
  820    /// use alongside 'justify_end' and `gutter_width` to
  821    /// right align content with the line numbers
  822    pub fn fold_area_width(&self) -> Pixels {
  823        self.margin + self.right_padding
  824    }
  825}
  826
  827#[derive(Debug)]
  828pub struct RemoteSelection {
  829    pub replica_id: ReplicaId,
  830    pub selection: Selection<Anchor>,
  831    pub cursor_shape: CursorShape,
  832    pub peer_id: PeerId,
  833    pub line_mode: bool,
  834    pub participant_index: Option<ParticipantIndex>,
  835    pub user_name: Option<SharedString>,
  836}
  837
  838#[derive(Clone, Debug)]
  839struct SelectionHistoryEntry {
  840    selections: Arc<[Selection<Anchor>]>,
  841    select_next_state: Option<SelectNextState>,
  842    select_prev_state: Option<SelectNextState>,
  843    add_selections_state: Option<AddSelectionsState>,
  844}
  845
  846enum SelectionHistoryMode {
  847    Normal,
  848    Undoing,
  849    Redoing,
  850}
  851
  852#[derive(Clone, PartialEq, Eq, Hash)]
  853struct HoveredCursor {
  854    replica_id: u16,
  855    selection_id: usize,
  856}
  857
  858impl Default for SelectionHistoryMode {
  859    fn default() -> Self {
  860        Self::Normal
  861    }
  862}
  863
  864#[derive(Default)]
  865struct SelectionHistory {
  866    #[allow(clippy::type_complexity)]
  867    selections_by_transaction:
  868        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  869    mode: SelectionHistoryMode,
  870    undo_stack: VecDeque<SelectionHistoryEntry>,
  871    redo_stack: VecDeque<SelectionHistoryEntry>,
  872}
  873
  874impl SelectionHistory {
  875    fn insert_transaction(
  876        &mut self,
  877        transaction_id: TransactionId,
  878        selections: Arc<[Selection<Anchor>]>,
  879    ) {
  880        self.selections_by_transaction
  881            .insert(transaction_id, (selections, None));
  882    }
  883
  884    #[allow(clippy::type_complexity)]
  885    fn transaction(
  886        &self,
  887        transaction_id: TransactionId,
  888    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  889        self.selections_by_transaction.get(&transaction_id)
  890    }
  891
  892    #[allow(clippy::type_complexity)]
  893    fn transaction_mut(
  894        &mut self,
  895        transaction_id: TransactionId,
  896    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  897        self.selections_by_transaction.get_mut(&transaction_id)
  898    }
  899
  900    fn push(&mut self, entry: SelectionHistoryEntry) {
  901        if !entry.selections.is_empty() {
  902            match self.mode {
  903                SelectionHistoryMode::Normal => {
  904                    self.push_undo(entry);
  905                    self.redo_stack.clear();
  906                }
  907                SelectionHistoryMode::Undoing => self.push_redo(entry),
  908                SelectionHistoryMode::Redoing => self.push_undo(entry),
  909            }
  910        }
  911    }
  912
  913    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  914        if self
  915            .undo_stack
  916            .back()
  917            .map_or(true, |e| e.selections != entry.selections)
  918        {
  919            self.undo_stack.push_back(entry);
  920            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  921                self.undo_stack.pop_front();
  922            }
  923        }
  924    }
  925
  926    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  927        if self
  928            .redo_stack
  929            .back()
  930            .map_or(true, |e| e.selections != entry.selections)
  931        {
  932            self.redo_stack.push_back(entry);
  933            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  934                self.redo_stack.pop_front();
  935            }
  936        }
  937    }
  938}
  939
  940struct RowHighlight {
  941    index: usize,
  942    range: Range<Anchor>,
  943    color: Hsla,
  944    should_autoscroll: bool,
  945}
  946
  947#[derive(Clone, Debug)]
  948struct AddSelectionsState {
  949    above: bool,
  950    stack: Vec<usize>,
  951}
  952
  953#[derive(Clone)]
  954struct SelectNextState {
  955    query: AhoCorasick,
  956    wordwise: bool,
  957    done: bool,
  958}
  959
  960impl std::fmt::Debug for SelectNextState {
  961    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  962        f.debug_struct(std::any::type_name::<Self>())
  963            .field("wordwise", &self.wordwise)
  964            .field("done", &self.done)
  965            .finish()
  966    }
  967}
  968
  969#[derive(Debug)]
  970struct AutocloseRegion {
  971    selection_id: usize,
  972    range: Range<Anchor>,
  973    pair: BracketPair,
  974}
  975
  976#[derive(Debug)]
  977struct SnippetState {
  978    ranges: Vec<Vec<Range<Anchor>>>,
  979    active_index: usize,
  980    choices: Vec<Option<Vec<String>>>,
  981}
  982
  983#[doc(hidden)]
  984pub struct RenameState {
  985    pub range: Range<Anchor>,
  986    pub old_name: Arc<str>,
  987    pub editor: Entity<Editor>,
  988    block_id: CustomBlockId,
  989}
  990
  991struct InvalidationStack<T>(Vec<T>);
  992
  993struct RegisteredInlineCompletionProvider {
  994    provider: Arc<dyn InlineCompletionProviderHandle>,
  995    _subscription: Subscription,
  996}
  997
  998#[derive(Debug)]
  999struct ActiveDiagnosticGroup {
 1000    primary_range: Range<Anchor>,
 1001    primary_message: String,
 1002    group_id: usize,
 1003    blocks: HashMap<CustomBlockId, Diagnostic>,
 1004    is_valid: bool,
 1005}
 1006
 1007#[derive(Serialize, Deserialize, Clone, Debug)]
 1008pub struct ClipboardSelection {
 1009    pub len: usize,
 1010    pub is_entire_line: bool,
 1011    pub first_line_indent: u32,
 1012}
 1013
 1014#[derive(Debug)]
 1015pub(crate) struct NavigationData {
 1016    cursor_anchor: Anchor,
 1017    cursor_position: Point,
 1018    scroll_anchor: ScrollAnchor,
 1019    scroll_top_row: u32,
 1020}
 1021
 1022#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1023pub enum GotoDefinitionKind {
 1024    Symbol,
 1025    Declaration,
 1026    Type,
 1027    Implementation,
 1028}
 1029
 1030#[derive(Debug, Clone)]
 1031enum InlayHintRefreshReason {
 1032    Toggle(bool),
 1033    SettingsChange(InlayHintSettings),
 1034    NewLinesShown,
 1035    BufferEdited(HashSet<Arc<Language>>),
 1036    RefreshRequested,
 1037    ExcerptsRemoved(Vec<ExcerptId>),
 1038}
 1039
 1040impl InlayHintRefreshReason {
 1041    fn description(&self) -> &'static str {
 1042        match self {
 1043            Self::Toggle(_) => "toggle",
 1044            Self::SettingsChange(_) => "settings change",
 1045            Self::NewLinesShown => "new lines shown",
 1046            Self::BufferEdited(_) => "buffer edited",
 1047            Self::RefreshRequested => "refresh requested",
 1048            Self::ExcerptsRemoved(_) => "excerpts removed",
 1049        }
 1050    }
 1051}
 1052
 1053pub enum FormatTarget {
 1054    Buffers,
 1055    Ranges(Vec<Range<MultiBufferPoint>>),
 1056}
 1057
 1058pub(crate) struct FocusedBlock {
 1059    id: BlockId,
 1060    focus_handle: WeakFocusHandle,
 1061}
 1062
 1063#[derive(Clone)]
 1064enum JumpData {
 1065    MultiBufferRow {
 1066        row: MultiBufferRow,
 1067        line_offset_from_top: u32,
 1068    },
 1069    MultiBufferPoint {
 1070        excerpt_id: ExcerptId,
 1071        position: Point,
 1072        anchor: text::Anchor,
 1073        line_offset_from_top: u32,
 1074    },
 1075}
 1076
 1077pub enum MultibufferSelectionMode {
 1078    First,
 1079    All,
 1080}
 1081
 1082impl Editor {
 1083    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1084        let buffer = cx.new(|cx| Buffer::local("", cx));
 1085        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1086        Self::new(
 1087            EditorMode::SingleLine { auto_width: false },
 1088            buffer,
 1089            None,
 1090            false,
 1091            window,
 1092            cx,
 1093        )
 1094    }
 1095
 1096    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1097        let buffer = cx.new(|cx| Buffer::local("", cx));
 1098        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1099        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1100    }
 1101
 1102    pub fn auto_width(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(
 1106            EditorMode::SingleLine { auto_width: true },
 1107            buffer,
 1108            None,
 1109            false,
 1110            window,
 1111            cx,
 1112        )
 1113    }
 1114
 1115    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1116        let buffer = cx.new(|cx| Buffer::local("", cx));
 1117        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1118        Self::new(
 1119            EditorMode::AutoHeight { max_lines },
 1120            buffer,
 1121            None,
 1122            false,
 1123            window,
 1124            cx,
 1125        )
 1126    }
 1127
 1128    pub fn for_buffer(
 1129        buffer: Entity<Buffer>,
 1130        project: Option<Entity<Project>>,
 1131        window: &mut Window,
 1132        cx: &mut Context<Self>,
 1133    ) -> Self {
 1134        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1135        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1136    }
 1137
 1138    pub fn for_multibuffer(
 1139        buffer: Entity<MultiBuffer>,
 1140        project: Option<Entity<Project>>,
 1141        show_excerpt_controls: bool,
 1142        window: &mut Window,
 1143        cx: &mut Context<Self>,
 1144    ) -> Self {
 1145        Self::new(
 1146            EditorMode::Full,
 1147            buffer,
 1148            project,
 1149            show_excerpt_controls,
 1150            window,
 1151            cx,
 1152        )
 1153    }
 1154
 1155    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1156        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1157        let mut clone = Self::new(
 1158            self.mode,
 1159            self.buffer.clone(),
 1160            self.project.clone(),
 1161            show_excerpt_controls,
 1162            window,
 1163            cx,
 1164        );
 1165        self.display_map.update(cx, |display_map, cx| {
 1166            let snapshot = display_map.snapshot(cx);
 1167            clone.display_map.update(cx, |display_map, cx| {
 1168                display_map.set_state(&snapshot, cx);
 1169            });
 1170        });
 1171        clone.selections.clone_state(&self.selections);
 1172        clone.scroll_manager.clone_state(&self.scroll_manager);
 1173        clone.searchable = self.searchable;
 1174        clone
 1175    }
 1176
 1177    pub fn new(
 1178        mode: EditorMode,
 1179        buffer: Entity<MultiBuffer>,
 1180        project: Option<Entity<Project>>,
 1181        show_excerpt_controls: bool,
 1182        window: &mut Window,
 1183        cx: &mut Context<Self>,
 1184    ) -> Self {
 1185        let style = window.text_style();
 1186        let font_size = style.font_size.to_pixels(window.rem_size());
 1187        let editor = cx.entity().downgrade();
 1188        let fold_placeholder = FoldPlaceholder {
 1189            constrain_width: true,
 1190            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1191                let editor = editor.clone();
 1192                div()
 1193                    .id(fold_id)
 1194                    .bg(cx.theme().colors().ghost_element_background)
 1195                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1196                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1197                    .rounded_sm()
 1198                    .size_full()
 1199                    .cursor_pointer()
 1200                    .child("")
 1201                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1202                    .on_click(move |_, _window, cx| {
 1203                        editor
 1204                            .update(cx, |editor, cx| {
 1205                                editor.unfold_ranges(
 1206                                    &[fold_range.start..fold_range.end],
 1207                                    true,
 1208                                    false,
 1209                                    cx,
 1210                                );
 1211                                cx.stop_propagation();
 1212                            })
 1213                            .ok();
 1214                    })
 1215                    .into_any()
 1216            }),
 1217            merge_adjacent: true,
 1218            ..Default::default()
 1219        };
 1220        let display_map = cx.new(|cx| {
 1221            DisplayMap::new(
 1222                buffer.clone(),
 1223                style.font(),
 1224                font_size,
 1225                None,
 1226                show_excerpt_controls,
 1227                FILE_HEADER_HEIGHT,
 1228                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1229                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1230                fold_placeholder,
 1231                cx,
 1232            )
 1233        });
 1234
 1235        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1236
 1237        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1238
 1239        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1240            .then(|| language_settings::SoftWrap::None);
 1241
 1242        let mut project_subscriptions = Vec::new();
 1243        if mode == EditorMode::Full {
 1244            if let Some(project) = project.as_ref() {
 1245                if buffer.read(cx).is_singleton() {
 1246                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1247                        cx.emit(EditorEvent::TitleChanged);
 1248                    }));
 1249                }
 1250                project_subscriptions.push(cx.subscribe_in(
 1251                    project,
 1252                    window,
 1253                    |editor, _, event, window, cx| {
 1254                        if let project::Event::RefreshInlayHints = event {
 1255                            editor
 1256                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1257                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1258                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1259                                let focus_handle = editor.focus_handle(cx);
 1260                                if focus_handle.is_focused(window) {
 1261                                    let snapshot = buffer.read(cx).snapshot();
 1262                                    for (range, snippet) in snippet_edits {
 1263                                        let editor_range =
 1264                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1265                                        editor
 1266                                            .insert_snippet(
 1267                                                &[editor_range],
 1268                                                snippet.clone(),
 1269                                                window,
 1270                                                cx,
 1271                                            )
 1272                                            .ok();
 1273                                    }
 1274                                }
 1275                            }
 1276                        }
 1277                    },
 1278                ));
 1279                if let Some(task_inventory) = project
 1280                    .read(cx)
 1281                    .task_store()
 1282                    .read(cx)
 1283                    .task_inventory()
 1284                    .cloned()
 1285                {
 1286                    project_subscriptions.push(cx.observe_in(
 1287                        &task_inventory,
 1288                        window,
 1289                        |editor, _, window, cx| {
 1290                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1291                        },
 1292                    ));
 1293                }
 1294            }
 1295        }
 1296
 1297        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1298
 1299        let inlay_hint_settings =
 1300            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1301        let focus_handle = cx.focus_handle();
 1302        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1303            .detach();
 1304        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1305            .detach();
 1306        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1307            .detach();
 1308        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1309            .detach();
 1310
 1311        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1312            Some(false)
 1313        } else {
 1314            None
 1315        };
 1316
 1317        let mut code_action_providers = Vec::new();
 1318        if let Some(project) = project.clone() {
 1319            get_uncommitted_diff_for_buffer(
 1320                &project,
 1321                buffer.read(cx).all_buffers(),
 1322                buffer.clone(),
 1323                cx,
 1324            );
 1325            code_action_providers.push(Rc::new(project) as Rc<_>);
 1326        }
 1327
 1328        let mut this = Self {
 1329            focus_handle,
 1330            show_cursor_when_unfocused: false,
 1331            last_focused_descendant: None,
 1332            buffer: buffer.clone(),
 1333            display_map: display_map.clone(),
 1334            selections,
 1335            scroll_manager: ScrollManager::new(cx),
 1336            columnar_selection_tail: None,
 1337            add_selections_state: None,
 1338            select_next_state: None,
 1339            select_prev_state: None,
 1340            selection_history: Default::default(),
 1341            autoclose_regions: Default::default(),
 1342            snippet_stack: Default::default(),
 1343            select_larger_syntax_node_stack: Vec::new(),
 1344            ime_transaction: Default::default(),
 1345            active_diagnostics: None,
 1346            soft_wrap_mode_override,
 1347            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1348            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1349            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1350            project,
 1351            blink_manager: blink_manager.clone(),
 1352            show_local_selections: true,
 1353            show_scrollbars: true,
 1354            mode,
 1355            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1356            show_gutter: mode == EditorMode::Full,
 1357            show_line_numbers: None,
 1358            use_relative_line_numbers: None,
 1359            show_git_diff_gutter: None,
 1360            show_code_actions: None,
 1361            show_runnables: None,
 1362            show_wrap_guides: None,
 1363            show_indent_guides,
 1364            placeholder_text: None,
 1365            highlight_order: 0,
 1366            highlighted_rows: HashMap::default(),
 1367            background_highlights: Default::default(),
 1368            gutter_highlights: TreeMap::default(),
 1369            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1370            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1371            nav_history: None,
 1372            context_menu: RefCell::new(None),
 1373            mouse_context_menu: None,
 1374            completion_tasks: Default::default(),
 1375            signature_help_state: SignatureHelpState::default(),
 1376            auto_signature_help: None,
 1377            find_all_references_task_sources: Vec::new(),
 1378            next_completion_id: 0,
 1379            next_inlay_id: 0,
 1380            code_action_providers,
 1381            available_code_actions: Default::default(),
 1382            code_actions_task: Default::default(),
 1383            document_highlights_task: Default::default(),
 1384            linked_editing_range_task: Default::default(),
 1385            pending_rename: Default::default(),
 1386            searchable: true,
 1387            cursor_shape: EditorSettings::get_global(cx)
 1388                .cursor_shape
 1389                .unwrap_or_default(),
 1390            current_line_highlight: None,
 1391            autoindent_mode: Some(AutoindentMode::EachLine),
 1392            collapse_matches: false,
 1393            workspace: None,
 1394            input_enabled: true,
 1395            use_modal_editing: mode == EditorMode::Full,
 1396            read_only: false,
 1397            use_autoclose: true,
 1398            use_auto_surround: true,
 1399            auto_replace_emoji_shortcode: false,
 1400            leader_peer_id: None,
 1401            remote_id: None,
 1402            hover_state: Default::default(),
 1403            pending_mouse_down: None,
 1404            hovered_link_state: Default::default(),
 1405            edit_prediction_provider: None,
 1406            active_inline_completion: None,
 1407            stale_inline_completion_in_menu: None,
 1408            edit_prediction_preview: EditPredictionPreview::Inactive,
 1409            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1410
 1411            gutter_hovered: false,
 1412            pixel_position_of_newest_cursor: None,
 1413            last_bounds: None,
 1414            last_position_map: None,
 1415            expect_bounds_change: None,
 1416            gutter_dimensions: GutterDimensions::default(),
 1417            style: None,
 1418            show_cursor_names: false,
 1419            hovered_cursors: Default::default(),
 1420            next_editor_action_id: EditorActionId::default(),
 1421            editor_actions: Rc::default(),
 1422            inline_completions_hidden_for_vim_mode: false,
 1423            show_inline_completions_override: None,
 1424            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1425            edit_prediction_settings: EditPredictionSettings::Disabled,
 1426            custom_context_menu: None,
 1427            show_git_blame_gutter: false,
 1428            show_git_blame_inline: false,
 1429            distinguish_unstaged_diff_hunks: false,
 1430            show_selection_menu: None,
 1431            show_git_blame_inline_delay_task: None,
 1432            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1433            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1434                .session
 1435                .restore_unsaved_buffers,
 1436            blame: None,
 1437            blame_subscription: None,
 1438            tasks: Default::default(),
 1439            _subscriptions: vec![
 1440                cx.observe(&buffer, Self::on_buffer_changed),
 1441                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1442                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1443                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1444                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1445                cx.observe_window_activation(window, |editor, window, cx| {
 1446                    let active = window.is_window_active();
 1447                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1448                        if active {
 1449                            blink_manager.enable(cx);
 1450                        } else {
 1451                            blink_manager.disable(cx);
 1452                        }
 1453                    });
 1454                }),
 1455            ],
 1456            tasks_update_task: None,
 1457            linked_edit_ranges: Default::default(),
 1458            in_project_search: false,
 1459            previous_search_ranges: None,
 1460            breadcrumb_header: None,
 1461            focused_block: None,
 1462            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1463            addons: HashMap::default(),
 1464            registered_buffers: HashMap::default(),
 1465            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1466            selection_mark_mode: false,
 1467            toggle_fold_multiple_buffers: Task::ready(()),
 1468            text_style_refinement: None,
 1469        };
 1470        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1471        this._subscriptions.extend(project_subscriptions);
 1472
 1473        this.end_selection(window, cx);
 1474        this.scroll_manager.show_scrollbar(window, cx);
 1475
 1476        if mode == EditorMode::Full {
 1477            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1478            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1479
 1480            if this.git_blame_inline_enabled {
 1481                this.git_blame_inline_enabled = true;
 1482                this.start_git_blame_inline(false, window, cx);
 1483            }
 1484
 1485            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1486                if let Some(project) = this.project.as_ref() {
 1487                    let lsp_store = project.read(cx).lsp_store();
 1488                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1489                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1490                    });
 1491                    this.registered_buffers
 1492                        .insert(buffer.read(cx).remote_id(), handle);
 1493                }
 1494            }
 1495        }
 1496
 1497        this.report_editor_event("Editor Opened", None, cx);
 1498        this
 1499    }
 1500
 1501    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1502        self.mouse_context_menu
 1503            .as_ref()
 1504            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1505    }
 1506
 1507    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1508        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1509    }
 1510
 1511    fn key_context_internal(
 1512        &self,
 1513        has_active_edit_prediction: bool,
 1514        window: &Window,
 1515        cx: &App,
 1516    ) -> KeyContext {
 1517        let mut key_context = KeyContext::new_with_defaults();
 1518        key_context.add("Editor");
 1519        let mode = match self.mode {
 1520            EditorMode::SingleLine { .. } => "single_line",
 1521            EditorMode::AutoHeight { .. } => "auto_height",
 1522            EditorMode::Full => "full",
 1523        };
 1524
 1525        if EditorSettings::jupyter_enabled(cx) {
 1526            key_context.add("jupyter");
 1527        }
 1528
 1529        key_context.set("mode", mode);
 1530        if self.pending_rename.is_some() {
 1531            key_context.add("renaming");
 1532        }
 1533
 1534        let mut showing_completions = false;
 1535
 1536        match self.context_menu.borrow().as_ref() {
 1537            Some(CodeContextMenu::Completions(_)) => {
 1538                key_context.add("menu");
 1539                key_context.add("showing_completions");
 1540                showing_completions = true;
 1541            }
 1542            Some(CodeContextMenu::CodeActions(_)) => {
 1543                key_context.add("menu");
 1544                key_context.add("showing_code_actions")
 1545            }
 1546            None => {}
 1547        }
 1548
 1549        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1550        if !self.focus_handle(cx).contains_focused(window, cx)
 1551            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1552        {
 1553            for addon in self.addons.values() {
 1554                addon.extend_key_context(&mut key_context, cx)
 1555            }
 1556        }
 1557
 1558        if let Some(extension) = self
 1559            .buffer
 1560            .read(cx)
 1561            .as_singleton()
 1562            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1563        {
 1564            key_context.set("extension", extension.to_string());
 1565        }
 1566
 1567        if has_active_edit_prediction {
 1568            key_context.add("copilot_suggestion");
 1569            key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1570            if showing_completions || self.edit_prediction_requires_modifier() {
 1571                key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
 1572            }
 1573        }
 1574
 1575        if self.selection_mark_mode {
 1576            key_context.add("selection_mode");
 1577        }
 1578
 1579        key_context
 1580    }
 1581
 1582    pub fn accept_edit_prediction_keybind(
 1583        &self,
 1584        window: &Window,
 1585        cx: &App,
 1586    ) -> AcceptEditPredictionBinding {
 1587        let key_context = self.key_context_internal(true, window, cx);
 1588        AcceptEditPredictionBinding(
 1589            window
 1590                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1591                .into_iter()
 1592                .rev()
 1593                .next(),
 1594        )
 1595    }
 1596
 1597    pub fn new_file(
 1598        workspace: &mut Workspace,
 1599        _: &workspace::NewFile,
 1600        window: &mut Window,
 1601        cx: &mut Context<Workspace>,
 1602    ) {
 1603        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1604            "Failed to create buffer",
 1605            window,
 1606            cx,
 1607            |e, _, _| match e.error_code() {
 1608                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1609                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1610                e.error_tag("required").unwrap_or("the latest version")
 1611            )),
 1612                _ => None,
 1613            },
 1614        );
 1615    }
 1616
 1617    pub fn new_in_workspace(
 1618        workspace: &mut Workspace,
 1619        window: &mut Window,
 1620        cx: &mut Context<Workspace>,
 1621    ) -> Task<Result<Entity<Editor>>> {
 1622        let project = workspace.project().clone();
 1623        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1624
 1625        cx.spawn_in(window, |workspace, mut cx| async move {
 1626            let buffer = create.await?;
 1627            workspace.update_in(&mut cx, |workspace, window, cx| {
 1628                let editor =
 1629                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1630                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1631                editor
 1632            })
 1633        })
 1634    }
 1635
 1636    fn new_file_vertical(
 1637        workspace: &mut Workspace,
 1638        _: &workspace::NewFileSplitVertical,
 1639        window: &mut Window,
 1640        cx: &mut Context<Workspace>,
 1641    ) {
 1642        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1643    }
 1644
 1645    fn new_file_horizontal(
 1646        workspace: &mut Workspace,
 1647        _: &workspace::NewFileSplitHorizontal,
 1648        window: &mut Window,
 1649        cx: &mut Context<Workspace>,
 1650    ) {
 1651        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1652    }
 1653
 1654    fn new_file_in_direction(
 1655        workspace: &mut Workspace,
 1656        direction: SplitDirection,
 1657        window: &mut Window,
 1658        cx: &mut Context<Workspace>,
 1659    ) {
 1660        let project = workspace.project().clone();
 1661        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1662
 1663        cx.spawn_in(window, |workspace, mut cx| async move {
 1664            let buffer = create.await?;
 1665            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1666                workspace.split_item(
 1667                    direction,
 1668                    Box::new(
 1669                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1670                    ),
 1671                    window,
 1672                    cx,
 1673                )
 1674            })?;
 1675            anyhow::Ok(())
 1676        })
 1677        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1678            match e.error_code() {
 1679                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1680                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1681                e.error_tag("required").unwrap_or("the latest version")
 1682            )),
 1683                _ => None,
 1684            }
 1685        });
 1686    }
 1687
 1688    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1689        self.leader_peer_id
 1690    }
 1691
 1692    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1693        &self.buffer
 1694    }
 1695
 1696    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1697        self.workspace.as_ref()?.0.upgrade()
 1698    }
 1699
 1700    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1701        self.buffer().read(cx).title(cx)
 1702    }
 1703
 1704    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1705        let git_blame_gutter_max_author_length = self
 1706            .render_git_blame_gutter(cx)
 1707            .then(|| {
 1708                if let Some(blame) = self.blame.as_ref() {
 1709                    let max_author_length =
 1710                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1711                    Some(max_author_length)
 1712                } else {
 1713                    None
 1714                }
 1715            })
 1716            .flatten();
 1717
 1718        EditorSnapshot {
 1719            mode: self.mode,
 1720            show_gutter: self.show_gutter,
 1721            show_line_numbers: self.show_line_numbers,
 1722            show_git_diff_gutter: self.show_git_diff_gutter,
 1723            show_code_actions: self.show_code_actions,
 1724            show_runnables: self.show_runnables,
 1725            git_blame_gutter_max_author_length,
 1726            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1727            scroll_anchor: self.scroll_manager.anchor(),
 1728            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1729            placeholder_text: self.placeholder_text.clone(),
 1730            is_focused: self.focus_handle.is_focused(window),
 1731            current_line_highlight: self
 1732                .current_line_highlight
 1733                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1734            gutter_hovered: self.gutter_hovered,
 1735        }
 1736    }
 1737
 1738    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1739        self.buffer.read(cx).language_at(point, cx)
 1740    }
 1741
 1742    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1743        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1744    }
 1745
 1746    pub fn active_excerpt(
 1747        &self,
 1748        cx: &App,
 1749    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1750        self.buffer
 1751            .read(cx)
 1752            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1753    }
 1754
 1755    pub fn mode(&self) -> EditorMode {
 1756        self.mode
 1757    }
 1758
 1759    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1760        self.collaboration_hub.as_deref()
 1761    }
 1762
 1763    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1764        self.collaboration_hub = Some(hub);
 1765    }
 1766
 1767    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1768        self.in_project_search = in_project_search;
 1769    }
 1770
 1771    pub fn set_custom_context_menu(
 1772        &mut self,
 1773        f: impl 'static
 1774            + Fn(
 1775                &mut Self,
 1776                DisplayPoint,
 1777                &mut Window,
 1778                &mut Context<Self>,
 1779            ) -> Option<Entity<ui::ContextMenu>>,
 1780    ) {
 1781        self.custom_context_menu = Some(Box::new(f))
 1782    }
 1783
 1784    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1785        self.completion_provider = provider;
 1786    }
 1787
 1788    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1789        self.semantics_provider.clone()
 1790    }
 1791
 1792    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1793        self.semantics_provider = provider;
 1794    }
 1795
 1796    pub fn set_edit_prediction_provider<T>(
 1797        &mut self,
 1798        provider: Option<Entity<T>>,
 1799        window: &mut Window,
 1800        cx: &mut Context<Self>,
 1801    ) where
 1802        T: EditPredictionProvider,
 1803    {
 1804        self.edit_prediction_provider =
 1805            provider.map(|provider| RegisteredInlineCompletionProvider {
 1806                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1807                    if this.focus_handle.is_focused(window) {
 1808                        this.update_visible_inline_completion(window, cx);
 1809                    }
 1810                }),
 1811                provider: Arc::new(provider),
 1812            });
 1813        self.refresh_inline_completion(false, false, window, cx);
 1814    }
 1815
 1816    pub fn placeholder_text(&self) -> Option<&str> {
 1817        self.placeholder_text.as_deref()
 1818    }
 1819
 1820    pub fn set_placeholder_text(
 1821        &mut self,
 1822        placeholder_text: impl Into<Arc<str>>,
 1823        cx: &mut Context<Self>,
 1824    ) {
 1825        let placeholder_text = Some(placeholder_text.into());
 1826        if self.placeholder_text != placeholder_text {
 1827            self.placeholder_text = placeholder_text;
 1828            cx.notify();
 1829        }
 1830    }
 1831
 1832    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1833        self.cursor_shape = cursor_shape;
 1834
 1835        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1836        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1837
 1838        cx.notify();
 1839    }
 1840
 1841    pub fn set_current_line_highlight(
 1842        &mut self,
 1843        current_line_highlight: Option<CurrentLineHighlight>,
 1844    ) {
 1845        self.current_line_highlight = current_line_highlight;
 1846    }
 1847
 1848    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1849        self.collapse_matches = collapse_matches;
 1850    }
 1851
 1852    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1853        let buffers = self.buffer.read(cx).all_buffers();
 1854        let Some(lsp_store) = self.lsp_store(cx) else {
 1855            return;
 1856        };
 1857        lsp_store.update(cx, |lsp_store, cx| {
 1858            for buffer in buffers {
 1859                self.registered_buffers
 1860                    .entry(buffer.read(cx).remote_id())
 1861                    .or_insert_with(|| {
 1862                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1863                    });
 1864            }
 1865        })
 1866    }
 1867
 1868    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1869        if self.collapse_matches {
 1870            return range.start..range.start;
 1871        }
 1872        range.clone()
 1873    }
 1874
 1875    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1876        if self.display_map.read(cx).clip_at_line_ends != clip {
 1877            self.display_map
 1878                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1879        }
 1880    }
 1881
 1882    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1883        self.input_enabled = input_enabled;
 1884    }
 1885
 1886    pub fn set_inline_completions_hidden_for_vim_mode(
 1887        &mut self,
 1888        hidden: bool,
 1889        window: &mut Window,
 1890        cx: &mut Context<Self>,
 1891    ) {
 1892        if hidden != self.inline_completions_hidden_for_vim_mode {
 1893            self.inline_completions_hidden_for_vim_mode = hidden;
 1894            if hidden {
 1895                self.update_visible_inline_completion(window, cx);
 1896            } else {
 1897                self.refresh_inline_completion(true, false, window, cx);
 1898            }
 1899        }
 1900    }
 1901
 1902    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1903        self.menu_inline_completions_policy = value;
 1904    }
 1905
 1906    pub fn set_autoindent(&mut self, autoindent: bool) {
 1907        if autoindent {
 1908            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1909        } else {
 1910            self.autoindent_mode = None;
 1911        }
 1912    }
 1913
 1914    pub fn read_only(&self, cx: &App) -> bool {
 1915        self.read_only || self.buffer.read(cx).read_only()
 1916    }
 1917
 1918    pub fn set_read_only(&mut self, read_only: bool) {
 1919        self.read_only = read_only;
 1920    }
 1921
 1922    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1923        self.use_autoclose = autoclose;
 1924    }
 1925
 1926    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1927        self.use_auto_surround = auto_surround;
 1928    }
 1929
 1930    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1931        self.auto_replace_emoji_shortcode = auto_replace;
 1932    }
 1933
 1934    pub fn toggle_inline_completions(
 1935        &mut self,
 1936        _: &ToggleEditPrediction,
 1937        window: &mut Window,
 1938        cx: &mut Context<Self>,
 1939    ) {
 1940        if self.show_inline_completions_override.is_some() {
 1941            self.set_show_edit_predictions(None, window, cx);
 1942        } else {
 1943            let show_edit_predictions = !self.edit_predictions_enabled();
 1944            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1945        }
 1946    }
 1947
 1948    pub fn set_show_edit_predictions(
 1949        &mut self,
 1950        show_edit_predictions: Option<bool>,
 1951        window: &mut Window,
 1952        cx: &mut Context<Self>,
 1953    ) {
 1954        self.show_inline_completions_override = show_edit_predictions;
 1955        self.refresh_inline_completion(false, true, window, cx);
 1956    }
 1957
 1958    fn inline_completions_disabled_in_scope(
 1959        &self,
 1960        buffer: &Entity<Buffer>,
 1961        buffer_position: language::Anchor,
 1962        cx: &App,
 1963    ) -> bool {
 1964        let snapshot = buffer.read(cx).snapshot();
 1965        let settings = snapshot.settings_at(buffer_position, cx);
 1966
 1967        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1968            return false;
 1969        };
 1970
 1971        scope.override_name().map_or(false, |scope_name| {
 1972            settings
 1973                .edit_predictions_disabled_in
 1974                .iter()
 1975                .any(|s| s == scope_name)
 1976        })
 1977    }
 1978
 1979    pub fn set_use_modal_editing(&mut self, to: bool) {
 1980        self.use_modal_editing = to;
 1981    }
 1982
 1983    pub fn use_modal_editing(&self) -> bool {
 1984        self.use_modal_editing
 1985    }
 1986
 1987    fn selections_did_change(
 1988        &mut self,
 1989        local: bool,
 1990        old_cursor_position: &Anchor,
 1991        show_completions: bool,
 1992        window: &mut Window,
 1993        cx: &mut Context<Self>,
 1994    ) {
 1995        window.invalidate_character_coordinates();
 1996
 1997        // Copy selections to primary selection buffer
 1998        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1999        if local {
 2000            let selections = self.selections.all::<usize>(cx);
 2001            let buffer_handle = self.buffer.read(cx).read(cx);
 2002
 2003            let mut text = String::new();
 2004            for (index, selection) in selections.iter().enumerate() {
 2005                let text_for_selection = buffer_handle
 2006                    .text_for_range(selection.start..selection.end)
 2007                    .collect::<String>();
 2008
 2009                text.push_str(&text_for_selection);
 2010                if index != selections.len() - 1 {
 2011                    text.push('\n');
 2012                }
 2013            }
 2014
 2015            if !text.is_empty() {
 2016                cx.write_to_primary(ClipboardItem::new_string(text));
 2017            }
 2018        }
 2019
 2020        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2021            self.buffer.update(cx, |buffer, cx| {
 2022                buffer.set_active_selections(
 2023                    &self.selections.disjoint_anchors(),
 2024                    self.selections.line_mode,
 2025                    self.cursor_shape,
 2026                    cx,
 2027                )
 2028            });
 2029        }
 2030        let display_map = self
 2031            .display_map
 2032            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2033        let buffer = &display_map.buffer_snapshot;
 2034        self.add_selections_state = None;
 2035        self.select_next_state = None;
 2036        self.select_prev_state = None;
 2037        self.select_larger_syntax_node_stack.clear();
 2038        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2039        self.snippet_stack
 2040            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2041        self.take_rename(false, window, cx);
 2042
 2043        let new_cursor_position = self.selections.newest_anchor().head();
 2044
 2045        self.push_to_nav_history(
 2046            *old_cursor_position,
 2047            Some(new_cursor_position.to_point(buffer)),
 2048            cx,
 2049        );
 2050
 2051        if local {
 2052            let new_cursor_position = self.selections.newest_anchor().head();
 2053            let mut context_menu = self.context_menu.borrow_mut();
 2054            let completion_menu = match context_menu.as_ref() {
 2055                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2056                _ => {
 2057                    *context_menu = None;
 2058                    None
 2059                }
 2060            };
 2061            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2062                if !self.registered_buffers.contains_key(&buffer_id) {
 2063                    if let Some(lsp_store) = self.lsp_store(cx) {
 2064                        lsp_store.update(cx, |lsp_store, cx| {
 2065                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2066                                return;
 2067                            };
 2068                            self.registered_buffers.insert(
 2069                                buffer_id,
 2070                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2071                            );
 2072                        })
 2073                    }
 2074                }
 2075            }
 2076
 2077            if let Some(completion_menu) = completion_menu {
 2078                let cursor_position = new_cursor_position.to_offset(buffer);
 2079                let (word_range, kind) =
 2080                    buffer.surrounding_word(completion_menu.initial_position, true);
 2081                if kind == Some(CharKind::Word)
 2082                    && word_range.to_inclusive().contains(&cursor_position)
 2083                {
 2084                    let mut completion_menu = completion_menu.clone();
 2085                    drop(context_menu);
 2086
 2087                    let query = Self::completion_query(buffer, cursor_position);
 2088                    cx.spawn(move |this, mut cx| async move {
 2089                        completion_menu
 2090                            .filter(query.as_deref(), cx.background_executor().clone())
 2091                            .await;
 2092
 2093                        this.update(&mut cx, |this, cx| {
 2094                            let mut context_menu = this.context_menu.borrow_mut();
 2095                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2096                            else {
 2097                                return;
 2098                            };
 2099
 2100                            if menu.id > completion_menu.id {
 2101                                return;
 2102                            }
 2103
 2104                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2105                            drop(context_menu);
 2106                            cx.notify();
 2107                        })
 2108                    })
 2109                    .detach();
 2110
 2111                    if show_completions {
 2112                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2113                    }
 2114                } else {
 2115                    drop(context_menu);
 2116                    self.hide_context_menu(window, cx);
 2117                }
 2118            } else {
 2119                drop(context_menu);
 2120            }
 2121
 2122            hide_hover(self, cx);
 2123
 2124            if old_cursor_position.to_display_point(&display_map).row()
 2125                != new_cursor_position.to_display_point(&display_map).row()
 2126            {
 2127                self.available_code_actions.take();
 2128            }
 2129            self.refresh_code_actions(window, cx);
 2130            self.refresh_document_highlights(cx);
 2131            refresh_matching_bracket_highlights(self, window, cx);
 2132            self.update_visible_inline_completion(window, cx);
 2133            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2134            if self.git_blame_inline_enabled {
 2135                self.start_inline_blame_timer(window, cx);
 2136            }
 2137        }
 2138
 2139        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2140        cx.emit(EditorEvent::SelectionsChanged { local });
 2141
 2142        if self.selections.disjoint_anchors().len() == 1 {
 2143            cx.emit(SearchEvent::ActiveMatchChanged)
 2144        }
 2145        cx.notify();
 2146    }
 2147
 2148    pub fn change_selections<R>(
 2149        &mut self,
 2150        autoscroll: Option<Autoscroll>,
 2151        window: &mut Window,
 2152        cx: &mut Context<Self>,
 2153        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2154    ) -> R {
 2155        self.change_selections_inner(autoscroll, true, window, cx, change)
 2156    }
 2157
 2158    pub fn change_selections_inner<R>(
 2159        &mut self,
 2160        autoscroll: Option<Autoscroll>,
 2161        request_completions: bool,
 2162        window: &mut Window,
 2163        cx: &mut Context<Self>,
 2164        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2165    ) -> R {
 2166        let old_cursor_position = self.selections.newest_anchor().head();
 2167        self.push_to_selection_history();
 2168
 2169        let (changed, result) = self.selections.change_with(cx, change);
 2170
 2171        if changed {
 2172            if let Some(autoscroll) = autoscroll {
 2173                self.request_autoscroll(autoscroll, cx);
 2174            }
 2175            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2176
 2177            if self.should_open_signature_help_automatically(
 2178                &old_cursor_position,
 2179                self.signature_help_state.backspace_pressed(),
 2180                cx,
 2181            ) {
 2182                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2183            }
 2184            self.signature_help_state.set_backspace_pressed(false);
 2185        }
 2186
 2187        result
 2188    }
 2189
 2190    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2191    where
 2192        I: IntoIterator<Item = (Range<S>, T)>,
 2193        S: ToOffset,
 2194        T: Into<Arc<str>>,
 2195    {
 2196        if self.read_only(cx) {
 2197            return;
 2198        }
 2199
 2200        self.buffer
 2201            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2202    }
 2203
 2204    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2205    where
 2206        I: IntoIterator<Item = (Range<S>, T)>,
 2207        S: ToOffset,
 2208        T: Into<Arc<str>>,
 2209    {
 2210        if self.read_only(cx) {
 2211            return;
 2212        }
 2213
 2214        self.buffer.update(cx, |buffer, cx| {
 2215            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2216        });
 2217    }
 2218
 2219    pub fn edit_with_block_indent<I, S, T>(
 2220        &mut self,
 2221        edits: I,
 2222        original_indent_columns: Vec<u32>,
 2223        cx: &mut Context<Self>,
 2224    ) where
 2225        I: IntoIterator<Item = (Range<S>, T)>,
 2226        S: ToOffset,
 2227        T: Into<Arc<str>>,
 2228    {
 2229        if self.read_only(cx) {
 2230            return;
 2231        }
 2232
 2233        self.buffer.update(cx, |buffer, cx| {
 2234            buffer.edit(
 2235                edits,
 2236                Some(AutoindentMode::Block {
 2237                    original_indent_columns,
 2238                }),
 2239                cx,
 2240            )
 2241        });
 2242    }
 2243
 2244    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2245        self.hide_context_menu(window, cx);
 2246
 2247        match phase {
 2248            SelectPhase::Begin {
 2249                position,
 2250                add,
 2251                click_count,
 2252            } => self.begin_selection(position, add, click_count, window, cx),
 2253            SelectPhase::BeginColumnar {
 2254                position,
 2255                goal_column,
 2256                reset,
 2257            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2258            SelectPhase::Extend {
 2259                position,
 2260                click_count,
 2261            } => self.extend_selection(position, click_count, window, cx),
 2262            SelectPhase::Update {
 2263                position,
 2264                goal_column,
 2265                scroll_delta,
 2266            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2267            SelectPhase::End => self.end_selection(window, cx),
 2268        }
 2269    }
 2270
 2271    fn extend_selection(
 2272        &mut self,
 2273        position: DisplayPoint,
 2274        click_count: usize,
 2275        window: &mut Window,
 2276        cx: &mut Context<Self>,
 2277    ) {
 2278        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2279        let tail = self.selections.newest::<usize>(cx).tail();
 2280        self.begin_selection(position, false, click_count, window, cx);
 2281
 2282        let position = position.to_offset(&display_map, Bias::Left);
 2283        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2284
 2285        let mut pending_selection = self
 2286            .selections
 2287            .pending_anchor()
 2288            .expect("extend_selection not called with pending selection");
 2289        if position >= tail {
 2290            pending_selection.start = tail_anchor;
 2291        } else {
 2292            pending_selection.end = tail_anchor;
 2293            pending_selection.reversed = true;
 2294        }
 2295
 2296        let mut pending_mode = self.selections.pending_mode().unwrap();
 2297        match &mut pending_mode {
 2298            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2299            _ => {}
 2300        }
 2301
 2302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2303            s.set_pending(pending_selection, pending_mode)
 2304        });
 2305    }
 2306
 2307    fn begin_selection(
 2308        &mut self,
 2309        position: DisplayPoint,
 2310        add: bool,
 2311        click_count: usize,
 2312        window: &mut Window,
 2313        cx: &mut Context<Self>,
 2314    ) {
 2315        if !self.focus_handle.is_focused(window) {
 2316            self.last_focused_descendant = None;
 2317            window.focus(&self.focus_handle);
 2318        }
 2319
 2320        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2321        let buffer = &display_map.buffer_snapshot;
 2322        let newest_selection = self.selections.newest_anchor().clone();
 2323        let position = display_map.clip_point(position, Bias::Left);
 2324
 2325        let start;
 2326        let end;
 2327        let mode;
 2328        let mut auto_scroll;
 2329        match click_count {
 2330            1 => {
 2331                start = buffer.anchor_before(position.to_point(&display_map));
 2332                end = start;
 2333                mode = SelectMode::Character;
 2334                auto_scroll = true;
 2335            }
 2336            2 => {
 2337                let range = movement::surrounding_word(&display_map, position);
 2338                start = buffer.anchor_before(range.start.to_point(&display_map));
 2339                end = buffer.anchor_before(range.end.to_point(&display_map));
 2340                mode = SelectMode::Word(start..end);
 2341                auto_scroll = true;
 2342            }
 2343            3 => {
 2344                let position = display_map
 2345                    .clip_point(position, Bias::Left)
 2346                    .to_point(&display_map);
 2347                let line_start = display_map.prev_line_boundary(position).0;
 2348                let next_line_start = buffer.clip_point(
 2349                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2350                    Bias::Left,
 2351                );
 2352                start = buffer.anchor_before(line_start);
 2353                end = buffer.anchor_before(next_line_start);
 2354                mode = SelectMode::Line(start..end);
 2355                auto_scroll = true;
 2356            }
 2357            _ => {
 2358                start = buffer.anchor_before(0);
 2359                end = buffer.anchor_before(buffer.len());
 2360                mode = SelectMode::All;
 2361                auto_scroll = false;
 2362            }
 2363        }
 2364        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2365
 2366        let point_to_delete: Option<usize> = {
 2367            let selected_points: Vec<Selection<Point>> =
 2368                self.selections.disjoint_in_range(start..end, cx);
 2369
 2370            if !add || click_count > 1 {
 2371                None
 2372            } else if !selected_points.is_empty() {
 2373                Some(selected_points[0].id)
 2374            } else {
 2375                let clicked_point_already_selected =
 2376                    self.selections.disjoint.iter().find(|selection| {
 2377                        selection.start.to_point(buffer) == start.to_point(buffer)
 2378                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2379                    });
 2380
 2381                clicked_point_already_selected.map(|selection| selection.id)
 2382            }
 2383        };
 2384
 2385        let selections_count = self.selections.count();
 2386
 2387        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2388            if let Some(point_to_delete) = point_to_delete {
 2389                s.delete(point_to_delete);
 2390
 2391                if selections_count == 1 {
 2392                    s.set_pending_anchor_range(start..end, mode);
 2393                }
 2394            } else {
 2395                if !add {
 2396                    s.clear_disjoint();
 2397                } else if click_count > 1 {
 2398                    s.delete(newest_selection.id)
 2399                }
 2400
 2401                s.set_pending_anchor_range(start..end, mode);
 2402            }
 2403        });
 2404    }
 2405
 2406    fn begin_columnar_selection(
 2407        &mut self,
 2408        position: DisplayPoint,
 2409        goal_column: u32,
 2410        reset: bool,
 2411        window: &mut Window,
 2412        cx: &mut Context<Self>,
 2413    ) {
 2414        if !self.focus_handle.is_focused(window) {
 2415            self.last_focused_descendant = None;
 2416            window.focus(&self.focus_handle);
 2417        }
 2418
 2419        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2420
 2421        if reset {
 2422            let pointer_position = display_map
 2423                .buffer_snapshot
 2424                .anchor_before(position.to_point(&display_map));
 2425
 2426            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2427                s.clear_disjoint();
 2428                s.set_pending_anchor_range(
 2429                    pointer_position..pointer_position,
 2430                    SelectMode::Character,
 2431                );
 2432            });
 2433        }
 2434
 2435        let tail = self.selections.newest::<Point>(cx).tail();
 2436        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2437
 2438        if !reset {
 2439            self.select_columns(
 2440                tail.to_display_point(&display_map),
 2441                position,
 2442                goal_column,
 2443                &display_map,
 2444                window,
 2445                cx,
 2446            );
 2447        }
 2448    }
 2449
 2450    fn update_selection(
 2451        &mut self,
 2452        position: DisplayPoint,
 2453        goal_column: u32,
 2454        scroll_delta: gpui::Point<f32>,
 2455        window: &mut Window,
 2456        cx: &mut Context<Self>,
 2457    ) {
 2458        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2459
 2460        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2461            let tail = tail.to_display_point(&display_map);
 2462            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2463        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2464            let buffer = self.buffer.read(cx).snapshot(cx);
 2465            let head;
 2466            let tail;
 2467            let mode = self.selections.pending_mode().unwrap();
 2468            match &mode {
 2469                SelectMode::Character => {
 2470                    head = position.to_point(&display_map);
 2471                    tail = pending.tail().to_point(&buffer);
 2472                }
 2473                SelectMode::Word(original_range) => {
 2474                    let original_display_range = original_range.start.to_display_point(&display_map)
 2475                        ..original_range.end.to_display_point(&display_map);
 2476                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2477                        ..original_display_range.end.to_point(&display_map);
 2478                    if movement::is_inside_word(&display_map, position)
 2479                        || original_display_range.contains(&position)
 2480                    {
 2481                        let word_range = movement::surrounding_word(&display_map, position);
 2482                        if word_range.start < original_display_range.start {
 2483                            head = word_range.start.to_point(&display_map);
 2484                        } else {
 2485                            head = word_range.end.to_point(&display_map);
 2486                        }
 2487                    } else {
 2488                        head = position.to_point(&display_map);
 2489                    }
 2490
 2491                    if head <= original_buffer_range.start {
 2492                        tail = original_buffer_range.end;
 2493                    } else {
 2494                        tail = original_buffer_range.start;
 2495                    }
 2496                }
 2497                SelectMode::Line(original_range) => {
 2498                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2499
 2500                    let position = display_map
 2501                        .clip_point(position, Bias::Left)
 2502                        .to_point(&display_map);
 2503                    let line_start = display_map.prev_line_boundary(position).0;
 2504                    let next_line_start = buffer.clip_point(
 2505                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2506                        Bias::Left,
 2507                    );
 2508
 2509                    if line_start < original_range.start {
 2510                        head = line_start
 2511                    } else {
 2512                        head = next_line_start
 2513                    }
 2514
 2515                    if head <= original_range.start {
 2516                        tail = original_range.end;
 2517                    } else {
 2518                        tail = original_range.start;
 2519                    }
 2520                }
 2521                SelectMode::All => {
 2522                    return;
 2523                }
 2524            };
 2525
 2526            if head < tail {
 2527                pending.start = buffer.anchor_before(head);
 2528                pending.end = buffer.anchor_before(tail);
 2529                pending.reversed = true;
 2530            } else {
 2531                pending.start = buffer.anchor_before(tail);
 2532                pending.end = buffer.anchor_before(head);
 2533                pending.reversed = false;
 2534            }
 2535
 2536            self.change_selections(None, window, cx, |s| {
 2537                s.set_pending(pending, mode);
 2538            });
 2539        } else {
 2540            log::error!("update_selection dispatched with no pending selection");
 2541            return;
 2542        }
 2543
 2544        self.apply_scroll_delta(scroll_delta, window, cx);
 2545        cx.notify();
 2546    }
 2547
 2548    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2549        self.columnar_selection_tail.take();
 2550        if self.selections.pending_anchor().is_some() {
 2551            let selections = self.selections.all::<usize>(cx);
 2552            self.change_selections(None, window, cx, |s| {
 2553                s.select(selections);
 2554                s.clear_pending();
 2555            });
 2556        }
 2557    }
 2558
 2559    fn select_columns(
 2560        &mut self,
 2561        tail: DisplayPoint,
 2562        head: DisplayPoint,
 2563        goal_column: u32,
 2564        display_map: &DisplaySnapshot,
 2565        window: &mut Window,
 2566        cx: &mut Context<Self>,
 2567    ) {
 2568        let start_row = cmp::min(tail.row(), head.row());
 2569        let end_row = cmp::max(tail.row(), head.row());
 2570        let start_column = cmp::min(tail.column(), goal_column);
 2571        let end_column = cmp::max(tail.column(), goal_column);
 2572        let reversed = start_column < tail.column();
 2573
 2574        let selection_ranges = (start_row.0..=end_row.0)
 2575            .map(DisplayRow)
 2576            .filter_map(|row| {
 2577                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2578                    let start = display_map
 2579                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2580                        .to_point(display_map);
 2581                    let end = display_map
 2582                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2583                        .to_point(display_map);
 2584                    if reversed {
 2585                        Some(end..start)
 2586                    } else {
 2587                        Some(start..end)
 2588                    }
 2589                } else {
 2590                    None
 2591                }
 2592            })
 2593            .collect::<Vec<_>>();
 2594
 2595        self.change_selections(None, window, cx, |s| {
 2596            s.select_ranges(selection_ranges);
 2597        });
 2598        cx.notify();
 2599    }
 2600
 2601    pub fn has_pending_nonempty_selection(&self) -> bool {
 2602        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2603            Some(Selection { start, end, .. }) => start != end,
 2604            None => false,
 2605        };
 2606
 2607        pending_nonempty_selection
 2608            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2609    }
 2610
 2611    pub fn has_pending_selection(&self) -> bool {
 2612        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2613    }
 2614
 2615    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2616        self.selection_mark_mode = false;
 2617
 2618        if self.clear_expanded_diff_hunks(cx) {
 2619            cx.notify();
 2620            return;
 2621        }
 2622        if self.dismiss_menus_and_popups(true, window, cx) {
 2623            return;
 2624        }
 2625
 2626        if self.mode == EditorMode::Full
 2627            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2628        {
 2629            return;
 2630        }
 2631
 2632        cx.propagate();
 2633    }
 2634
 2635    pub fn dismiss_menus_and_popups(
 2636        &mut self,
 2637        is_user_requested: bool,
 2638        window: &mut Window,
 2639        cx: &mut Context<Self>,
 2640    ) -> bool {
 2641        if self.take_rename(false, window, cx).is_some() {
 2642            return true;
 2643        }
 2644
 2645        if hide_hover(self, cx) {
 2646            return true;
 2647        }
 2648
 2649        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2650            return true;
 2651        }
 2652
 2653        if self.hide_context_menu(window, cx).is_some() {
 2654            return true;
 2655        }
 2656
 2657        if self.mouse_context_menu.take().is_some() {
 2658            return true;
 2659        }
 2660
 2661        if is_user_requested && self.discard_inline_completion(true, cx) {
 2662            return true;
 2663        }
 2664
 2665        if self.snippet_stack.pop().is_some() {
 2666            return true;
 2667        }
 2668
 2669        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2670            self.dismiss_diagnostics(cx);
 2671            return true;
 2672        }
 2673
 2674        false
 2675    }
 2676
 2677    fn linked_editing_ranges_for(
 2678        &self,
 2679        selection: Range<text::Anchor>,
 2680        cx: &App,
 2681    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2682        if self.linked_edit_ranges.is_empty() {
 2683            return None;
 2684        }
 2685        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2686            selection.end.buffer_id.and_then(|end_buffer_id| {
 2687                if selection.start.buffer_id != Some(end_buffer_id) {
 2688                    return None;
 2689                }
 2690                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2691                let snapshot = buffer.read(cx).snapshot();
 2692                self.linked_edit_ranges
 2693                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2694                    .map(|ranges| (ranges, snapshot, buffer))
 2695            })?;
 2696        use text::ToOffset as TO;
 2697        // find offset from the start of current range to current cursor position
 2698        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2699
 2700        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2701        let start_difference = start_offset - start_byte_offset;
 2702        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2703        let end_difference = end_offset - start_byte_offset;
 2704        // Current range has associated linked ranges.
 2705        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2706        for range in linked_ranges.iter() {
 2707            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2708            let end_offset = start_offset + end_difference;
 2709            let start_offset = start_offset + start_difference;
 2710            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2711                continue;
 2712            }
 2713            if self.selections.disjoint_anchor_ranges().any(|s| {
 2714                if s.start.buffer_id != selection.start.buffer_id
 2715                    || s.end.buffer_id != selection.end.buffer_id
 2716                {
 2717                    return false;
 2718                }
 2719                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2720                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2721            }) {
 2722                continue;
 2723            }
 2724            let start = buffer_snapshot.anchor_after(start_offset);
 2725            let end = buffer_snapshot.anchor_after(end_offset);
 2726            linked_edits
 2727                .entry(buffer.clone())
 2728                .or_default()
 2729                .push(start..end);
 2730        }
 2731        Some(linked_edits)
 2732    }
 2733
 2734    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2735        let text: Arc<str> = text.into();
 2736
 2737        if self.read_only(cx) {
 2738            return;
 2739        }
 2740
 2741        let selections = self.selections.all_adjusted(cx);
 2742        let mut bracket_inserted = false;
 2743        let mut edits = Vec::new();
 2744        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2745        let mut new_selections = Vec::with_capacity(selections.len());
 2746        let mut new_autoclose_regions = Vec::new();
 2747        let snapshot = self.buffer.read(cx).read(cx);
 2748
 2749        for (selection, autoclose_region) in
 2750            self.selections_with_autoclose_regions(selections, &snapshot)
 2751        {
 2752            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2753                // Determine if the inserted text matches the opening or closing
 2754                // bracket of any of this language's bracket pairs.
 2755                let mut bracket_pair = None;
 2756                let mut is_bracket_pair_start = false;
 2757                let mut is_bracket_pair_end = false;
 2758                if !text.is_empty() {
 2759                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2760                    //  and they are removing the character that triggered IME popup.
 2761                    for (pair, enabled) in scope.brackets() {
 2762                        if !pair.close && !pair.surround {
 2763                            continue;
 2764                        }
 2765
 2766                        if enabled && pair.start.ends_with(text.as_ref()) {
 2767                            let prefix_len = pair.start.len() - text.len();
 2768                            let preceding_text_matches_prefix = prefix_len == 0
 2769                                || (selection.start.column >= (prefix_len as u32)
 2770                                    && snapshot.contains_str_at(
 2771                                        Point::new(
 2772                                            selection.start.row,
 2773                                            selection.start.column - (prefix_len as u32),
 2774                                        ),
 2775                                        &pair.start[..prefix_len],
 2776                                    ));
 2777                            if preceding_text_matches_prefix {
 2778                                bracket_pair = Some(pair.clone());
 2779                                is_bracket_pair_start = true;
 2780                                break;
 2781                            }
 2782                        }
 2783                        if pair.end.as_str() == text.as_ref() {
 2784                            bracket_pair = Some(pair.clone());
 2785                            is_bracket_pair_end = true;
 2786                            break;
 2787                        }
 2788                    }
 2789                }
 2790
 2791                if let Some(bracket_pair) = bracket_pair {
 2792                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2793                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2794                    let auto_surround =
 2795                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2796                    if selection.is_empty() {
 2797                        if is_bracket_pair_start {
 2798                            // If the inserted text is a suffix of an opening bracket and the
 2799                            // selection is preceded by the rest of the opening bracket, then
 2800                            // insert the closing bracket.
 2801                            let following_text_allows_autoclose = snapshot
 2802                                .chars_at(selection.start)
 2803                                .next()
 2804                                .map_or(true, |c| scope.should_autoclose_before(c));
 2805
 2806                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2807                                && bracket_pair.start.len() == 1
 2808                            {
 2809                                let target = bracket_pair.start.chars().next().unwrap();
 2810                                let current_line_count = snapshot
 2811                                    .reversed_chars_at(selection.start)
 2812                                    .take_while(|&c| c != '\n')
 2813                                    .filter(|&c| c == target)
 2814                                    .count();
 2815                                current_line_count % 2 == 1
 2816                            } else {
 2817                                false
 2818                            };
 2819
 2820                            if autoclose
 2821                                && bracket_pair.close
 2822                                && following_text_allows_autoclose
 2823                                && !is_closing_quote
 2824                            {
 2825                                let anchor = snapshot.anchor_before(selection.end);
 2826                                new_selections.push((selection.map(|_| anchor), text.len()));
 2827                                new_autoclose_regions.push((
 2828                                    anchor,
 2829                                    text.len(),
 2830                                    selection.id,
 2831                                    bracket_pair.clone(),
 2832                                ));
 2833                                edits.push((
 2834                                    selection.range(),
 2835                                    format!("{}{}", text, bracket_pair.end).into(),
 2836                                ));
 2837                                bracket_inserted = true;
 2838                                continue;
 2839                            }
 2840                        }
 2841
 2842                        if let Some(region) = autoclose_region {
 2843                            // If the selection is followed by an auto-inserted closing bracket,
 2844                            // then don't insert that closing bracket again; just move the selection
 2845                            // past the closing bracket.
 2846                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2847                                && text.as_ref() == region.pair.end.as_str();
 2848                            if should_skip {
 2849                                let anchor = snapshot.anchor_after(selection.end);
 2850                                new_selections
 2851                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2852                                continue;
 2853                            }
 2854                        }
 2855
 2856                        let always_treat_brackets_as_autoclosed = snapshot
 2857                            .settings_at(selection.start, cx)
 2858                            .always_treat_brackets_as_autoclosed;
 2859                        if always_treat_brackets_as_autoclosed
 2860                            && is_bracket_pair_end
 2861                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2862                        {
 2863                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2864                            // and the inserted text is a closing bracket and the selection is followed
 2865                            // by the closing bracket then move the selection past the closing bracket.
 2866                            let anchor = snapshot.anchor_after(selection.end);
 2867                            new_selections.push((selection.map(|_| anchor), text.len()));
 2868                            continue;
 2869                        }
 2870                    }
 2871                    // If an opening bracket is 1 character long and is typed while
 2872                    // text is selected, then surround that text with the bracket pair.
 2873                    else if auto_surround
 2874                        && bracket_pair.surround
 2875                        && is_bracket_pair_start
 2876                        && bracket_pair.start.chars().count() == 1
 2877                    {
 2878                        edits.push((selection.start..selection.start, text.clone()));
 2879                        edits.push((
 2880                            selection.end..selection.end,
 2881                            bracket_pair.end.as_str().into(),
 2882                        ));
 2883                        bracket_inserted = true;
 2884                        new_selections.push((
 2885                            Selection {
 2886                                id: selection.id,
 2887                                start: snapshot.anchor_after(selection.start),
 2888                                end: snapshot.anchor_before(selection.end),
 2889                                reversed: selection.reversed,
 2890                                goal: selection.goal,
 2891                            },
 2892                            0,
 2893                        ));
 2894                        continue;
 2895                    }
 2896                }
 2897            }
 2898
 2899            if self.auto_replace_emoji_shortcode
 2900                && selection.is_empty()
 2901                && text.as_ref().ends_with(':')
 2902            {
 2903                if let Some(possible_emoji_short_code) =
 2904                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2905                {
 2906                    if !possible_emoji_short_code.is_empty() {
 2907                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2908                            let emoji_shortcode_start = Point::new(
 2909                                selection.start.row,
 2910                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2911                            );
 2912
 2913                            // Remove shortcode from buffer
 2914                            edits.push((
 2915                                emoji_shortcode_start..selection.start,
 2916                                "".to_string().into(),
 2917                            ));
 2918                            new_selections.push((
 2919                                Selection {
 2920                                    id: selection.id,
 2921                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2922                                    end: snapshot.anchor_before(selection.start),
 2923                                    reversed: selection.reversed,
 2924                                    goal: selection.goal,
 2925                                },
 2926                                0,
 2927                            ));
 2928
 2929                            // Insert emoji
 2930                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2931                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2932                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2933
 2934                            continue;
 2935                        }
 2936                    }
 2937                }
 2938            }
 2939
 2940            // If not handling any auto-close operation, then just replace the selected
 2941            // text with the given input and move the selection to the end of the
 2942            // newly inserted text.
 2943            let anchor = snapshot.anchor_after(selection.end);
 2944            if !self.linked_edit_ranges.is_empty() {
 2945                let start_anchor = snapshot.anchor_before(selection.start);
 2946
 2947                let is_word_char = text.chars().next().map_or(true, |char| {
 2948                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2949                    classifier.is_word(char)
 2950                });
 2951
 2952                if is_word_char {
 2953                    if let Some(ranges) = self
 2954                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2955                    {
 2956                        for (buffer, edits) in ranges {
 2957                            linked_edits
 2958                                .entry(buffer.clone())
 2959                                .or_default()
 2960                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2961                        }
 2962                    }
 2963                }
 2964            }
 2965
 2966            new_selections.push((selection.map(|_| anchor), 0));
 2967            edits.push((selection.start..selection.end, text.clone()));
 2968        }
 2969
 2970        drop(snapshot);
 2971
 2972        self.transact(window, cx, |this, window, cx| {
 2973            this.buffer.update(cx, |buffer, cx| {
 2974                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2975            });
 2976            for (buffer, edits) in linked_edits {
 2977                buffer.update(cx, |buffer, cx| {
 2978                    let snapshot = buffer.snapshot();
 2979                    let edits = edits
 2980                        .into_iter()
 2981                        .map(|(range, text)| {
 2982                            use text::ToPoint as TP;
 2983                            let end_point = TP::to_point(&range.end, &snapshot);
 2984                            let start_point = TP::to_point(&range.start, &snapshot);
 2985                            (start_point..end_point, text)
 2986                        })
 2987                        .sorted_by_key(|(range, _)| range.start)
 2988                        .collect::<Vec<_>>();
 2989                    buffer.edit(edits, None, cx);
 2990                })
 2991            }
 2992            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2993            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2994            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2995            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2996                .zip(new_selection_deltas)
 2997                .map(|(selection, delta)| Selection {
 2998                    id: selection.id,
 2999                    start: selection.start + delta,
 3000                    end: selection.end + delta,
 3001                    reversed: selection.reversed,
 3002                    goal: SelectionGoal::None,
 3003                })
 3004                .collect::<Vec<_>>();
 3005
 3006            let mut i = 0;
 3007            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3008                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3009                let start = map.buffer_snapshot.anchor_before(position);
 3010                let end = map.buffer_snapshot.anchor_after(position);
 3011                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3012                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3013                        Ordering::Less => i += 1,
 3014                        Ordering::Greater => break,
 3015                        Ordering::Equal => {
 3016                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3017                                Ordering::Less => i += 1,
 3018                                Ordering::Equal => break,
 3019                                Ordering::Greater => break,
 3020                            }
 3021                        }
 3022                    }
 3023                }
 3024                this.autoclose_regions.insert(
 3025                    i,
 3026                    AutocloseRegion {
 3027                        selection_id,
 3028                        range: start..end,
 3029                        pair,
 3030                    },
 3031                );
 3032            }
 3033
 3034            let had_active_inline_completion = this.has_active_inline_completion();
 3035            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3036                s.select(new_selections)
 3037            });
 3038
 3039            if !bracket_inserted {
 3040                if let Some(on_type_format_task) =
 3041                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3042                {
 3043                    on_type_format_task.detach_and_log_err(cx);
 3044                }
 3045            }
 3046
 3047            let editor_settings = EditorSettings::get_global(cx);
 3048            if bracket_inserted
 3049                && (editor_settings.auto_signature_help
 3050                    || editor_settings.show_signature_help_after_edits)
 3051            {
 3052                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3053            }
 3054
 3055            let trigger_in_words =
 3056                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3057            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3058            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3059            this.refresh_inline_completion(true, false, window, cx);
 3060        });
 3061    }
 3062
 3063    fn find_possible_emoji_shortcode_at_position(
 3064        snapshot: &MultiBufferSnapshot,
 3065        position: Point,
 3066    ) -> Option<String> {
 3067        let mut chars = Vec::new();
 3068        let mut found_colon = false;
 3069        for char in snapshot.reversed_chars_at(position).take(100) {
 3070            // Found a possible emoji shortcode in the middle of the buffer
 3071            if found_colon {
 3072                if char.is_whitespace() {
 3073                    chars.reverse();
 3074                    return Some(chars.iter().collect());
 3075                }
 3076                // If the previous character is not a whitespace, we are in the middle of a word
 3077                // and we only want to complete the shortcode if the word is made up of other emojis
 3078                let mut containing_word = String::new();
 3079                for ch in snapshot
 3080                    .reversed_chars_at(position)
 3081                    .skip(chars.len() + 1)
 3082                    .take(100)
 3083                {
 3084                    if ch.is_whitespace() {
 3085                        break;
 3086                    }
 3087                    containing_word.push(ch);
 3088                }
 3089                let containing_word = containing_word.chars().rev().collect::<String>();
 3090                if util::word_consists_of_emojis(containing_word.as_str()) {
 3091                    chars.reverse();
 3092                    return Some(chars.iter().collect());
 3093                }
 3094            }
 3095
 3096            if char.is_whitespace() || !char.is_ascii() {
 3097                return None;
 3098            }
 3099            if char == ':' {
 3100                found_colon = true;
 3101            } else {
 3102                chars.push(char);
 3103            }
 3104        }
 3105        // Found a possible emoji shortcode at the beginning of the buffer
 3106        chars.reverse();
 3107        Some(chars.iter().collect())
 3108    }
 3109
 3110    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3111        self.transact(window, cx, |this, window, cx| {
 3112            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3113                let selections = this.selections.all::<usize>(cx);
 3114                let multi_buffer = this.buffer.read(cx);
 3115                let buffer = multi_buffer.snapshot(cx);
 3116                selections
 3117                    .iter()
 3118                    .map(|selection| {
 3119                        let start_point = selection.start.to_point(&buffer);
 3120                        let mut indent =
 3121                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3122                        indent.len = cmp::min(indent.len, start_point.column);
 3123                        let start = selection.start;
 3124                        let end = selection.end;
 3125                        let selection_is_empty = start == end;
 3126                        let language_scope = buffer.language_scope_at(start);
 3127                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3128                            &language_scope
 3129                        {
 3130                            let leading_whitespace_len = buffer
 3131                                .reversed_chars_at(start)
 3132                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3133                                .map(|c| c.len_utf8())
 3134                                .sum::<usize>();
 3135
 3136                            let trailing_whitespace_len = buffer
 3137                                .chars_at(end)
 3138                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3139                                .map(|c| c.len_utf8())
 3140                                .sum::<usize>();
 3141
 3142                            let insert_extra_newline =
 3143                                language.brackets().any(|(pair, enabled)| {
 3144                                    let pair_start = pair.start.trim_end();
 3145                                    let pair_end = pair.end.trim_start();
 3146
 3147                                    enabled
 3148                                        && pair.newline
 3149                                        && buffer.contains_str_at(
 3150                                            end + trailing_whitespace_len,
 3151                                            pair_end,
 3152                                        )
 3153                                        && buffer.contains_str_at(
 3154                                            (start - leading_whitespace_len)
 3155                                                .saturating_sub(pair_start.len()),
 3156                                            pair_start,
 3157                                        )
 3158                                });
 3159
 3160                            // Comment extension on newline is allowed only for cursor selections
 3161                            let comment_delimiter = maybe!({
 3162                                if !selection_is_empty {
 3163                                    return None;
 3164                                }
 3165
 3166                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3167                                    return None;
 3168                                }
 3169
 3170                                let delimiters = language.line_comment_prefixes();
 3171                                let max_len_of_delimiter =
 3172                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3173                                let (snapshot, range) =
 3174                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3175
 3176                                let mut index_of_first_non_whitespace = 0;
 3177                                let comment_candidate = snapshot
 3178                                    .chars_for_range(range)
 3179                                    .skip_while(|c| {
 3180                                        let should_skip = c.is_whitespace();
 3181                                        if should_skip {
 3182                                            index_of_first_non_whitespace += 1;
 3183                                        }
 3184                                        should_skip
 3185                                    })
 3186                                    .take(max_len_of_delimiter)
 3187                                    .collect::<String>();
 3188                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3189                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3190                                })?;
 3191                                let cursor_is_placed_after_comment_marker =
 3192                                    index_of_first_non_whitespace + comment_prefix.len()
 3193                                        <= start_point.column as usize;
 3194                                if cursor_is_placed_after_comment_marker {
 3195                                    Some(comment_prefix.clone())
 3196                                } else {
 3197                                    None
 3198                                }
 3199                            });
 3200                            (comment_delimiter, insert_extra_newline)
 3201                        } else {
 3202                            (None, false)
 3203                        };
 3204
 3205                        let capacity_for_delimiter = comment_delimiter
 3206                            .as_deref()
 3207                            .map(str::len)
 3208                            .unwrap_or_default();
 3209                        let mut new_text =
 3210                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3211                        new_text.push('\n');
 3212                        new_text.extend(indent.chars());
 3213                        if let Some(delimiter) = &comment_delimiter {
 3214                            new_text.push_str(delimiter);
 3215                        }
 3216                        if insert_extra_newline {
 3217                            new_text = new_text.repeat(2);
 3218                        }
 3219
 3220                        let anchor = buffer.anchor_after(end);
 3221                        let new_selection = selection.map(|_| anchor);
 3222                        (
 3223                            (start..end, new_text),
 3224                            (insert_extra_newline, new_selection),
 3225                        )
 3226                    })
 3227                    .unzip()
 3228            };
 3229
 3230            this.edit_with_autoindent(edits, cx);
 3231            let buffer = this.buffer.read(cx).snapshot(cx);
 3232            let new_selections = selection_fixup_info
 3233                .into_iter()
 3234                .map(|(extra_newline_inserted, new_selection)| {
 3235                    let mut cursor = new_selection.end.to_point(&buffer);
 3236                    if extra_newline_inserted {
 3237                        cursor.row -= 1;
 3238                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3239                    }
 3240                    new_selection.map(|_| cursor)
 3241                })
 3242                .collect();
 3243
 3244            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3245                s.select(new_selections)
 3246            });
 3247            this.refresh_inline_completion(true, false, window, cx);
 3248        });
 3249    }
 3250
 3251    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3252        let buffer = self.buffer.read(cx);
 3253        let snapshot = buffer.snapshot(cx);
 3254
 3255        let mut edits = Vec::new();
 3256        let mut rows = Vec::new();
 3257
 3258        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3259            let cursor = selection.head();
 3260            let row = cursor.row;
 3261
 3262            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3263
 3264            let newline = "\n".to_string();
 3265            edits.push((start_of_line..start_of_line, newline));
 3266
 3267            rows.push(row + rows_inserted as u32);
 3268        }
 3269
 3270        self.transact(window, cx, |editor, window, cx| {
 3271            editor.edit(edits, cx);
 3272
 3273            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3274                let mut index = 0;
 3275                s.move_cursors_with(|map, _, _| {
 3276                    let row = rows[index];
 3277                    index += 1;
 3278
 3279                    let point = Point::new(row, 0);
 3280                    let boundary = map.next_line_boundary(point).1;
 3281                    let clipped = map.clip_point(boundary, Bias::Left);
 3282
 3283                    (clipped, SelectionGoal::None)
 3284                });
 3285            });
 3286
 3287            let mut indent_edits = Vec::new();
 3288            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3289            for row in rows {
 3290                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3291                for (row, indent) in indents {
 3292                    if indent.len == 0 {
 3293                        continue;
 3294                    }
 3295
 3296                    let text = match indent.kind {
 3297                        IndentKind::Space => " ".repeat(indent.len as usize),
 3298                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3299                    };
 3300                    let point = Point::new(row.0, 0);
 3301                    indent_edits.push((point..point, text));
 3302                }
 3303            }
 3304            editor.edit(indent_edits, cx);
 3305        });
 3306    }
 3307
 3308    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3309        let buffer = self.buffer.read(cx);
 3310        let snapshot = buffer.snapshot(cx);
 3311
 3312        let mut edits = Vec::new();
 3313        let mut rows = Vec::new();
 3314        let mut rows_inserted = 0;
 3315
 3316        for selection in self.selections.all_adjusted(cx) {
 3317            let cursor = selection.head();
 3318            let row = cursor.row;
 3319
 3320            let point = Point::new(row + 1, 0);
 3321            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3322
 3323            let newline = "\n".to_string();
 3324            edits.push((start_of_line..start_of_line, newline));
 3325
 3326            rows_inserted += 1;
 3327            rows.push(row + rows_inserted);
 3328        }
 3329
 3330        self.transact(window, cx, |editor, window, cx| {
 3331            editor.edit(edits, cx);
 3332
 3333            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3334                let mut index = 0;
 3335                s.move_cursors_with(|map, _, _| {
 3336                    let row = rows[index];
 3337                    index += 1;
 3338
 3339                    let point = Point::new(row, 0);
 3340                    let boundary = map.next_line_boundary(point).1;
 3341                    let clipped = map.clip_point(boundary, Bias::Left);
 3342
 3343                    (clipped, SelectionGoal::None)
 3344                });
 3345            });
 3346
 3347            let mut indent_edits = Vec::new();
 3348            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3349            for row in rows {
 3350                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3351                for (row, indent) in indents {
 3352                    if indent.len == 0 {
 3353                        continue;
 3354                    }
 3355
 3356                    let text = match indent.kind {
 3357                        IndentKind::Space => " ".repeat(indent.len as usize),
 3358                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3359                    };
 3360                    let point = Point::new(row.0, 0);
 3361                    indent_edits.push((point..point, text));
 3362                }
 3363            }
 3364            editor.edit(indent_edits, cx);
 3365        });
 3366    }
 3367
 3368    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3369        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3370            original_indent_columns: Vec::new(),
 3371        });
 3372        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3373    }
 3374
 3375    fn insert_with_autoindent_mode(
 3376        &mut self,
 3377        text: &str,
 3378        autoindent_mode: Option<AutoindentMode>,
 3379        window: &mut Window,
 3380        cx: &mut Context<Self>,
 3381    ) {
 3382        if self.read_only(cx) {
 3383            return;
 3384        }
 3385
 3386        let text: Arc<str> = text.into();
 3387        self.transact(window, cx, |this, window, cx| {
 3388            let old_selections = this.selections.all_adjusted(cx);
 3389            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3390                let anchors = {
 3391                    let snapshot = buffer.read(cx);
 3392                    old_selections
 3393                        .iter()
 3394                        .map(|s| {
 3395                            let anchor = snapshot.anchor_after(s.head());
 3396                            s.map(|_| anchor)
 3397                        })
 3398                        .collect::<Vec<_>>()
 3399                };
 3400                buffer.edit(
 3401                    old_selections
 3402                        .iter()
 3403                        .map(|s| (s.start..s.end, text.clone())),
 3404                    autoindent_mode,
 3405                    cx,
 3406                );
 3407                anchors
 3408            });
 3409
 3410            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3411                s.select_anchors(selection_anchors);
 3412            });
 3413
 3414            cx.notify();
 3415        });
 3416    }
 3417
 3418    fn trigger_completion_on_input(
 3419        &mut self,
 3420        text: &str,
 3421        trigger_in_words: bool,
 3422        window: &mut Window,
 3423        cx: &mut Context<Self>,
 3424    ) {
 3425        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3426            self.show_completions(
 3427                &ShowCompletions {
 3428                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3429                },
 3430                window,
 3431                cx,
 3432            );
 3433        } else {
 3434            self.hide_context_menu(window, cx);
 3435        }
 3436    }
 3437
 3438    fn is_completion_trigger(
 3439        &self,
 3440        text: &str,
 3441        trigger_in_words: bool,
 3442        cx: &mut Context<Self>,
 3443    ) -> bool {
 3444        let position = self.selections.newest_anchor().head();
 3445        let multibuffer = self.buffer.read(cx);
 3446        let Some(buffer) = position
 3447            .buffer_id
 3448            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3449        else {
 3450            return false;
 3451        };
 3452
 3453        if let Some(completion_provider) = &self.completion_provider {
 3454            completion_provider.is_completion_trigger(
 3455                &buffer,
 3456                position.text_anchor,
 3457                text,
 3458                trigger_in_words,
 3459                cx,
 3460            )
 3461        } else {
 3462            false
 3463        }
 3464    }
 3465
 3466    /// If any empty selections is touching the start of its innermost containing autoclose
 3467    /// region, expand it to select the brackets.
 3468    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3469        let selections = self.selections.all::<usize>(cx);
 3470        let buffer = self.buffer.read(cx).read(cx);
 3471        let new_selections = self
 3472            .selections_with_autoclose_regions(selections, &buffer)
 3473            .map(|(mut selection, region)| {
 3474                if !selection.is_empty() {
 3475                    return selection;
 3476                }
 3477
 3478                if let Some(region) = region {
 3479                    let mut range = region.range.to_offset(&buffer);
 3480                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3481                        range.start -= region.pair.start.len();
 3482                        if buffer.contains_str_at(range.start, &region.pair.start)
 3483                            && buffer.contains_str_at(range.end, &region.pair.end)
 3484                        {
 3485                            range.end += region.pair.end.len();
 3486                            selection.start = range.start;
 3487                            selection.end = range.end;
 3488
 3489                            return selection;
 3490                        }
 3491                    }
 3492                }
 3493
 3494                let always_treat_brackets_as_autoclosed = buffer
 3495                    .settings_at(selection.start, cx)
 3496                    .always_treat_brackets_as_autoclosed;
 3497
 3498                if !always_treat_brackets_as_autoclosed {
 3499                    return selection;
 3500                }
 3501
 3502                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3503                    for (pair, enabled) in scope.brackets() {
 3504                        if !enabled || !pair.close {
 3505                            continue;
 3506                        }
 3507
 3508                        if buffer.contains_str_at(selection.start, &pair.end) {
 3509                            let pair_start_len = pair.start.len();
 3510                            if buffer.contains_str_at(
 3511                                selection.start.saturating_sub(pair_start_len),
 3512                                &pair.start,
 3513                            ) {
 3514                                selection.start -= pair_start_len;
 3515                                selection.end += pair.end.len();
 3516
 3517                                return selection;
 3518                            }
 3519                        }
 3520                    }
 3521                }
 3522
 3523                selection
 3524            })
 3525            .collect();
 3526
 3527        drop(buffer);
 3528        self.change_selections(None, window, cx, |selections| {
 3529            selections.select(new_selections)
 3530        });
 3531    }
 3532
 3533    /// Iterate the given selections, and for each one, find the smallest surrounding
 3534    /// autoclose region. This uses the ordering of the selections and the autoclose
 3535    /// regions to avoid repeated comparisons.
 3536    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3537        &'a self,
 3538        selections: impl IntoIterator<Item = Selection<D>>,
 3539        buffer: &'a MultiBufferSnapshot,
 3540    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3541        let mut i = 0;
 3542        let mut regions = self.autoclose_regions.as_slice();
 3543        selections.into_iter().map(move |selection| {
 3544            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3545
 3546            let mut enclosing = None;
 3547            while let Some(pair_state) = regions.get(i) {
 3548                if pair_state.range.end.to_offset(buffer) < range.start {
 3549                    regions = &regions[i + 1..];
 3550                    i = 0;
 3551                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3552                    break;
 3553                } else {
 3554                    if pair_state.selection_id == selection.id {
 3555                        enclosing = Some(pair_state);
 3556                    }
 3557                    i += 1;
 3558                }
 3559            }
 3560
 3561            (selection, enclosing)
 3562        })
 3563    }
 3564
 3565    /// Remove any autoclose regions that no longer contain their selection.
 3566    fn invalidate_autoclose_regions(
 3567        &mut self,
 3568        mut selections: &[Selection<Anchor>],
 3569        buffer: &MultiBufferSnapshot,
 3570    ) {
 3571        self.autoclose_regions.retain(|state| {
 3572            let mut i = 0;
 3573            while let Some(selection) = selections.get(i) {
 3574                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3575                    selections = &selections[1..];
 3576                    continue;
 3577                }
 3578                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3579                    break;
 3580                }
 3581                if selection.id == state.selection_id {
 3582                    return true;
 3583                } else {
 3584                    i += 1;
 3585                }
 3586            }
 3587            false
 3588        });
 3589    }
 3590
 3591    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3592        let offset = position.to_offset(buffer);
 3593        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3594        if offset > word_range.start && kind == Some(CharKind::Word) {
 3595            Some(
 3596                buffer
 3597                    .text_for_range(word_range.start..offset)
 3598                    .collect::<String>(),
 3599            )
 3600        } else {
 3601            None
 3602        }
 3603    }
 3604
 3605    pub fn toggle_inlay_hints(
 3606        &mut self,
 3607        _: &ToggleInlayHints,
 3608        _: &mut Window,
 3609        cx: &mut Context<Self>,
 3610    ) {
 3611        self.refresh_inlay_hints(
 3612            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3613            cx,
 3614        );
 3615    }
 3616
 3617    pub fn inlay_hints_enabled(&self) -> bool {
 3618        self.inlay_hint_cache.enabled
 3619    }
 3620
 3621    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3622        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3623            return;
 3624        }
 3625
 3626        let reason_description = reason.description();
 3627        let ignore_debounce = matches!(
 3628            reason,
 3629            InlayHintRefreshReason::SettingsChange(_)
 3630                | InlayHintRefreshReason::Toggle(_)
 3631                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3632        );
 3633        let (invalidate_cache, required_languages) = match reason {
 3634            InlayHintRefreshReason::Toggle(enabled) => {
 3635                self.inlay_hint_cache.enabled = enabled;
 3636                if enabled {
 3637                    (InvalidationStrategy::RefreshRequested, None)
 3638                } else {
 3639                    self.inlay_hint_cache.clear();
 3640                    self.splice_inlays(
 3641                        &self
 3642                            .visible_inlay_hints(cx)
 3643                            .iter()
 3644                            .map(|inlay| inlay.id)
 3645                            .collect::<Vec<InlayId>>(),
 3646                        Vec::new(),
 3647                        cx,
 3648                    );
 3649                    return;
 3650                }
 3651            }
 3652            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3653                match self.inlay_hint_cache.update_settings(
 3654                    &self.buffer,
 3655                    new_settings,
 3656                    self.visible_inlay_hints(cx),
 3657                    cx,
 3658                ) {
 3659                    ControlFlow::Break(Some(InlaySplice {
 3660                        to_remove,
 3661                        to_insert,
 3662                    })) => {
 3663                        self.splice_inlays(&to_remove, to_insert, cx);
 3664                        return;
 3665                    }
 3666                    ControlFlow::Break(None) => return,
 3667                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3668                }
 3669            }
 3670            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3671                if let Some(InlaySplice {
 3672                    to_remove,
 3673                    to_insert,
 3674                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3675                {
 3676                    self.splice_inlays(&to_remove, to_insert, cx);
 3677                }
 3678                return;
 3679            }
 3680            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3681            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3682                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3683            }
 3684            InlayHintRefreshReason::RefreshRequested => {
 3685                (InvalidationStrategy::RefreshRequested, None)
 3686            }
 3687        };
 3688
 3689        if let Some(InlaySplice {
 3690            to_remove,
 3691            to_insert,
 3692        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3693            reason_description,
 3694            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3695            invalidate_cache,
 3696            ignore_debounce,
 3697            cx,
 3698        ) {
 3699            self.splice_inlays(&to_remove, to_insert, cx);
 3700        }
 3701    }
 3702
 3703    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3704        self.display_map
 3705            .read(cx)
 3706            .current_inlays()
 3707            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3708            .cloned()
 3709            .collect()
 3710    }
 3711
 3712    pub fn excerpts_for_inlay_hints_query(
 3713        &self,
 3714        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3715        cx: &mut Context<Editor>,
 3716    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3717        let Some(project) = self.project.as_ref() else {
 3718            return HashMap::default();
 3719        };
 3720        let project = project.read(cx);
 3721        let multi_buffer = self.buffer().read(cx);
 3722        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3723        let multi_buffer_visible_start = self
 3724            .scroll_manager
 3725            .anchor()
 3726            .anchor
 3727            .to_point(&multi_buffer_snapshot);
 3728        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3729            multi_buffer_visible_start
 3730                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3731            Bias::Left,
 3732        );
 3733        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3734        multi_buffer_snapshot
 3735            .range_to_buffer_ranges(multi_buffer_visible_range)
 3736            .into_iter()
 3737            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3738            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3739                let buffer_file = project::File::from_dyn(buffer.file())?;
 3740                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3741                let worktree_entry = buffer_worktree
 3742                    .read(cx)
 3743                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3744                if worktree_entry.is_ignored {
 3745                    return None;
 3746                }
 3747
 3748                let language = buffer.language()?;
 3749                if let Some(restrict_to_languages) = restrict_to_languages {
 3750                    if !restrict_to_languages.contains(language) {
 3751                        return None;
 3752                    }
 3753                }
 3754                Some((
 3755                    excerpt_id,
 3756                    (
 3757                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3758                        buffer.version().clone(),
 3759                        excerpt_visible_range,
 3760                    ),
 3761                ))
 3762            })
 3763            .collect()
 3764    }
 3765
 3766    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3767        TextLayoutDetails {
 3768            text_system: window.text_system().clone(),
 3769            editor_style: self.style.clone().unwrap(),
 3770            rem_size: window.rem_size(),
 3771            scroll_anchor: self.scroll_manager.anchor(),
 3772            visible_rows: self.visible_line_count(),
 3773            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3774        }
 3775    }
 3776
 3777    pub fn splice_inlays(
 3778        &self,
 3779        to_remove: &[InlayId],
 3780        to_insert: Vec<Inlay>,
 3781        cx: &mut Context<Self>,
 3782    ) {
 3783        self.display_map.update(cx, |display_map, cx| {
 3784            display_map.splice_inlays(to_remove, to_insert, cx)
 3785        });
 3786        cx.notify();
 3787    }
 3788
 3789    fn trigger_on_type_formatting(
 3790        &self,
 3791        input: String,
 3792        window: &mut Window,
 3793        cx: &mut Context<Self>,
 3794    ) -> Option<Task<Result<()>>> {
 3795        if input.len() != 1 {
 3796            return None;
 3797        }
 3798
 3799        let project = self.project.as_ref()?;
 3800        let position = self.selections.newest_anchor().head();
 3801        let (buffer, buffer_position) = self
 3802            .buffer
 3803            .read(cx)
 3804            .text_anchor_for_position(position, cx)?;
 3805
 3806        let settings = language_settings::language_settings(
 3807            buffer
 3808                .read(cx)
 3809                .language_at(buffer_position)
 3810                .map(|l| l.name()),
 3811            buffer.read(cx).file(),
 3812            cx,
 3813        );
 3814        if !settings.use_on_type_format {
 3815            return None;
 3816        }
 3817
 3818        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3819        // hence we do LSP request & edit on host side only — add formats to host's history.
 3820        let push_to_lsp_host_history = true;
 3821        // If this is not the host, append its history with new edits.
 3822        let push_to_client_history = project.read(cx).is_via_collab();
 3823
 3824        let on_type_formatting = project.update(cx, |project, cx| {
 3825            project.on_type_format(
 3826                buffer.clone(),
 3827                buffer_position,
 3828                input,
 3829                push_to_lsp_host_history,
 3830                cx,
 3831            )
 3832        });
 3833        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3834            if let Some(transaction) = on_type_formatting.await? {
 3835                if push_to_client_history {
 3836                    buffer
 3837                        .update(&mut cx, |buffer, _| {
 3838                            buffer.push_transaction(transaction, Instant::now());
 3839                        })
 3840                        .ok();
 3841                }
 3842                editor.update(&mut cx, |editor, cx| {
 3843                    editor.refresh_document_highlights(cx);
 3844                })?;
 3845            }
 3846            Ok(())
 3847        }))
 3848    }
 3849
 3850    pub fn show_completions(
 3851        &mut self,
 3852        options: &ShowCompletions,
 3853        window: &mut Window,
 3854        cx: &mut Context<Self>,
 3855    ) {
 3856        if self.pending_rename.is_some() {
 3857            return;
 3858        }
 3859
 3860        let Some(provider) = self.completion_provider.as_ref() else {
 3861            return;
 3862        };
 3863
 3864        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3865            return;
 3866        }
 3867
 3868        let position = self.selections.newest_anchor().head();
 3869        if position.diff_base_anchor.is_some() {
 3870            return;
 3871        }
 3872        let (buffer, buffer_position) =
 3873            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3874                output
 3875            } else {
 3876                return;
 3877            };
 3878        let show_completion_documentation = buffer
 3879            .read(cx)
 3880            .snapshot()
 3881            .settings_at(buffer_position, cx)
 3882            .show_completion_documentation;
 3883
 3884        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3885
 3886        let trigger_kind = match &options.trigger {
 3887            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3888                CompletionTriggerKind::TRIGGER_CHARACTER
 3889            }
 3890            _ => CompletionTriggerKind::INVOKED,
 3891        };
 3892        let completion_context = CompletionContext {
 3893            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3894                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3895                    Some(String::from(trigger))
 3896                } else {
 3897                    None
 3898                }
 3899            }),
 3900            trigger_kind,
 3901        };
 3902        let completions =
 3903            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3904        let sort_completions = provider.sort_completions();
 3905
 3906        let id = post_inc(&mut self.next_completion_id);
 3907        let task = cx.spawn_in(window, |editor, mut cx| {
 3908            async move {
 3909                editor.update(&mut cx, |this, _| {
 3910                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3911                })?;
 3912                let completions = completions.await.log_err();
 3913                let menu = if let Some(completions) = completions {
 3914                    let mut menu = CompletionsMenu::new(
 3915                        id,
 3916                        sort_completions,
 3917                        show_completion_documentation,
 3918                        position,
 3919                        buffer.clone(),
 3920                        completions.into(),
 3921                    );
 3922
 3923                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3924                        .await;
 3925
 3926                    menu.visible().then_some(menu)
 3927                } else {
 3928                    None
 3929                };
 3930
 3931                editor.update_in(&mut cx, |editor, window, cx| {
 3932                    match editor.context_menu.borrow().as_ref() {
 3933                        None => {}
 3934                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3935                            if prev_menu.id > id {
 3936                                return;
 3937                            }
 3938                        }
 3939                        _ => return,
 3940                    }
 3941
 3942                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3943                        let mut menu = menu.unwrap();
 3944                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3945
 3946                        *editor.context_menu.borrow_mut() =
 3947                            Some(CodeContextMenu::Completions(menu));
 3948
 3949                        if editor.show_edit_predictions_in_menu() {
 3950                            editor.update_visible_inline_completion(window, cx);
 3951                        } else {
 3952                            editor.discard_inline_completion(false, cx);
 3953                        }
 3954
 3955                        cx.notify();
 3956                    } else if editor.completion_tasks.len() <= 1 {
 3957                        // If there are no more completion tasks and the last menu was
 3958                        // empty, we should hide it.
 3959                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3960                        // If it was already hidden and we don't show inline
 3961                        // completions in the menu, we should also show the
 3962                        // inline-completion when available.
 3963                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3964                            editor.update_visible_inline_completion(window, cx);
 3965                        }
 3966                    }
 3967                })?;
 3968
 3969                Ok::<_, anyhow::Error>(())
 3970            }
 3971            .log_err()
 3972        });
 3973
 3974        self.completion_tasks.push((id, task));
 3975    }
 3976
 3977    pub fn confirm_completion(
 3978        &mut self,
 3979        action: &ConfirmCompletion,
 3980        window: &mut Window,
 3981        cx: &mut Context<Self>,
 3982    ) -> Option<Task<Result<()>>> {
 3983        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3984    }
 3985
 3986    pub fn compose_completion(
 3987        &mut self,
 3988        action: &ComposeCompletion,
 3989        window: &mut Window,
 3990        cx: &mut Context<Self>,
 3991    ) -> Option<Task<Result<()>>> {
 3992        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3993    }
 3994
 3995    fn do_completion(
 3996        &mut self,
 3997        item_ix: Option<usize>,
 3998        intent: CompletionIntent,
 3999        window: &mut Window,
 4000        cx: &mut Context<Editor>,
 4001    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4002        use language::ToOffset as _;
 4003
 4004        let completions_menu =
 4005            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4006                menu
 4007            } else {
 4008                return None;
 4009            };
 4010
 4011        let entries = completions_menu.entries.borrow();
 4012        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4013        if self.show_edit_predictions_in_menu() {
 4014            self.discard_inline_completion(true, cx);
 4015        }
 4016        let candidate_id = mat.candidate_id;
 4017        drop(entries);
 4018
 4019        let buffer_handle = completions_menu.buffer;
 4020        let completion = completions_menu
 4021            .completions
 4022            .borrow()
 4023            .get(candidate_id)?
 4024            .clone();
 4025        cx.stop_propagation();
 4026
 4027        let snippet;
 4028        let text;
 4029
 4030        if completion.is_snippet() {
 4031            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4032            text = snippet.as_ref().unwrap().text.clone();
 4033        } else {
 4034            snippet = None;
 4035            text = completion.new_text.clone();
 4036        };
 4037        let selections = self.selections.all::<usize>(cx);
 4038        let buffer = buffer_handle.read(cx);
 4039        let old_range = completion.old_range.to_offset(buffer);
 4040        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4041
 4042        let newest_selection = self.selections.newest_anchor();
 4043        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4044            return None;
 4045        }
 4046
 4047        let lookbehind = newest_selection
 4048            .start
 4049            .text_anchor
 4050            .to_offset(buffer)
 4051            .saturating_sub(old_range.start);
 4052        let lookahead = old_range
 4053            .end
 4054            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4055        let mut common_prefix_len = old_text
 4056            .bytes()
 4057            .zip(text.bytes())
 4058            .take_while(|(a, b)| a == b)
 4059            .count();
 4060
 4061        let snapshot = self.buffer.read(cx).snapshot(cx);
 4062        let mut range_to_replace: Option<Range<isize>> = None;
 4063        let mut ranges = Vec::new();
 4064        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4065        for selection in &selections {
 4066            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4067                let start = selection.start.saturating_sub(lookbehind);
 4068                let end = selection.end + lookahead;
 4069                if selection.id == newest_selection.id {
 4070                    range_to_replace = Some(
 4071                        ((start + common_prefix_len) as isize - selection.start as isize)
 4072                            ..(end as isize - selection.start as isize),
 4073                    );
 4074                }
 4075                ranges.push(start + common_prefix_len..end);
 4076            } else {
 4077                common_prefix_len = 0;
 4078                ranges.clear();
 4079                ranges.extend(selections.iter().map(|s| {
 4080                    if s.id == newest_selection.id {
 4081                        range_to_replace = Some(
 4082                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4083                                - selection.start as isize
 4084                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4085                                    - selection.start as isize,
 4086                        );
 4087                        old_range.clone()
 4088                    } else {
 4089                        s.start..s.end
 4090                    }
 4091                }));
 4092                break;
 4093            }
 4094            if !self.linked_edit_ranges.is_empty() {
 4095                let start_anchor = snapshot.anchor_before(selection.head());
 4096                let end_anchor = snapshot.anchor_after(selection.tail());
 4097                if let Some(ranges) = self
 4098                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4099                {
 4100                    for (buffer, edits) in ranges {
 4101                        linked_edits.entry(buffer.clone()).or_default().extend(
 4102                            edits
 4103                                .into_iter()
 4104                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4105                        );
 4106                    }
 4107                }
 4108            }
 4109        }
 4110        let text = &text[common_prefix_len..];
 4111
 4112        cx.emit(EditorEvent::InputHandled {
 4113            utf16_range_to_replace: range_to_replace,
 4114            text: text.into(),
 4115        });
 4116
 4117        self.transact(window, cx, |this, window, cx| {
 4118            if let Some(mut snippet) = snippet {
 4119                snippet.text = text.to_string();
 4120                for tabstop in snippet
 4121                    .tabstops
 4122                    .iter_mut()
 4123                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4124                {
 4125                    tabstop.start -= common_prefix_len as isize;
 4126                    tabstop.end -= common_prefix_len as isize;
 4127                }
 4128
 4129                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4130            } else {
 4131                this.buffer.update(cx, |buffer, cx| {
 4132                    buffer.edit(
 4133                        ranges.iter().map(|range| (range.clone(), text)),
 4134                        this.autoindent_mode.clone(),
 4135                        cx,
 4136                    );
 4137                });
 4138            }
 4139            for (buffer, edits) in linked_edits {
 4140                buffer.update(cx, |buffer, cx| {
 4141                    let snapshot = buffer.snapshot();
 4142                    let edits = edits
 4143                        .into_iter()
 4144                        .map(|(range, text)| {
 4145                            use text::ToPoint as TP;
 4146                            let end_point = TP::to_point(&range.end, &snapshot);
 4147                            let start_point = TP::to_point(&range.start, &snapshot);
 4148                            (start_point..end_point, text)
 4149                        })
 4150                        .sorted_by_key(|(range, _)| range.start)
 4151                        .collect::<Vec<_>>();
 4152                    buffer.edit(edits, None, cx);
 4153                })
 4154            }
 4155
 4156            this.refresh_inline_completion(true, false, window, cx);
 4157        });
 4158
 4159        let show_new_completions_on_confirm = completion
 4160            .confirm
 4161            .as_ref()
 4162            .map_or(false, |confirm| confirm(intent, window, cx));
 4163        if show_new_completions_on_confirm {
 4164            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4165        }
 4166
 4167        let provider = self.completion_provider.as_ref()?;
 4168        drop(completion);
 4169        let apply_edits = provider.apply_additional_edits_for_completion(
 4170            buffer_handle,
 4171            completions_menu.completions.clone(),
 4172            candidate_id,
 4173            true,
 4174            cx,
 4175        );
 4176
 4177        let editor_settings = EditorSettings::get_global(cx);
 4178        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4179            // After the code completion is finished, users often want to know what signatures are needed.
 4180            // so we should automatically call signature_help
 4181            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4182        }
 4183
 4184        Some(cx.foreground_executor().spawn(async move {
 4185            apply_edits.await?;
 4186            Ok(())
 4187        }))
 4188    }
 4189
 4190    pub fn toggle_code_actions(
 4191        &mut self,
 4192        action: &ToggleCodeActions,
 4193        window: &mut Window,
 4194        cx: &mut Context<Self>,
 4195    ) {
 4196        let mut context_menu = self.context_menu.borrow_mut();
 4197        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4198            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4199                // Toggle if we're selecting the same one
 4200                *context_menu = None;
 4201                cx.notify();
 4202                return;
 4203            } else {
 4204                // Otherwise, clear it and start a new one
 4205                *context_menu = None;
 4206                cx.notify();
 4207            }
 4208        }
 4209        drop(context_menu);
 4210        let snapshot = self.snapshot(window, cx);
 4211        let deployed_from_indicator = action.deployed_from_indicator;
 4212        let mut task = self.code_actions_task.take();
 4213        let action = action.clone();
 4214        cx.spawn_in(window, |editor, mut cx| async move {
 4215            while let Some(prev_task) = task {
 4216                prev_task.await.log_err();
 4217                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4218            }
 4219
 4220            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4221                if editor.focus_handle.is_focused(window) {
 4222                    let multibuffer_point = action
 4223                        .deployed_from_indicator
 4224                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4225                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4226                    let (buffer, buffer_row) = snapshot
 4227                        .buffer_snapshot
 4228                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4229                        .and_then(|(buffer_snapshot, range)| {
 4230                            editor
 4231                                .buffer
 4232                                .read(cx)
 4233                                .buffer(buffer_snapshot.remote_id())
 4234                                .map(|buffer| (buffer, range.start.row))
 4235                        })?;
 4236                    let (_, code_actions) = editor
 4237                        .available_code_actions
 4238                        .clone()
 4239                        .and_then(|(location, code_actions)| {
 4240                            let snapshot = location.buffer.read(cx).snapshot();
 4241                            let point_range = location.range.to_point(&snapshot);
 4242                            let point_range = point_range.start.row..=point_range.end.row;
 4243                            if point_range.contains(&buffer_row) {
 4244                                Some((location, code_actions))
 4245                            } else {
 4246                                None
 4247                            }
 4248                        })
 4249                        .unzip();
 4250                    let buffer_id = buffer.read(cx).remote_id();
 4251                    let tasks = editor
 4252                        .tasks
 4253                        .get(&(buffer_id, buffer_row))
 4254                        .map(|t| Arc::new(t.to_owned()));
 4255                    if tasks.is_none() && code_actions.is_none() {
 4256                        return None;
 4257                    }
 4258
 4259                    editor.completion_tasks.clear();
 4260                    editor.discard_inline_completion(false, cx);
 4261                    let task_context =
 4262                        tasks
 4263                            .as_ref()
 4264                            .zip(editor.project.clone())
 4265                            .map(|(tasks, project)| {
 4266                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4267                            });
 4268
 4269                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4270                        let task_context = match task_context {
 4271                            Some(task_context) => task_context.await,
 4272                            None => None,
 4273                        };
 4274                        let resolved_tasks =
 4275                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4276                                Rc::new(ResolvedTasks {
 4277                                    templates: tasks.resolve(&task_context).collect(),
 4278                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4279                                        multibuffer_point.row,
 4280                                        tasks.column,
 4281                                    )),
 4282                                })
 4283                            });
 4284                        let spawn_straight_away = resolved_tasks
 4285                            .as_ref()
 4286                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4287                            && code_actions
 4288                                .as_ref()
 4289                                .map_or(true, |actions| actions.is_empty());
 4290                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4291                            *editor.context_menu.borrow_mut() =
 4292                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4293                                    buffer,
 4294                                    actions: CodeActionContents {
 4295                                        tasks: resolved_tasks,
 4296                                        actions: code_actions,
 4297                                    },
 4298                                    selected_item: Default::default(),
 4299                                    scroll_handle: UniformListScrollHandle::default(),
 4300                                    deployed_from_indicator,
 4301                                }));
 4302                            if spawn_straight_away {
 4303                                if let Some(task) = editor.confirm_code_action(
 4304                                    &ConfirmCodeAction { item_ix: Some(0) },
 4305                                    window,
 4306                                    cx,
 4307                                ) {
 4308                                    cx.notify();
 4309                                    return task;
 4310                                }
 4311                            }
 4312                            cx.notify();
 4313                            Task::ready(Ok(()))
 4314                        }) {
 4315                            task.await
 4316                        } else {
 4317                            Ok(())
 4318                        }
 4319                    }))
 4320                } else {
 4321                    Some(Task::ready(Ok(())))
 4322                }
 4323            })?;
 4324            if let Some(task) = spawned_test_task {
 4325                task.await?;
 4326            }
 4327
 4328            Ok::<_, anyhow::Error>(())
 4329        })
 4330        .detach_and_log_err(cx);
 4331    }
 4332
 4333    pub fn confirm_code_action(
 4334        &mut self,
 4335        action: &ConfirmCodeAction,
 4336        window: &mut Window,
 4337        cx: &mut Context<Self>,
 4338    ) -> Option<Task<Result<()>>> {
 4339        let actions_menu =
 4340            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4341                menu
 4342            } else {
 4343                return None;
 4344            };
 4345        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4346        let action = actions_menu.actions.get(action_ix)?;
 4347        let title = action.label();
 4348        let buffer = actions_menu.buffer;
 4349        let workspace = self.workspace()?;
 4350
 4351        match action {
 4352            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4353                workspace.update(cx, |workspace, cx| {
 4354                    workspace::tasks::schedule_resolved_task(
 4355                        workspace,
 4356                        task_source_kind,
 4357                        resolved_task,
 4358                        false,
 4359                        cx,
 4360                    );
 4361
 4362                    Some(Task::ready(Ok(())))
 4363                })
 4364            }
 4365            CodeActionsItem::CodeAction {
 4366                excerpt_id,
 4367                action,
 4368                provider,
 4369            } => {
 4370                let apply_code_action =
 4371                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4372                let workspace = workspace.downgrade();
 4373                Some(cx.spawn_in(window, |editor, cx| async move {
 4374                    let project_transaction = apply_code_action.await?;
 4375                    Self::open_project_transaction(
 4376                        &editor,
 4377                        workspace,
 4378                        project_transaction,
 4379                        title,
 4380                        cx,
 4381                    )
 4382                    .await
 4383                }))
 4384            }
 4385        }
 4386    }
 4387
 4388    pub async fn open_project_transaction(
 4389        this: &WeakEntity<Editor>,
 4390        workspace: WeakEntity<Workspace>,
 4391        transaction: ProjectTransaction,
 4392        title: String,
 4393        mut cx: AsyncWindowContext,
 4394    ) -> Result<()> {
 4395        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4396        cx.update(|_, cx| {
 4397            entries.sort_unstable_by_key(|(buffer, _)| {
 4398                buffer.read(cx).file().map(|f| f.path().clone())
 4399            });
 4400        })?;
 4401
 4402        // If the project transaction's edits are all contained within this editor, then
 4403        // avoid opening a new editor to display them.
 4404
 4405        if let Some((buffer, transaction)) = entries.first() {
 4406            if entries.len() == 1 {
 4407                let excerpt = this.update(&mut cx, |editor, cx| {
 4408                    editor
 4409                        .buffer()
 4410                        .read(cx)
 4411                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4412                })?;
 4413                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4414                    if excerpted_buffer == *buffer {
 4415                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4416                            let excerpt_range = excerpt_range.to_offset(buffer);
 4417                            buffer
 4418                                .edited_ranges_for_transaction::<usize>(transaction)
 4419                                .all(|range| {
 4420                                    excerpt_range.start <= range.start
 4421                                        && excerpt_range.end >= range.end
 4422                                })
 4423                        })?;
 4424
 4425                        if all_edits_within_excerpt {
 4426                            return Ok(());
 4427                        }
 4428                    }
 4429                }
 4430            }
 4431        } else {
 4432            return Ok(());
 4433        }
 4434
 4435        let mut ranges_to_highlight = Vec::new();
 4436        let excerpt_buffer = cx.new(|cx| {
 4437            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4438            for (buffer_handle, transaction) in &entries {
 4439                let buffer = buffer_handle.read(cx);
 4440                ranges_to_highlight.extend(
 4441                    multibuffer.push_excerpts_with_context_lines(
 4442                        buffer_handle.clone(),
 4443                        buffer
 4444                            .edited_ranges_for_transaction::<usize>(transaction)
 4445                            .collect(),
 4446                        DEFAULT_MULTIBUFFER_CONTEXT,
 4447                        cx,
 4448                    ),
 4449                );
 4450            }
 4451            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4452            multibuffer
 4453        })?;
 4454
 4455        workspace.update_in(&mut cx, |workspace, window, cx| {
 4456            let project = workspace.project().clone();
 4457            let editor = cx
 4458                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4459            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4460            editor.update(cx, |editor, cx| {
 4461                editor.highlight_background::<Self>(
 4462                    &ranges_to_highlight,
 4463                    |theme| theme.editor_highlighted_line_background,
 4464                    cx,
 4465                );
 4466            });
 4467        })?;
 4468
 4469        Ok(())
 4470    }
 4471
 4472    pub fn clear_code_action_providers(&mut self) {
 4473        self.code_action_providers.clear();
 4474        self.available_code_actions.take();
 4475    }
 4476
 4477    pub fn add_code_action_provider(
 4478        &mut self,
 4479        provider: Rc<dyn CodeActionProvider>,
 4480        window: &mut Window,
 4481        cx: &mut Context<Self>,
 4482    ) {
 4483        if self
 4484            .code_action_providers
 4485            .iter()
 4486            .any(|existing_provider| existing_provider.id() == provider.id())
 4487        {
 4488            return;
 4489        }
 4490
 4491        self.code_action_providers.push(provider);
 4492        self.refresh_code_actions(window, cx);
 4493    }
 4494
 4495    pub fn remove_code_action_provider(
 4496        &mut self,
 4497        id: Arc<str>,
 4498        window: &mut Window,
 4499        cx: &mut Context<Self>,
 4500    ) {
 4501        self.code_action_providers
 4502            .retain(|provider| provider.id() != id);
 4503        self.refresh_code_actions(window, cx);
 4504    }
 4505
 4506    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4507        let buffer = self.buffer.read(cx);
 4508        let newest_selection = self.selections.newest_anchor().clone();
 4509        if newest_selection.head().diff_base_anchor.is_some() {
 4510            return None;
 4511        }
 4512        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4513        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4514        if start_buffer != end_buffer {
 4515            return None;
 4516        }
 4517
 4518        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4519            cx.background_executor()
 4520                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4521                .await;
 4522
 4523            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4524                let providers = this.code_action_providers.clone();
 4525                let tasks = this
 4526                    .code_action_providers
 4527                    .iter()
 4528                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4529                    .collect::<Vec<_>>();
 4530                (providers, tasks)
 4531            })?;
 4532
 4533            let mut actions = Vec::new();
 4534            for (provider, provider_actions) in
 4535                providers.into_iter().zip(future::join_all(tasks).await)
 4536            {
 4537                if let Some(provider_actions) = provider_actions.log_err() {
 4538                    actions.extend(provider_actions.into_iter().map(|action| {
 4539                        AvailableCodeAction {
 4540                            excerpt_id: newest_selection.start.excerpt_id,
 4541                            action,
 4542                            provider: provider.clone(),
 4543                        }
 4544                    }));
 4545                }
 4546            }
 4547
 4548            this.update(&mut cx, |this, cx| {
 4549                this.available_code_actions = if actions.is_empty() {
 4550                    None
 4551                } else {
 4552                    Some((
 4553                        Location {
 4554                            buffer: start_buffer,
 4555                            range: start..end,
 4556                        },
 4557                        actions.into(),
 4558                    ))
 4559                };
 4560                cx.notify();
 4561            })
 4562        }));
 4563        None
 4564    }
 4565
 4566    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4567        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4568            self.show_git_blame_inline = false;
 4569
 4570            self.show_git_blame_inline_delay_task =
 4571                Some(cx.spawn_in(window, |this, mut cx| async move {
 4572                    cx.background_executor().timer(delay).await;
 4573
 4574                    this.update(&mut cx, |this, cx| {
 4575                        this.show_git_blame_inline = true;
 4576                        cx.notify();
 4577                    })
 4578                    .log_err();
 4579                }));
 4580        }
 4581    }
 4582
 4583    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4584        if self.pending_rename.is_some() {
 4585            return None;
 4586        }
 4587
 4588        let provider = self.semantics_provider.clone()?;
 4589        let buffer = self.buffer.read(cx);
 4590        let newest_selection = self.selections.newest_anchor().clone();
 4591        let cursor_position = newest_selection.head();
 4592        let (cursor_buffer, cursor_buffer_position) =
 4593            buffer.text_anchor_for_position(cursor_position, cx)?;
 4594        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4595        if cursor_buffer != tail_buffer {
 4596            return None;
 4597        }
 4598        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4599        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4600            cx.background_executor()
 4601                .timer(Duration::from_millis(debounce))
 4602                .await;
 4603
 4604            let highlights = if let Some(highlights) = cx
 4605                .update(|cx| {
 4606                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4607                })
 4608                .ok()
 4609                .flatten()
 4610            {
 4611                highlights.await.log_err()
 4612            } else {
 4613                None
 4614            };
 4615
 4616            if let Some(highlights) = highlights {
 4617                this.update(&mut cx, |this, cx| {
 4618                    if this.pending_rename.is_some() {
 4619                        return;
 4620                    }
 4621
 4622                    let buffer_id = cursor_position.buffer_id;
 4623                    let buffer = this.buffer.read(cx);
 4624                    if !buffer
 4625                        .text_anchor_for_position(cursor_position, cx)
 4626                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4627                    {
 4628                        return;
 4629                    }
 4630
 4631                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4632                    let mut write_ranges = Vec::new();
 4633                    let mut read_ranges = Vec::new();
 4634                    for highlight in highlights {
 4635                        for (excerpt_id, excerpt_range) in
 4636                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4637                        {
 4638                            let start = highlight
 4639                                .range
 4640                                .start
 4641                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4642                            let end = highlight
 4643                                .range
 4644                                .end
 4645                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4646                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4647                                continue;
 4648                            }
 4649
 4650                            let range = Anchor {
 4651                                buffer_id,
 4652                                excerpt_id,
 4653                                text_anchor: start,
 4654                                diff_base_anchor: None,
 4655                            }..Anchor {
 4656                                buffer_id,
 4657                                excerpt_id,
 4658                                text_anchor: end,
 4659                                diff_base_anchor: None,
 4660                            };
 4661                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4662                                write_ranges.push(range);
 4663                            } else {
 4664                                read_ranges.push(range);
 4665                            }
 4666                        }
 4667                    }
 4668
 4669                    this.highlight_background::<DocumentHighlightRead>(
 4670                        &read_ranges,
 4671                        |theme| theme.editor_document_highlight_read_background,
 4672                        cx,
 4673                    );
 4674                    this.highlight_background::<DocumentHighlightWrite>(
 4675                        &write_ranges,
 4676                        |theme| theme.editor_document_highlight_write_background,
 4677                        cx,
 4678                    );
 4679                    cx.notify();
 4680                })
 4681                .log_err();
 4682            }
 4683        }));
 4684        None
 4685    }
 4686
 4687    pub fn refresh_inline_completion(
 4688        &mut self,
 4689        debounce: bool,
 4690        user_requested: bool,
 4691        window: &mut Window,
 4692        cx: &mut Context<Self>,
 4693    ) -> Option<()> {
 4694        let provider = self.edit_prediction_provider()?;
 4695        let cursor = self.selections.newest_anchor().head();
 4696        let (buffer, cursor_buffer_position) =
 4697            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4698
 4699        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4700            self.discard_inline_completion(false, cx);
 4701            return None;
 4702        }
 4703
 4704        if !user_requested
 4705            && (!self.should_show_edit_predictions()
 4706                || !self.is_focused(window)
 4707                || buffer.read(cx).is_empty())
 4708        {
 4709            self.discard_inline_completion(false, cx);
 4710            return None;
 4711        }
 4712
 4713        self.update_visible_inline_completion(window, cx);
 4714        provider.refresh(
 4715            self.project.clone(),
 4716            buffer,
 4717            cursor_buffer_position,
 4718            debounce,
 4719            cx,
 4720        );
 4721        Some(())
 4722    }
 4723
 4724    fn show_edit_predictions_in_menu(&self) -> bool {
 4725        match self.edit_prediction_settings {
 4726            EditPredictionSettings::Disabled => false,
 4727            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4728        }
 4729    }
 4730
 4731    pub fn edit_predictions_enabled(&self) -> bool {
 4732        match self.edit_prediction_settings {
 4733            EditPredictionSettings::Disabled => false,
 4734            EditPredictionSettings::Enabled { .. } => true,
 4735        }
 4736    }
 4737
 4738    fn edit_prediction_requires_modifier(&self) -> bool {
 4739        match self.edit_prediction_settings {
 4740            EditPredictionSettings::Disabled => false,
 4741            EditPredictionSettings::Enabled {
 4742                preview_requires_modifier,
 4743                ..
 4744            } => preview_requires_modifier,
 4745        }
 4746    }
 4747
 4748    fn edit_prediction_settings_at_position(
 4749        &self,
 4750        buffer: &Entity<Buffer>,
 4751        buffer_position: language::Anchor,
 4752        cx: &App,
 4753    ) -> EditPredictionSettings {
 4754        if self.mode != EditorMode::Full
 4755            || !self.show_inline_completions_override.unwrap_or(true)
 4756            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4757        {
 4758            return EditPredictionSettings::Disabled;
 4759        }
 4760
 4761        let buffer = buffer.read(cx);
 4762
 4763        let file = buffer.file();
 4764
 4765        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4766            return EditPredictionSettings::Disabled;
 4767        };
 4768
 4769        let by_provider = matches!(
 4770            self.menu_inline_completions_policy,
 4771            MenuInlineCompletionsPolicy::ByProvider
 4772        );
 4773
 4774        let show_in_menu = by_provider
 4775            && self
 4776                .edit_prediction_provider
 4777                .as_ref()
 4778                .map_or(false, |provider| {
 4779                    provider.provider.show_completions_in_menu()
 4780                });
 4781
 4782        let preview_requires_modifier =
 4783            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4784
 4785        EditPredictionSettings::Enabled {
 4786            show_in_menu,
 4787            preview_requires_modifier,
 4788        }
 4789    }
 4790
 4791    fn should_show_edit_predictions(&self) -> bool {
 4792        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4793    }
 4794
 4795    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4796        match self.edit_prediction_preview {
 4797            EditPredictionPreview::Inactive => false,
 4798            EditPredictionPreview::Active { .. } => {
 4799                self.edit_prediction_requires_modifier() || self.has_visible_completions_menu()
 4800            }
 4801        }
 4802    }
 4803
 4804    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4805        let cursor = self.selections.newest_anchor().head();
 4806        if let Some((buffer, cursor_position)) =
 4807            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4808        {
 4809            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4810        } else {
 4811            false
 4812        }
 4813    }
 4814
 4815    fn inline_completions_enabled_in_buffer(
 4816        &self,
 4817        buffer: &Entity<Buffer>,
 4818        buffer_position: language::Anchor,
 4819        cx: &App,
 4820    ) -> bool {
 4821        maybe!({
 4822            let provider = self.edit_prediction_provider()?;
 4823            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4824                return Some(false);
 4825            }
 4826            let buffer = buffer.read(cx);
 4827            let Some(file) = buffer.file() else {
 4828                return Some(true);
 4829            };
 4830            let settings = all_language_settings(Some(file), cx);
 4831            Some(settings.inline_completions_enabled_for_path(file.path()))
 4832        })
 4833        .unwrap_or(false)
 4834    }
 4835
 4836    fn cycle_inline_completion(
 4837        &mut self,
 4838        direction: Direction,
 4839        window: &mut Window,
 4840        cx: &mut Context<Self>,
 4841    ) -> Option<()> {
 4842        let provider = self.edit_prediction_provider()?;
 4843        let cursor = self.selections.newest_anchor().head();
 4844        let (buffer, cursor_buffer_position) =
 4845            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4846        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4847            return None;
 4848        }
 4849
 4850        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4851        self.update_visible_inline_completion(window, cx);
 4852
 4853        Some(())
 4854    }
 4855
 4856    pub fn show_inline_completion(
 4857        &mut self,
 4858        _: &ShowEditPrediction,
 4859        window: &mut Window,
 4860        cx: &mut Context<Self>,
 4861    ) {
 4862        if !self.has_active_inline_completion() {
 4863            self.refresh_inline_completion(false, true, window, cx);
 4864            return;
 4865        }
 4866
 4867        self.update_visible_inline_completion(window, cx);
 4868    }
 4869
 4870    pub fn display_cursor_names(
 4871        &mut self,
 4872        _: &DisplayCursorNames,
 4873        window: &mut Window,
 4874        cx: &mut Context<Self>,
 4875    ) {
 4876        self.show_cursor_names(window, cx);
 4877    }
 4878
 4879    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4880        self.show_cursor_names = true;
 4881        cx.notify();
 4882        cx.spawn_in(window, |this, mut cx| async move {
 4883            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4884            this.update(&mut cx, |this, cx| {
 4885                this.show_cursor_names = false;
 4886                cx.notify()
 4887            })
 4888            .ok()
 4889        })
 4890        .detach();
 4891    }
 4892
 4893    pub fn next_edit_prediction(
 4894        &mut self,
 4895        _: &NextEditPrediction,
 4896        window: &mut Window,
 4897        cx: &mut Context<Self>,
 4898    ) {
 4899        if self.has_active_inline_completion() {
 4900            self.cycle_inline_completion(Direction::Next, window, cx);
 4901        } else {
 4902            let is_copilot_disabled = self
 4903                .refresh_inline_completion(false, true, window, cx)
 4904                .is_none();
 4905            if is_copilot_disabled {
 4906                cx.propagate();
 4907            }
 4908        }
 4909    }
 4910
 4911    pub fn previous_edit_prediction(
 4912        &mut self,
 4913        _: &PreviousEditPrediction,
 4914        window: &mut Window,
 4915        cx: &mut Context<Self>,
 4916    ) {
 4917        if self.has_active_inline_completion() {
 4918            self.cycle_inline_completion(Direction::Prev, window, cx);
 4919        } else {
 4920            let is_copilot_disabled = self
 4921                .refresh_inline_completion(false, true, window, cx)
 4922                .is_none();
 4923            if is_copilot_disabled {
 4924                cx.propagate();
 4925            }
 4926        }
 4927    }
 4928
 4929    pub fn accept_edit_prediction(
 4930        &mut self,
 4931        _: &AcceptEditPrediction,
 4932        window: &mut Window,
 4933        cx: &mut Context<Self>,
 4934    ) {
 4935        let buffer = self.buffer.read(cx);
 4936        let snapshot = buffer.snapshot(cx);
 4937        let selection = self.selections.newest_adjusted(cx);
 4938        let cursor = selection.head();
 4939        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4940        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4941        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4942        {
 4943            if cursor.column < suggested_indent.len
 4944                && cursor.column <= current_indent.len
 4945                && current_indent.len <= suggested_indent.len
 4946            {
 4947                self.tab(&Default::default(), window, cx);
 4948                return;
 4949            }
 4950        }
 4951
 4952        if self.show_edit_predictions_in_menu() {
 4953            self.hide_context_menu(window, cx);
 4954        }
 4955
 4956        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4957            return;
 4958        };
 4959
 4960        self.report_inline_completion_event(
 4961            active_inline_completion.completion_id.clone(),
 4962            true,
 4963            cx,
 4964        );
 4965
 4966        match &active_inline_completion.completion {
 4967            InlineCompletion::Move { target, .. } => {
 4968                let target = *target;
 4969
 4970                if let Some(position_map) = &self.last_position_map {
 4971                    if position_map
 4972                        .visible_row_range
 4973                        .contains(&target.to_display_point(&position_map.snapshot).row())
 4974                        || !self.edit_prediction_preview_is_active()
 4975                    {
 4976                        // Note that this is also done in vim's handler of the Tab action.
 4977                        self.change_selections(
 4978                            Some(Autoscroll::newest()),
 4979                            window,
 4980                            cx,
 4981                            |selections| {
 4982                                selections.select_anchor_ranges([target..target]);
 4983                            },
 4984                        );
 4985                        self.clear_row_highlights::<EditPredictionPreview>();
 4986
 4987                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4988                            previous_scroll_position: None,
 4989                        };
 4990                    } else {
 4991                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4992                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 4993                        };
 4994                        self.highlight_rows::<EditPredictionPreview>(
 4995                            target..target,
 4996                            cx.theme().colors().editor_highlighted_line_background,
 4997                            true,
 4998                            cx,
 4999                        );
 5000                        self.request_autoscroll(Autoscroll::fit(), cx);
 5001                    }
 5002                }
 5003            }
 5004            InlineCompletion::Edit { edits, .. } => {
 5005                if let Some(provider) = self.edit_prediction_provider() {
 5006                    provider.accept(cx);
 5007                }
 5008
 5009                let snapshot = self.buffer.read(cx).snapshot(cx);
 5010                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5011
 5012                self.buffer.update(cx, |buffer, cx| {
 5013                    buffer.edit(edits.iter().cloned(), None, cx)
 5014                });
 5015
 5016                self.change_selections(None, window, cx, |s| {
 5017                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5018                });
 5019
 5020                self.update_visible_inline_completion(window, cx);
 5021                if self.active_inline_completion.is_none() {
 5022                    self.refresh_inline_completion(true, true, window, cx);
 5023                }
 5024
 5025                cx.notify();
 5026            }
 5027        }
 5028    }
 5029
 5030    pub fn accept_partial_inline_completion(
 5031        &mut self,
 5032        _: &AcceptPartialEditPrediction,
 5033        window: &mut Window,
 5034        cx: &mut Context<Self>,
 5035    ) {
 5036        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5037            return;
 5038        };
 5039        if self.selections.count() != 1 {
 5040            return;
 5041        }
 5042
 5043        self.report_inline_completion_event(
 5044            active_inline_completion.completion_id.clone(),
 5045            true,
 5046            cx,
 5047        );
 5048
 5049        match &active_inline_completion.completion {
 5050            InlineCompletion::Move { target, .. } => {
 5051                let target = *target;
 5052                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5053                    selections.select_anchor_ranges([target..target]);
 5054                });
 5055            }
 5056            InlineCompletion::Edit { edits, .. } => {
 5057                // Find an insertion that starts at the cursor position.
 5058                let snapshot = self.buffer.read(cx).snapshot(cx);
 5059                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5060                let insertion = edits.iter().find_map(|(range, text)| {
 5061                    let range = range.to_offset(&snapshot);
 5062                    if range.is_empty() && range.start == cursor_offset {
 5063                        Some(text)
 5064                    } else {
 5065                        None
 5066                    }
 5067                });
 5068
 5069                if let Some(text) = insertion {
 5070                    let mut partial_completion = text
 5071                        .chars()
 5072                        .by_ref()
 5073                        .take_while(|c| c.is_alphabetic())
 5074                        .collect::<String>();
 5075                    if partial_completion.is_empty() {
 5076                        partial_completion = text
 5077                            .chars()
 5078                            .by_ref()
 5079                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5080                            .collect::<String>();
 5081                    }
 5082
 5083                    cx.emit(EditorEvent::InputHandled {
 5084                        utf16_range_to_replace: None,
 5085                        text: partial_completion.clone().into(),
 5086                    });
 5087
 5088                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5089
 5090                    self.refresh_inline_completion(true, true, window, cx);
 5091                    cx.notify();
 5092                } else {
 5093                    self.accept_edit_prediction(&Default::default(), window, cx);
 5094                }
 5095            }
 5096        }
 5097    }
 5098
 5099    fn discard_inline_completion(
 5100        &mut self,
 5101        should_report_inline_completion_event: bool,
 5102        cx: &mut Context<Self>,
 5103    ) -> bool {
 5104        if should_report_inline_completion_event {
 5105            let completion_id = self
 5106                .active_inline_completion
 5107                .as_ref()
 5108                .and_then(|active_completion| active_completion.completion_id.clone());
 5109
 5110            self.report_inline_completion_event(completion_id, false, cx);
 5111        }
 5112
 5113        if let Some(provider) = self.edit_prediction_provider() {
 5114            provider.discard(cx);
 5115        }
 5116
 5117        self.take_active_inline_completion(cx)
 5118    }
 5119
 5120    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5121        let Some(provider) = self.edit_prediction_provider() else {
 5122            return;
 5123        };
 5124
 5125        let Some((_, buffer, _)) = self
 5126            .buffer
 5127            .read(cx)
 5128            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5129        else {
 5130            return;
 5131        };
 5132
 5133        let extension = buffer
 5134            .read(cx)
 5135            .file()
 5136            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5137
 5138        let event_type = match accepted {
 5139            true => "Edit Prediction Accepted",
 5140            false => "Edit Prediction Discarded",
 5141        };
 5142        telemetry::event!(
 5143            event_type,
 5144            provider = provider.name(),
 5145            prediction_id = id,
 5146            suggestion_accepted = accepted,
 5147            file_extension = extension,
 5148        );
 5149    }
 5150
 5151    pub fn has_active_inline_completion(&self) -> bool {
 5152        self.active_inline_completion.is_some()
 5153    }
 5154
 5155    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5156        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5157            return false;
 5158        };
 5159
 5160        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5161        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5162        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5163        true
 5164    }
 5165
 5166    /// Returns true when we're displaying the edit prediction popover below the cursor
 5167    /// like we are not previewing and the LSP autocomplete menu is visible
 5168    /// or we are in `when_holding_modifier` mode.
 5169    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5170        if self.edit_prediction_preview_is_active()
 5171            || !self.show_edit_predictions_in_menu()
 5172            || !self.edit_predictions_enabled()
 5173        {
 5174            return false;
 5175        }
 5176
 5177        if self.has_visible_completions_menu() {
 5178            return true;
 5179        }
 5180
 5181        has_completion && self.edit_prediction_requires_modifier()
 5182    }
 5183
 5184    fn handle_modifiers_changed(
 5185        &mut self,
 5186        modifiers: Modifiers,
 5187        position_map: &PositionMap,
 5188        window: &mut Window,
 5189        cx: &mut Context<Self>,
 5190    ) {
 5191        if self.show_edit_predictions_in_menu() {
 5192            self.update_edit_prediction_preview(&modifiers, window, cx);
 5193        }
 5194
 5195        let mouse_position = window.mouse_position();
 5196        if !position_map.text_hitbox.is_hovered(window) {
 5197            return;
 5198        }
 5199
 5200        self.update_hovered_link(
 5201            position_map.point_for_position(mouse_position),
 5202            &position_map.snapshot,
 5203            modifiers,
 5204            window,
 5205            cx,
 5206        )
 5207    }
 5208
 5209    fn update_edit_prediction_preview(
 5210        &mut self,
 5211        modifiers: &Modifiers,
 5212        window: &mut Window,
 5213        cx: &mut Context<Self>,
 5214    ) {
 5215        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5216        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5217            return;
 5218        };
 5219
 5220        if &accept_keystroke.modifiers == modifiers {
 5221            if !self.edit_prediction_preview_is_active() {
 5222                self.edit_prediction_preview = EditPredictionPreview::Active {
 5223                    previous_scroll_position: None,
 5224                };
 5225
 5226                self.update_visible_inline_completion(window, cx);
 5227                cx.notify();
 5228            }
 5229        } else if let EditPredictionPreview::Active {
 5230            previous_scroll_position,
 5231        } = self.edit_prediction_preview
 5232        {
 5233            if let (Some(previous_scroll_position), Some(position_map)) =
 5234                (previous_scroll_position, self.last_position_map.as_ref())
 5235            {
 5236                self.set_scroll_position(
 5237                    previous_scroll_position
 5238                        .scroll_position(&position_map.snapshot.display_snapshot),
 5239                    window,
 5240                    cx,
 5241                );
 5242            }
 5243
 5244            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5245            self.clear_row_highlights::<EditPredictionPreview>();
 5246            self.update_visible_inline_completion(window, cx);
 5247            cx.notify();
 5248        }
 5249    }
 5250
 5251    fn update_visible_inline_completion(
 5252        &mut self,
 5253        _window: &mut Window,
 5254        cx: &mut Context<Self>,
 5255    ) -> Option<()> {
 5256        let selection = self.selections.newest_anchor();
 5257        let cursor = selection.head();
 5258        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5259        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5260        let excerpt_id = cursor.excerpt_id;
 5261
 5262        let show_in_menu = self.show_edit_predictions_in_menu();
 5263        let completions_menu_has_precedence = !show_in_menu
 5264            && (self.context_menu.borrow().is_some()
 5265                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5266
 5267        if completions_menu_has_precedence
 5268            || !offset_selection.is_empty()
 5269            || self
 5270                .active_inline_completion
 5271                .as_ref()
 5272                .map_or(false, |completion| {
 5273                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5274                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5275                    !invalidation_range.contains(&offset_selection.head())
 5276                })
 5277        {
 5278            self.discard_inline_completion(false, cx);
 5279            return None;
 5280        }
 5281
 5282        self.take_active_inline_completion(cx);
 5283        let Some(provider) = self.edit_prediction_provider() else {
 5284            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5285            return None;
 5286        };
 5287
 5288        let (buffer, cursor_buffer_position) =
 5289            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5290
 5291        self.edit_prediction_settings =
 5292            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5293
 5294        if !self.edit_prediction_settings.is_enabled() {
 5295            self.discard_inline_completion(false, cx);
 5296            return None;
 5297        }
 5298
 5299        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5300        let edits = inline_completion
 5301            .edits
 5302            .into_iter()
 5303            .flat_map(|(range, new_text)| {
 5304                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5305                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5306                Some((start..end, new_text))
 5307            })
 5308            .collect::<Vec<_>>();
 5309        if edits.is_empty() {
 5310            return None;
 5311        }
 5312
 5313        let first_edit_start = edits.first().unwrap().0.start;
 5314        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5315        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5316
 5317        let last_edit_end = edits.last().unwrap().0.end;
 5318        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5319        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5320
 5321        let cursor_row = cursor.to_point(&multibuffer).row;
 5322
 5323        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5324
 5325        let mut inlay_ids = Vec::new();
 5326        let invalidation_row_range;
 5327        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5328            Some(cursor_row..edit_end_row)
 5329        } else if cursor_row > edit_end_row {
 5330            Some(edit_start_row..cursor_row)
 5331        } else {
 5332            None
 5333        };
 5334        let is_move =
 5335            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5336        let completion = if is_move {
 5337            invalidation_row_range =
 5338                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5339            let target = first_edit_start;
 5340            InlineCompletion::Move { target, snapshot }
 5341        } else {
 5342            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5343                && !self.inline_completions_hidden_for_vim_mode;
 5344
 5345            if show_completions_in_buffer {
 5346                if edits
 5347                    .iter()
 5348                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5349                {
 5350                    let mut inlays = Vec::new();
 5351                    for (range, new_text) in &edits {
 5352                        let inlay = Inlay::inline_completion(
 5353                            post_inc(&mut self.next_inlay_id),
 5354                            range.start,
 5355                            new_text.as_str(),
 5356                        );
 5357                        inlay_ids.push(inlay.id);
 5358                        inlays.push(inlay);
 5359                    }
 5360
 5361                    self.splice_inlays(&[], inlays, cx);
 5362                } else {
 5363                    let background_color = cx.theme().status().deleted_background;
 5364                    self.highlight_text::<InlineCompletionHighlight>(
 5365                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5366                        HighlightStyle {
 5367                            background_color: Some(background_color),
 5368                            ..Default::default()
 5369                        },
 5370                        cx,
 5371                    );
 5372                }
 5373            }
 5374
 5375            invalidation_row_range = edit_start_row..edit_end_row;
 5376
 5377            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5378                if provider.show_tab_accept_marker() {
 5379                    EditDisplayMode::TabAccept
 5380                } else {
 5381                    EditDisplayMode::Inline
 5382                }
 5383            } else {
 5384                EditDisplayMode::DiffPopover
 5385            };
 5386
 5387            InlineCompletion::Edit {
 5388                edits,
 5389                edit_preview: inline_completion.edit_preview,
 5390                display_mode,
 5391                snapshot,
 5392            }
 5393        };
 5394
 5395        let invalidation_range = multibuffer
 5396            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5397            ..multibuffer.anchor_after(Point::new(
 5398                invalidation_row_range.end,
 5399                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5400            ));
 5401
 5402        self.stale_inline_completion_in_menu = None;
 5403        self.active_inline_completion = Some(InlineCompletionState {
 5404            inlay_ids,
 5405            completion,
 5406            completion_id: inline_completion.id,
 5407            invalidation_range,
 5408        });
 5409
 5410        cx.notify();
 5411
 5412        Some(())
 5413    }
 5414
 5415    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5416        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5417    }
 5418
 5419    fn render_code_actions_indicator(
 5420        &self,
 5421        _style: &EditorStyle,
 5422        row: DisplayRow,
 5423        is_active: bool,
 5424        cx: &mut Context<Self>,
 5425    ) -> Option<IconButton> {
 5426        if self.available_code_actions.is_some() {
 5427            Some(
 5428                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5429                    .shape(ui::IconButtonShape::Square)
 5430                    .icon_size(IconSize::XSmall)
 5431                    .icon_color(Color::Muted)
 5432                    .toggle_state(is_active)
 5433                    .tooltip({
 5434                        let focus_handle = self.focus_handle.clone();
 5435                        move |window, cx| {
 5436                            Tooltip::for_action_in(
 5437                                "Toggle Code Actions",
 5438                                &ToggleCodeActions {
 5439                                    deployed_from_indicator: None,
 5440                                },
 5441                                &focus_handle,
 5442                                window,
 5443                                cx,
 5444                            )
 5445                        }
 5446                    })
 5447                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5448                        window.focus(&editor.focus_handle(cx));
 5449                        editor.toggle_code_actions(
 5450                            &ToggleCodeActions {
 5451                                deployed_from_indicator: Some(row),
 5452                            },
 5453                            window,
 5454                            cx,
 5455                        );
 5456                    })),
 5457            )
 5458        } else {
 5459            None
 5460        }
 5461    }
 5462
 5463    fn clear_tasks(&mut self) {
 5464        self.tasks.clear()
 5465    }
 5466
 5467    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5468        if self.tasks.insert(key, value).is_some() {
 5469            // This case should hopefully be rare, but just in case...
 5470            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5471        }
 5472    }
 5473
 5474    fn build_tasks_context(
 5475        project: &Entity<Project>,
 5476        buffer: &Entity<Buffer>,
 5477        buffer_row: u32,
 5478        tasks: &Arc<RunnableTasks>,
 5479        cx: &mut Context<Self>,
 5480    ) -> Task<Option<task::TaskContext>> {
 5481        let position = Point::new(buffer_row, tasks.column);
 5482        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5483        let location = Location {
 5484            buffer: buffer.clone(),
 5485            range: range_start..range_start,
 5486        };
 5487        // Fill in the environmental variables from the tree-sitter captures
 5488        let mut captured_task_variables = TaskVariables::default();
 5489        for (capture_name, value) in tasks.extra_variables.clone() {
 5490            captured_task_variables.insert(
 5491                task::VariableName::Custom(capture_name.into()),
 5492                value.clone(),
 5493            );
 5494        }
 5495        project.update(cx, |project, cx| {
 5496            project.task_store().update(cx, |task_store, cx| {
 5497                task_store.task_context_for_location(captured_task_variables, location, cx)
 5498            })
 5499        })
 5500    }
 5501
 5502    pub fn spawn_nearest_task(
 5503        &mut self,
 5504        action: &SpawnNearestTask,
 5505        window: &mut Window,
 5506        cx: &mut Context<Self>,
 5507    ) {
 5508        let Some((workspace, _)) = self.workspace.clone() else {
 5509            return;
 5510        };
 5511        let Some(project) = self.project.clone() else {
 5512            return;
 5513        };
 5514
 5515        // Try to find a closest, enclosing node using tree-sitter that has a
 5516        // task
 5517        let Some((buffer, buffer_row, tasks)) = self
 5518            .find_enclosing_node_task(cx)
 5519            // Or find the task that's closest in row-distance.
 5520            .or_else(|| self.find_closest_task(cx))
 5521        else {
 5522            return;
 5523        };
 5524
 5525        let reveal_strategy = action.reveal;
 5526        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5527        cx.spawn_in(window, |_, mut cx| async move {
 5528            let context = task_context.await?;
 5529            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5530
 5531            let resolved = resolved_task.resolved.as_mut()?;
 5532            resolved.reveal = reveal_strategy;
 5533
 5534            workspace
 5535                .update(&mut cx, |workspace, cx| {
 5536                    workspace::tasks::schedule_resolved_task(
 5537                        workspace,
 5538                        task_source_kind,
 5539                        resolved_task,
 5540                        false,
 5541                        cx,
 5542                    );
 5543                })
 5544                .ok()
 5545        })
 5546        .detach();
 5547    }
 5548
 5549    fn find_closest_task(
 5550        &mut self,
 5551        cx: &mut Context<Self>,
 5552    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5553        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5554
 5555        let ((buffer_id, row), tasks) = self
 5556            .tasks
 5557            .iter()
 5558            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5559
 5560        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5561        let tasks = Arc::new(tasks.to_owned());
 5562        Some((buffer, *row, tasks))
 5563    }
 5564
 5565    fn find_enclosing_node_task(
 5566        &mut self,
 5567        cx: &mut Context<Self>,
 5568    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5569        let snapshot = self.buffer.read(cx).snapshot(cx);
 5570        let offset = self.selections.newest::<usize>(cx).head();
 5571        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5572        let buffer_id = excerpt.buffer().remote_id();
 5573
 5574        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5575        let mut cursor = layer.node().walk();
 5576
 5577        while cursor.goto_first_child_for_byte(offset).is_some() {
 5578            if cursor.node().end_byte() == offset {
 5579                cursor.goto_next_sibling();
 5580            }
 5581        }
 5582
 5583        // Ascend to the smallest ancestor that contains the range and has a task.
 5584        loop {
 5585            let node = cursor.node();
 5586            let node_range = node.byte_range();
 5587            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5588
 5589            // Check if this node contains our offset
 5590            if node_range.start <= offset && node_range.end >= offset {
 5591                // If it contains offset, check for task
 5592                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5593                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5594                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5595                }
 5596            }
 5597
 5598            if !cursor.goto_parent() {
 5599                break;
 5600            }
 5601        }
 5602        None
 5603    }
 5604
 5605    fn render_run_indicator(
 5606        &self,
 5607        _style: &EditorStyle,
 5608        is_active: bool,
 5609        row: DisplayRow,
 5610        cx: &mut Context<Self>,
 5611    ) -> IconButton {
 5612        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5613            .shape(ui::IconButtonShape::Square)
 5614            .icon_size(IconSize::XSmall)
 5615            .icon_color(Color::Muted)
 5616            .toggle_state(is_active)
 5617            .on_click(cx.listener(move |editor, _e, window, cx| {
 5618                window.focus(&editor.focus_handle(cx));
 5619                editor.toggle_code_actions(
 5620                    &ToggleCodeActions {
 5621                        deployed_from_indicator: Some(row),
 5622                    },
 5623                    window,
 5624                    cx,
 5625                );
 5626            }))
 5627    }
 5628
 5629    pub fn context_menu_visible(&self) -> bool {
 5630        !self.edit_prediction_preview_is_active()
 5631            && self
 5632                .context_menu
 5633                .borrow()
 5634                .as_ref()
 5635                .map_or(false, |menu| menu.visible())
 5636    }
 5637
 5638    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5639        self.context_menu
 5640            .borrow()
 5641            .as_ref()
 5642            .map(|menu| menu.origin())
 5643    }
 5644
 5645    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5646        px(30.)
 5647    }
 5648
 5649    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5650        if self.read_only(cx) {
 5651            cx.theme().players().read_only()
 5652        } else {
 5653            self.style.as_ref().unwrap().local_player
 5654        }
 5655    }
 5656
 5657    #[allow(clippy::too_many_arguments)]
 5658    fn render_edit_prediction_cursor_popover(
 5659        &self,
 5660        min_width: Pixels,
 5661        max_width: Pixels,
 5662        cursor_point: Point,
 5663        style: &EditorStyle,
 5664        accept_keystroke: &gpui::Keystroke,
 5665        _window: &Window,
 5666        cx: &mut Context<Editor>,
 5667    ) -> Option<AnyElement> {
 5668        let provider = self.edit_prediction_provider.as_ref()?;
 5669
 5670        if provider.provider.needs_terms_acceptance(cx) {
 5671            return Some(
 5672                h_flex()
 5673                    .min_w(min_width)
 5674                    .flex_1()
 5675                    .px_2()
 5676                    .py_1()
 5677                    .gap_3()
 5678                    .elevation_2(cx)
 5679                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5680                    .id("accept-terms")
 5681                    .cursor_pointer()
 5682                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5683                    .on_click(cx.listener(|this, _event, window, cx| {
 5684                        cx.stop_propagation();
 5685                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5686                        window.dispatch_action(
 5687                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5688                            cx,
 5689                        );
 5690                    }))
 5691                    .child(
 5692                        h_flex()
 5693                            .flex_1()
 5694                            .gap_2()
 5695                            .child(Icon::new(IconName::ZedPredict))
 5696                            .child(Label::new("Accept Terms of Service"))
 5697                            .child(div().w_full())
 5698                            .child(
 5699                                Icon::new(IconName::ArrowUpRight)
 5700                                    .color(Color::Muted)
 5701                                    .size(IconSize::Small),
 5702                            )
 5703                            .into_any_element(),
 5704                    )
 5705                    .into_any(),
 5706            );
 5707        }
 5708
 5709        let is_refreshing = provider.provider.is_refreshing(cx);
 5710
 5711        fn pending_completion_container() -> Div {
 5712            h_flex()
 5713                .h_full()
 5714                .flex_1()
 5715                .gap_2()
 5716                .child(Icon::new(IconName::ZedPredict))
 5717        }
 5718
 5719        let completion = match &self.active_inline_completion {
 5720            Some(completion) => match &completion.completion {
 5721                InlineCompletion::Move {
 5722                    target, snapshot, ..
 5723                } if !self.has_visible_completions_menu() => {
 5724                    use text::ToPoint as _;
 5725
 5726                    return Some(
 5727                        h_flex()
 5728                            .px_2()
 5729                            .py_1()
 5730                            .elevation_2(cx)
 5731                            .border_color(cx.theme().colors().border)
 5732                            .rounded_tl(px(0.))
 5733                            .gap_2()
 5734                            .child(
 5735                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5736                                    Icon::new(IconName::ZedPredictDown)
 5737                                } else {
 5738                                    Icon::new(IconName::ZedPredictUp)
 5739                                },
 5740                            )
 5741                            .child(Label::new("Hold").size(LabelSize::Small))
 5742                            .children(ui::render_modifiers(
 5743                                &accept_keystroke.modifiers,
 5744                                PlatformStyle::platform(),
 5745                                Some(Color::Default),
 5746                                Some(IconSize::Small.rems().into()),
 5747                                true,
 5748                            ))
 5749                            .into_any(),
 5750                    );
 5751                }
 5752                _ => self.render_edit_prediction_cursor_popover_preview(
 5753                    completion,
 5754                    cursor_point,
 5755                    style,
 5756                    cx,
 5757                )?,
 5758            },
 5759
 5760            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5761                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5762                    stale_completion,
 5763                    cursor_point,
 5764                    style,
 5765                    cx,
 5766                )?,
 5767
 5768                None => {
 5769                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5770                }
 5771            },
 5772
 5773            None => pending_completion_container().child(Label::new("No Prediction")),
 5774        };
 5775
 5776        let completion = if is_refreshing {
 5777            completion
 5778                .with_animation(
 5779                    "loading-completion",
 5780                    Animation::new(Duration::from_secs(2))
 5781                        .repeat()
 5782                        .with_easing(pulsating_between(0.4, 0.8)),
 5783                    |label, delta| label.opacity(delta),
 5784                )
 5785                .into_any_element()
 5786        } else {
 5787            completion.into_any_element()
 5788        };
 5789
 5790        let has_completion = self.active_inline_completion.is_some();
 5791
 5792        Some(
 5793            h_flex()
 5794                .min_w(min_width)
 5795                .max_w(max_width)
 5796                .flex_1()
 5797                .px_2()
 5798                .py_1()
 5799                .elevation_2(cx)
 5800                .border_color(cx.theme().colors().border)
 5801                .child(completion)
 5802                .child(ui::Divider::vertical())
 5803                .child(
 5804                    h_flex()
 5805                        .h_full()
 5806                        .gap_1()
 5807                        .pl_2()
 5808                        .child(
 5809                            h_flex()
 5810                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5811                                .gap_1()
 5812                                .children(ui::render_modifiers(
 5813                                    &accept_keystroke.modifiers,
 5814                                    PlatformStyle::platform(),
 5815                                    Some(if !has_completion {
 5816                                        Color::Muted
 5817                                    } else {
 5818                                        Color::Default
 5819                                    }),
 5820                                    None,
 5821                                    true,
 5822                                )),
 5823                        )
 5824                        .child(Label::new("Preview").into_any_element())
 5825                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5826                )
 5827                .into_any(),
 5828        )
 5829    }
 5830
 5831    fn render_edit_prediction_cursor_popover_preview(
 5832        &self,
 5833        completion: &InlineCompletionState,
 5834        cursor_point: Point,
 5835        style: &EditorStyle,
 5836        cx: &mut Context<Editor>,
 5837    ) -> Option<Div> {
 5838        use text::ToPoint as _;
 5839
 5840        fn render_relative_row_jump(
 5841            prefix: impl Into<String>,
 5842            current_row: u32,
 5843            target_row: u32,
 5844        ) -> Div {
 5845            let (row_diff, arrow) = if target_row < current_row {
 5846                (current_row - target_row, IconName::ArrowUp)
 5847            } else {
 5848                (target_row - current_row, IconName::ArrowDown)
 5849            };
 5850
 5851            h_flex()
 5852                .child(
 5853                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5854                        .color(Color::Muted)
 5855                        .size(LabelSize::Small),
 5856                )
 5857                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5858        }
 5859
 5860        match &completion.completion {
 5861            InlineCompletion::Move {
 5862                target, snapshot, ..
 5863            } => Some(
 5864                h_flex()
 5865                    .px_2()
 5866                    .gap_2()
 5867                    .flex_1()
 5868                    .child(
 5869                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5870                            Icon::new(IconName::ZedPredictDown)
 5871                        } else {
 5872                            Icon::new(IconName::ZedPredictUp)
 5873                        },
 5874                    )
 5875                    .child(Label::new("Jump to Edit")),
 5876            ),
 5877
 5878            InlineCompletion::Edit {
 5879                edits,
 5880                edit_preview,
 5881                snapshot,
 5882                display_mode: _,
 5883            } => {
 5884                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5885
 5886                let highlighted_edits = crate::inline_completion_edit_text(
 5887                    &snapshot,
 5888                    &edits,
 5889                    edit_preview.as_ref()?,
 5890                    true,
 5891                    cx,
 5892                );
 5893
 5894                let len_total = highlighted_edits.text.len();
 5895                let first_line = &highlighted_edits.text
 5896                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5897                let first_line_len = first_line.len();
 5898
 5899                let first_highlight_start = highlighted_edits
 5900                    .highlights
 5901                    .first()
 5902                    .map_or(0, |(range, _)| range.start);
 5903                let drop_prefix_len = first_line
 5904                    .char_indices()
 5905                    .find(|(_, c)| !c.is_whitespace())
 5906                    .map_or(first_highlight_start, |(ix, _)| {
 5907                        ix.min(first_highlight_start)
 5908                    });
 5909
 5910                let preview_text = &first_line[drop_prefix_len..];
 5911                let preview_len = preview_text.len();
 5912                let highlights = highlighted_edits
 5913                    .highlights
 5914                    .into_iter()
 5915                    .take_until(|(range, _)| range.start > first_line_len)
 5916                    .map(|(range, style)| {
 5917                        (
 5918                            range.start - drop_prefix_len
 5919                                ..(range.end - drop_prefix_len).min(preview_len),
 5920                            style,
 5921                        )
 5922                    });
 5923
 5924                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5925                    .with_highlights(&style.text, highlights);
 5926
 5927                let preview = h_flex()
 5928                    .gap_1()
 5929                    .min_w_16()
 5930                    .child(styled_text)
 5931                    .when(len_total > first_line_len, |parent| parent.child(""));
 5932
 5933                let left = if first_edit_row != cursor_point.row {
 5934                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5935                        .into_any_element()
 5936                } else {
 5937                    Icon::new(IconName::ZedPredict).into_any_element()
 5938                };
 5939
 5940                Some(
 5941                    h_flex()
 5942                        .h_full()
 5943                        .flex_1()
 5944                        .gap_2()
 5945                        .pr_1()
 5946                        .overflow_x_hidden()
 5947                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5948                        .child(left)
 5949                        .child(preview),
 5950                )
 5951            }
 5952        }
 5953    }
 5954
 5955    fn render_context_menu(
 5956        &self,
 5957        style: &EditorStyle,
 5958        max_height_in_lines: u32,
 5959        y_flipped: bool,
 5960        window: &mut Window,
 5961        cx: &mut Context<Editor>,
 5962    ) -> Option<AnyElement> {
 5963        let menu = self.context_menu.borrow();
 5964        let menu = menu.as_ref()?;
 5965        if !menu.visible() {
 5966            return None;
 5967        };
 5968        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5969    }
 5970
 5971    fn render_context_menu_aside(
 5972        &self,
 5973        style: &EditorStyle,
 5974        max_size: Size<Pixels>,
 5975        cx: &mut Context<Editor>,
 5976    ) -> Option<AnyElement> {
 5977        self.context_menu.borrow().as_ref().and_then(|menu| {
 5978            if menu.visible() {
 5979                menu.render_aside(
 5980                    style,
 5981                    max_size,
 5982                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5983                    cx,
 5984                )
 5985            } else {
 5986                None
 5987            }
 5988        })
 5989    }
 5990
 5991    fn hide_context_menu(
 5992        &mut self,
 5993        window: &mut Window,
 5994        cx: &mut Context<Self>,
 5995    ) -> Option<CodeContextMenu> {
 5996        cx.notify();
 5997        self.completion_tasks.clear();
 5998        let context_menu = self.context_menu.borrow_mut().take();
 5999        self.stale_inline_completion_in_menu.take();
 6000        self.update_visible_inline_completion(window, cx);
 6001        context_menu
 6002    }
 6003
 6004    fn show_snippet_choices(
 6005        &mut self,
 6006        choices: &Vec<String>,
 6007        selection: Range<Anchor>,
 6008        cx: &mut Context<Self>,
 6009    ) {
 6010        if selection.start.buffer_id.is_none() {
 6011            return;
 6012        }
 6013        let buffer_id = selection.start.buffer_id.unwrap();
 6014        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6015        let id = post_inc(&mut self.next_completion_id);
 6016
 6017        if let Some(buffer) = buffer {
 6018            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6019                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6020            ));
 6021        }
 6022    }
 6023
 6024    pub fn insert_snippet(
 6025        &mut self,
 6026        insertion_ranges: &[Range<usize>],
 6027        snippet: Snippet,
 6028        window: &mut Window,
 6029        cx: &mut Context<Self>,
 6030    ) -> Result<()> {
 6031        struct Tabstop<T> {
 6032            is_end_tabstop: bool,
 6033            ranges: Vec<Range<T>>,
 6034            choices: Option<Vec<String>>,
 6035        }
 6036
 6037        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6038            let snippet_text: Arc<str> = snippet.text.clone().into();
 6039            buffer.edit(
 6040                insertion_ranges
 6041                    .iter()
 6042                    .cloned()
 6043                    .map(|range| (range, snippet_text.clone())),
 6044                Some(AutoindentMode::EachLine),
 6045                cx,
 6046            );
 6047
 6048            let snapshot = &*buffer.read(cx);
 6049            let snippet = &snippet;
 6050            snippet
 6051                .tabstops
 6052                .iter()
 6053                .map(|tabstop| {
 6054                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6055                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6056                    });
 6057                    let mut tabstop_ranges = tabstop
 6058                        .ranges
 6059                        .iter()
 6060                        .flat_map(|tabstop_range| {
 6061                            let mut delta = 0_isize;
 6062                            insertion_ranges.iter().map(move |insertion_range| {
 6063                                let insertion_start = insertion_range.start as isize + delta;
 6064                                delta +=
 6065                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6066
 6067                                let start = ((insertion_start + tabstop_range.start) as usize)
 6068                                    .min(snapshot.len());
 6069                                let end = ((insertion_start + tabstop_range.end) as usize)
 6070                                    .min(snapshot.len());
 6071                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6072                            })
 6073                        })
 6074                        .collect::<Vec<_>>();
 6075                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6076
 6077                    Tabstop {
 6078                        is_end_tabstop,
 6079                        ranges: tabstop_ranges,
 6080                        choices: tabstop.choices.clone(),
 6081                    }
 6082                })
 6083                .collect::<Vec<_>>()
 6084        });
 6085        if let Some(tabstop) = tabstops.first() {
 6086            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6087                s.select_ranges(tabstop.ranges.iter().cloned());
 6088            });
 6089
 6090            if let Some(choices) = &tabstop.choices {
 6091                if let Some(selection) = tabstop.ranges.first() {
 6092                    self.show_snippet_choices(choices, selection.clone(), cx)
 6093                }
 6094            }
 6095
 6096            // If we're already at the last tabstop and it's at the end of the snippet,
 6097            // we're done, we don't need to keep the state around.
 6098            if !tabstop.is_end_tabstop {
 6099                let choices = tabstops
 6100                    .iter()
 6101                    .map(|tabstop| tabstop.choices.clone())
 6102                    .collect();
 6103
 6104                let ranges = tabstops
 6105                    .into_iter()
 6106                    .map(|tabstop| tabstop.ranges)
 6107                    .collect::<Vec<_>>();
 6108
 6109                self.snippet_stack.push(SnippetState {
 6110                    active_index: 0,
 6111                    ranges,
 6112                    choices,
 6113                });
 6114            }
 6115
 6116            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6117            if self.autoclose_regions.is_empty() {
 6118                let snapshot = self.buffer.read(cx).snapshot(cx);
 6119                for selection in &mut self.selections.all::<Point>(cx) {
 6120                    let selection_head = selection.head();
 6121                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6122                        continue;
 6123                    };
 6124
 6125                    let mut bracket_pair = None;
 6126                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6127                    let prev_chars = snapshot
 6128                        .reversed_chars_at(selection_head)
 6129                        .collect::<String>();
 6130                    for (pair, enabled) in scope.brackets() {
 6131                        if enabled
 6132                            && pair.close
 6133                            && prev_chars.starts_with(pair.start.as_str())
 6134                            && next_chars.starts_with(pair.end.as_str())
 6135                        {
 6136                            bracket_pair = Some(pair.clone());
 6137                            break;
 6138                        }
 6139                    }
 6140                    if let Some(pair) = bracket_pair {
 6141                        let start = snapshot.anchor_after(selection_head);
 6142                        let end = snapshot.anchor_after(selection_head);
 6143                        self.autoclose_regions.push(AutocloseRegion {
 6144                            selection_id: selection.id,
 6145                            range: start..end,
 6146                            pair,
 6147                        });
 6148                    }
 6149                }
 6150            }
 6151        }
 6152        Ok(())
 6153    }
 6154
 6155    pub fn move_to_next_snippet_tabstop(
 6156        &mut self,
 6157        window: &mut Window,
 6158        cx: &mut Context<Self>,
 6159    ) -> bool {
 6160        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6161    }
 6162
 6163    pub fn move_to_prev_snippet_tabstop(
 6164        &mut self,
 6165        window: &mut Window,
 6166        cx: &mut Context<Self>,
 6167    ) -> bool {
 6168        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6169    }
 6170
 6171    pub fn move_to_snippet_tabstop(
 6172        &mut self,
 6173        bias: Bias,
 6174        window: &mut Window,
 6175        cx: &mut Context<Self>,
 6176    ) -> bool {
 6177        if let Some(mut snippet) = self.snippet_stack.pop() {
 6178            match bias {
 6179                Bias::Left => {
 6180                    if snippet.active_index > 0 {
 6181                        snippet.active_index -= 1;
 6182                    } else {
 6183                        self.snippet_stack.push(snippet);
 6184                        return false;
 6185                    }
 6186                }
 6187                Bias::Right => {
 6188                    if snippet.active_index + 1 < snippet.ranges.len() {
 6189                        snippet.active_index += 1;
 6190                    } else {
 6191                        self.snippet_stack.push(snippet);
 6192                        return false;
 6193                    }
 6194                }
 6195            }
 6196            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6197                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6198                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6199                });
 6200
 6201                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6202                    if let Some(selection) = current_ranges.first() {
 6203                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6204                    }
 6205                }
 6206
 6207                // If snippet state is not at the last tabstop, push it back on the stack
 6208                if snippet.active_index + 1 < snippet.ranges.len() {
 6209                    self.snippet_stack.push(snippet);
 6210                }
 6211                return true;
 6212            }
 6213        }
 6214
 6215        false
 6216    }
 6217
 6218    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6219        self.transact(window, cx, |this, window, cx| {
 6220            this.select_all(&SelectAll, window, cx);
 6221            this.insert("", window, cx);
 6222        });
 6223    }
 6224
 6225    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6226        self.transact(window, cx, |this, window, cx| {
 6227            this.select_autoclose_pair(window, cx);
 6228            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6229            if !this.linked_edit_ranges.is_empty() {
 6230                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6231                let snapshot = this.buffer.read(cx).snapshot(cx);
 6232
 6233                for selection in selections.iter() {
 6234                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6235                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6236                    if selection_start.buffer_id != selection_end.buffer_id {
 6237                        continue;
 6238                    }
 6239                    if let Some(ranges) =
 6240                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6241                    {
 6242                        for (buffer, entries) in ranges {
 6243                            linked_ranges.entry(buffer).or_default().extend(entries);
 6244                        }
 6245                    }
 6246                }
 6247            }
 6248
 6249            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6250            if !this.selections.line_mode {
 6251                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6252                for selection in &mut selections {
 6253                    if selection.is_empty() {
 6254                        let old_head = selection.head();
 6255                        let mut new_head =
 6256                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6257                                .to_point(&display_map);
 6258                        if let Some((buffer, line_buffer_range)) = display_map
 6259                            .buffer_snapshot
 6260                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6261                        {
 6262                            let indent_size =
 6263                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6264                            let indent_len = match indent_size.kind {
 6265                                IndentKind::Space => {
 6266                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6267                                }
 6268                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6269                            };
 6270                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6271                                let indent_len = indent_len.get();
 6272                                new_head = cmp::min(
 6273                                    new_head,
 6274                                    MultiBufferPoint::new(
 6275                                        old_head.row,
 6276                                        ((old_head.column - 1) / indent_len) * indent_len,
 6277                                    ),
 6278                                );
 6279                            }
 6280                        }
 6281
 6282                        selection.set_head(new_head, SelectionGoal::None);
 6283                    }
 6284                }
 6285            }
 6286
 6287            this.signature_help_state.set_backspace_pressed(true);
 6288            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6289                s.select(selections)
 6290            });
 6291            this.insert("", window, cx);
 6292            let empty_str: Arc<str> = Arc::from("");
 6293            for (buffer, edits) in linked_ranges {
 6294                let snapshot = buffer.read(cx).snapshot();
 6295                use text::ToPoint as TP;
 6296
 6297                let edits = edits
 6298                    .into_iter()
 6299                    .map(|range| {
 6300                        let end_point = TP::to_point(&range.end, &snapshot);
 6301                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6302
 6303                        if end_point == start_point {
 6304                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6305                                .saturating_sub(1);
 6306                            start_point =
 6307                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6308                        };
 6309
 6310                        (start_point..end_point, empty_str.clone())
 6311                    })
 6312                    .sorted_by_key(|(range, _)| range.start)
 6313                    .collect::<Vec<_>>();
 6314                buffer.update(cx, |this, cx| {
 6315                    this.edit(edits, None, cx);
 6316                })
 6317            }
 6318            this.refresh_inline_completion(true, false, window, cx);
 6319            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6320        });
 6321    }
 6322
 6323    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6324        self.transact(window, cx, |this, window, cx| {
 6325            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6326                let line_mode = s.line_mode;
 6327                s.move_with(|map, selection| {
 6328                    if selection.is_empty() && !line_mode {
 6329                        let cursor = movement::right(map, selection.head());
 6330                        selection.end = cursor;
 6331                        selection.reversed = true;
 6332                        selection.goal = SelectionGoal::None;
 6333                    }
 6334                })
 6335            });
 6336            this.insert("", window, cx);
 6337            this.refresh_inline_completion(true, false, window, cx);
 6338        });
 6339    }
 6340
 6341    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6342        if self.move_to_prev_snippet_tabstop(window, cx) {
 6343            return;
 6344        }
 6345
 6346        self.outdent(&Outdent, window, cx);
 6347    }
 6348
 6349    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6350        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6351            return;
 6352        }
 6353
 6354        let mut selections = self.selections.all_adjusted(cx);
 6355        let buffer = self.buffer.read(cx);
 6356        let snapshot = buffer.snapshot(cx);
 6357        let rows_iter = selections.iter().map(|s| s.head().row);
 6358        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6359
 6360        let mut edits = Vec::new();
 6361        let mut prev_edited_row = 0;
 6362        let mut row_delta = 0;
 6363        for selection in &mut selections {
 6364            if selection.start.row != prev_edited_row {
 6365                row_delta = 0;
 6366            }
 6367            prev_edited_row = selection.end.row;
 6368
 6369            // If the selection is non-empty, then increase the indentation of the selected lines.
 6370            if !selection.is_empty() {
 6371                row_delta =
 6372                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6373                continue;
 6374            }
 6375
 6376            // If the selection is empty and the cursor is in the leading whitespace before the
 6377            // suggested indentation, then auto-indent the line.
 6378            let cursor = selection.head();
 6379            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6380            if let Some(suggested_indent) =
 6381                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6382            {
 6383                if cursor.column < suggested_indent.len
 6384                    && cursor.column <= current_indent.len
 6385                    && current_indent.len <= suggested_indent.len
 6386                {
 6387                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6388                    selection.end = selection.start;
 6389                    if row_delta == 0 {
 6390                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6391                            cursor.row,
 6392                            current_indent,
 6393                            suggested_indent,
 6394                        ));
 6395                        row_delta = suggested_indent.len - current_indent.len;
 6396                    }
 6397                    continue;
 6398                }
 6399            }
 6400
 6401            // Otherwise, insert a hard or soft tab.
 6402            let settings = buffer.settings_at(cursor, cx);
 6403            let tab_size = if settings.hard_tabs {
 6404                IndentSize::tab()
 6405            } else {
 6406                let tab_size = settings.tab_size.get();
 6407                let char_column = snapshot
 6408                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6409                    .flat_map(str::chars)
 6410                    .count()
 6411                    + row_delta as usize;
 6412                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6413                IndentSize::spaces(chars_to_next_tab_stop)
 6414            };
 6415            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6416            selection.end = selection.start;
 6417            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6418            row_delta += tab_size.len;
 6419        }
 6420
 6421        self.transact(window, cx, |this, window, cx| {
 6422            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6423            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6424                s.select(selections)
 6425            });
 6426            this.refresh_inline_completion(true, false, window, cx);
 6427        });
 6428    }
 6429
 6430    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6431        if self.read_only(cx) {
 6432            return;
 6433        }
 6434        let mut selections = self.selections.all::<Point>(cx);
 6435        let mut prev_edited_row = 0;
 6436        let mut row_delta = 0;
 6437        let mut edits = Vec::new();
 6438        let buffer = self.buffer.read(cx);
 6439        let snapshot = buffer.snapshot(cx);
 6440        for selection in &mut selections {
 6441            if selection.start.row != prev_edited_row {
 6442                row_delta = 0;
 6443            }
 6444            prev_edited_row = selection.end.row;
 6445
 6446            row_delta =
 6447                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6448        }
 6449
 6450        self.transact(window, cx, |this, window, cx| {
 6451            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6452            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6453                s.select(selections)
 6454            });
 6455        });
 6456    }
 6457
 6458    fn indent_selection(
 6459        buffer: &MultiBuffer,
 6460        snapshot: &MultiBufferSnapshot,
 6461        selection: &mut Selection<Point>,
 6462        edits: &mut Vec<(Range<Point>, String)>,
 6463        delta_for_start_row: u32,
 6464        cx: &App,
 6465    ) -> u32 {
 6466        let settings = buffer.settings_at(selection.start, cx);
 6467        let tab_size = settings.tab_size.get();
 6468        let indent_kind = if settings.hard_tabs {
 6469            IndentKind::Tab
 6470        } else {
 6471            IndentKind::Space
 6472        };
 6473        let mut start_row = selection.start.row;
 6474        let mut end_row = selection.end.row + 1;
 6475
 6476        // If a selection ends at the beginning of a line, don't indent
 6477        // that last line.
 6478        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6479            end_row -= 1;
 6480        }
 6481
 6482        // Avoid re-indenting a row that has already been indented by a
 6483        // previous selection, but still update this selection's column
 6484        // to reflect that indentation.
 6485        if delta_for_start_row > 0 {
 6486            start_row += 1;
 6487            selection.start.column += delta_for_start_row;
 6488            if selection.end.row == selection.start.row {
 6489                selection.end.column += delta_for_start_row;
 6490            }
 6491        }
 6492
 6493        let mut delta_for_end_row = 0;
 6494        let has_multiple_rows = start_row + 1 != end_row;
 6495        for row in start_row..end_row {
 6496            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6497            let indent_delta = match (current_indent.kind, indent_kind) {
 6498                (IndentKind::Space, IndentKind::Space) => {
 6499                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6500                    IndentSize::spaces(columns_to_next_tab_stop)
 6501                }
 6502                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6503                (_, IndentKind::Tab) => IndentSize::tab(),
 6504            };
 6505
 6506            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6507                0
 6508            } else {
 6509                selection.start.column
 6510            };
 6511            let row_start = Point::new(row, start);
 6512            edits.push((
 6513                row_start..row_start,
 6514                indent_delta.chars().collect::<String>(),
 6515            ));
 6516
 6517            // Update this selection's endpoints to reflect the indentation.
 6518            if row == selection.start.row {
 6519                selection.start.column += indent_delta.len;
 6520            }
 6521            if row == selection.end.row {
 6522                selection.end.column += indent_delta.len;
 6523                delta_for_end_row = indent_delta.len;
 6524            }
 6525        }
 6526
 6527        if selection.start.row == selection.end.row {
 6528            delta_for_start_row + delta_for_end_row
 6529        } else {
 6530            delta_for_end_row
 6531        }
 6532    }
 6533
 6534    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6535        if self.read_only(cx) {
 6536            return;
 6537        }
 6538        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6539        let selections = self.selections.all::<Point>(cx);
 6540        let mut deletion_ranges = Vec::new();
 6541        let mut last_outdent = None;
 6542        {
 6543            let buffer = self.buffer.read(cx);
 6544            let snapshot = buffer.snapshot(cx);
 6545            for selection in &selections {
 6546                let settings = buffer.settings_at(selection.start, cx);
 6547                let tab_size = settings.tab_size.get();
 6548                let mut rows = selection.spanned_rows(false, &display_map);
 6549
 6550                // Avoid re-outdenting a row that has already been outdented by a
 6551                // previous selection.
 6552                if let Some(last_row) = last_outdent {
 6553                    if last_row == rows.start {
 6554                        rows.start = rows.start.next_row();
 6555                    }
 6556                }
 6557                let has_multiple_rows = rows.len() > 1;
 6558                for row in rows.iter_rows() {
 6559                    let indent_size = snapshot.indent_size_for_line(row);
 6560                    if indent_size.len > 0 {
 6561                        let deletion_len = match indent_size.kind {
 6562                            IndentKind::Space => {
 6563                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6564                                if columns_to_prev_tab_stop == 0 {
 6565                                    tab_size
 6566                                } else {
 6567                                    columns_to_prev_tab_stop
 6568                                }
 6569                            }
 6570                            IndentKind::Tab => 1,
 6571                        };
 6572                        let start = if has_multiple_rows
 6573                            || deletion_len > selection.start.column
 6574                            || indent_size.len < selection.start.column
 6575                        {
 6576                            0
 6577                        } else {
 6578                            selection.start.column - deletion_len
 6579                        };
 6580                        deletion_ranges.push(
 6581                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6582                        );
 6583                        last_outdent = Some(row);
 6584                    }
 6585                }
 6586            }
 6587        }
 6588
 6589        self.transact(window, cx, |this, window, cx| {
 6590            this.buffer.update(cx, |buffer, cx| {
 6591                let empty_str: Arc<str> = Arc::default();
 6592                buffer.edit(
 6593                    deletion_ranges
 6594                        .into_iter()
 6595                        .map(|range| (range, empty_str.clone())),
 6596                    None,
 6597                    cx,
 6598                );
 6599            });
 6600            let selections = this.selections.all::<usize>(cx);
 6601            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6602                s.select(selections)
 6603            });
 6604        });
 6605    }
 6606
 6607    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6608        if self.read_only(cx) {
 6609            return;
 6610        }
 6611        let selections = self
 6612            .selections
 6613            .all::<usize>(cx)
 6614            .into_iter()
 6615            .map(|s| s.range());
 6616
 6617        self.transact(window, cx, |this, window, cx| {
 6618            this.buffer.update(cx, |buffer, cx| {
 6619                buffer.autoindent_ranges(selections, cx);
 6620            });
 6621            let selections = this.selections.all::<usize>(cx);
 6622            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6623                s.select(selections)
 6624            });
 6625        });
 6626    }
 6627
 6628    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6629        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6630        let selections = self.selections.all::<Point>(cx);
 6631
 6632        let mut new_cursors = Vec::new();
 6633        let mut edit_ranges = Vec::new();
 6634        let mut selections = selections.iter().peekable();
 6635        while let Some(selection) = selections.next() {
 6636            let mut rows = selection.spanned_rows(false, &display_map);
 6637            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6638
 6639            // Accumulate contiguous regions of rows that we want to delete.
 6640            while let Some(next_selection) = selections.peek() {
 6641                let next_rows = next_selection.spanned_rows(false, &display_map);
 6642                if next_rows.start <= rows.end {
 6643                    rows.end = next_rows.end;
 6644                    selections.next().unwrap();
 6645                } else {
 6646                    break;
 6647                }
 6648            }
 6649
 6650            let buffer = &display_map.buffer_snapshot;
 6651            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6652            let edit_end;
 6653            let cursor_buffer_row;
 6654            if buffer.max_point().row >= rows.end.0 {
 6655                // If there's a line after the range, delete the \n from the end of the row range
 6656                // and position the cursor on the next line.
 6657                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6658                cursor_buffer_row = rows.end;
 6659            } else {
 6660                // If there isn't a line after the range, delete the \n from the line before the
 6661                // start of the row range and position the cursor there.
 6662                edit_start = edit_start.saturating_sub(1);
 6663                edit_end = buffer.len();
 6664                cursor_buffer_row = rows.start.previous_row();
 6665            }
 6666
 6667            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6668            *cursor.column_mut() =
 6669                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6670
 6671            new_cursors.push((
 6672                selection.id,
 6673                buffer.anchor_after(cursor.to_point(&display_map)),
 6674            ));
 6675            edit_ranges.push(edit_start..edit_end);
 6676        }
 6677
 6678        self.transact(window, cx, |this, window, cx| {
 6679            let buffer = this.buffer.update(cx, |buffer, cx| {
 6680                let empty_str: Arc<str> = Arc::default();
 6681                buffer.edit(
 6682                    edit_ranges
 6683                        .into_iter()
 6684                        .map(|range| (range, empty_str.clone())),
 6685                    None,
 6686                    cx,
 6687                );
 6688                buffer.snapshot(cx)
 6689            });
 6690            let new_selections = new_cursors
 6691                .into_iter()
 6692                .map(|(id, cursor)| {
 6693                    let cursor = cursor.to_point(&buffer);
 6694                    Selection {
 6695                        id,
 6696                        start: cursor,
 6697                        end: cursor,
 6698                        reversed: false,
 6699                        goal: SelectionGoal::None,
 6700                    }
 6701                })
 6702                .collect();
 6703
 6704            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6705                s.select(new_selections);
 6706            });
 6707        });
 6708    }
 6709
 6710    pub fn join_lines_impl(
 6711        &mut self,
 6712        insert_whitespace: bool,
 6713        window: &mut Window,
 6714        cx: &mut Context<Self>,
 6715    ) {
 6716        if self.read_only(cx) {
 6717            return;
 6718        }
 6719        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6720        for selection in self.selections.all::<Point>(cx) {
 6721            let start = MultiBufferRow(selection.start.row);
 6722            // Treat single line selections as if they include the next line. Otherwise this action
 6723            // would do nothing for single line selections individual cursors.
 6724            let end = if selection.start.row == selection.end.row {
 6725                MultiBufferRow(selection.start.row + 1)
 6726            } else {
 6727                MultiBufferRow(selection.end.row)
 6728            };
 6729
 6730            if let Some(last_row_range) = row_ranges.last_mut() {
 6731                if start <= last_row_range.end {
 6732                    last_row_range.end = end;
 6733                    continue;
 6734                }
 6735            }
 6736            row_ranges.push(start..end);
 6737        }
 6738
 6739        let snapshot = self.buffer.read(cx).snapshot(cx);
 6740        let mut cursor_positions = Vec::new();
 6741        for row_range in &row_ranges {
 6742            let anchor = snapshot.anchor_before(Point::new(
 6743                row_range.end.previous_row().0,
 6744                snapshot.line_len(row_range.end.previous_row()),
 6745            ));
 6746            cursor_positions.push(anchor..anchor);
 6747        }
 6748
 6749        self.transact(window, cx, |this, window, cx| {
 6750            for row_range in row_ranges.into_iter().rev() {
 6751                for row in row_range.iter_rows().rev() {
 6752                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6753                    let next_line_row = row.next_row();
 6754                    let indent = snapshot.indent_size_for_line(next_line_row);
 6755                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6756
 6757                    let replace =
 6758                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6759                            " "
 6760                        } else {
 6761                            ""
 6762                        };
 6763
 6764                    this.buffer.update(cx, |buffer, cx| {
 6765                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6766                    });
 6767                }
 6768            }
 6769
 6770            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6771                s.select_anchor_ranges(cursor_positions)
 6772            });
 6773        });
 6774    }
 6775
 6776    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6777        self.join_lines_impl(true, window, cx);
 6778    }
 6779
 6780    pub fn sort_lines_case_sensitive(
 6781        &mut self,
 6782        _: &SortLinesCaseSensitive,
 6783        window: &mut Window,
 6784        cx: &mut Context<Self>,
 6785    ) {
 6786        self.manipulate_lines(window, cx, |lines| lines.sort())
 6787    }
 6788
 6789    pub fn sort_lines_case_insensitive(
 6790        &mut self,
 6791        _: &SortLinesCaseInsensitive,
 6792        window: &mut Window,
 6793        cx: &mut Context<Self>,
 6794    ) {
 6795        self.manipulate_lines(window, cx, |lines| {
 6796            lines.sort_by_key(|line| line.to_lowercase())
 6797        })
 6798    }
 6799
 6800    pub fn unique_lines_case_insensitive(
 6801        &mut self,
 6802        _: &UniqueLinesCaseInsensitive,
 6803        window: &mut Window,
 6804        cx: &mut Context<Self>,
 6805    ) {
 6806        self.manipulate_lines(window, cx, |lines| {
 6807            let mut seen = HashSet::default();
 6808            lines.retain(|line| seen.insert(line.to_lowercase()));
 6809        })
 6810    }
 6811
 6812    pub fn unique_lines_case_sensitive(
 6813        &mut self,
 6814        _: &UniqueLinesCaseSensitive,
 6815        window: &mut Window,
 6816        cx: &mut Context<Self>,
 6817    ) {
 6818        self.manipulate_lines(window, cx, |lines| {
 6819            let mut seen = HashSet::default();
 6820            lines.retain(|line| seen.insert(*line));
 6821        })
 6822    }
 6823
 6824    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6825        let mut revert_changes = HashMap::default();
 6826        let snapshot = self.snapshot(window, cx);
 6827        for hunk in snapshot
 6828            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6829        {
 6830            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6831        }
 6832        if !revert_changes.is_empty() {
 6833            self.transact(window, cx, |editor, window, cx| {
 6834                editor.revert(revert_changes, window, cx);
 6835            });
 6836        }
 6837    }
 6838
 6839    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6840        let Some(project) = self.project.clone() else {
 6841            return;
 6842        };
 6843        self.reload(project, window, cx)
 6844            .detach_and_notify_err(window, cx);
 6845    }
 6846
 6847    pub fn revert_selected_hunks(
 6848        &mut self,
 6849        _: &RevertSelectedHunks,
 6850        window: &mut Window,
 6851        cx: &mut Context<Self>,
 6852    ) {
 6853        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6854        self.revert_hunks_in_ranges(selections, window, cx);
 6855    }
 6856
 6857    fn revert_hunks_in_ranges(
 6858        &mut self,
 6859        ranges: impl Iterator<Item = Range<Point>>,
 6860        window: &mut Window,
 6861        cx: &mut Context<Editor>,
 6862    ) {
 6863        let mut revert_changes = HashMap::default();
 6864        let snapshot = self.snapshot(window, cx);
 6865        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6866            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6867        }
 6868        if !revert_changes.is_empty() {
 6869            self.transact(window, cx, |editor, window, cx| {
 6870                editor.revert(revert_changes, window, cx);
 6871            });
 6872        }
 6873    }
 6874
 6875    pub fn open_active_item_in_terminal(
 6876        &mut self,
 6877        _: &OpenInTerminal,
 6878        window: &mut Window,
 6879        cx: &mut Context<Self>,
 6880    ) {
 6881        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6882            let project_path = buffer.read(cx).project_path(cx)?;
 6883            let project = self.project.as_ref()?.read(cx);
 6884            let entry = project.entry_for_path(&project_path, cx)?;
 6885            let parent = match &entry.canonical_path {
 6886                Some(canonical_path) => canonical_path.to_path_buf(),
 6887                None => project.absolute_path(&project_path, cx)?,
 6888            }
 6889            .parent()?
 6890            .to_path_buf();
 6891            Some(parent)
 6892        }) {
 6893            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6894        }
 6895    }
 6896
 6897    pub fn prepare_revert_change(
 6898        &self,
 6899        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6900        hunk: &MultiBufferDiffHunk,
 6901        cx: &mut App,
 6902    ) -> Option<()> {
 6903        let buffer = self.buffer.read(cx);
 6904        let diff = buffer.diff_for(hunk.buffer_id)?;
 6905        let buffer = buffer.buffer(hunk.buffer_id)?;
 6906        let buffer = buffer.read(cx);
 6907        let original_text = diff
 6908            .read(cx)
 6909            .base_text()
 6910            .as_ref()?
 6911            .as_rope()
 6912            .slice(hunk.diff_base_byte_range.clone());
 6913        let buffer_snapshot = buffer.snapshot();
 6914        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6915        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6916            probe
 6917                .0
 6918                .start
 6919                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6920                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6921        }) {
 6922            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6923            Some(())
 6924        } else {
 6925            None
 6926        }
 6927    }
 6928
 6929    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6930        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6931    }
 6932
 6933    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6934        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6935    }
 6936
 6937    fn manipulate_lines<Fn>(
 6938        &mut self,
 6939        window: &mut Window,
 6940        cx: &mut Context<Self>,
 6941        mut callback: Fn,
 6942    ) where
 6943        Fn: FnMut(&mut Vec<&str>),
 6944    {
 6945        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6946        let buffer = self.buffer.read(cx).snapshot(cx);
 6947
 6948        let mut edits = Vec::new();
 6949
 6950        let selections = self.selections.all::<Point>(cx);
 6951        let mut selections = selections.iter().peekable();
 6952        let mut contiguous_row_selections = Vec::new();
 6953        let mut new_selections = Vec::new();
 6954        let mut added_lines = 0;
 6955        let mut removed_lines = 0;
 6956
 6957        while let Some(selection) = selections.next() {
 6958            let (start_row, end_row) = consume_contiguous_rows(
 6959                &mut contiguous_row_selections,
 6960                selection,
 6961                &display_map,
 6962                &mut selections,
 6963            );
 6964
 6965            let start_point = Point::new(start_row.0, 0);
 6966            let end_point = Point::new(
 6967                end_row.previous_row().0,
 6968                buffer.line_len(end_row.previous_row()),
 6969            );
 6970            let text = buffer
 6971                .text_for_range(start_point..end_point)
 6972                .collect::<String>();
 6973
 6974            let mut lines = text.split('\n').collect_vec();
 6975
 6976            let lines_before = lines.len();
 6977            callback(&mut lines);
 6978            let lines_after = lines.len();
 6979
 6980            edits.push((start_point..end_point, lines.join("\n")));
 6981
 6982            // Selections must change based on added and removed line count
 6983            let start_row =
 6984                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6985            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6986            new_selections.push(Selection {
 6987                id: selection.id,
 6988                start: start_row,
 6989                end: end_row,
 6990                goal: SelectionGoal::None,
 6991                reversed: selection.reversed,
 6992            });
 6993
 6994            if lines_after > lines_before {
 6995                added_lines += lines_after - lines_before;
 6996            } else if lines_before > lines_after {
 6997                removed_lines += lines_before - lines_after;
 6998            }
 6999        }
 7000
 7001        self.transact(window, cx, |this, window, cx| {
 7002            let buffer = this.buffer.update(cx, |buffer, cx| {
 7003                buffer.edit(edits, None, cx);
 7004                buffer.snapshot(cx)
 7005            });
 7006
 7007            // Recalculate offsets on newly edited buffer
 7008            let new_selections = new_selections
 7009                .iter()
 7010                .map(|s| {
 7011                    let start_point = Point::new(s.start.0, 0);
 7012                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7013                    Selection {
 7014                        id: s.id,
 7015                        start: buffer.point_to_offset(start_point),
 7016                        end: buffer.point_to_offset(end_point),
 7017                        goal: s.goal,
 7018                        reversed: s.reversed,
 7019                    }
 7020                })
 7021                .collect();
 7022
 7023            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7024                s.select(new_selections);
 7025            });
 7026
 7027            this.request_autoscroll(Autoscroll::fit(), cx);
 7028        });
 7029    }
 7030
 7031    pub fn convert_to_upper_case(
 7032        &mut self,
 7033        _: &ConvertToUpperCase,
 7034        window: &mut Window,
 7035        cx: &mut Context<Self>,
 7036    ) {
 7037        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7038    }
 7039
 7040    pub fn convert_to_lower_case(
 7041        &mut self,
 7042        _: &ConvertToLowerCase,
 7043        window: &mut Window,
 7044        cx: &mut Context<Self>,
 7045    ) {
 7046        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7047    }
 7048
 7049    pub fn convert_to_title_case(
 7050        &mut self,
 7051        _: &ConvertToTitleCase,
 7052        window: &mut Window,
 7053        cx: &mut Context<Self>,
 7054    ) {
 7055        self.manipulate_text(window, cx, |text| {
 7056            text.split('\n')
 7057                .map(|line| line.to_case(Case::Title))
 7058                .join("\n")
 7059        })
 7060    }
 7061
 7062    pub fn convert_to_snake_case(
 7063        &mut self,
 7064        _: &ConvertToSnakeCase,
 7065        window: &mut Window,
 7066        cx: &mut Context<Self>,
 7067    ) {
 7068        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7069    }
 7070
 7071    pub fn convert_to_kebab_case(
 7072        &mut self,
 7073        _: &ConvertToKebabCase,
 7074        window: &mut Window,
 7075        cx: &mut Context<Self>,
 7076    ) {
 7077        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7078    }
 7079
 7080    pub fn convert_to_upper_camel_case(
 7081        &mut self,
 7082        _: &ConvertToUpperCamelCase,
 7083        window: &mut Window,
 7084        cx: &mut Context<Self>,
 7085    ) {
 7086        self.manipulate_text(window, cx, |text| {
 7087            text.split('\n')
 7088                .map(|line| line.to_case(Case::UpperCamel))
 7089                .join("\n")
 7090        })
 7091    }
 7092
 7093    pub fn convert_to_lower_camel_case(
 7094        &mut self,
 7095        _: &ConvertToLowerCamelCase,
 7096        window: &mut Window,
 7097        cx: &mut Context<Self>,
 7098    ) {
 7099        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7100    }
 7101
 7102    pub fn convert_to_opposite_case(
 7103        &mut self,
 7104        _: &ConvertToOppositeCase,
 7105        window: &mut Window,
 7106        cx: &mut Context<Self>,
 7107    ) {
 7108        self.manipulate_text(window, cx, |text| {
 7109            text.chars()
 7110                .fold(String::with_capacity(text.len()), |mut t, c| {
 7111                    if c.is_uppercase() {
 7112                        t.extend(c.to_lowercase());
 7113                    } else {
 7114                        t.extend(c.to_uppercase());
 7115                    }
 7116                    t
 7117                })
 7118        })
 7119    }
 7120
 7121    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7122    where
 7123        Fn: FnMut(&str) -> String,
 7124    {
 7125        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7126        let buffer = self.buffer.read(cx).snapshot(cx);
 7127
 7128        let mut new_selections = Vec::new();
 7129        let mut edits = Vec::new();
 7130        let mut selection_adjustment = 0i32;
 7131
 7132        for selection in self.selections.all::<usize>(cx) {
 7133            let selection_is_empty = selection.is_empty();
 7134
 7135            let (start, end) = if selection_is_empty {
 7136                let word_range = movement::surrounding_word(
 7137                    &display_map,
 7138                    selection.start.to_display_point(&display_map),
 7139                );
 7140                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7141                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7142                (start, end)
 7143            } else {
 7144                (selection.start, selection.end)
 7145            };
 7146
 7147            let text = buffer.text_for_range(start..end).collect::<String>();
 7148            let old_length = text.len() as i32;
 7149            let text = callback(&text);
 7150
 7151            new_selections.push(Selection {
 7152                start: (start as i32 - selection_adjustment) as usize,
 7153                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7154                goal: SelectionGoal::None,
 7155                ..selection
 7156            });
 7157
 7158            selection_adjustment += old_length - text.len() as i32;
 7159
 7160            edits.push((start..end, text));
 7161        }
 7162
 7163        self.transact(window, cx, |this, window, cx| {
 7164            this.buffer.update(cx, |buffer, cx| {
 7165                buffer.edit(edits, None, cx);
 7166            });
 7167
 7168            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7169                s.select(new_selections);
 7170            });
 7171
 7172            this.request_autoscroll(Autoscroll::fit(), cx);
 7173        });
 7174    }
 7175
 7176    pub fn duplicate(
 7177        &mut self,
 7178        upwards: bool,
 7179        whole_lines: bool,
 7180        window: &mut Window,
 7181        cx: &mut Context<Self>,
 7182    ) {
 7183        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7184        let buffer = &display_map.buffer_snapshot;
 7185        let selections = self.selections.all::<Point>(cx);
 7186
 7187        let mut edits = Vec::new();
 7188        let mut selections_iter = selections.iter().peekable();
 7189        while let Some(selection) = selections_iter.next() {
 7190            let mut rows = selection.spanned_rows(false, &display_map);
 7191            // duplicate line-wise
 7192            if whole_lines || selection.start == selection.end {
 7193                // Avoid duplicating the same lines twice.
 7194                while let Some(next_selection) = selections_iter.peek() {
 7195                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7196                    if next_rows.start < rows.end {
 7197                        rows.end = next_rows.end;
 7198                        selections_iter.next().unwrap();
 7199                    } else {
 7200                        break;
 7201                    }
 7202                }
 7203
 7204                // Copy the text from the selected row region and splice it either at the start
 7205                // or end of the region.
 7206                let start = Point::new(rows.start.0, 0);
 7207                let end = Point::new(
 7208                    rows.end.previous_row().0,
 7209                    buffer.line_len(rows.end.previous_row()),
 7210                );
 7211                let text = buffer
 7212                    .text_for_range(start..end)
 7213                    .chain(Some("\n"))
 7214                    .collect::<String>();
 7215                let insert_location = if upwards {
 7216                    Point::new(rows.end.0, 0)
 7217                } else {
 7218                    start
 7219                };
 7220                edits.push((insert_location..insert_location, text));
 7221            } else {
 7222                // duplicate character-wise
 7223                let start = selection.start;
 7224                let end = selection.end;
 7225                let text = buffer.text_for_range(start..end).collect::<String>();
 7226                edits.push((selection.end..selection.end, text));
 7227            }
 7228        }
 7229
 7230        self.transact(window, cx, |this, _, cx| {
 7231            this.buffer.update(cx, |buffer, cx| {
 7232                buffer.edit(edits, None, cx);
 7233            });
 7234
 7235            this.request_autoscroll(Autoscroll::fit(), cx);
 7236        });
 7237    }
 7238
 7239    pub fn duplicate_line_up(
 7240        &mut self,
 7241        _: &DuplicateLineUp,
 7242        window: &mut Window,
 7243        cx: &mut Context<Self>,
 7244    ) {
 7245        self.duplicate(true, true, window, cx);
 7246    }
 7247
 7248    pub fn duplicate_line_down(
 7249        &mut self,
 7250        _: &DuplicateLineDown,
 7251        window: &mut Window,
 7252        cx: &mut Context<Self>,
 7253    ) {
 7254        self.duplicate(false, true, window, cx);
 7255    }
 7256
 7257    pub fn duplicate_selection(
 7258        &mut self,
 7259        _: &DuplicateSelection,
 7260        window: &mut Window,
 7261        cx: &mut Context<Self>,
 7262    ) {
 7263        self.duplicate(false, false, window, cx);
 7264    }
 7265
 7266    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7267        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7268        let buffer = self.buffer.read(cx).snapshot(cx);
 7269
 7270        let mut edits = Vec::new();
 7271        let mut unfold_ranges = Vec::new();
 7272        let mut refold_creases = Vec::new();
 7273
 7274        let selections = self.selections.all::<Point>(cx);
 7275        let mut selections = selections.iter().peekable();
 7276        let mut contiguous_row_selections = Vec::new();
 7277        let mut new_selections = Vec::new();
 7278
 7279        while let Some(selection) = selections.next() {
 7280            // Find all the selections that span a contiguous row range
 7281            let (start_row, end_row) = consume_contiguous_rows(
 7282                &mut contiguous_row_selections,
 7283                selection,
 7284                &display_map,
 7285                &mut selections,
 7286            );
 7287
 7288            // Move the text spanned by the row range to be before the line preceding the row range
 7289            if start_row.0 > 0 {
 7290                let range_to_move = Point::new(
 7291                    start_row.previous_row().0,
 7292                    buffer.line_len(start_row.previous_row()),
 7293                )
 7294                    ..Point::new(
 7295                        end_row.previous_row().0,
 7296                        buffer.line_len(end_row.previous_row()),
 7297                    );
 7298                let insertion_point = display_map
 7299                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7300                    .0;
 7301
 7302                // Don't move lines across excerpts
 7303                if buffer
 7304                    .excerpt_containing(insertion_point..range_to_move.end)
 7305                    .is_some()
 7306                {
 7307                    let text = buffer
 7308                        .text_for_range(range_to_move.clone())
 7309                        .flat_map(|s| s.chars())
 7310                        .skip(1)
 7311                        .chain(['\n'])
 7312                        .collect::<String>();
 7313
 7314                    edits.push((
 7315                        buffer.anchor_after(range_to_move.start)
 7316                            ..buffer.anchor_before(range_to_move.end),
 7317                        String::new(),
 7318                    ));
 7319                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7320                    edits.push((insertion_anchor..insertion_anchor, text));
 7321
 7322                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7323
 7324                    // Move selections up
 7325                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7326                        |mut selection| {
 7327                            selection.start.row -= row_delta;
 7328                            selection.end.row -= row_delta;
 7329                            selection
 7330                        },
 7331                    ));
 7332
 7333                    // Move folds up
 7334                    unfold_ranges.push(range_to_move.clone());
 7335                    for fold in display_map.folds_in_range(
 7336                        buffer.anchor_before(range_to_move.start)
 7337                            ..buffer.anchor_after(range_to_move.end),
 7338                    ) {
 7339                        let mut start = fold.range.start.to_point(&buffer);
 7340                        let mut end = fold.range.end.to_point(&buffer);
 7341                        start.row -= row_delta;
 7342                        end.row -= row_delta;
 7343                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7344                    }
 7345                }
 7346            }
 7347
 7348            // If we didn't move line(s), preserve the existing selections
 7349            new_selections.append(&mut contiguous_row_selections);
 7350        }
 7351
 7352        self.transact(window, cx, |this, window, cx| {
 7353            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7354            this.buffer.update(cx, |buffer, cx| {
 7355                for (range, text) in edits {
 7356                    buffer.edit([(range, text)], None, cx);
 7357                }
 7358            });
 7359            this.fold_creases(refold_creases, true, window, cx);
 7360            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7361                s.select(new_selections);
 7362            })
 7363        });
 7364    }
 7365
 7366    pub fn move_line_down(
 7367        &mut self,
 7368        _: &MoveLineDown,
 7369        window: &mut Window,
 7370        cx: &mut Context<Self>,
 7371    ) {
 7372        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7373        let buffer = self.buffer.read(cx).snapshot(cx);
 7374
 7375        let mut edits = Vec::new();
 7376        let mut unfold_ranges = Vec::new();
 7377        let mut refold_creases = Vec::new();
 7378
 7379        let selections = self.selections.all::<Point>(cx);
 7380        let mut selections = selections.iter().peekable();
 7381        let mut contiguous_row_selections = Vec::new();
 7382        let mut new_selections = Vec::new();
 7383
 7384        while let Some(selection) = selections.next() {
 7385            // Find all the selections that span a contiguous row range
 7386            let (start_row, end_row) = consume_contiguous_rows(
 7387                &mut contiguous_row_selections,
 7388                selection,
 7389                &display_map,
 7390                &mut selections,
 7391            );
 7392
 7393            // Move the text spanned by the row range to be after the last line of the row range
 7394            if end_row.0 <= buffer.max_point().row {
 7395                let range_to_move =
 7396                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7397                let insertion_point = display_map
 7398                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7399                    .0;
 7400
 7401                // Don't move lines across excerpt boundaries
 7402                if buffer
 7403                    .excerpt_containing(range_to_move.start..insertion_point)
 7404                    .is_some()
 7405                {
 7406                    let mut text = String::from("\n");
 7407                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7408                    text.pop(); // Drop trailing newline
 7409                    edits.push((
 7410                        buffer.anchor_after(range_to_move.start)
 7411                            ..buffer.anchor_before(range_to_move.end),
 7412                        String::new(),
 7413                    ));
 7414                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7415                    edits.push((insertion_anchor..insertion_anchor, text));
 7416
 7417                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7418
 7419                    // Move selections down
 7420                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7421                        |mut selection| {
 7422                            selection.start.row += row_delta;
 7423                            selection.end.row += row_delta;
 7424                            selection
 7425                        },
 7426                    ));
 7427
 7428                    // Move folds down
 7429                    unfold_ranges.push(range_to_move.clone());
 7430                    for fold in display_map.folds_in_range(
 7431                        buffer.anchor_before(range_to_move.start)
 7432                            ..buffer.anchor_after(range_to_move.end),
 7433                    ) {
 7434                        let mut start = fold.range.start.to_point(&buffer);
 7435                        let mut end = fold.range.end.to_point(&buffer);
 7436                        start.row += row_delta;
 7437                        end.row += row_delta;
 7438                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7439                    }
 7440                }
 7441            }
 7442
 7443            // If we didn't move line(s), preserve the existing selections
 7444            new_selections.append(&mut contiguous_row_selections);
 7445        }
 7446
 7447        self.transact(window, cx, |this, window, cx| {
 7448            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7449            this.buffer.update(cx, |buffer, cx| {
 7450                for (range, text) in edits {
 7451                    buffer.edit([(range, text)], None, cx);
 7452                }
 7453            });
 7454            this.fold_creases(refold_creases, true, window, cx);
 7455            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7456                s.select(new_selections)
 7457            });
 7458        });
 7459    }
 7460
 7461    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7462        let text_layout_details = &self.text_layout_details(window);
 7463        self.transact(window, cx, |this, window, cx| {
 7464            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7465                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7466                let line_mode = s.line_mode;
 7467                s.move_with(|display_map, selection| {
 7468                    if !selection.is_empty() || line_mode {
 7469                        return;
 7470                    }
 7471
 7472                    let mut head = selection.head();
 7473                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7474                    if head.column() == display_map.line_len(head.row()) {
 7475                        transpose_offset = display_map
 7476                            .buffer_snapshot
 7477                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7478                    }
 7479
 7480                    if transpose_offset == 0 {
 7481                        return;
 7482                    }
 7483
 7484                    *head.column_mut() += 1;
 7485                    head = display_map.clip_point(head, Bias::Right);
 7486                    let goal = SelectionGoal::HorizontalPosition(
 7487                        display_map
 7488                            .x_for_display_point(head, text_layout_details)
 7489                            .into(),
 7490                    );
 7491                    selection.collapse_to(head, goal);
 7492
 7493                    let transpose_start = display_map
 7494                        .buffer_snapshot
 7495                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7496                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7497                        let transpose_end = display_map
 7498                            .buffer_snapshot
 7499                            .clip_offset(transpose_offset + 1, Bias::Right);
 7500                        if let Some(ch) =
 7501                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7502                        {
 7503                            edits.push((transpose_start..transpose_offset, String::new()));
 7504                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7505                        }
 7506                    }
 7507                });
 7508                edits
 7509            });
 7510            this.buffer
 7511                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7512            let selections = this.selections.all::<usize>(cx);
 7513            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7514                s.select(selections);
 7515            });
 7516        });
 7517    }
 7518
 7519    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7520        self.rewrap_impl(IsVimMode::No, cx)
 7521    }
 7522
 7523    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7524        let buffer = self.buffer.read(cx).snapshot(cx);
 7525        let selections = self.selections.all::<Point>(cx);
 7526        let mut selections = selections.iter().peekable();
 7527
 7528        let mut edits = Vec::new();
 7529        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7530
 7531        while let Some(selection) = selections.next() {
 7532            let mut start_row = selection.start.row;
 7533            let mut end_row = selection.end.row;
 7534
 7535            // Skip selections that overlap with a range that has already been rewrapped.
 7536            let selection_range = start_row..end_row;
 7537            if rewrapped_row_ranges
 7538                .iter()
 7539                .any(|range| range.overlaps(&selection_range))
 7540            {
 7541                continue;
 7542            }
 7543
 7544            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7545
 7546            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7547                match language_scope.language_name().as_ref() {
 7548                    "Markdown" | "Plain Text" => {
 7549                        should_rewrap = true;
 7550                    }
 7551                    _ => {}
 7552                }
 7553            }
 7554
 7555            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7556
 7557            // Since not all lines in the selection may be at the same indent
 7558            // level, choose the indent size that is the most common between all
 7559            // of the lines.
 7560            //
 7561            // If there is a tie, we use the deepest indent.
 7562            let (indent_size, indent_end) = {
 7563                let mut indent_size_occurrences = HashMap::default();
 7564                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7565
 7566                for row in start_row..=end_row {
 7567                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7568                    rows_by_indent_size.entry(indent).or_default().push(row);
 7569                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7570                }
 7571
 7572                let indent_size = indent_size_occurrences
 7573                    .into_iter()
 7574                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7575                    .map(|(indent, _)| indent)
 7576                    .unwrap_or_default();
 7577                let row = rows_by_indent_size[&indent_size][0];
 7578                let indent_end = Point::new(row, indent_size.len);
 7579
 7580                (indent_size, indent_end)
 7581            };
 7582
 7583            let mut line_prefix = indent_size.chars().collect::<String>();
 7584
 7585            if let Some(comment_prefix) =
 7586                buffer
 7587                    .language_scope_at(selection.head())
 7588                    .and_then(|language| {
 7589                        language
 7590                            .line_comment_prefixes()
 7591                            .iter()
 7592                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7593                            .cloned()
 7594                    })
 7595            {
 7596                line_prefix.push_str(&comment_prefix);
 7597                should_rewrap = true;
 7598            }
 7599
 7600            if !should_rewrap {
 7601                continue;
 7602            }
 7603
 7604            if selection.is_empty() {
 7605                'expand_upwards: while start_row > 0 {
 7606                    let prev_row = start_row - 1;
 7607                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7608                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7609                    {
 7610                        start_row = prev_row;
 7611                    } else {
 7612                        break 'expand_upwards;
 7613                    }
 7614                }
 7615
 7616                'expand_downwards: while end_row < buffer.max_point().row {
 7617                    let next_row = end_row + 1;
 7618                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7619                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7620                    {
 7621                        end_row = next_row;
 7622                    } else {
 7623                        break 'expand_downwards;
 7624                    }
 7625                }
 7626            }
 7627
 7628            let start = Point::new(start_row, 0);
 7629            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7630            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7631            let Some(lines_without_prefixes) = selection_text
 7632                .lines()
 7633                .map(|line| {
 7634                    line.strip_prefix(&line_prefix)
 7635                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7636                        .ok_or_else(|| {
 7637                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7638                        })
 7639                })
 7640                .collect::<Result<Vec<_>, _>>()
 7641                .log_err()
 7642            else {
 7643                continue;
 7644            };
 7645
 7646            let wrap_column = buffer
 7647                .settings_at(Point::new(start_row, 0), cx)
 7648                .preferred_line_length as usize;
 7649            let wrapped_text = wrap_with_prefix(
 7650                line_prefix,
 7651                lines_without_prefixes.join(" "),
 7652                wrap_column,
 7653                tab_size,
 7654            );
 7655
 7656            // TODO: should always use char-based diff while still supporting cursor behavior that
 7657            // matches vim.
 7658            let diff = match is_vim_mode {
 7659                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7660                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7661            };
 7662            let mut offset = start.to_offset(&buffer);
 7663            let mut moved_since_edit = true;
 7664
 7665            for change in diff.iter_all_changes() {
 7666                let value = change.value();
 7667                match change.tag() {
 7668                    ChangeTag::Equal => {
 7669                        offset += value.len();
 7670                        moved_since_edit = true;
 7671                    }
 7672                    ChangeTag::Delete => {
 7673                        let start = buffer.anchor_after(offset);
 7674                        let end = buffer.anchor_before(offset + value.len());
 7675
 7676                        if moved_since_edit {
 7677                            edits.push((start..end, String::new()));
 7678                        } else {
 7679                            edits.last_mut().unwrap().0.end = end;
 7680                        }
 7681
 7682                        offset += value.len();
 7683                        moved_since_edit = false;
 7684                    }
 7685                    ChangeTag::Insert => {
 7686                        if moved_since_edit {
 7687                            let anchor = buffer.anchor_after(offset);
 7688                            edits.push((anchor..anchor, value.to_string()));
 7689                        } else {
 7690                            edits.last_mut().unwrap().1.push_str(value);
 7691                        }
 7692
 7693                        moved_since_edit = false;
 7694                    }
 7695                }
 7696            }
 7697
 7698            rewrapped_row_ranges.push(start_row..=end_row);
 7699        }
 7700
 7701        self.buffer
 7702            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7703    }
 7704
 7705    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7706        let mut text = String::new();
 7707        let buffer = self.buffer.read(cx).snapshot(cx);
 7708        let mut selections = self.selections.all::<Point>(cx);
 7709        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7710        {
 7711            let max_point = buffer.max_point();
 7712            let mut is_first = true;
 7713            for selection in &mut selections {
 7714                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7715                if is_entire_line {
 7716                    selection.start = Point::new(selection.start.row, 0);
 7717                    if !selection.is_empty() && selection.end.column == 0 {
 7718                        selection.end = cmp::min(max_point, selection.end);
 7719                    } else {
 7720                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7721                    }
 7722                    selection.goal = SelectionGoal::None;
 7723                }
 7724                if is_first {
 7725                    is_first = false;
 7726                } else {
 7727                    text += "\n";
 7728                }
 7729                let mut len = 0;
 7730                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7731                    text.push_str(chunk);
 7732                    len += chunk.len();
 7733                }
 7734                clipboard_selections.push(ClipboardSelection {
 7735                    len,
 7736                    is_entire_line,
 7737                    first_line_indent: buffer
 7738                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7739                        .len,
 7740                });
 7741            }
 7742        }
 7743
 7744        self.transact(window, cx, |this, window, cx| {
 7745            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7746                s.select(selections);
 7747            });
 7748            this.insert("", window, cx);
 7749        });
 7750        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7751    }
 7752
 7753    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7754        let item = self.cut_common(window, cx);
 7755        cx.write_to_clipboard(item);
 7756    }
 7757
 7758    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7759        self.change_selections(None, window, cx, |s| {
 7760            s.move_with(|snapshot, sel| {
 7761                if sel.is_empty() {
 7762                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7763                }
 7764            });
 7765        });
 7766        let item = self.cut_common(window, cx);
 7767        cx.set_global(KillRing(item))
 7768    }
 7769
 7770    pub fn kill_ring_yank(
 7771        &mut self,
 7772        _: &KillRingYank,
 7773        window: &mut Window,
 7774        cx: &mut Context<Self>,
 7775    ) {
 7776        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7777            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7778                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7779            } else {
 7780                return;
 7781            }
 7782        } else {
 7783            return;
 7784        };
 7785        self.do_paste(&text, metadata, false, window, cx);
 7786    }
 7787
 7788    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7789        let selections = self.selections.all::<Point>(cx);
 7790        let buffer = self.buffer.read(cx).read(cx);
 7791        let mut text = String::new();
 7792
 7793        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7794        {
 7795            let max_point = buffer.max_point();
 7796            let mut is_first = true;
 7797            for selection in selections.iter() {
 7798                let mut start = selection.start;
 7799                let mut end = selection.end;
 7800                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7801                if is_entire_line {
 7802                    start = Point::new(start.row, 0);
 7803                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7804                }
 7805                if is_first {
 7806                    is_first = false;
 7807                } else {
 7808                    text += "\n";
 7809                }
 7810                let mut len = 0;
 7811                for chunk in buffer.text_for_range(start..end) {
 7812                    text.push_str(chunk);
 7813                    len += chunk.len();
 7814                }
 7815                clipboard_selections.push(ClipboardSelection {
 7816                    len,
 7817                    is_entire_line,
 7818                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7819                });
 7820            }
 7821        }
 7822
 7823        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7824            text,
 7825            clipboard_selections,
 7826        ));
 7827    }
 7828
 7829    pub fn do_paste(
 7830        &mut self,
 7831        text: &String,
 7832        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7833        handle_entire_lines: bool,
 7834        window: &mut Window,
 7835        cx: &mut Context<Self>,
 7836    ) {
 7837        if self.read_only(cx) {
 7838            return;
 7839        }
 7840
 7841        let clipboard_text = Cow::Borrowed(text);
 7842
 7843        self.transact(window, cx, |this, window, cx| {
 7844            if let Some(mut clipboard_selections) = clipboard_selections {
 7845                let old_selections = this.selections.all::<usize>(cx);
 7846                let all_selections_were_entire_line =
 7847                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7848                let first_selection_indent_column =
 7849                    clipboard_selections.first().map(|s| s.first_line_indent);
 7850                if clipboard_selections.len() != old_selections.len() {
 7851                    clipboard_selections.drain(..);
 7852                }
 7853                let cursor_offset = this.selections.last::<usize>(cx).head();
 7854                let mut auto_indent_on_paste = true;
 7855
 7856                this.buffer.update(cx, |buffer, cx| {
 7857                    let snapshot = buffer.read(cx);
 7858                    auto_indent_on_paste =
 7859                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7860
 7861                    let mut start_offset = 0;
 7862                    let mut edits = Vec::new();
 7863                    let mut original_indent_columns = Vec::new();
 7864                    for (ix, selection) in old_selections.iter().enumerate() {
 7865                        let to_insert;
 7866                        let entire_line;
 7867                        let original_indent_column;
 7868                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7869                            let end_offset = start_offset + clipboard_selection.len;
 7870                            to_insert = &clipboard_text[start_offset..end_offset];
 7871                            entire_line = clipboard_selection.is_entire_line;
 7872                            start_offset = end_offset + 1;
 7873                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7874                        } else {
 7875                            to_insert = clipboard_text.as_str();
 7876                            entire_line = all_selections_were_entire_line;
 7877                            original_indent_column = first_selection_indent_column
 7878                        }
 7879
 7880                        // If the corresponding selection was empty when this slice of the
 7881                        // clipboard text was written, then the entire line containing the
 7882                        // selection was copied. If this selection is also currently empty,
 7883                        // then paste the line before the current line of the buffer.
 7884                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7885                            let column = selection.start.to_point(&snapshot).column as usize;
 7886                            let line_start = selection.start - column;
 7887                            line_start..line_start
 7888                        } else {
 7889                            selection.range()
 7890                        };
 7891
 7892                        edits.push((range, to_insert));
 7893                        original_indent_columns.extend(original_indent_column);
 7894                    }
 7895                    drop(snapshot);
 7896
 7897                    buffer.edit(
 7898                        edits,
 7899                        if auto_indent_on_paste {
 7900                            Some(AutoindentMode::Block {
 7901                                original_indent_columns,
 7902                            })
 7903                        } else {
 7904                            None
 7905                        },
 7906                        cx,
 7907                    );
 7908                });
 7909
 7910                let selections = this.selections.all::<usize>(cx);
 7911                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7912                    s.select(selections)
 7913                });
 7914            } else {
 7915                this.insert(&clipboard_text, window, cx);
 7916            }
 7917        });
 7918    }
 7919
 7920    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7921        if let Some(item) = cx.read_from_clipboard() {
 7922            let entries = item.entries();
 7923
 7924            match entries.first() {
 7925                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7926                // of all the pasted entries.
 7927                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7928                    .do_paste(
 7929                        clipboard_string.text(),
 7930                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7931                        true,
 7932                        window,
 7933                        cx,
 7934                    ),
 7935                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7936            }
 7937        }
 7938    }
 7939
 7940    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7941        if self.read_only(cx) {
 7942            return;
 7943        }
 7944
 7945        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7946            if let Some((selections, _)) =
 7947                self.selection_history.transaction(transaction_id).cloned()
 7948            {
 7949                self.change_selections(None, window, cx, |s| {
 7950                    s.select_anchors(selections.to_vec());
 7951                });
 7952            }
 7953            self.request_autoscroll(Autoscroll::fit(), cx);
 7954            self.unmark_text(window, cx);
 7955            self.refresh_inline_completion(true, false, window, cx);
 7956            cx.emit(EditorEvent::Edited { transaction_id });
 7957            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7958        }
 7959    }
 7960
 7961    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7962        if self.read_only(cx) {
 7963            return;
 7964        }
 7965
 7966        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7967            if let Some((_, Some(selections))) =
 7968                self.selection_history.transaction(transaction_id).cloned()
 7969            {
 7970                self.change_selections(None, window, cx, |s| {
 7971                    s.select_anchors(selections.to_vec());
 7972                });
 7973            }
 7974            self.request_autoscroll(Autoscroll::fit(), cx);
 7975            self.unmark_text(window, cx);
 7976            self.refresh_inline_completion(true, false, window, cx);
 7977            cx.emit(EditorEvent::Edited { transaction_id });
 7978        }
 7979    }
 7980
 7981    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7982        self.buffer
 7983            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7984    }
 7985
 7986    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7987        self.buffer
 7988            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7989    }
 7990
 7991    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7992        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7993            let line_mode = s.line_mode;
 7994            s.move_with(|map, selection| {
 7995                let cursor = if selection.is_empty() && !line_mode {
 7996                    movement::left(map, selection.start)
 7997                } else {
 7998                    selection.start
 7999                };
 8000                selection.collapse_to(cursor, SelectionGoal::None);
 8001            });
 8002        })
 8003    }
 8004
 8005    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8006        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8007            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8008        })
 8009    }
 8010
 8011    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8012        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8013            let line_mode = s.line_mode;
 8014            s.move_with(|map, selection| {
 8015                let cursor = if selection.is_empty() && !line_mode {
 8016                    movement::right(map, selection.end)
 8017                } else {
 8018                    selection.end
 8019                };
 8020                selection.collapse_to(cursor, SelectionGoal::None)
 8021            });
 8022        })
 8023    }
 8024
 8025    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8026        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8027            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8028        })
 8029    }
 8030
 8031    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8032        if self.take_rename(true, window, cx).is_some() {
 8033            return;
 8034        }
 8035
 8036        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8037            cx.propagate();
 8038            return;
 8039        }
 8040
 8041        let text_layout_details = &self.text_layout_details(window);
 8042        let selection_count = self.selections.count();
 8043        let first_selection = self.selections.first_anchor();
 8044
 8045        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8046            let line_mode = s.line_mode;
 8047            s.move_with(|map, selection| {
 8048                if !selection.is_empty() && !line_mode {
 8049                    selection.goal = SelectionGoal::None;
 8050                }
 8051                let (cursor, goal) = movement::up(
 8052                    map,
 8053                    selection.start,
 8054                    selection.goal,
 8055                    false,
 8056                    text_layout_details,
 8057                );
 8058                selection.collapse_to(cursor, goal);
 8059            });
 8060        });
 8061
 8062        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8063        {
 8064            cx.propagate();
 8065        }
 8066    }
 8067
 8068    pub fn move_up_by_lines(
 8069        &mut self,
 8070        action: &MoveUpByLines,
 8071        window: &mut Window,
 8072        cx: &mut Context<Self>,
 8073    ) {
 8074        if self.take_rename(true, window, cx).is_some() {
 8075            return;
 8076        }
 8077
 8078        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8079            cx.propagate();
 8080            return;
 8081        }
 8082
 8083        let text_layout_details = &self.text_layout_details(window);
 8084
 8085        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8086            let line_mode = s.line_mode;
 8087            s.move_with(|map, selection| {
 8088                if !selection.is_empty() && !line_mode {
 8089                    selection.goal = SelectionGoal::None;
 8090                }
 8091                let (cursor, goal) = movement::up_by_rows(
 8092                    map,
 8093                    selection.start,
 8094                    action.lines,
 8095                    selection.goal,
 8096                    false,
 8097                    text_layout_details,
 8098                );
 8099                selection.collapse_to(cursor, goal);
 8100            });
 8101        })
 8102    }
 8103
 8104    pub fn move_down_by_lines(
 8105        &mut self,
 8106        action: &MoveDownByLines,
 8107        window: &mut Window,
 8108        cx: &mut Context<Self>,
 8109    ) {
 8110        if self.take_rename(true, window, cx).is_some() {
 8111            return;
 8112        }
 8113
 8114        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8115            cx.propagate();
 8116            return;
 8117        }
 8118
 8119        let text_layout_details = &self.text_layout_details(window);
 8120
 8121        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8122            let line_mode = s.line_mode;
 8123            s.move_with(|map, selection| {
 8124                if !selection.is_empty() && !line_mode {
 8125                    selection.goal = SelectionGoal::None;
 8126                }
 8127                let (cursor, goal) = movement::down_by_rows(
 8128                    map,
 8129                    selection.start,
 8130                    action.lines,
 8131                    selection.goal,
 8132                    false,
 8133                    text_layout_details,
 8134                );
 8135                selection.collapse_to(cursor, goal);
 8136            });
 8137        })
 8138    }
 8139
 8140    pub fn select_down_by_lines(
 8141        &mut self,
 8142        action: &SelectDownByLines,
 8143        window: &mut Window,
 8144        cx: &mut Context<Self>,
 8145    ) {
 8146        let text_layout_details = &self.text_layout_details(window);
 8147        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8148            s.move_heads_with(|map, head, goal| {
 8149                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8150            })
 8151        })
 8152    }
 8153
 8154    pub fn select_up_by_lines(
 8155        &mut self,
 8156        action: &SelectUpByLines,
 8157        window: &mut Window,
 8158        cx: &mut Context<Self>,
 8159    ) {
 8160        let text_layout_details = &self.text_layout_details(window);
 8161        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8162            s.move_heads_with(|map, head, goal| {
 8163                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8164            })
 8165        })
 8166    }
 8167
 8168    pub fn select_page_up(
 8169        &mut self,
 8170        _: &SelectPageUp,
 8171        window: &mut Window,
 8172        cx: &mut Context<Self>,
 8173    ) {
 8174        let Some(row_count) = self.visible_row_count() else {
 8175            return;
 8176        };
 8177
 8178        let text_layout_details = &self.text_layout_details(window);
 8179
 8180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8181            s.move_heads_with(|map, head, goal| {
 8182                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8183            })
 8184        })
 8185    }
 8186
 8187    pub fn move_page_up(
 8188        &mut self,
 8189        action: &MovePageUp,
 8190        window: &mut Window,
 8191        cx: &mut Context<Self>,
 8192    ) {
 8193        if self.take_rename(true, window, cx).is_some() {
 8194            return;
 8195        }
 8196
 8197        if self
 8198            .context_menu
 8199            .borrow_mut()
 8200            .as_mut()
 8201            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8202            .unwrap_or(false)
 8203        {
 8204            return;
 8205        }
 8206
 8207        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8208            cx.propagate();
 8209            return;
 8210        }
 8211
 8212        let Some(row_count) = self.visible_row_count() else {
 8213            return;
 8214        };
 8215
 8216        let autoscroll = if action.center_cursor {
 8217            Autoscroll::center()
 8218        } else {
 8219            Autoscroll::fit()
 8220        };
 8221
 8222        let text_layout_details = &self.text_layout_details(window);
 8223
 8224        self.change_selections(Some(autoscroll), window, cx, |s| {
 8225            let line_mode = s.line_mode;
 8226            s.move_with(|map, selection| {
 8227                if !selection.is_empty() && !line_mode {
 8228                    selection.goal = SelectionGoal::None;
 8229                }
 8230                let (cursor, goal) = movement::up_by_rows(
 8231                    map,
 8232                    selection.end,
 8233                    row_count,
 8234                    selection.goal,
 8235                    false,
 8236                    text_layout_details,
 8237                );
 8238                selection.collapse_to(cursor, goal);
 8239            });
 8240        });
 8241    }
 8242
 8243    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8244        let text_layout_details = &self.text_layout_details(window);
 8245        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8246            s.move_heads_with(|map, head, goal| {
 8247                movement::up(map, head, goal, false, text_layout_details)
 8248            })
 8249        })
 8250    }
 8251
 8252    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8253        self.take_rename(true, window, cx);
 8254
 8255        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8256            cx.propagate();
 8257            return;
 8258        }
 8259
 8260        let text_layout_details = &self.text_layout_details(window);
 8261        let selection_count = self.selections.count();
 8262        let first_selection = self.selections.first_anchor();
 8263
 8264        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8265            let line_mode = s.line_mode;
 8266            s.move_with(|map, selection| {
 8267                if !selection.is_empty() && !line_mode {
 8268                    selection.goal = SelectionGoal::None;
 8269                }
 8270                let (cursor, goal) = movement::down(
 8271                    map,
 8272                    selection.end,
 8273                    selection.goal,
 8274                    false,
 8275                    text_layout_details,
 8276                );
 8277                selection.collapse_to(cursor, goal);
 8278            });
 8279        });
 8280
 8281        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8282        {
 8283            cx.propagate();
 8284        }
 8285    }
 8286
 8287    pub fn select_page_down(
 8288        &mut self,
 8289        _: &SelectPageDown,
 8290        window: &mut Window,
 8291        cx: &mut Context<Self>,
 8292    ) {
 8293        let Some(row_count) = self.visible_row_count() else {
 8294            return;
 8295        };
 8296
 8297        let text_layout_details = &self.text_layout_details(window);
 8298
 8299        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8300            s.move_heads_with(|map, head, goal| {
 8301                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8302            })
 8303        })
 8304    }
 8305
 8306    pub fn move_page_down(
 8307        &mut self,
 8308        action: &MovePageDown,
 8309        window: &mut Window,
 8310        cx: &mut Context<Self>,
 8311    ) {
 8312        if self.take_rename(true, window, cx).is_some() {
 8313            return;
 8314        }
 8315
 8316        if self
 8317            .context_menu
 8318            .borrow_mut()
 8319            .as_mut()
 8320            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8321            .unwrap_or(false)
 8322        {
 8323            return;
 8324        }
 8325
 8326        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8327            cx.propagate();
 8328            return;
 8329        }
 8330
 8331        let Some(row_count) = self.visible_row_count() else {
 8332            return;
 8333        };
 8334
 8335        let autoscroll = if action.center_cursor {
 8336            Autoscroll::center()
 8337        } else {
 8338            Autoscroll::fit()
 8339        };
 8340
 8341        let text_layout_details = &self.text_layout_details(window);
 8342        self.change_selections(Some(autoscroll), window, cx, |s| {
 8343            let line_mode = s.line_mode;
 8344            s.move_with(|map, selection| {
 8345                if !selection.is_empty() && !line_mode {
 8346                    selection.goal = SelectionGoal::None;
 8347                }
 8348                let (cursor, goal) = movement::down_by_rows(
 8349                    map,
 8350                    selection.end,
 8351                    row_count,
 8352                    selection.goal,
 8353                    false,
 8354                    text_layout_details,
 8355                );
 8356                selection.collapse_to(cursor, goal);
 8357            });
 8358        });
 8359    }
 8360
 8361    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8362        let text_layout_details = &self.text_layout_details(window);
 8363        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8364            s.move_heads_with(|map, head, goal| {
 8365                movement::down(map, head, goal, false, text_layout_details)
 8366            })
 8367        });
 8368    }
 8369
 8370    pub fn context_menu_first(
 8371        &mut self,
 8372        _: &ContextMenuFirst,
 8373        _window: &mut Window,
 8374        cx: &mut Context<Self>,
 8375    ) {
 8376        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8377            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8378        }
 8379    }
 8380
 8381    pub fn context_menu_prev(
 8382        &mut self,
 8383        _: &ContextMenuPrev,
 8384        _window: &mut Window,
 8385        cx: &mut Context<Self>,
 8386    ) {
 8387        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8388            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8389        }
 8390    }
 8391
 8392    pub fn context_menu_next(
 8393        &mut self,
 8394        _: &ContextMenuNext,
 8395        _window: &mut Window,
 8396        cx: &mut Context<Self>,
 8397    ) {
 8398        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8399            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8400        }
 8401    }
 8402
 8403    pub fn context_menu_last(
 8404        &mut self,
 8405        _: &ContextMenuLast,
 8406        _window: &mut Window,
 8407        cx: &mut Context<Self>,
 8408    ) {
 8409        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8410            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8411        }
 8412    }
 8413
 8414    pub fn move_to_previous_word_start(
 8415        &mut self,
 8416        _: &MoveToPreviousWordStart,
 8417        window: &mut Window,
 8418        cx: &mut Context<Self>,
 8419    ) {
 8420        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8421            s.move_cursors_with(|map, head, _| {
 8422                (
 8423                    movement::previous_word_start(map, head),
 8424                    SelectionGoal::None,
 8425                )
 8426            });
 8427        })
 8428    }
 8429
 8430    pub fn move_to_previous_subword_start(
 8431        &mut self,
 8432        _: &MoveToPreviousSubwordStart,
 8433        window: &mut Window,
 8434        cx: &mut Context<Self>,
 8435    ) {
 8436        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8437            s.move_cursors_with(|map, head, _| {
 8438                (
 8439                    movement::previous_subword_start(map, head),
 8440                    SelectionGoal::None,
 8441                )
 8442            });
 8443        })
 8444    }
 8445
 8446    pub fn select_to_previous_word_start(
 8447        &mut self,
 8448        _: &SelectToPreviousWordStart,
 8449        window: &mut Window,
 8450        cx: &mut Context<Self>,
 8451    ) {
 8452        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8453            s.move_heads_with(|map, head, _| {
 8454                (
 8455                    movement::previous_word_start(map, head),
 8456                    SelectionGoal::None,
 8457                )
 8458            });
 8459        })
 8460    }
 8461
 8462    pub fn select_to_previous_subword_start(
 8463        &mut self,
 8464        _: &SelectToPreviousSubwordStart,
 8465        window: &mut Window,
 8466        cx: &mut Context<Self>,
 8467    ) {
 8468        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8469            s.move_heads_with(|map, head, _| {
 8470                (
 8471                    movement::previous_subword_start(map, head),
 8472                    SelectionGoal::None,
 8473                )
 8474            });
 8475        })
 8476    }
 8477
 8478    pub fn delete_to_previous_word_start(
 8479        &mut self,
 8480        action: &DeleteToPreviousWordStart,
 8481        window: &mut Window,
 8482        cx: &mut Context<Self>,
 8483    ) {
 8484        self.transact(window, cx, |this, window, cx| {
 8485            this.select_autoclose_pair(window, cx);
 8486            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8487                let line_mode = s.line_mode;
 8488                s.move_with(|map, selection| {
 8489                    if selection.is_empty() && !line_mode {
 8490                        let cursor = if action.ignore_newlines {
 8491                            movement::previous_word_start(map, selection.head())
 8492                        } else {
 8493                            movement::previous_word_start_or_newline(map, selection.head())
 8494                        };
 8495                        selection.set_head(cursor, SelectionGoal::None);
 8496                    }
 8497                });
 8498            });
 8499            this.insert("", window, cx);
 8500        });
 8501    }
 8502
 8503    pub fn delete_to_previous_subword_start(
 8504        &mut self,
 8505        _: &DeleteToPreviousSubwordStart,
 8506        window: &mut Window,
 8507        cx: &mut Context<Self>,
 8508    ) {
 8509        self.transact(window, cx, |this, window, cx| {
 8510            this.select_autoclose_pair(window, cx);
 8511            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8512                let line_mode = s.line_mode;
 8513                s.move_with(|map, selection| {
 8514                    if selection.is_empty() && !line_mode {
 8515                        let cursor = movement::previous_subword_start(map, selection.head());
 8516                        selection.set_head(cursor, SelectionGoal::None);
 8517                    }
 8518                });
 8519            });
 8520            this.insert("", window, cx);
 8521        });
 8522    }
 8523
 8524    pub fn move_to_next_word_end(
 8525        &mut self,
 8526        _: &MoveToNextWordEnd,
 8527        window: &mut Window,
 8528        cx: &mut Context<Self>,
 8529    ) {
 8530        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8531            s.move_cursors_with(|map, head, _| {
 8532                (movement::next_word_end(map, head), SelectionGoal::None)
 8533            });
 8534        })
 8535    }
 8536
 8537    pub fn move_to_next_subword_end(
 8538        &mut self,
 8539        _: &MoveToNextSubwordEnd,
 8540        window: &mut Window,
 8541        cx: &mut Context<Self>,
 8542    ) {
 8543        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8544            s.move_cursors_with(|map, head, _| {
 8545                (movement::next_subword_end(map, head), SelectionGoal::None)
 8546            });
 8547        })
 8548    }
 8549
 8550    pub fn select_to_next_word_end(
 8551        &mut self,
 8552        _: &SelectToNextWordEnd,
 8553        window: &mut Window,
 8554        cx: &mut Context<Self>,
 8555    ) {
 8556        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8557            s.move_heads_with(|map, head, _| {
 8558                (movement::next_word_end(map, head), SelectionGoal::None)
 8559            });
 8560        })
 8561    }
 8562
 8563    pub fn select_to_next_subword_end(
 8564        &mut self,
 8565        _: &SelectToNextSubwordEnd,
 8566        window: &mut Window,
 8567        cx: &mut Context<Self>,
 8568    ) {
 8569        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8570            s.move_heads_with(|map, head, _| {
 8571                (movement::next_subword_end(map, head), SelectionGoal::None)
 8572            });
 8573        })
 8574    }
 8575
 8576    pub fn delete_to_next_word_end(
 8577        &mut self,
 8578        action: &DeleteToNextWordEnd,
 8579        window: &mut Window,
 8580        cx: &mut Context<Self>,
 8581    ) {
 8582        self.transact(window, cx, |this, window, cx| {
 8583            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8584                let line_mode = s.line_mode;
 8585                s.move_with(|map, selection| {
 8586                    if selection.is_empty() && !line_mode {
 8587                        let cursor = if action.ignore_newlines {
 8588                            movement::next_word_end(map, selection.head())
 8589                        } else {
 8590                            movement::next_word_end_or_newline(map, selection.head())
 8591                        };
 8592                        selection.set_head(cursor, SelectionGoal::None);
 8593                    }
 8594                });
 8595            });
 8596            this.insert("", window, cx);
 8597        });
 8598    }
 8599
 8600    pub fn delete_to_next_subword_end(
 8601        &mut self,
 8602        _: &DeleteToNextSubwordEnd,
 8603        window: &mut Window,
 8604        cx: &mut Context<Self>,
 8605    ) {
 8606        self.transact(window, cx, |this, window, cx| {
 8607            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8608                s.move_with(|map, selection| {
 8609                    if selection.is_empty() {
 8610                        let cursor = movement::next_subword_end(map, selection.head());
 8611                        selection.set_head(cursor, SelectionGoal::None);
 8612                    }
 8613                });
 8614            });
 8615            this.insert("", window, cx);
 8616        });
 8617    }
 8618
 8619    pub fn move_to_beginning_of_line(
 8620        &mut self,
 8621        action: &MoveToBeginningOfLine,
 8622        window: &mut Window,
 8623        cx: &mut Context<Self>,
 8624    ) {
 8625        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8626            s.move_cursors_with(|map, head, _| {
 8627                (
 8628                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8629                    SelectionGoal::None,
 8630                )
 8631            });
 8632        })
 8633    }
 8634
 8635    pub fn select_to_beginning_of_line(
 8636        &mut self,
 8637        action: &SelectToBeginningOfLine,
 8638        window: &mut Window,
 8639        cx: &mut Context<Self>,
 8640    ) {
 8641        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8642            s.move_heads_with(|map, head, _| {
 8643                (
 8644                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8645                    SelectionGoal::None,
 8646                )
 8647            });
 8648        });
 8649    }
 8650
 8651    pub fn delete_to_beginning_of_line(
 8652        &mut self,
 8653        _: &DeleteToBeginningOfLine,
 8654        window: &mut Window,
 8655        cx: &mut Context<Self>,
 8656    ) {
 8657        self.transact(window, cx, |this, window, cx| {
 8658            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8659                s.move_with(|_, selection| {
 8660                    selection.reversed = true;
 8661                });
 8662            });
 8663
 8664            this.select_to_beginning_of_line(
 8665                &SelectToBeginningOfLine {
 8666                    stop_at_soft_wraps: false,
 8667                },
 8668                window,
 8669                cx,
 8670            );
 8671            this.backspace(&Backspace, window, cx);
 8672        });
 8673    }
 8674
 8675    pub fn move_to_end_of_line(
 8676        &mut self,
 8677        action: &MoveToEndOfLine,
 8678        window: &mut Window,
 8679        cx: &mut Context<Self>,
 8680    ) {
 8681        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8682            s.move_cursors_with(|map, head, _| {
 8683                (
 8684                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8685                    SelectionGoal::None,
 8686                )
 8687            });
 8688        })
 8689    }
 8690
 8691    pub fn select_to_end_of_line(
 8692        &mut self,
 8693        action: &SelectToEndOfLine,
 8694        window: &mut Window,
 8695        cx: &mut Context<Self>,
 8696    ) {
 8697        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8698            s.move_heads_with(|map, head, _| {
 8699                (
 8700                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8701                    SelectionGoal::None,
 8702                )
 8703            });
 8704        })
 8705    }
 8706
 8707    pub fn delete_to_end_of_line(
 8708        &mut self,
 8709        _: &DeleteToEndOfLine,
 8710        window: &mut Window,
 8711        cx: &mut Context<Self>,
 8712    ) {
 8713        self.transact(window, cx, |this, window, cx| {
 8714            this.select_to_end_of_line(
 8715                &SelectToEndOfLine {
 8716                    stop_at_soft_wraps: false,
 8717                },
 8718                window,
 8719                cx,
 8720            );
 8721            this.delete(&Delete, window, cx);
 8722        });
 8723    }
 8724
 8725    pub fn cut_to_end_of_line(
 8726        &mut self,
 8727        _: &CutToEndOfLine,
 8728        window: &mut Window,
 8729        cx: &mut Context<Self>,
 8730    ) {
 8731        self.transact(window, cx, |this, window, cx| {
 8732            this.select_to_end_of_line(
 8733                &SelectToEndOfLine {
 8734                    stop_at_soft_wraps: false,
 8735                },
 8736                window,
 8737                cx,
 8738            );
 8739            this.cut(&Cut, window, cx);
 8740        });
 8741    }
 8742
 8743    pub fn move_to_start_of_paragraph(
 8744        &mut self,
 8745        _: &MoveToStartOfParagraph,
 8746        window: &mut Window,
 8747        cx: &mut Context<Self>,
 8748    ) {
 8749        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8750            cx.propagate();
 8751            return;
 8752        }
 8753
 8754        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8755            s.move_with(|map, selection| {
 8756                selection.collapse_to(
 8757                    movement::start_of_paragraph(map, selection.head(), 1),
 8758                    SelectionGoal::None,
 8759                )
 8760            });
 8761        })
 8762    }
 8763
 8764    pub fn move_to_end_of_paragraph(
 8765        &mut self,
 8766        _: &MoveToEndOfParagraph,
 8767        window: &mut Window,
 8768        cx: &mut Context<Self>,
 8769    ) {
 8770        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8771            cx.propagate();
 8772            return;
 8773        }
 8774
 8775        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8776            s.move_with(|map, selection| {
 8777                selection.collapse_to(
 8778                    movement::end_of_paragraph(map, selection.head(), 1),
 8779                    SelectionGoal::None,
 8780                )
 8781            });
 8782        })
 8783    }
 8784
 8785    pub fn select_to_start_of_paragraph(
 8786        &mut self,
 8787        _: &SelectToStartOfParagraph,
 8788        window: &mut Window,
 8789        cx: &mut Context<Self>,
 8790    ) {
 8791        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8792            cx.propagate();
 8793            return;
 8794        }
 8795
 8796        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8797            s.move_heads_with(|map, head, _| {
 8798                (
 8799                    movement::start_of_paragraph(map, head, 1),
 8800                    SelectionGoal::None,
 8801                )
 8802            });
 8803        })
 8804    }
 8805
 8806    pub fn select_to_end_of_paragraph(
 8807        &mut self,
 8808        _: &SelectToEndOfParagraph,
 8809        window: &mut Window,
 8810        cx: &mut Context<Self>,
 8811    ) {
 8812        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8813            cx.propagate();
 8814            return;
 8815        }
 8816
 8817        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8818            s.move_heads_with(|map, head, _| {
 8819                (
 8820                    movement::end_of_paragraph(map, head, 1),
 8821                    SelectionGoal::None,
 8822                )
 8823            });
 8824        })
 8825    }
 8826
 8827    pub fn move_to_beginning(
 8828        &mut self,
 8829        _: &MoveToBeginning,
 8830        window: &mut Window,
 8831        cx: &mut Context<Self>,
 8832    ) {
 8833        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8834            cx.propagate();
 8835            return;
 8836        }
 8837
 8838        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8839            s.select_ranges(vec![0..0]);
 8840        });
 8841    }
 8842
 8843    pub fn select_to_beginning(
 8844        &mut self,
 8845        _: &SelectToBeginning,
 8846        window: &mut Window,
 8847        cx: &mut Context<Self>,
 8848    ) {
 8849        let mut selection = self.selections.last::<Point>(cx);
 8850        selection.set_head(Point::zero(), SelectionGoal::None);
 8851
 8852        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8853            s.select(vec![selection]);
 8854        });
 8855    }
 8856
 8857    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8858        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8859            cx.propagate();
 8860            return;
 8861        }
 8862
 8863        let cursor = self.buffer.read(cx).read(cx).len();
 8864        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8865            s.select_ranges(vec![cursor..cursor])
 8866        });
 8867    }
 8868
 8869    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8870        self.nav_history = nav_history;
 8871    }
 8872
 8873    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8874        self.nav_history.as_ref()
 8875    }
 8876
 8877    fn push_to_nav_history(
 8878        &mut self,
 8879        cursor_anchor: Anchor,
 8880        new_position: Option<Point>,
 8881        cx: &mut Context<Self>,
 8882    ) {
 8883        if let Some(nav_history) = self.nav_history.as_mut() {
 8884            let buffer = self.buffer.read(cx).read(cx);
 8885            let cursor_position = cursor_anchor.to_point(&buffer);
 8886            let scroll_state = self.scroll_manager.anchor();
 8887            let scroll_top_row = scroll_state.top_row(&buffer);
 8888            drop(buffer);
 8889
 8890            if let Some(new_position) = new_position {
 8891                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8892                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8893                    return;
 8894                }
 8895            }
 8896
 8897            nav_history.push(
 8898                Some(NavigationData {
 8899                    cursor_anchor,
 8900                    cursor_position,
 8901                    scroll_anchor: scroll_state,
 8902                    scroll_top_row,
 8903                }),
 8904                cx,
 8905            );
 8906        }
 8907    }
 8908
 8909    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8910        let buffer = self.buffer.read(cx).snapshot(cx);
 8911        let mut selection = self.selections.first::<usize>(cx);
 8912        selection.set_head(buffer.len(), SelectionGoal::None);
 8913        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8914            s.select(vec![selection]);
 8915        });
 8916    }
 8917
 8918    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8919        let end = self.buffer.read(cx).read(cx).len();
 8920        self.change_selections(None, window, cx, |s| {
 8921            s.select_ranges(vec![0..end]);
 8922        });
 8923    }
 8924
 8925    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8926        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8927        let mut selections = self.selections.all::<Point>(cx);
 8928        let max_point = display_map.buffer_snapshot.max_point();
 8929        for selection in &mut selections {
 8930            let rows = selection.spanned_rows(true, &display_map);
 8931            selection.start = Point::new(rows.start.0, 0);
 8932            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8933            selection.reversed = false;
 8934        }
 8935        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8936            s.select(selections);
 8937        });
 8938    }
 8939
 8940    pub fn split_selection_into_lines(
 8941        &mut self,
 8942        _: &SplitSelectionIntoLines,
 8943        window: &mut Window,
 8944        cx: &mut Context<Self>,
 8945    ) {
 8946        let mut to_unfold = Vec::new();
 8947        let mut new_selection_ranges = Vec::new();
 8948        {
 8949            let selections = self.selections.all::<Point>(cx);
 8950            let buffer = self.buffer.read(cx).read(cx);
 8951            for selection in selections {
 8952                for row in selection.start.row..selection.end.row {
 8953                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8954                    new_selection_ranges.push(cursor..cursor);
 8955                }
 8956                new_selection_ranges.push(selection.end..selection.end);
 8957                to_unfold.push(selection.start..selection.end);
 8958            }
 8959        }
 8960        self.unfold_ranges(&to_unfold, true, true, cx);
 8961        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8962            s.select_ranges(new_selection_ranges);
 8963        });
 8964    }
 8965
 8966    pub fn add_selection_above(
 8967        &mut self,
 8968        _: &AddSelectionAbove,
 8969        window: &mut Window,
 8970        cx: &mut Context<Self>,
 8971    ) {
 8972        self.add_selection(true, window, cx);
 8973    }
 8974
 8975    pub fn add_selection_below(
 8976        &mut self,
 8977        _: &AddSelectionBelow,
 8978        window: &mut Window,
 8979        cx: &mut Context<Self>,
 8980    ) {
 8981        self.add_selection(false, window, cx);
 8982    }
 8983
 8984    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8985        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8986        let mut selections = self.selections.all::<Point>(cx);
 8987        let text_layout_details = self.text_layout_details(window);
 8988        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8989            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8990            let range = oldest_selection.display_range(&display_map).sorted();
 8991
 8992            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8993            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8994            let positions = start_x.min(end_x)..start_x.max(end_x);
 8995
 8996            selections.clear();
 8997            let mut stack = Vec::new();
 8998            for row in range.start.row().0..=range.end.row().0 {
 8999                if let Some(selection) = self.selections.build_columnar_selection(
 9000                    &display_map,
 9001                    DisplayRow(row),
 9002                    &positions,
 9003                    oldest_selection.reversed,
 9004                    &text_layout_details,
 9005                ) {
 9006                    stack.push(selection.id);
 9007                    selections.push(selection);
 9008                }
 9009            }
 9010
 9011            if above {
 9012                stack.reverse();
 9013            }
 9014
 9015            AddSelectionsState { above, stack }
 9016        });
 9017
 9018        let last_added_selection = *state.stack.last().unwrap();
 9019        let mut new_selections = Vec::new();
 9020        if above == state.above {
 9021            let end_row = if above {
 9022                DisplayRow(0)
 9023            } else {
 9024                display_map.max_point().row()
 9025            };
 9026
 9027            'outer: for selection in selections {
 9028                if selection.id == last_added_selection {
 9029                    let range = selection.display_range(&display_map).sorted();
 9030                    debug_assert_eq!(range.start.row(), range.end.row());
 9031                    let mut row = range.start.row();
 9032                    let positions =
 9033                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9034                            px(start)..px(end)
 9035                        } else {
 9036                            let start_x =
 9037                                display_map.x_for_display_point(range.start, &text_layout_details);
 9038                            let end_x =
 9039                                display_map.x_for_display_point(range.end, &text_layout_details);
 9040                            start_x.min(end_x)..start_x.max(end_x)
 9041                        };
 9042
 9043                    while row != end_row {
 9044                        if above {
 9045                            row.0 -= 1;
 9046                        } else {
 9047                            row.0 += 1;
 9048                        }
 9049
 9050                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9051                            &display_map,
 9052                            row,
 9053                            &positions,
 9054                            selection.reversed,
 9055                            &text_layout_details,
 9056                        ) {
 9057                            state.stack.push(new_selection.id);
 9058                            if above {
 9059                                new_selections.push(new_selection);
 9060                                new_selections.push(selection);
 9061                            } else {
 9062                                new_selections.push(selection);
 9063                                new_selections.push(new_selection);
 9064                            }
 9065
 9066                            continue 'outer;
 9067                        }
 9068                    }
 9069                }
 9070
 9071                new_selections.push(selection);
 9072            }
 9073        } else {
 9074            new_selections = selections;
 9075            new_selections.retain(|s| s.id != last_added_selection);
 9076            state.stack.pop();
 9077        }
 9078
 9079        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9080            s.select(new_selections);
 9081        });
 9082        if state.stack.len() > 1 {
 9083            self.add_selections_state = Some(state);
 9084        }
 9085    }
 9086
 9087    pub fn select_next_match_internal(
 9088        &mut self,
 9089        display_map: &DisplaySnapshot,
 9090        replace_newest: bool,
 9091        autoscroll: Option<Autoscroll>,
 9092        window: &mut Window,
 9093        cx: &mut Context<Self>,
 9094    ) -> Result<()> {
 9095        fn select_next_match_ranges(
 9096            this: &mut Editor,
 9097            range: Range<usize>,
 9098            replace_newest: bool,
 9099            auto_scroll: Option<Autoscroll>,
 9100            window: &mut Window,
 9101            cx: &mut Context<Editor>,
 9102        ) {
 9103            this.unfold_ranges(&[range.clone()], false, true, cx);
 9104            this.change_selections(auto_scroll, window, cx, |s| {
 9105                if replace_newest {
 9106                    s.delete(s.newest_anchor().id);
 9107                }
 9108                s.insert_range(range.clone());
 9109            });
 9110        }
 9111
 9112        let buffer = &display_map.buffer_snapshot;
 9113        let mut selections = self.selections.all::<usize>(cx);
 9114        if let Some(mut select_next_state) = self.select_next_state.take() {
 9115            let query = &select_next_state.query;
 9116            if !select_next_state.done {
 9117                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9118                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9119                let mut next_selected_range = None;
 9120
 9121                let bytes_after_last_selection =
 9122                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9123                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9124                let query_matches = query
 9125                    .stream_find_iter(bytes_after_last_selection)
 9126                    .map(|result| (last_selection.end, result))
 9127                    .chain(
 9128                        query
 9129                            .stream_find_iter(bytes_before_first_selection)
 9130                            .map(|result| (0, result)),
 9131                    );
 9132
 9133                for (start_offset, query_match) in query_matches {
 9134                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9135                    let offset_range =
 9136                        start_offset + query_match.start()..start_offset + query_match.end();
 9137                    let display_range = offset_range.start.to_display_point(display_map)
 9138                        ..offset_range.end.to_display_point(display_map);
 9139
 9140                    if !select_next_state.wordwise
 9141                        || (!movement::is_inside_word(display_map, display_range.start)
 9142                            && !movement::is_inside_word(display_map, display_range.end))
 9143                    {
 9144                        // TODO: This is n^2, because we might check all the selections
 9145                        if !selections
 9146                            .iter()
 9147                            .any(|selection| selection.range().overlaps(&offset_range))
 9148                        {
 9149                            next_selected_range = Some(offset_range);
 9150                            break;
 9151                        }
 9152                    }
 9153                }
 9154
 9155                if let Some(next_selected_range) = next_selected_range {
 9156                    select_next_match_ranges(
 9157                        self,
 9158                        next_selected_range,
 9159                        replace_newest,
 9160                        autoscroll,
 9161                        window,
 9162                        cx,
 9163                    );
 9164                } else {
 9165                    select_next_state.done = true;
 9166                }
 9167            }
 9168
 9169            self.select_next_state = Some(select_next_state);
 9170        } else {
 9171            let mut only_carets = true;
 9172            let mut same_text_selected = true;
 9173            let mut selected_text = None;
 9174
 9175            let mut selections_iter = selections.iter().peekable();
 9176            while let Some(selection) = selections_iter.next() {
 9177                if selection.start != selection.end {
 9178                    only_carets = false;
 9179                }
 9180
 9181                if same_text_selected {
 9182                    if selected_text.is_none() {
 9183                        selected_text =
 9184                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9185                    }
 9186
 9187                    if let Some(next_selection) = selections_iter.peek() {
 9188                        if next_selection.range().len() == selection.range().len() {
 9189                            let next_selected_text = buffer
 9190                                .text_for_range(next_selection.range())
 9191                                .collect::<String>();
 9192                            if Some(next_selected_text) != selected_text {
 9193                                same_text_selected = false;
 9194                                selected_text = None;
 9195                            }
 9196                        } else {
 9197                            same_text_selected = false;
 9198                            selected_text = None;
 9199                        }
 9200                    }
 9201                }
 9202            }
 9203
 9204            if only_carets {
 9205                for selection in &mut selections {
 9206                    let word_range = movement::surrounding_word(
 9207                        display_map,
 9208                        selection.start.to_display_point(display_map),
 9209                    );
 9210                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9211                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9212                    selection.goal = SelectionGoal::None;
 9213                    selection.reversed = false;
 9214                    select_next_match_ranges(
 9215                        self,
 9216                        selection.start..selection.end,
 9217                        replace_newest,
 9218                        autoscroll,
 9219                        window,
 9220                        cx,
 9221                    );
 9222                }
 9223
 9224                if selections.len() == 1 {
 9225                    let selection = selections
 9226                        .last()
 9227                        .expect("ensured that there's only one selection");
 9228                    let query = buffer
 9229                        .text_for_range(selection.start..selection.end)
 9230                        .collect::<String>();
 9231                    let is_empty = query.is_empty();
 9232                    let select_state = SelectNextState {
 9233                        query: AhoCorasick::new(&[query])?,
 9234                        wordwise: true,
 9235                        done: is_empty,
 9236                    };
 9237                    self.select_next_state = Some(select_state);
 9238                } else {
 9239                    self.select_next_state = None;
 9240                }
 9241            } else if let Some(selected_text) = selected_text {
 9242                self.select_next_state = Some(SelectNextState {
 9243                    query: AhoCorasick::new(&[selected_text])?,
 9244                    wordwise: false,
 9245                    done: false,
 9246                });
 9247                self.select_next_match_internal(
 9248                    display_map,
 9249                    replace_newest,
 9250                    autoscroll,
 9251                    window,
 9252                    cx,
 9253                )?;
 9254            }
 9255        }
 9256        Ok(())
 9257    }
 9258
 9259    pub fn select_all_matches(
 9260        &mut self,
 9261        _action: &SelectAllMatches,
 9262        window: &mut Window,
 9263        cx: &mut Context<Self>,
 9264    ) -> Result<()> {
 9265        self.push_to_selection_history();
 9266        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9267
 9268        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9269        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9270            return Ok(());
 9271        };
 9272        if select_next_state.done {
 9273            return Ok(());
 9274        }
 9275
 9276        let mut new_selections = self.selections.all::<usize>(cx);
 9277
 9278        let buffer = &display_map.buffer_snapshot;
 9279        let query_matches = select_next_state
 9280            .query
 9281            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9282
 9283        for query_match in query_matches {
 9284            let query_match = query_match.unwrap(); // can only fail due to I/O
 9285            let offset_range = query_match.start()..query_match.end();
 9286            let display_range = offset_range.start.to_display_point(&display_map)
 9287                ..offset_range.end.to_display_point(&display_map);
 9288
 9289            if !select_next_state.wordwise
 9290                || (!movement::is_inside_word(&display_map, display_range.start)
 9291                    && !movement::is_inside_word(&display_map, display_range.end))
 9292            {
 9293                self.selections.change_with(cx, |selections| {
 9294                    new_selections.push(Selection {
 9295                        id: selections.new_selection_id(),
 9296                        start: offset_range.start,
 9297                        end: offset_range.end,
 9298                        reversed: false,
 9299                        goal: SelectionGoal::None,
 9300                    });
 9301                });
 9302            }
 9303        }
 9304
 9305        new_selections.sort_by_key(|selection| selection.start);
 9306        let mut ix = 0;
 9307        while ix + 1 < new_selections.len() {
 9308            let current_selection = &new_selections[ix];
 9309            let next_selection = &new_selections[ix + 1];
 9310            if current_selection.range().overlaps(&next_selection.range()) {
 9311                if current_selection.id < next_selection.id {
 9312                    new_selections.remove(ix + 1);
 9313                } else {
 9314                    new_selections.remove(ix);
 9315                }
 9316            } else {
 9317                ix += 1;
 9318            }
 9319        }
 9320
 9321        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9322
 9323        for selection in new_selections.iter_mut() {
 9324            selection.reversed = reversed;
 9325        }
 9326
 9327        select_next_state.done = true;
 9328        self.unfold_ranges(
 9329            &new_selections
 9330                .iter()
 9331                .map(|selection| selection.range())
 9332                .collect::<Vec<_>>(),
 9333            false,
 9334            false,
 9335            cx,
 9336        );
 9337        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9338            selections.select(new_selections)
 9339        });
 9340
 9341        Ok(())
 9342    }
 9343
 9344    pub fn select_next(
 9345        &mut self,
 9346        action: &SelectNext,
 9347        window: &mut Window,
 9348        cx: &mut Context<Self>,
 9349    ) -> Result<()> {
 9350        self.push_to_selection_history();
 9351        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9352        self.select_next_match_internal(
 9353            &display_map,
 9354            action.replace_newest,
 9355            Some(Autoscroll::newest()),
 9356            window,
 9357            cx,
 9358        )?;
 9359        Ok(())
 9360    }
 9361
 9362    pub fn select_previous(
 9363        &mut self,
 9364        action: &SelectPrevious,
 9365        window: &mut Window,
 9366        cx: &mut Context<Self>,
 9367    ) -> Result<()> {
 9368        self.push_to_selection_history();
 9369        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9370        let buffer = &display_map.buffer_snapshot;
 9371        let mut selections = self.selections.all::<usize>(cx);
 9372        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9373            let query = &select_prev_state.query;
 9374            if !select_prev_state.done {
 9375                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9376                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9377                let mut next_selected_range = None;
 9378                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9379                let bytes_before_last_selection =
 9380                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9381                let bytes_after_first_selection =
 9382                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9383                let query_matches = query
 9384                    .stream_find_iter(bytes_before_last_selection)
 9385                    .map(|result| (last_selection.start, result))
 9386                    .chain(
 9387                        query
 9388                            .stream_find_iter(bytes_after_first_selection)
 9389                            .map(|result| (buffer.len(), result)),
 9390                    );
 9391                for (end_offset, query_match) in query_matches {
 9392                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9393                    let offset_range =
 9394                        end_offset - query_match.end()..end_offset - query_match.start();
 9395                    let display_range = offset_range.start.to_display_point(&display_map)
 9396                        ..offset_range.end.to_display_point(&display_map);
 9397
 9398                    if !select_prev_state.wordwise
 9399                        || (!movement::is_inside_word(&display_map, display_range.start)
 9400                            && !movement::is_inside_word(&display_map, display_range.end))
 9401                    {
 9402                        next_selected_range = Some(offset_range);
 9403                        break;
 9404                    }
 9405                }
 9406
 9407                if let Some(next_selected_range) = next_selected_range {
 9408                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9409                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9410                        if action.replace_newest {
 9411                            s.delete(s.newest_anchor().id);
 9412                        }
 9413                        s.insert_range(next_selected_range);
 9414                    });
 9415                } else {
 9416                    select_prev_state.done = true;
 9417                }
 9418            }
 9419
 9420            self.select_prev_state = Some(select_prev_state);
 9421        } else {
 9422            let mut only_carets = true;
 9423            let mut same_text_selected = true;
 9424            let mut selected_text = None;
 9425
 9426            let mut selections_iter = selections.iter().peekable();
 9427            while let Some(selection) = selections_iter.next() {
 9428                if selection.start != selection.end {
 9429                    only_carets = false;
 9430                }
 9431
 9432                if same_text_selected {
 9433                    if selected_text.is_none() {
 9434                        selected_text =
 9435                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9436                    }
 9437
 9438                    if let Some(next_selection) = selections_iter.peek() {
 9439                        if next_selection.range().len() == selection.range().len() {
 9440                            let next_selected_text = buffer
 9441                                .text_for_range(next_selection.range())
 9442                                .collect::<String>();
 9443                            if Some(next_selected_text) != selected_text {
 9444                                same_text_selected = false;
 9445                                selected_text = None;
 9446                            }
 9447                        } else {
 9448                            same_text_selected = false;
 9449                            selected_text = None;
 9450                        }
 9451                    }
 9452                }
 9453            }
 9454
 9455            if only_carets {
 9456                for selection in &mut selections {
 9457                    let word_range = movement::surrounding_word(
 9458                        &display_map,
 9459                        selection.start.to_display_point(&display_map),
 9460                    );
 9461                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9462                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9463                    selection.goal = SelectionGoal::None;
 9464                    selection.reversed = false;
 9465                }
 9466                if selections.len() == 1 {
 9467                    let selection = selections
 9468                        .last()
 9469                        .expect("ensured that there's only one selection");
 9470                    let query = buffer
 9471                        .text_for_range(selection.start..selection.end)
 9472                        .collect::<String>();
 9473                    let is_empty = query.is_empty();
 9474                    let select_state = SelectNextState {
 9475                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9476                        wordwise: true,
 9477                        done: is_empty,
 9478                    };
 9479                    self.select_prev_state = Some(select_state);
 9480                } else {
 9481                    self.select_prev_state = None;
 9482                }
 9483
 9484                self.unfold_ranges(
 9485                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9486                    false,
 9487                    true,
 9488                    cx,
 9489                );
 9490                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9491                    s.select(selections);
 9492                });
 9493            } else if let Some(selected_text) = selected_text {
 9494                self.select_prev_state = Some(SelectNextState {
 9495                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9496                    wordwise: false,
 9497                    done: false,
 9498                });
 9499                self.select_previous(action, window, cx)?;
 9500            }
 9501        }
 9502        Ok(())
 9503    }
 9504
 9505    pub fn toggle_comments(
 9506        &mut self,
 9507        action: &ToggleComments,
 9508        window: &mut Window,
 9509        cx: &mut Context<Self>,
 9510    ) {
 9511        if self.read_only(cx) {
 9512            return;
 9513        }
 9514        let text_layout_details = &self.text_layout_details(window);
 9515        self.transact(window, cx, |this, window, cx| {
 9516            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9517            let mut edits = Vec::new();
 9518            let mut selection_edit_ranges = Vec::new();
 9519            let mut last_toggled_row = None;
 9520            let snapshot = this.buffer.read(cx).read(cx);
 9521            let empty_str: Arc<str> = Arc::default();
 9522            let mut suffixes_inserted = Vec::new();
 9523            let ignore_indent = action.ignore_indent;
 9524
 9525            fn comment_prefix_range(
 9526                snapshot: &MultiBufferSnapshot,
 9527                row: MultiBufferRow,
 9528                comment_prefix: &str,
 9529                comment_prefix_whitespace: &str,
 9530                ignore_indent: bool,
 9531            ) -> Range<Point> {
 9532                let indent_size = if ignore_indent {
 9533                    0
 9534                } else {
 9535                    snapshot.indent_size_for_line(row).len
 9536                };
 9537
 9538                let start = Point::new(row.0, indent_size);
 9539
 9540                let mut line_bytes = snapshot
 9541                    .bytes_in_range(start..snapshot.max_point())
 9542                    .flatten()
 9543                    .copied();
 9544
 9545                // If this line currently begins with the line comment prefix, then record
 9546                // the range containing the prefix.
 9547                if line_bytes
 9548                    .by_ref()
 9549                    .take(comment_prefix.len())
 9550                    .eq(comment_prefix.bytes())
 9551                {
 9552                    // Include any whitespace that matches the comment prefix.
 9553                    let matching_whitespace_len = line_bytes
 9554                        .zip(comment_prefix_whitespace.bytes())
 9555                        .take_while(|(a, b)| a == b)
 9556                        .count() as u32;
 9557                    let end = Point::new(
 9558                        start.row,
 9559                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9560                    );
 9561                    start..end
 9562                } else {
 9563                    start..start
 9564                }
 9565            }
 9566
 9567            fn comment_suffix_range(
 9568                snapshot: &MultiBufferSnapshot,
 9569                row: MultiBufferRow,
 9570                comment_suffix: &str,
 9571                comment_suffix_has_leading_space: bool,
 9572            ) -> Range<Point> {
 9573                let end = Point::new(row.0, snapshot.line_len(row));
 9574                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9575
 9576                let mut line_end_bytes = snapshot
 9577                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9578                    .flatten()
 9579                    .copied();
 9580
 9581                let leading_space_len = if suffix_start_column > 0
 9582                    && line_end_bytes.next() == Some(b' ')
 9583                    && comment_suffix_has_leading_space
 9584                {
 9585                    1
 9586                } else {
 9587                    0
 9588                };
 9589
 9590                // If this line currently begins with the line comment prefix, then record
 9591                // the range containing the prefix.
 9592                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9593                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9594                    start..end
 9595                } else {
 9596                    end..end
 9597                }
 9598            }
 9599
 9600            // TODO: Handle selections that cross excerpts
 9601            for selection in &mut selections {
 9602                let start_column = snapshot
 9603                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9604                    .len;
 9605                let language = if let Some(language) =
 9606                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9607                {
 9608                    language
 9609                } else {
 9610                    continue;
 9611                };
 9612
 9613                selection_edit_ranges.clear();
 9614
 9615                // If multiple selections contain a given row, avoid processing that
 9616                // row more than once.
 9617                let mut start_row = MultiBufferRow(selection.start.row);
 9618                if last_toggled_row == Some(start_row) {
 9619                    start_row = start_row.next_row();
 9620                }
 9621                let end_row =
 9622                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9623                        MultiBufferRow(selection.end.row - 1)
 9624                    } else {
 9625                        MultiBufferRow(selection.end.row)
 9626                    };
 9627                last_toggled_row = Some(end_row);
 9628
 9629                if start_row > end_row {
 9630                    continue;
 9631                }
 9632
 9633                // If the language has line comments, toggle those.
 9634                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9635
 9636                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9637                if ignore_indent {
 9638                    full_comment_prefixes = full_comment_prefixes
 9639                        .into_iter()
 9640                        .map(|s| Arc::from(s.trim_end()))
 9641                        .collect();
 9642                }
 9643
 9644                if !full_comment_prefixes.is_empty() {
 9645                    let first_prefix = full_comment_prefixes
 9646                        .first()
 9647                        .expect("prefixes is non-empty");
 9648                    let prefix_trimmed_lengths = full_comment_prefixes
 9649                        .iter()
 9650                        .map(|p| p.trim_end_matches(' ').len())
 9651                        .collect::<SmallVec<[usize; 4]>>();
 9652
 9653                    let mut all_selection_lines_are_comments = true;
 9654
 9655                    for row in start_row.0..=end_row.0 {
 9656                        let row = MultiBufferRow(row);
 9657                        if start_row < end_row && snapshot.is_line_blank(row) {
 9658                            continue;
 9659                        }
 9660
 9661                        let prefix_range = full_comment_prefixes
 9662                            .iter()
 9663                            .zip(prefix_trimmed_lengths.iter().copied())
 9664                            .map(|(prefix, trimmed_prefix_len)| {
 9665                                comment_prefix_range(
 9666                                    snapshot.deref(),
 9667                                    row,
 9668                                    &prefix[..trimmed_prefix_len],
 9669                                    &prefix[trimmed_prefix_len..],
 9670                                    ignore_indent,
 9671                                )
 9672                            })
 9673                            .max_by_key(|range| range.end.column - range.start.column)
 9674                            .expect("prefixes is non-empty");
 9675
 9676                        if prefix_range.is_empty() {
 9677                            all_selection_lines_are_comments = false;
 9678                        }
 9679
 9680                        selection_edit_ranges.push(prefix_range);
 9681                    }
 9682
 9683                    if all_selection_lines_are_comments {
 9684                        edits.extend(
 9685                            selection_edit_ranges
 9686                                .iter()
 9687                                .cloned()
 9688                                .map(|range| (range, empty_str.clone())),
 9689                        );
 9690                    } else {
 9691                        let min_column = selection_edit_ranges
 9692                            .iter()
 9693                            .map(|range| range.start.column)
 9694                            .min()
 9695                            .unwrap_or(0);
 9696                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9697                            let position = Point::new(range.start.row, min_column);
 9698                            (position..position, first_prefix.clone())
 9699                        }));
 9700                    }
 9701                } else if let Some((full_comment_prefix, comment_suffix)) =
 9702                    language.block_comment_delimiters()
 9703                {
 9704                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9705                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9706                    let prefix_range = comment_prefix_range(
 9707                        snapshot.deref(),
 9708                        start_row,
 9709                        comment_prefix,
 9710                        comment_prefix_whitespace,
 9711                        ignore_indent,
 9712                    );
 9713                    let suffix_range = comment_suffix_range(
 9714                        snapshot.deref(),
 9715                        end_row,
 9716                        comment_suffix.trim_start_matches(' '),
 9717                        comment_suffix.starts_with(' '),
 9718                    );
 9719
 9720                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9721                        edits.push((
 9722                            prefix_range.start..prefix_range.start,
 9723                            full_comment_prefix.clone(),
 9724                        ));
 9725                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9726                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9727                    } else {
 9728                        edits.push((prefix_range, empty_str.clone()));
 9729                        edits.push((suffix_range, empty_str.clone()));
 9730                    }
 9731                } else {
 9732                    continue;
 9733                }
 9734            }
 9735
 9736            drop(snapshot);
 9737            this.buffer.update(cx, |buffer, cx| {
 9738                buffer.edit(edits, None, cx);
 9739            });
 9740
 9741            // Adjust selections so that they end before any comment suffixes that
 9742            // were inserted.
 9743            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9744            let mut selections = this.selections.all::<Point>(cx);
 9745            let snapshot = this.buffer.read(cx).read(cx);
 9746            for selection in &mut selections {
 9747                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9748                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9749                        Ordering::Less => {
 9750                            suffixes_inserted.next();
 9751                            continue;
 9752                        }
 9753                        Ordering::Greater => break,
 9754                        Ordering::Equal => {
 9755                            if selection.end.column == snapshot.line_len(row) {
 9756                                if selection.is_empty() {
 9757                                    selection.start.column -= suffix_len as u32;
 9758                                }
 9759                                selection.end.column -= suffix_len as u32;
 9760                            }
 9761                            break;
 9762                        }
 9763                    }
 9764                }
 9765            }
 9766
 9767            drop(snapshot);
 9768            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9769                s.select(selections)
 9770            });
 9771
 9772            let selections = this.selections.all::<Point>(cx);
 9773            let selections_on_single_row = selections.windows(2).all(|selections| {
 9774                selections[0].start.row == selections[1].start.row
 9775                    && selections[0].end.row == selections[1].end.row
 9776                    && selections[0].start.row == selections[0].end.row
 9777            });
 9778            let selections_selecting = selections
 9779                .iter()
 9780                .any(|selection| selection.start != selection.end);
 9781            let advance_downwards = action.advance_downwards
 9782                && selections_on_single_row
 9783                && !selections_selecting
 9784                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9785
 9786            if advance_downwards {
 9787                let snapshot = this.buffer.read(cx).snapshot(cx);
 9788
 9789                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9790                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9791                        let mut point = display_point.to_point(display_snapshot);
 9792                        point.row += 1;
 9793                        point = snapshot.clip_point(point, Bias::Left);
 9794                        let display_point = point.to_display_point(display_snapshot);
 9795                        let goal = SelectionGoal::HorizontalPosition(
 9796                            display_snapshot
 9797                                .x_for_display_point(display_point, text_layout_details)
 9798                                .into(),
 9799                        );
 9800                        (display_point, goal)
 9801                    })
 9802                });
 9803            }
 9804        });
 9805    }
 9806
 9807    pub fn select_enclosing_symbol(
 9808        &mut self,
 9809        _: &SelectEnclosingSymbol,
 9810        window: &mut Window,
 9811        cx: &mut Context<Self>,
 9812    ) {
 9813        let buffer = self.buffer.read(cx).snapshot(cx);
 9814        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9815
 9816        fn update_selection(
 9817            selection: &Selection<usize>,
 9818            buffer_snap: &MultiBufferSnapshot,
 9819        ) -> Option<Selection<usize>> {
 9820            let cursor = selection.head();
 9821            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9822            for symbol in symbols.iter().rev() {
 9823                let start = symbol.range.start.to_offset(buffer_snap);
 9824                let end = symbol.range.end.to_offset(buffer_snap);
 9825                let new_range = start..end;
 9826                if start < selection.start || end > selection.end {
 9827                    return Some(Selection {
 9828                        id: selection.id,
 9829                        start: new_range.start,
 9830                        end: new_range.end,
 9831                        goal: SelectionGoal::None,
 9832                        reversed: selection.reversed,
 9833                    });
 9834                }
 9835            }
 9836            None
 9837        }
 9838
 9839        let mut selected_larger_symbol = false;
 9840        let new_selections = old_selections
 9841            .iter()
 9842            .map(|selection| match update_selection(selection, &buffer) {
 9843                Some(new_selection) => {
 9844                    if new_selection.range() != selection.range() {
 9845                        selected_larger_symbol = true;
 9846                    }
 9847                    new_selection
 9848                }
 9849                None => selection.clone(),
 9850            })
 9851            .collect::<Vec<_>>();
 9852
 9853        if selected_larger_symbol {
 9854            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9855                s.select(new_selections);
 9856            });
 9857        }
 9858    }
 9859
 9860    pub fn select_larger_syntax_node(
 9861        &mut self,
 9862        _: &SelectLargerSyntaxNode,
 9863        window: &mut Window,
 9864        cx: &mut Context<Self>,
 9865    ) {
 9866        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9867        let buffer = self.buffer.read(cx).snapshot(cx);
 9868        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9869
 9870        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9871        let mut selected_larger_node = false;
 9872        let new_selections = old_selections
 9873            .iter()
 9874            .map(|selection| {
 9875                let old_range = selection.start..selection.end;
 9876                let mut new_range = old_range.clone();
 9877                let mut new_node = None;
 9878                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9879                {
 9880                    new_node = Some(node);
 9881                    new_range = containing_range;
 9882                    if !display_map.intersects_fold(new_range.start)
 9883                        && !display_map.intersects_fold(new_range.end)
 9884                    {
 9885                        break;
 9886                    }
 9887                }
 9888
 9889                if let Some(node) = new_node {
 9890                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9891                    // nodes. Parent and grandparent are also logged because this operation will not
 9892                    // visit nodes that have the same range as their parent.
 9893                    log::info!("Node: {node:?}");
 9894                    let parent = node.parent();
 9895                    log::info!("Parent: {parent:?}");
 9896                    let grandparent = parent.and_then(|x| x.parent());
 9897                    log::info!("Grandparent: {grandparent:?}");
 9898                }
 9899
 9900                selected_larger_node |= new_range != old_range;
 9901                Selection {
 9902                    id: selection.id,
 9903                    start: new_range.start,
 9904                    end: new_range.end,
 9905                    goal: SelectionGoal::None,
 9906                    reversed: selection.reversed,
 9907                }
 9908            })
 9909            .collect::<Vec<_>>();
 9910
 9911        if selected_larger_node {
 9912            stack.push(old_selections);
 9913            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9914                s.select(new_selections);
 9915            });
 9916        }
 9917        self.select_larger_syntax_node_stack = stack;
 9918    }
 9919
 9920    pub fn select_smaller_syntax_node(
 9921        &mut self,
 9922        _: &SelectSmallerSyntaxNode,
 9923        window: &mut Window,
 9924        cx: &mut Context<Self>,
 9925    ) {
 9926        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9927        if let Some(selections) = stack.pop() {
 9928            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9929                s.select(selections.to_vec());
 9930            });
 9931        }
 9932        self.select_larger_syntax_node_stack = stack;
 9933    }
 9934
 9935    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9936        if !EditorSettings::get_global(cx).gutter.runnables {
 9937            self.clear_tasks();
 9938            return Task::ready(());
 9939        }
 9940        let project = self.project.as_ref().map(Entity::downgrade);
 9941        cx.spawn_in(window, |this, mut cx| async move {
 9942            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9943            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9944                return;
 9945            };
 9946            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9947                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9948            }) else {
 9949                return;
 9950            };
 9951
 9952            let hide_runnables = project
 9953                .update(&mut cx, |project, cx| {
 9954                    // Do not display any test indicators in non-dev server remote projects.
 9955                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9956                })
 9957                .unwrap_or(true);
 9958            if hide_runnables {
 9959                return;
 9960            }
 9961            let new_rows =
 9962                cx.background_executor()
 9963                    .spawn({
 9964                        let snapshot = display_snapshot.clone();
 9965                        async move {
 9966                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9967                        }
 9968                    })
 9969                    .await;
 9970
 9971            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9972            this.update(&mut cx, |this, _| {
 9973                this.clear_tasks();
 9974                for (key, value) in rows {
 9975                    this.insert_tasks(key, value);
 9976                }
 9977            })
 9978            .ok();
 9979        })
 9980    }
 9981    fn fetch_runnable_ranges(
 9982        snapshot: &DisplaySnapshot,
 9983        range: Range<Anchor>,
 9984    ) -> Vec<language::RunnableRange> {
 9985        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9986    }
 9987
 9988    fn runnable_rows(
 9989        project: Entity<Project>,
 9990        snapshot: DisplaySnapshot,
 9991        runnable_ranges: Vec<RunnableRange>,
 9992        mut cx: AsyncWindowContext,
 9993    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9994        runnable_ranges
 9995            .into_iter()
 9996            .filter_map(|mut runnable| {
 9997                let tasks = cx
 9998                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9999                    .ok()?;
10000                if tasks.is_empty() {
10001                    return None;
10002                }
10003
10004                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10005
10006                let row = snapshot
10007                    .buffer_snapshot
10008                    .buffer_line_for_row(MultiBufferRow(point.row))?
10009                    .1
10010                    .start
10011                    .row;
10012
10013                let context_range =
10014                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10015                Some((
10016                    (runnable.buffer_id, row),
10017                    RunnableTasks {
10018                        templates: tasks,
10019                        offset: MultiBufferOffset(runnable.run_range.start),
10020                        context_range,
10021                        column: point.column,
10022                        extra_variables: runnable.extra_captures,
10023                    },
10024                ))
10025            })
10026            .collect()
10027    }
10028
10029    fn templates_with_tags(
10030        project: &Entity<Project>,
10031        runnable: &mut Runnable,
10032        cx: &mut App,
10033    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10034        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10035            let (worktree_id, file) = project
10036                .buffer_for_id(runnable.buffer, cx)
10037                .and_then(|buffer| buffer.read(cx).file())
10038                .map(|file| (file.worktree_id(cx), file.clone()))
10039                .unzip();
10040
10041            (
10042                project.task_store().read(cx).task_inventory().cloned(),
10043                worktree_id,
10044                file,
10045            )
10046        });
10047
10048        let tags = mem::take(&mut runnable.tags);
10049        let mut tags: Vec<_> = tags
10050            .into_iter()
10051            .flat_map(|tag| {
10052                let tag = tag.0.clone();
10053                inventory
10054                    .as_ref()
10055                    .into_iter()
10056                    .flat_map(|inventory| {
10057                        inventory.read(cx).list_tasks(
10058                            file.clone(),
10059                            Some(runnable.language.clone()),
10060                            worktree_id,
10061                            cx,
10062                        )
10063                    })
10064                    .filter(move |(_, template)| {
10065                        template.tags.iter().any(|source_tag| source_tag == &tag)
10066                    })
10067            })
10068            .sorted_by_key(|(kind, _)| kind.to_owned())
10069            .collect();
10070        if let Some((leading_tag_source, _)) = tags.first() {
10071            // Strongest source wins; if we have worktree tag binding, prefer that to
10072            // global and language bindings;
10073            // if we have a global binding, prefer that to language binding.
10074            let first_mismatch = tags
10075                .iter()
10076                .position(|(tag_source, _)| tag_source != leading_tag_source);
10077            if let Some(index) = first_mismatch {
10078                tags.truncate(index);
10079            }
10080        }
10081
10082        tags
10083    }
10084
10085    pub fn move_to_enclosing_bracket(
10086        &mut self,
10087        _: &MoveToEnclosingBracket,
10088        window: &mut Window,
10089        cx: &mut Context<Self>,
10090    ) {
10091        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10092            s.move_offsets_with(|snapshot, selection| {
10093                let Some(enclosing_bracket_ranges) =
10094                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10095                else {
10096                    return;
10097                };
10098
10099                let mut best_length = usize::MAX;
10100                let mut best_inside = false;
10101                let mut best_in_bracket_range = false;
10102                let mut best_destination = None;
10103                for (open, close) in enclosing_bracket_ranges {
10104                    let close = close.to_inclusive();
10105                    let length = close.end() - open.start;
10106                    let inside = selection.start >= open.end && selection.end <= *close.start();
10107                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10108                        || close.contains(&selection.head());
10109
10110                    // If best is next to a bracket and current isn't, skip
10111                    if !in_bracket_range && best_in_bracket_range {
10112                        continue;
10113                    }
10114
10115                    // Prefer smaller lengths unless best is inside and current isn't
10116                    if length > best_length && (best_inside || !inside) {
10117                        continue;
10118                    }
10119
10120                    best_length = length;
10121                    best_inside = inside;
10122                    best_in_bracket_range = in_bracket_range;
10123                    best_destination = Some(
10124                        if close.contains(&selection.start) && close.contains(&selection.end) {
10125                            if inside {
10126                                open.end
10127                            } else {
10128                                open.start
10129                            }
10130                        } else if inside {
10131                            *close.start()
10132                        } else {
10133                            *close.end()
10134                        },
10135                    );
10136                }
10137
10138                if let Some(destination) = best_destination {
10139                    selection.collapse_to(destination, SelectionGoal::None);
10140                }
10141            })
10142        });
10143    }
10144
10145    pub fn undo_selection(
10146        &mut self,
10147        _: &UndoSelection,
10148        window: &mut Window,
10149        cx: &mut Context<Self>,
10150    ) {
10151        self.end_selection(window, cx);
10152        self.selection_history.mode = SelectionHistoryMode::Undoing;
10153        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10154            self.change_selections(None, window, cx, |s| {
10155                s.select_anchors(entry.selections.to_vec())
10156            });
10157            self.select_next_state = entry.select_next_state;
10158            self.select_prev_state = entry.select_prev_state;
10159            self.add_selections_state = entry.add_selections_state;
10160            self.request_autoscroll(Autoscroll::newest(), cx);
10161        }
10162        self.selection_history.mode = SelectionHistoryMode::Normal;
10163    }
10164
10165    pub fn redo_selection(
10166        &mut self,
10167        _: &RedoSelection,
10168        window: &mut Window,
10169        cx: &mut Context<Self>,
10170    ) {
10171        self.end_selection(window, cx);
10172        self.selection_history.mode = SelectionHistoryMode::Redoing;
10173        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10174            self.change_selections(None, window, cx, |s| {
10175                s.select_anchors(entry.selections.to_vec())
10176            });
10177            self.select_next_state = entry.select_next_state;
10178            self.select_prev_state = entry.select_prev_state;
10179            self.add_selections_state = entry.add_selections_state;
10180            self.request_autoscroll(Autoscroll::newest(), cx);
10181        }
10182        self.selection_history.mode = SelectionHistoryMode::Normal;
10183    }
10184
10185    pub fn expand_excerpts(
10186        &mut self,
10187        action: &ExpandExcerpts,
10188        _: &mut Window,
10189        cx: &mut Context<Self>,
10190    ) {
10191        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10192    }
10193
10194    pub fn expand_excerpts_down(
10195        &mut self,
10196        action: &ExpandExcerptsDown,
10197        _: &mut Window,
10198        cx: &mut Context<Self>,
10199    ) {
10200        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10201    }
10202
10203    pub fn expand_excerpts_up(
10204        &mut self,
10205        action: &ExpandExcerptsUp,
10206        _: &mut Window,
10207        cx: &mut Context<Self>,
10208    ) {
10209        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10210    }
10211
10212    pub fn expand_excerpts_for_direction(
10213        &mut self,
10214        lines: u32,
10215        direction: ExpandExcerptDirection,
10216
10217        cx: &mut Context<Self>,
10218    ) {
10219        let selections = self.selections.disjoint_anchors();
10220
10221        let lines = if lines == 0 {
10222            EditorSettings::get_global(cx).expand_excerpt_lines
10223        } else {
10224            lines
10225        };
10226
10227        self.buffer.update(cx, |buffer, cx| {
10228            let snapshot = buffer.snapshot(cx);
10229            let mut excerpt_ids = selections
10230                .iter()
10231                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10232                .collect::<Vec<_>>();
10233            excerpt_ids.sort();
10234            excerpt_ids.dedup();
10235            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10236        })
10237    }
10238
10239    pub fn expand_excerpt(
10240        &mut self,
10241        excerpt: ExcerptId,
10242        direction: ExpandExcerptDirection,
10243        cx: &mut Context<Self>,
10244    ) {
10245        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10246        self.buffer.update(cx, |buffer, cx| {
10247            buffer.expand_excerpts([excerpt], lines, direction, cx)
10248        })
10249    }
10250
10251    pub fn go_to_singleton_buffer_point(
10252        &mut self,
10253        point: Point,
10254        window: &mut Window,
10255        cx: &mut Context<Self>,
10256    ) {
10257        self.go_to_singleton_buffer_range(point..point, window, cx);
10258    }
10259
10260    pub fn go_to_singleton_buffer_range(
10261        &mut self,
10262        range: Range<Point>,
10263        window: &mut Window,
10264        cx: &mut Context<Self>,
10265    ) {
10266        let multibuffer = self.buffer().read(cx);
10267        let Some(buffer) = multibuffer.as_singleton() else {
10268            return;
10269        };
10270        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10271            return;
10272        };
10273        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10274            return;
10275        };
10276        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10277            s.select_anchor_ranges([start..end])
10278        });
10279    }
10280
10281    fn go_to_diagnostic(
10282        &mut self,
10283        _: &GoToDiagnostic,
10284        window: &mut Window,
10285        cx: &mut Context<Self>,
10286    ) {
10287        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10288    }
10289
10290    fn go_to_prev_diagnostic(
10291        &mut self,
10292        _: &GoToPrevDiagnostic,
10293        window: &mut Window,
10294        cx: &mut Context<Self>,
10295    ) {
10296        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10297    }
10298
10299    pub fn go_to_diagnostic_impl(
10300        &mut self,
10301        direction: Direction,
10302        window: &mut Window,
10303        cx: &mut Context<Self>,
10304    ) {
10305        let buffer = self.buffer.read(cx).snapshot(cx);
10306        let selection = self.selections.newest::<usize>(cx);
10307
10308        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10309        if direction == Direction::Next {
10310            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10311                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10312                    return;
10313                };
10314                self.activate_diagnostics(
10315                    buffer_id,
10316                    popover.local_diagnostic.diagnostic.group_id,
10317                    window,
10318                    cx,
10319                );
10320                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10321                    let primary_range_start = active_diagnostics.primary_range.start;
10322                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10323                        let mut new_selection = s.newest_anchor().clone();
10324                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10325                        s.select_anchors(vec![new_selection.clone()]);
10326                    });
10327                    self.refresh_inline_completion(false, true, window, cx);
10328                }
10329                return;
10330            }
10331        }
10332
10333        let active_group_id = self
10334            .active_diagnostics
10335            .as_ref()
10336            .map(|active_group| active_group.group_id);
10337        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10338            active_diagnostics
10339                .primary_range
10340                .to_offset(&buffer)
10341                .to_inclusive()
10342        });
10343        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10344            if active_primary_range.contains(&selection.head()) {
10345                *active_primary_range.start()
10346            } else {
10347                selection.head()
10348            }
10349        } else {
10350            selection.head()
10351        };
10352
10353        let snapshot = self.snapshot(window, cx);
10354        let primary_diagnostics_before = buffer
10355            .diagnostics_in_range::<usize>(0..search_start)
10356            .filter(|entry| entry.diagnostic.is_primary)
10357            .filter(|entry| entry.range.start != entry.range.end)
10358            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10359            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10360            .collect::<Vec<_>>();
10361        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10362            primary_diagnostics_before
10363                .iter()
10364                .position(|entry| entry.diagnostic.group_id == active_group_id)
10365        });
10366
10367        let primary_diagnostics_after = buffer
10368            .diagnostics_in_range::<usize>(search_start..buffer.len())
10369            .filter(|entry| entry.diagnostic.is_primary)
10370            .filter(|entry| entry.range.start != entry.range.end)
10371            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10372            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10373            .collect::<Vec<_>>();
10374        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10375            primary_diagnostics_after
10376                .iter()
10377                .enumerate()
10378                .rev()
10379                .find_map(|(i, entry)| {
10380                    if entry.diagnostic.group_id == active_group_id {
10381                        Some(i)
10382                    } else {
10383                        None
10384                    }
10385                })
10386        });
10387
10388        let next_primary_diagnostic = match direction {
10389            Direction::Prev => primary_diagnostics_before
10390                .iter()
10391                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10392                .rev()
10393                .next(),
10394            Direction::Next => primary_diagnostics_after
10395                .iter()
10396                .skip(
10397                    last_same_group_diagnostic_after
10398                        .map(|index| index + 1)
10399                        .unwrap_or(0),
10400                )
10401                .next(),
10402        };
10403
10404        // Cycle around to the start of the buffer, potentially moving back to the start of
10405        // the currently active diagnostic.
10406        let cycle_around = || match direction {
10407            Direction::Prev => primary_diagnostics_after
10408                .iter()
10409                .rev()
10410                .chain(primary_diagnostics_before.iter().rev())
10411                .next(),
10412            Direction::Next => primary_diagnostics_before
10413                .iter()
10414                .chain(primary_diagnostics_after.iter())
10415                .next(),
10416        };
10417
10418        if let Some((primary_range, group_id)) = next_primary_diagnostic
10419            .or_else(cycle_around)
10420            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10421        {
10422            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10423                return;
10424            };
10425            self.activate_diagnostics(buffer_id, group_id, window, cx);
10426            if self.active_diagnostics.is_some() {
10427                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10428                    s.select(vec![Selection {
10429                        id: selection.id,
10430                        start: primary_range.start,
10431                        end: primary_range.start,
10432                        reversed: false,
10433                        goal: SelectionGoal::None,
10434                    }]);
10435                });
10436                self.refresh_inline_completion(false, true, window, cx);
10437            }
10438        }
10439    }
10440
10441    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10442        let snapshot = self.snapshot(window, cx);
10443        let selection = self.selections.newest::<Point>(cx);
10444        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10445    }
10446
10447    fn go_to_hunk_after_position(
10448        &mut self,
10449        snapshot: &EditorSnapshot,
10450        position: Point,
10451        window: &mut Window,
10452        cx: &mut Context<Editor>,
10453    ) -> Option<MultiBufferDiffHunk> {
10454        let mut hunk = snapshot
10455            .buffer_snapshot
10456            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10457            .find(|hunk| hunk.row_range.start.0 > position.row);
10458        if hunk.is_none() {
10459            hunk = snapshot
10460                .buffer_snapshot
10461                .diff_hunks_in_range(Point::zero()..position)
10462                .find(|hunk| hunk.row_range.end.0 < position.row)
10463        }
10464        if let Some(hunk) = &hunk {
10465            let destination = Point::new(hunk.row_range.start.0, 0);
10466            self.unfold_ranges(&[destination..destination], false, false, cx);
10467            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10468                s.select_ranges(vec![destination..destination]);
10469            });
10470        }
10471
10472        hunk
10473    }
10474
10475    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10476        let snapshot = self.snapshot(window, cx);
10477        let selection = self.selections.newest::<Point>(cx);
10478        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10479    }
10480
10481    fn go_to_hunk_before_position(
10482        &mut self,
10483        snapshot: &EditorSnapshot,
10484        position: Point,
10485        window: &mut Window,
10486        cx: &mut Context<Editor>,
10487    ) -> Option<MultiBufferDiffHunk> {
10488        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10489        if hunk.is_none() {
10490            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10491        }
10492        if let Some(hunk) = &hunk {
10493            let destination = Point::new(hunk.row_range.start.0, 0);
10494            self.unfold_ranges(&[destination..destination], false, false, cx);
10495            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10496                s.select_ranges(vec![destination..destination]);
10497            });
10498        }
10499
10500        hunk
10501    }
10502
10503    pub fn go_to_definition(
10504        &mut self,
10505        _: &GoToDefinition,
10506        window: &mut Window,
10507        cx: &mut Context<Self>,
10508    ) -> Task<Result<Navigated>> {
10509        let definition =
10510            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10511        cx.spawn_in(window, |editor, mut cx| async move {
10512            if definition.await? == Navigated::Yes {
10513                return Ok(Navigated::Yes);
10514            }
10515            match editor.update_in(&mut cx, |editor, window, cx| {
10516                editor.find_all_references(&FindAllReferences, window, cx)
10517            })? {
10518                Some(references) => references.await,
10519                None => Ok(Navigated::No),
10520            }
10521        })
10522    }
10523
10524    pub fn go_to_declaration(
10525        &mut self,
10526        _: &GoToDeclaration,
10527        window: &mut Window,
10528        cx: &mut Context<Self>,
10529    ) -> Task<Result<Navigated>> {
10530        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10531    }
10532
10533    pub fn go_to_declaration_split(
10534        &mut self,
10535        _: &GoToDeclaration,
10536        window: &mut Window,
10537        cx: &mut Context<Self>,
10538    ) -> Task<Result<Navigated>> {
10539        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10540    }
10541
10542    pub fn go_to_implementation(
10543        &mut self,
10544        _: &GoToImplementation,
10545        window: &mut Window,
10546        cx: &mut Context<Self>,
10547    ) -> Task<Result<Navigated>> {
10548        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10549    }
10550
10551    pub fn go_to_implementation_split(
10552        &mut self,
10553        _: &GoToImplementationSplit,
10554        window: &mut Window,
10555        cx: &mut Context<Self>,
10556    ) -> Task<Result<Navigated>> {
10557        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10558    }
10559
10560    pub fn go_to_type_definition(
10561        &mut self,
10562        _: &GoToTypeDefinition,
10563        window: &mut Window,
10564        cx: &mut Context<Self>,
10565    ) -> Task<Result<Navigated>> {
10566        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10567    }
10568
10569    pub fn go_to_definition_split(
10570        &mut self,
10571        _: &GoToDefinitionSplit,
10572        window: &mut Window,
10573        cx: &mut Context<Self>,
10574    ) -> Task<Result<Navigated>> {
10575        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10576    }
10577
10578    pub fn go_to_type_definition_split(
10579        &mut self,
10580        _: &GoToTypeDefinitionSplit,
10581        window: &mut Window,
10582        cx: &mut Context<Self>,
10583    ) -> Task<Result<Navigated>> {
10584        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10585    }
10586
10587    fn go_to_definition_of_kind(
10588        &mut self,
10589        kind: GotoDefinitionKind,
10590        split: bool,
10591        window: &mut Window,
10592        cx: &mut Context<Self>,
10593    ) -> Task<Result<Navigated>> {
10594        let Some(provider) = self.semantics_provider.clone() else {
10595            return Task::ready(Ok(Navigated::No));
10596        };
10597        let head = self.selections.newest::<usize>(cx).head();
10598        let buffer = self.buffer.read(cx);
10599        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10600            text_anchor
10601        } else {
10602            return Task::ready(Ok(Navigated::No));
10603        };
10604
10605        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10606            return Task::ready(Ok(Navigated::No));
10607        };
10608
10609        cx.spawn_in(window, |editor, mut cx| async move {
10610            let definitions = definitions.await?;
10611            let navigated = editor
10612                .update_in(&mut cx, |editor, window, cx| {
10613                    editor.navigate_to_hover_links(
10614                        Some(kind),
10615                        definitions
10616                            .into_iter()
10617                            .filter(|location| {
10618                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10619                            })
10620                            .map(HoverLink::Text)
10621                            .collect::<Vec<_>>(),
10622                        split,
10623                        window,
10624                        cx,
10625                    )
10626                })?
10627                .await?;
10628            anyhow::Ok(navigated)
10629        })
10630    }
10631
10632    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10633        let selection = self.selections.newest_anchor();
10634        let head = selection.head();
10635        let tail = selection.tail();
10636
10637        let Some((buffer, start_position)) =
10638            self.buffer.read(cx).text_anchor_for_position(head, cx)
10639        else {
10640            return;
10641        };
10642
10643        let end_position = if head != tail {
10644            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10645                return;
10646            };
10647            Some(pos)
10648        } else {
10649            None
10650        };
10651
10652        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10653            let url = if let Some(end_pos) = end_position {
10654                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10655            } else {
10656                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10657            };
10658
10659            if let Some(url) = url {
10660                editor.update(&mut cx, |_, cx| {
10661                    cx.open_url(&url);
10662                })
10663            } else {
10664                Ok(())
10665            }
10666        });
10667
10668        url_finder.detach();
10669    }
10670
10671    pub fn open_selected_filename(
10672        &mut self,
10673        _: &OpenSelectedFilename,
10674        window: &mut Window,
10675        cx: &mut Context<Self>,
10676    ) {
10677        let Some(workspace) = self.workspace() else {
10678            return;
10679        };
10680
10681        let position = self.selections.newest_anchor().head();
10682
10683        let Some((buffer, buffer_position)) =
10684            self.buffer.read(cx).text_anchor_for_position(position, cx)
10685        else {
10686            return;
10687        };
10688
10689        let project = self.project.clone();
10690
10691        cx.spawn_in(window, |_, mut cx| async move {
10692            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10693
10694            if let Some((_, path)) = result {
10695                workspace
10696                    .update_in(&mut cx, |workspace, window, cx| {
10697                        workspace.open_resolved_path(path, window, cx)
10698                    })?
10699                    .await?;
10700            }
10701            anyhow::Ok(())
10702        })
10703        .detach();
10704    }
10705
10706    pub(crate) fn navigate_to_hover_links(
10707        &mut self,
10708        kind: Option<GotoDefinitionKind>,
10709        mut definitions: Vec<HoverLink>,
10710        split: bool,
10711        window: &mut Window,
10712        cx: &mut Context<Editor>,
10713    ) -> Task<Result<Navigated>> {
10714        // If there is one definition, just open it directly
10715        if definitions.len() == 1 {
10716            let definition = definitions.pop().unwrap();
10717
10718            enum TargetTaskResult {
10719                Location(Option<Location>),
10720                AlreadyNavigated,
10721            }
10722
10723            let target_task = match definition {
10724                HoverLink::Text(link) => {
10725                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10726                }
10727                HoverLink::InlayHint(lsp_location, server_id) => {
10728                    let computation =
10729                        self.compute_target_location(lsp_location, server_id, window, cx);
10730                    cx.background_executor().spawn(async move {
10731                        let location = computation.await?;
10732                        Ok(TargetTaskResult::Location(location))
10733                    })
10734                }
10735                HoverLink::Url(url) => {
10736                    cx.open_url(&url);
10737                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10738                }
10739                HoverLink::File(path) => {
10740                    if let Some(workspace) = self.workspace() {
10741                        cx.spawn_in(window, |_, mut cx| async move {
10742                            workspace
10743                                .update_in(&mut cx, |workspace, window, cx| {
10744                                    workspace.open_resolved_path(path, window, cx)
10745                                })?
10746                                .await
10747                                .map(|_| TargetTaskResult::AlreadyNavigated)
10748                        })
10749                    } else {
10750                        Task::ready(Ok(TargetTaskResult::Location(None)))
10751                    }
10752                }
10753            };
10754            cx.spawn_in(window, |editor, mut cx| async move {
10755                let target = match target_task.await.context("target resolution task")? {
10756                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10757                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10758                    TargetTaskResult::Location(Some(target)) => target,
10759                };
10760
10761                editor.update_in(&mut cx, |editor, window, cx| {
10762                    let Some(workspace) = editor.workspace() else {
10763                        return Navigated::No;
10764                    };
10765                    let pane = workspace.read(cx).active_pane().clone();
10766
10767                    let range = target.range.to_point(target.buffer.read(cx));
10768                    let range = editor.range_for_match(&range);
10769                    let range = collapse_multiline_range(range);
10770
10771                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10772                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10773                    } else {
10774                        window.defer(cx, move |window, cx| {
10775                            let target_editor: Entity<Self> =
10776                                workspace.update(cx, |workspace, cx| {
10777                                    let pane = if split {
10778                                        workspace.adjacent_pane(window, cx)
10779                                    } else {
10780                                        workspace.active_pane().clone()
10781                                    };
10782
10783                                    workspace.open_project_item(
10784                                        pane,
10785                                        target.buffer.clone(),
10786                                        true,
10787                                        true,
10788                                        window,
10789                                        cx,
10790                                    )
10791                                });
10792                            target_editor.update(cx, |target_editor, cx| {
10793                                // When selecting a definition in a different buffer, disable the nav history
10794                                // to avoid creating a history entry at the previous cursor location.
10795                                pane.update(cx, |pane, _| pane.disable_history());
10796                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10797                                pane.update(cx, |pane, _| pane.enable_history());
10798                            });
10799                        });
10800                    }
10801                    Navigated::Yes
10802                })
10803            })
10804        } else if !definitions.is_empty() {
10805            cx.spawn_in(window, |editor, mut cx| async move {
10806                let (title, location_tasks, workspace) = editor
10807                    .update_in(&mut cx, |editor, window, cx| {
10808                        let tab_kind = match kind {
10809                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10810                            _ => "Definitions",
10811                        };
10812                        let title = definitions
10813                            .iter()
10814                            .find_map(|definition| match definition {
10815                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10816                                    let buffer = origin.buffer.read(cx);
10817                                    format!(
10818                                        "{} for {}",
10819                                        tab_kind,
10820                                        buffer
10821                                            .text_for_range(origin.range.clone())
10822                                            .collect::<String>()
10823                                    )
10824                                }),
10825                                HoverLink::InlayHint(_, _) => None,
10826                                HoverLink::Url(_) => None,
10827                                HoverLink::File(_) => None,
10828                            })
10829                            .unwrap_or(tab_kind.to_string());
10830                        let location_tasks = definitions
10831                            .into_iter()
10832                            .map(|definition| match definition {
10833                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10834                                HoverLink::InlayHint(lsp_location, server_id) => editor
10835                                    .compute_target_location(lsp_location, server_id, window, cx),
10836                                HoverLink::Url(_) => Task::ready(Ok(None)),
10837                                HoverLink::File(_) => Task::ready(Ok(None)),
10838                            })
10839                            .collect::<Vec<_>>();
10840                        (title, location_tasks, editor.workspace().clone())
10841                    })
10842                    .context("location tasks preparation")?;
10843
10844                let locations = future::join_all(location_tasks)
10845                    .await
10846                    .into_iter()
10847                    .filter_map(|location| location.transpose())
10848                    .collect::<Result<_>>()
10849                    .context("location tasks")?;
10850
10851                let Some(workspace) = workspace else {
10852                    return Ok(Navigated::No);
10853                };
10854                let opened = workspace
10855                    .update_in(&mut cx, |workspace, window, cx| {
10856                        Self::open_locations_in_multibuffer(
10857                            workspace,
10858                            locations,
10859                            title,
10860                            split,
10861                            MultibufferSelectionMode::First,
10862                            window,
10863                            cx,
10864                        )
10865                    })
10866                    .ok();
10867
10868                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10869            })
10870        } else {
10871            Task::ready(Ok(Navigated::No))
10872        }
10873    }
10874
10875    fn compute_target_location(
10876        &self,
10877        lsp_location: lsp::Location,
10878        server_id: LanguageServerId,
10879        window: &mut Window,
10880        cx: &mut Context<Self>,
10881    ) -> Task<anyhow::Result<Option<Location>>> {
10882        let Some(project) = self.project.clone() else {
10883            return Task::ready(Ok(None));
10884        };
10885
10886        cx.spawn_in(window, move |editor, mut cx| async move {
10887            let location_task = editor.update(&mut cx, |_, cx| {
10888                project.update(cx, |project, cx| {
10889                    let language_server_name = project
10890                        .language_server_statuses(cx)
10891                        .find(|(id, _)| server_id == *id)
10892                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10893                    language_server_name.map(|language_server_name| {
10894                        project.open_local_buffer_via_lsp(
10895                            lsp_location.uri.clone(),
10896                            server_id,
10897                            language_server_name,
10898                            cx,
10899                        )
10900                    })
10901                })
10902            })?;
10903            let location = match location_task {
10904                Some(task) => Some({
10905                    let target_buffer_handle = task.await.context("open local buffer")?;
10906                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10907                        let target_start = target_buffer
10908                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10909                        let target_end = target_buffer
10910                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10911                        target_buffer.anchor_after(target_start)
10912                            ..target_buffer.anchor_before(target_end)
10913                    })?;
10914                    Location {
10915                        buffer: target_buffer_handle,
10916                        range,
10917                    }
10918                }),
10919                None => None,
10920            };
10921            Ok(location)
10922        })
10923    }
10924
10925    pub fn find_all_references(
10926        &mut self,
10927        _: &FindAllReferences,
10928        window: &mut Window,
10929        cx: &mut Context<Self>,
10930    ) -> Option<Task<Result<Navigated>>> {
10931        let selection = self.selections.newest::<usize>(cx);
10932        let multi_buffer = self.buffer.read(cx);
10933        let head = selection.head();
10934
10935        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10936        let head_anchor = multi_buffer_snapshot.anchor_at(
10937            head,
10938            if head < selection.tail() {
10939                Bias::Right
10940            } else {
10941                Bias::Left
10942            },
10943        );
10944
10945        match self
10946            .find_all_references_task_sources
10947            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10948        {
10949            Ok(_) => {
10950                log::info!(
10951                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10952                );
10953                return None;
10954            }
10955            Err(i) => {
10956                self.find_all_references_task_sources.insert(i, head_anchor);
10957            }
10958        }
10959
10960        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10961        let workspace = self.workspace()?;
10962        let project = workspace.read(cx).project().clone();
10963        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10964        Some(cx.spawn_in(window, |editor, mut cx| async move {
10965            let _cleanup = defer({
10966                let mut cx = cx.clone();
10967                move || {
10968                    let _ = editor.update(&mut cx, |editor, _| {
10969                        if let Ok(i) =
10970                            editor
10971                                .find_all_references_task_sources
10972                                .binary_search_by(|anchor| {
10973                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10974                                })
10975                        {
10976                            editor.find_all_references_task_sources.remove(i);
10977                        }
10978                    });
10979                }
10980            });
10981
10982            let locations = references.await?;
10983            if locations.is_empty() {
10984                return anyhow::Ok(Navigated::No);
10985            }
10986
10987            workspace.update_in(&mut cx, |workspace, window, cx| {
10988                let title = locations
10989                    .first()
10990                    .as_ref()
10991                    .map(|location| {
10992                        let buffer = location.buffer.read(cx);
10993                        format!(
10994                            "References to `{}`",
10995                            buffer
10996                                .text_for_range(location.range.clone())
10997                                .collect::<String>()
10998                        )
10999                    })
11000                    .unwrap();
11001                Self::open_locations_in_multibuffer(
11002                    workspace,
11003                    locations,
11004                    title,
11005                    false,
11006                    MultibufferSelectionMode::First,
11007                    window,
11008                    cx,
11009                );
11010                Navigated::Yes
11011            })
11012        }))
11013    }
11014
11015    /// Opens a multibuffer with the given project locations in it
11016    pub fn open_locations_in_multibuffer(
11017        workspace: &mut Workspace,
11018        mut locations: Vec<Location>,
11019        title: String,
11020        split: bool,
11021        multibuffer_selection_mode: MultibufferSelectionMode,
11022        window: &mut Window,
11023        cx: &mut Context<Workspace>,
11024    ) {
11025        // If there are multiple definitions, open them in a multibuffer
11026        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11027        let mut locations = locations.into_iter().peekable();
11028        let mut ranges = Vec::new();
11029        let capability = workspace.project().read(cx).capability();
11030
11031        let excerpt_buffer = cx.new(|cx| {
11032            let mut multibuffer = MultiBuffer::new(capability);
11033            while let Some(location) = locations.next() {
11034                let buffer = location.buffer.read(cx);
11035                let mut ranges_for_buffer = Vec::new();
11036                let range = location.range.to_offset(buffer);
11037                ranges_for_buffer.push(range.clone());
11038
11039                while let Some(next_location) = locations.peek() {
11040                    if next_location.buffer == location.buffer {
11041                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11042                        locations.next();
11043                    } else {
11044                        break;
11045                    }
11046                }
11047
11048                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11049                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11050                    location.buffer.clone(),
11051                    ranges_for_buffer,
11052                    DEFAULT_MULTIBUFFER_CONTEXT,
11053                    cx,
11054                ))
11055            }
11056
11057            multibuffer.with_title(title)
11058        });
11059
11060        let editor = cx.new(|cx| {
11061            Editor::for_multibuffer(
11062                excerpt_buffer,
11063                Some(workspace.project().clone()),
11064                true,
11065                window,
11066                cx,
11067            )
11068        });
11069        editor.update(cx, |editor, cx| {
11070            match multibuffer_selection_mode {
11071                MultibufferSelectionMode::First => {
11072                    if let Some(first_range) = ranges.first() {
11073                        editor.change_selections(None, window, cx, |selections| {
11074                            selections.clear_disjoint();
11075                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11076                        });
11077                    }
11078                    editor.highlight_background::<Self>(
11079                        &ranges,
11080                        |theme| theme.editor_highlighted_line_background,
11081                        cx,
11082                    );
11083                }
11084                MultibufferSelectionMode::All => {
11085                    editor.change_selections(None, window, cx, |selections| {
11086                        selections.clear_disjoint();
11087                        selections.select_anchor_ranges(ranges);
11088                    });
11089                }
11090            }
11091            editor.register_buffers_with_language_servers(cx);
11092        });
11093
11094        let item = Box::new(editor);
11095        let item_id = item.item_id();
11096
11097        if split {
11098            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11099        } else {
11100            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11101                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11102                    pane.close_current_preview_item(window, cx)
11103                } else {
11104                    None
11105                }
11106            });
11107            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11108        }
11109        workspace.active_pane().update(cx, |pane, cx| {
11110            pane.set_preview_item_id(Some(item_id), cx);
11111        });
11112    }
11113
11114    pub fn rename(
11115        &mut self,
11116        _: &Rename,
11117        window: &mut Window,
11118        cx: &mut Context<Self>,
11119    ) -> Option<Task<Result<()>>> {
11120        use language::ToOffset as _;
11121
11122        let provider = self.semantics_provider.clone()?;
11123        let selection = self.selections.newest_anchor().clone();
11124        let (cursor_buffer, cursor_buffer_position) = self
11125            .buffer
11126            .read(cx)
11127            .text_anchor_for_position(selection.head(), cx)?;
11128        let (tail_buffer, cursor_buffer_position_end) = self
11129            .buffer
11130            .read(cx)
11131            .text_anchor_for_position(selection.tail(), cx)?;
11132        if tail_buffer != cursor_buffer {
11133            return None;
11134        }
11135
11136        let snapshot = cursor_buffer.read(cx).snapshot();
11137        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11138        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11139        let prepare_rename = provider
11140            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11141            .unwrap_or_else(|| Task::ready(Ok(None)));
11142        drop(snapshot);
11143
11144        Some(cx.spawn_in(window, |this, mut cx| async move {
11145            let rename_range = if let Some(range) = prepare_rename.await? {
11146                Some(range)
11147            } else {
11148                this.update(&mut cx, |this, cx| {
11149                    let buffer = this.buffer.read(cx).snapshot(cx);
11150                    let mut buffer_highlights = this
11151                        .document_highlights_for_position(selection.head(), &buffer)
11152                        .filter(|highlight| {
11153                            highlight.start.excerpt_id == selection.head().excerpt_id
11154                                && highlight.end.excerpt_id == selection.head().excerpt_id
11155                        });
11156                    buffer_highlights
11157                        .next()
11158                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11159                })?
11160            };
11161            if let Some(rename_range) = rename_range {
11162                this.update_in(&mut cx, |this, window, cx| {
11163                    let snapshot = cursor_buffer.read(cx).snapshot();
11164                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11165                    let cursor_offset_in_rename_range =
11166                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11167                    let cursor_offset_in_rename_range_end =
11168                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11169
11170                    this.take_rename(false, window, cx);
11171                    let buffer = this.buffer.read(cx).read(cx);
11172                    let cursor_offset = selection.head().to_offset(&buffer);
11173                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11174                    let rename_end = rename_start + rename_buffer_range.len();
11175                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11176                    let mut old_highlight_id = None;
11177                    let old_name: Arc<str> = buffer
11178                        .chunks(rename_start..rename_end, true)
11179                        .map(|chunk| {
11180                            if old_highlight_id.is_none() {
11181                                old_highlight_id = chunk.syntax_highlight_id;
11182                            }
11183                            chunk.text
11184                        })
11185                        .collect::<String>()
11186                        .into();
11187
11188                    drop(buffer);
11189
11190                    // Position the selection in the rename editor so that it matches the current selection.
11191                    this.show_local_selections = false;
11192                    let rename_editor = cx.new(|cx| {
11193                        let mut editor = Editor::single_line(window, cx);
11194                        editor.buffer.update(cx, |buffer, cx| {
11195                            buffer.edit([(0..0, old_name.clone())], None, cx)
11196                        });
11197                        let rename_selection_range = match cursor_offset_in_rename_range
11198                            .cmp(&cursor_offset_in_rename_range_end)
11199                        {
11200                            Ordering::Equal => {
11201                                editor.select_all(&SelectAll, window, cx);
11202                                return editor;
11203                            }
11204                            Ordering::Less => {
11205                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11206                            }
11207                            Ordering::Greater => {
11208                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11209                            }
11210                        };
11211                        if rename_selection_range.end > old_name.len() {
11212                            editor.select_all(&SelectAll, window, cx);
11213                        } else {
11214                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11215                                s.select_ranges([rename_selection_range]);
11216                            });
11217                        }
11218                        editor
11219                    });
11220                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11221                        if e == &EditorEvent::Focused {
11222                            cx.emit(EditorEvent::FocusedIn)
11223                        }
11224                    })
11225                    .detach();
11226
11227                    let write_highlights =
11228                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11229                    let read_highlights =
11230                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11231                    let ranges = write_highlights
11232                        .iter()
11233                        .flat_map(|(_, ranges)| ranges.iter())
11234                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11235                        .cloned()
11236                        .collect();
11237
11238                    this.highlight_text::<Rename>(
11239                        ranges,
11240                        HighlightStyle {
11241                            fade_out: Some(0.6),
11242                            ..Default::default()
11243                        },
11244                        cx,
11245                    );
11246                    let rename_focus_handle = rename_editor.focus_handle(cx);
11247                    window.focus(&rename_focus_handle);
11248                    let block_id = this.insert_blocks(
11249                        [BlockProperties {
11250                            style: BlockStyle::Flex,
11251                            placement: BlockPlacement::Below(range.start),
11252                            height: 1,
11253                            render: Arc::new({
11254                                let rename_editor = rename_editor.clone();
11255                                move |cx: &mut BlockContext| {
11256                                    let mut text_style = cx.editor_style.text.clone();
11257                                    if let Some(highlight_style) = old_highlight_id
11258                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11259                                    {
11260                                        text_style = text_style.highlight(highlight_style);
11261                                    }
11262                                    div()
11263                                        .block_mouse_down()
11264                                        .pl(cx.anchor_x)
11265                                        .child(EditorElement::new(
11266                                            &rename_editor,
11267                                            EditorStyle {
11268                                                background: cx.theme().system().transparent,
11269                                                local_player: cx.editor_style.local_player,
11270                                                text: text_style,
11271                                                scrollbar_width: cx.editor_style.scrollbar_width,
11272                                                syntax: cx.editor_style.syntax.clone(),
11273                                                status: cx.editor_style.status.clone(),
11274                                                inlay_hints_style: HighlightStyle {
11275                                                    font_weight: Some(FontWeight::BOLD),
11276                                                    ..make_inlay_hints_style(cx.app)
11277                                                },
11278                                                inline_completion_styles: make_suggestion_styles(
11279                                                    cx.app,
11280                                                ),
11281                                                ..EditorStyle::default()
11282                                            },
11283                                        ))
11284                                        .into_any_element()
11285                                }
11286                            }),
11287                            priority: 0,
11288                        }],
11289                        Some(Autoscroll::fit()),
11290                        cx,
11291                    )[0];
11292                    this.pending_rename = Some(RenameState {
11293                        range,
11294                        old_name,
11295                        editor: rename_editor,
11296                        block_id,
11297                    });
11298                })?;
11299            }
11300
11301            Ok(())
11302        }))
11303    }
11304
11305    pub fn confirm_rename(
11306        &mut self,
11307        _: &ConfirmRename,
11308        window: &mut Window,
11309        cx: &mut Context<Self>,
11310    ) -> Option<Task<Result<()>>> {
11311        let rename = self.take_rename(false, window, cx)?;
11312        let workspace = self.workspace()?.downgrade();
11313        let (buffer, start) = self
11314            .buffer
11315            .read(cx)
11316            .text_anchor_for_position(rename.range.start, cx)?;
11317        let (end_buffer, _) = self
11318            .buffer
11319            .read(cx)
11320            .text_anchor_for_position(rename.range.end, cx)?;
11321        if buffer != end_buffer {
11322            return None;
11323        }
11324
11325        let old_name = rename.old_name;
11326        let new_name = rename.editor.read(cx).text(cx);
11327
11328        let rename = self.semantics_provider.as_ref()?.perform_rename(
11329            &buffer,
11330            start,
11331            new_name.clone(),
11332            cx,
11333        )?;
11334
11335        Some(cx.spawn_in(window, |editor, mut cx| async move {
11336            let project_transaction = rename.await?;
11337            Self::open_project_transaction(
11338                &editor,
11339                workspace,
11340                project_transaction,
11341                format!("Rename: {}{}", old_name, new_name),
11342                cx.clone(),
11343            )
11344            .await?;
11345
11346            editor.update(&mut cx, |editor, cx| {
11347                editor.refresh_document_highlights(cx);
11348            })?;
11349            Ok(())
11350        }))
11351    }
11352
11353    fn take_rename(
11354        &mut self,
11355        moving_cursor: bool,
11356        window: &mut Window,
11357        cx: &mut Context<Self>,
11358    ) -> Option<RenameState> {
11359        let rename = self.pending_rename.take()?;
11360        if rename.editor.focus_handle(cx).is_focused(window) {
11361            window.focus(&self.focus_handle);
11362        }
11363
11364        self.remove_blocks(
11365            [rename.block_id].into_iter().collect(),
11366            Some(Autoscroll::fit()),
11367            cx,
11368        );
11369        self.clear_highlights::<Rename>(cx);
11370        self.show_local_selections = true;
11371
11372        if moving_cursor {
11373            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11374                editor.selections.newest::<usize>(cx).head()
11375            });
11376
11377            // Update the selection to match the position of the selection inside
11378            // the rename editor.
11379            let snapshot = self.buffer.read(cx).read(cx);
11380            let rename_range = rename.range.to_offset(&snapshot);
11381            let cursor_in_editor = snapshot
11382                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11383                .min(rename_range.end);
11384            drop(snapshot);
11385
11386            self.change_selections(None, window, cx, |s| {
11387                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11388            });
11389        } else {
11390            self.refresh_document_highlights(cx);
11391        }
11392
11393        Some(rename)
11394    }
11395
11396    pub fn pending_rename(&self) -> Option<&RenameState> {
11397        self.pending_rename.as_ref()
11398    }
11399
11400    fn format(
11401        &mut self,
11402        _: &Format,
11403        window: &mut Window,
11404        cx: &mut Context<Self>,
11405    ) -> Option<Task<Result<()>>> {
11406        let project = match &self.project {
11407            Some(project) => project.clone(),
11408            None => return None,
11409        };
11410
11411        Some(self.perform_format(
11412            project,
11413            FormatTrigger::Manual,
11414            FormatTarget::Buffers,
11415            window,
11416            cx,
11417        ))
11418    }
11419
11420    fn format_selections(
11421        &mut self,
11422        _: &FormatSelections,
11423        window: &mut Window,
11424        cx: &mut Context<Self>,
11425    ) -> Option<Task<Result<()>>> {
11426        let project = match &self.project {
11427            Some(project) => project.clone(),
11428            None => return None,
11429        };
11430
11431        let ranges = self
11432            .selections
11433            .all_adjusted(cx)
11434            .into_iter()
11435            .map(|selection| selection.range())
11436            .collect_vec();
11437
11438        Some(self.perform_format(
11439            project,
11440            FormatTrigger::Manual,
11441            FormatTarget::Ranges(ranges),
11442            window,
11443            cx,
11444        ))
11445    }
11446
11447    fn perform_format(
11448        &mut self,
11449        project: Entity<Project>,
11450        trigger: FormatTrigger,
11451        target: FormatTarget,
11452        window: &mut Window,
11453        cx: &mut Context<Self>,
11454    ) -> Task<Result<()>> {
11455        let buffer = self.buffer.clone();
11456        let (buffers, target) = match target {
11457            FormatTarget::Buffers => {
11458                let mut buffers = buffer.read(cx).all_buffers();
11459                if trigger == FormatTrigger::Save {
11460                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11461                }
11462                (buffers, LspFormatTarget::Buffers)
11463            }
11464            FormatTarget::Ranges(selection_ranges) => {
11465                let multi_buffer = buffer.read(cx);
11466                let snapshot = multi_buffer.read(cx);
11467                let mut buffers = HashSet::default();
11468                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11469                    BTreeMap::new();
11470                for selection_range in selection_ranges {
11471                    for (buffer, buffer_range, _) in
11472                        snapshot.range_to_buffer_ranges(selection_range)
11473                    {
11474                        let buffer_id = buffer.remote_id();
11475                        let start = buffer.anchor_before(buffer_range.start);
11476                        let end = buffer.anchor_after(buffer_range.end);
11477                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11478                        buffer_id_to_ranges
11479                            .entry(buffer_id)
11480                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11481                            .or_insert_with(|| vec![start..end]);
11482                    }
11483                }
11484                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11485            }
11486        };
11487
11488        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11489        let format = project.update(cx, |project, cx| {
11490            project.format(buffers, target, true, trigger, cx)
11491        });
11492
11493        cx.spawn_in(window, |_, mut cx| async move {
11494            let transaction = futures::select_biased! {
11495                () = timeout => {
11496                    log::warn!("timed out waiting for formatting");
11497                    None
11498                }
11499                transaction = format.log_err().fuse() => transaction,
11500            };
11501
11502            buffer
11503                .update(&mut cx, |buffer, cx| {
11504                    if let Some(transaction) = transaction {
11505                        if !buffer.is_singleton() {
11506                            buffer.push_transaction(&transaction.0, cx);
11507                        }
11508                    }
11509
11510                    cx.notify();
11511                })
11512                .ok();
11513
11514            Ok(())
11515        })
11516    }
11517
11518    fn restart_language_server(
11519        &mut self,
11520        _: &RestartLanguageServer,
11521        _: &mut Window,
11522        cx: &mut Context<Self>,
11523    ) {
11524        if let Some(project) = self.project.clone() {
11525            self.buffer.update(cx, |multi_buffer, cx| {
11526                project.update(cx, |project, cx| {
11527                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11528                });
11529            })
11530        }
11531    }
11532
11533    fn cancel_language_server_work(
11534        workspace: &mut Workspace,
11535        _: &actions::CancelLanguageServerWork,
11536        _: &mut Window,
11537        cx: &mut Context<Workspace>,
11538    ) {
11539        let project = workspace.project();
11540        let buffers = workspace
11541            .active_item(cx)
11542            .and_then(|item| item.act_as::<Editor>(cx))
11543            .map_or(HashSet::default(), |editor| {
11544                editor.read(cx).buffer.read(cx).all_buffers()
11545            });
11546        project.update(cx, |project, cx| {
11547            project.cancel_language_server_work_for_buffers(buffers, cx);
11548        });
11549    }
11550
11551    fn show_character_palette(
11552        &mut self,
11553        _: &ShowCharacterPalette,
11554        window: &mut Window,
11555        _: &mut Context<Self>,
11556    ) {
11557        window.show_character_palette();
11558    }
11559
11560    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11561        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11562            let buffer = self.buffer.read(cx).snapshot(cx);
11563            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11564            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11565            let is_valid = buffer
11566                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11567                .any(|entry| {
11568                    entry.diagnostic.is_primary
11569                        && !entry.range.is_empty()
11570                        && entry.range.start == primary_range_start
11571                        && entry.diagnostic.message == active_diagnostics.primary_message
11572                });
11573
11574            if is_valid != active_diagnostics.is_valid {
11575                active_diagnostics.is_valid = is_valid;
11576                let mut new_styles = HashMap::default();
11577                for (block_id, diagnostic) in &active_diagnostics.blocks {
11578                    new_styles.insert(
11579                        *block_id,
11580                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11581                    );
11582                }
11583                self.display_map.update(cx, |display_map, _cx| {
11584                    display_map.replace_blocks(new_styles)
11585                });
11586            }
11587        }
11588    }
11589
11590    fn activate_diagnostics(
11591        &mut self,
11592        buffer_id: BufferId,
11593        group_id: usize,
11594        window: &mut Window,
11595        cx: &mut Context<Self>,
11596    ) {
11597        self.dismiss_diagnostics(cx);
11598        let snapshot = self.snapshot(window, cx);
11599        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11600            let buffer = self.buffer.read(cx).snapshot(cx);
11601
11602            let mut primary_range = None;
11603            let mut primary_message = None;
11604            let diagnostic_group = buffer
11605                .diagnostic_group(buffer_id, group_id)
11606                .filter_map(|entry| {
11607                    let start = entry.range.start;
11608                    let end = entry.range.end;
11609                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11610                        && (start.row == end.row
11611                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11612                    {
11613                        return None;
11614                    }
11615                    if entry.diagnostic.is_primary {
11616                        primary_range = Some(entry.range.clone());
11617                        primary_message = Some(entry.diagnostic.message.clone());
11618                    }
11619                    Some(entry)
11620                })
11621                .collect::<Vec<_>>();
11622            let primary_range = primary_range?;
11623            let primary_message = primary_message?;
11624
11625            let blocks = display_map
11626                .insert_blocks(
11627                    diagnostic_group.iter().map(|entry| {
11628                        let diagnostic = entry.diagnostic.clone();
11629                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11630                        BlockProperties {
11631                            style: BlockStyle::Fixed,
11632                            placement: BlockPlacement::Below(
11633                                buffer.anchor_after(entry.range.start),
11634                            ),
11635                            height: message_height,
11636                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11637                            priority: 0,
11638                        }
11639                    }),
11640                    cx,
11641                )
11642                .into_iter()
11643                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11644                .collect();
11645
11646            Some(ActiveDiagnosticGroup {
11647                primary_range: buffer.anchor_before(primary_range.start)
11648                    ..buffer.anchor_after(primary_range.end),
11649                primary_message,
11650                group_id,
11651                blocks,
11652                is_valid: true,
11653            })
11654        });
11655    }
11656
11657    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11658        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11659            self.display_map.update(cx, |display_map, cx| {
11660                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11661            });
11662            cx.notify();
11663        }
11664    }
11665
11666    pub fn set_selections_from_remote(
11667        &mut self,
11668        selections: Vec<Selection<Anchor>>,
11669        pending_selection: Option<Selection<Anchor>>,
11670        window: &mut Window,
11671        cx: &mut Context<Self>,
11672    ) {
11673        let old_cursor_position = self.selections.newest_anchor().head();
11674        self.selections.change_with(cx, |s| {
11675            s.select_anchors(selections);
11676            if let Some(pending_selection) = pending_selection {
11677                s.set_pending(pending_selection, SelectMode::Character);
11678            } else {
11679                s.clear_pending();
11680            }
11681        });
11682        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11683    }
11684
11685    fn push_to_selection_history(&mut self) {
11686        self.selection_history.push(SelectionHistoryEntry {
11687            selections: self.selections.disjoint_anchors(),
11688            select_next_state: self.select_next_state.clone(),
11689            select_prev_state: self.select_prev_state.clone(),
11690            add_selections_state: self.add_selections_state.clone(),
11691        });
11692    }
11693
11694    pub fn transact(
11695        &mut self,
11696        window: &mut Window,
11697        cx: &mut Context<Self>,
11698        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11699    ) -> Option<TransactionId> {
11700        self.start_transaction_at(Instant::now(), window, cx);
11701        update(self, window, cx);
11702        self.end_transaction_at(Instant::now(), cx)
11703    }
11704
11705    pub fn start_transaction_at(
11706        &mut self,
11707        now: Instant,
11708        window: &mut Window,
11709        cx: &mut Context<Self>,
11710    ) {
11711        self.end_selection(window, cx);
11712        if let Some(tx_id) = self
11713            .buffer
11714            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11715        {
11716            self.selection_history
11717                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11718            cx.emit(EditorEvent::TransactionBegun {
11719                transaction_id: tx_id,
11720            })
11721        }
11722    }
11723
11724    pub fn end_transaction_at(
11725        &mut self,
11726        now: Instant,
11727        cx: &mut Context<Self>,
11728    ) -> Option<TransactionId> {
11729        if let Some(transaction_id) = self
11730            .buffer
11731            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11732        {
11733            if let Some((_, end_selections)) =
11734                self.selection_history.transaction_mut(transaction_id)
11735            {
11736                *end_selections = Some(self.selections.disjoint_anchors());
11737            } else {
11738                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11739            }
11740
11741            cx.emit(EditorEvent::Edited { transaction_id });
11742            Some(transaction_id)
11743        } else {
11744            None
11745        }
11746    }
11747
11748    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11749        if self.selection_mark_mode {
11750            self.change_selections(None, window, cx, |s| {
11751                s.move_with(|_, sel| {
11752                    sel.collapse_to(sel.head(), SelectionGoal::None);
11753                });
11754            })
11755        }
11756        self.selection_mark_mode = true;
11757        cx.notify();
11758    }
11759
11760    pub fn swap_selection_ends(
11761        &mut self,
11762        _: &actions::SwapSelectionEnds,
11763        window: &mut Window,
11764        cx: &mut Context<Self>,
11765    ) {
11766        self.change_selections(None, window, cx, |s| {
11767            s.move_with(|_, sel| {
11768                if sel.start != sel.end {
11769                    sel.reversed = !sel.reversed
11770                }
11771            });
11772        });
11773        self.request_autoscroll(Autoscroll::newest(), cx);
11774        cx.notify();
11775    }
11776
11777    pub fn toggle_fold(
11778        &mut self,
11779        _: &actions::ToggleFold,
11780        window: &mut Window,
11781        cx: &mut Context<Self>,
11782    ) {
11783        if self.is_singleton(cx) {
11784            let selection = self.selections.newest::<Point>(cx);
11785
11786            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11787            let range = if selection.is_empty() {
11788                let point = selection.head().to_display_point(&display_map);
11789                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11790                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11791                    .to_point(&display_map);
11792                start..end
11793            } else {
11794                selection.range()
11795            };
11796            if display_map.folds_in_range(range).next().is_some() {
11797                self.unfold_lines(&Default::default(), window, cx)
11798            } else {
11799                self.fold(&Default::default(), window, cx)
11800            }
11801        } else {
11802            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11803            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11804                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11805                .map(|(snapshot, _, _)| snapshot.remote_id())
11806                .collect();
11807
11808            for buffer_id in buffer_ids {
11809                if self.is_buffer_folded(buffer_id, cx) {
11810                    self.unfold_buffer(buffer_id, cx);
11811                } else {
11812                    self.fold_buffer(buffer_id, cx);
11813                }
11814            }
11815        }
11816    }
11817
11818    pub fn toggle_fold_recursive(
11819        &mut self,
11820        _: &actions::ToggleFoldRecursive,
11821        window: &mut Window,
11822        cx: &mut Context<Self>,
11823    ) {
11824        let selection = self.selections.newest::<Point>(cx);
11825
11826        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11827        let range = if selection.is_empty() {
11828            let point = selection.head().to_display_point(&display_map);
11829            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11830            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11831                .to_point(&display_map);
11832            start..end
11833        } else {
11834            selection.range()
11835        };
11836        if display_map.folds_in_range(range).next().is_some() {
11837            self.unfold_recursive(&Default::default(), window, cx)
11838        } else {
11839            self.fold_recursive(&Default::default(), window, cx)
11840        }
11841    }
11842
11843    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11844        if self.is_singleton(cx) {
11845            let mut to_fold = Vec::new();
11846            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11847            let selections = self.selections.all_adjusted(cx);
11848
11849            for selection in selections {
11850                let range = selection.range().sorted();
11851                let buffer_start_row = range.start.row;
11852
11853                if range.start.row != range.end.row {
11854                    let mut found = false;
11855                    let mut row = range.start.row;
11856                    while row <= range.end.row {
11857                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11858                        {
11859                            found = true;
11860                            row = crease.range().end.row + 1;
11861                            to_fold.push(crease);
11862                        } else {
11863                            row += 1
11864                        }
11865                    }
11866                    if found {
11867                        continue;
11868                    }
11869                }
11870
11871                for row in (0..=range.start.row).rev() {
11872                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11873                        if crease.range().end.row >= buffer_start_row {
11874                            to_fold.push(crease);
11875                            if row <= range.start.row {
11876                                break;
11877                            }
11878                        }
11879                    }
11880                }
11881            }
11882
11883            self.fold_creases(to_fold, true, window, cx);
11884        } else {
11885            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11886
11887            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11888                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11889                .map(|(snapshot, _, _)| snapshot.remote_id())
11890                .collect();
11891            for buffer_id in buffer_ids {
11892                self.fold_buffer(buffer_id, cx);
11893            }
11894        }
11895    }
11896
11897    fn fold_at_level(
11898        &mut self,
11899        fold_at: &FoldAtLevel,
11900        window: &mut Window,
11901        cx: &mut Context<Self>,
11902    ) {
11903        if !self.buffer.read(cx).is_singleton() {
11904            return;
11905        }
11906
11907        let fold_at_level = fold_at.0;
11908        let snapshot = self.buffer.read(cx).snapshot(cx);
11909        let mut to_fold = Vec::new();
11910        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11911
11912        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11913            while start_row < end_row {
11914                match self
11915                    .snapshot(window, cx)
11916                    .crease_for_buffer_row(MultiBufferRow(start_row))
11917                {
11918                    Some(crease) => {
11919                        let nested_start_row = crease.range().start.row + 1;
11920                        let nested_end_row = crease.range().end.row;
11921
11922                        if current_level < fold_at_level {
11923                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11924                        } else if current_level == fold_at_level {
11925                            to_fold.push(crease);
11926                        }
11927
11928                        start_row = nested_end_row + 1;
11929                    }
11930                    None => start_row += 1,
11931                }
11932            }
11933        }
11934
11935        self.fold_creases(to_fold, true, window, cx);
11936    }
11937
11938    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11939        if self.buffer.read(cx).is_singleton() {
11940            let mut fold_ranges = Vec::new();
11941            let snapshot = self.buffer.read(cx).snapshot(cx);
11942
11943            for row in 0..snapshot.max_row().0 {
11944                if let Some(foldable_range) = self
11945                    .snapshot(window, cx)
11946                    .crease_for_buffer_row(MultiBufferRow(row))
11947                {
11948                    fold_ranges.push(foldable_range);
11949                }
11950            }
11951
11952            self.fold_creases(fold_ranges, true, window, cx);
11953        } else {
11954            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11955                editor
11956                    .update_in(&mut cx, |editor, _, cx| {
11957                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11958                            editor.fold_buffer(buffer_id, cx);
11959                        }
11960                    })
11961                    .ok();
11962            });
11963        }
11964    }
11965
11966    pub fn fold_function_bodies(
11967        &mut self,
11968        _: &actions::FoldFunctionBodies,
11969        window: &mut Window,
11970        cx: &mut Context<Self>,
11971    ) {
11972        let snapshot = self.buffer.read(cx).snapshot(cx);
11973
11974        let ranges = snapshot
11975            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11976            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11977            .collect::<Vec<_>>();
11978
11979        let creases = ranges
11980            .into_iter()
11981            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11982            .collect();
11983
11984        self.fold_creases(creases, true, window, cx);
11985    }
11986
11987    pub fn fold_recursive(
11988        &mut self,
11989        _: &actions::FoldRecursive,
11990        window: &mut Window,
11991        cx: &mut Context<Self>,
11992    ) {
11993        let mut to_fold = Vec::new();
11994        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11995        let selections = self.selections.all_adjusted(cx);
11996
11997        for selection in selections {
11998            let range = selection.range().sorted();
11999            let buffer_start_row = range.start.row;
12000
12001            if range.start.row != range.end.row {
12002                let mut found = false;
12003                for row in range.start.row..=range.end.row {
12004                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12005                        found = true;
12006                        to_fold.push(crease);
12007                    }
12008                }
12009                if found {
12010                    continue;
12011                }
12012            }
12013
12014            for row in (0..=range.start.row).rev() {
12015                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12016                    if crease.range().end.row >= buffer_start_row {
12017                        to_fold.push(crease);
12018                    } else {
12019                        break;
12020                    }
12021                }
12022            }
12023        }
12024
12025        self.fold_creases(to_fold, true, window, cx);
12026    }
12027
12028    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12029        let buffer_row = fold_at.buffer_row;
12030        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12031
12032        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12033            let autoscroll = self
12034                .selections
12035                .all::<Point>(cx)
12036                .iter()
12037                .any(|selection| crease.range().overlaps(&selection.range()));
12038
12039            self.fold_creases(vec![crease], autoscroll, window, cx);
12040        }
12041    }
12042
12043    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12044        if self.is_singleton(cx) {
12045            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12046            let buffer = &display_map.buffer_snapshot;
12047            let selections = self.selections.all::<Point>(cx);
12048            let ranges = selections
12049                .iter()
12050                .map(|s| {
12051                    let range = s.display_range(&display_map).sorted();
12052                    let mut start = range.start.to_point(&display_map);
12053                    let mut end = range.end.to_point(&display_map);
12054                    start.column = 0;
12055                    end.column = buffer.line_len(MultiBufferRow(end.row));
12056                    start..end
12057                })
12058                .collect::<Vec<_>>();
12059
12060            self.unfold_ranges(&ranges, true, true, cx);
12061        } else {
12062            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12063            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12064                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12065                .map(|(snapshot, _, _)| snapshot.remote_id())
12066                .collect();
12067            for buffer_id in buffer_ids {
12068                self.unfold_buffer(buffer_id, cx);
12069            }
12070        }
12071    }
12072
12073    pub fn unfold_recursive(
12074        &mut self,
12075        _: &UnfoldRecursive,
12076        _window: &mut Window,
12077        cx: &mut Context<Self>,
12078    ) {
12079        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12080        let selections = self.selections.all::<Point>(cx);
12081        let ranges = selections
12082            .iter()
12083            .map(|s| {
12084                let mut range = s.display_range(&display_map).sorted();
12085                *range.start.column_mut() = 0;
12086                *range.end.column_mut() = display_map.line_len(range.end.row());
12087                let start = range.start.to_point(&display_map);
12088                let end = range.end.to_point(&display_map);
12089                start..end
12090            })
12091            .collect::<Vec<_>>();
12092
12093        self.unfold_ranges(&ranges, true, true, cx);
12094    }
12095
12096    pub fn unfold_at(
12097        &mut self,
12098        unfold_at: &UnfoldAt,
12099        _window: &mut Window,
12100        cx: &mut Context<Self>,
12101    ) {
12102        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12103
12104        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12105            ..Point::new(
12106                unfold_at.buffer_row.0,
12107                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12108            );
12109
12110        let autoscroll = self
12111            .selections
12112            .all::<Point>(cx)
12113            .iter()
12114            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12115
12116        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12117    }
12118
12119    pub fn unfold_all(
12120        &mut self,
12121        _: &actions::UnfoldAll,
12122        _window: &mut Window,
12123        cx: &mut Context<Self>,
12124    ) {
12125        if self.buffer.read(cx).is_singleton() {
12126            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12127            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12128        } else {
12129            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12130                editor
12131                    .update(&mut cx, |editor, cx| {
12132                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12133                            editor.unfold_buffer(buffer_id, cx);
12134                        }
12135                    })
12136                    .ok();
12137            });
12138        }
12139    }
12140
12141    pub fn fold_selected_ranges(
12142        &mut self,
12143        _: &FoldSelectedRanges,
12144        window: &mut Window,
12145        cx: &mut Context<Self>,
12146    ) {
12147        let selections = self.selections.all::<Point>(cx);
12148        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12149        let line_mode = self.selections.line_mode;
12150        let ranges = selections
12151            .into_iter()
12152            .map(|s| {
12153                if line_mode {
12154                    let start = Point::new(s.start.row, 0);
12155                    let end = Point::new(
12156                        s.end.row,
12157                        display_map
12158                            .buffer_snapshot
12159                            .line_len(MultiBufferRow(s.end.row)),
12160                    );
12161                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12162                } else {
12163                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12164                }
12165            })
12166            .collect::<Vec<_>>();
12167        self.fold_creases(ranges, true, window, cx);
12168    }
12169
12170    pub fn fold_ranges<T: ToOffset + Clone>(
12171        &mut self,
12172        ranges: Vec<Range<T>>,
12173        auto_scroll: bool,
12174        window: &mut Window,
12175        cx: &mut Context<Self>,
12176    ) {
12177        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12178        let ranges = ranges
12179            .into_iter()
12180            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12181            .collect::<Vec<_>>();
12182        self.fold_creases(ranges, auto_scroll, window, cx);
12183    }
12184
12185    pub fn fold_creases<T: ToOffset + Clone>(
12186        &mut self,
12187        creases: Vec<Crease<T>>,
12188        auto_scroll: bool,
12189        window: &mut Window,
12190        cx: &mut Context<Self>,
12191    ) {
12192        if creases.is_empty() {
12193            return;
12194        }
12195
12196        let mut buffers_affected = HashSet::default();
12197        let multi_buffer = self.buffer().read(cx);
12198        for crease in &creases {
12199            if let Some((_, buffer, _)) =
12200                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12201            {
12202                buffers_affected.insert(buffer.read(cx).remote_id());
12203            };
12204        }
12205
12206        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12207
12208        if auto_scroll {
12209            self.request_autoscroll(Autoscroll::fit(), cx);
12210        }
12211
12212        cx.notify();
12213
12214        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12215            // Clear diagnostics block when folding a range that contains it.
12216            let snapshot = self.snapshot(window, cx);
12217            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12218                drop(snapshot);
12219                self.active_diagnostics = Some(active_diagnostics);
12220                self.dismiss_diagnostics(cx);
12221            } else {
12222                self.active_diagnostics = Some(active_diagnostics);
12223            }
12224        }
12225
12226        self.scrollbar_marker_state.dirty = true;
12227    }
12228
12229    /// Removes any folds whose ranges intersect any of the given ranges.
12230    pub fn unfold_ranges<T: ToOffset + Clone>(
12231        &mut self,
12232        ranges: &[Range<T>],
12233        inclusive: bool,
12234        auto_scroll: bool,
12235        cx: &mut Context<Self>,
12236    ) {
12237        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12238            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12239        });
12240    }
12241
12242    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12243        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12244            return;
12245        }
12246        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12247        self.display_map
12248            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12249        cx.emit(EditorEvent::BufferFoldToggled {
12250            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12251            folded: true,
12252        });
12253        cx.notify();
12254    }
12255
12256    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12257        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12258            return;
12259        }
12260        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12261        self.display_map.update(cx, |display_map, cx| {
12262            display_map.unfold_buffer(buffer_id, cx);
12263        });
12264        cx.emit(EditorEvent::BufferFoldToggled {
12265            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12266            folded: false,
12267        });
12268        cx.notify();
12269    }
12270
12271    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12272        self.display_map.read(cx).is_buffer_folded(buffer)
12273    }
12274
12275    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12276        self.display_map.read(cx).folded_buffers()
12277    }
12278
12279    /// Removes any folds with the given ranges.
12280    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12281        &mut self,
12282        ranges: &[Range<T>],
12283        type_id: TypeId,
12284        auto_scroll: bool,
12285        cx: &mut Context<Self>,
12286    ) {
12287        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12288            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12289        });
12290    }
12291
12292    fn remove_folds_with<T: ToOffset + Clone>(
12293        &mut self,
12294        ranges: &[Range<T>],
12295        auto_scroll: bool,
12296        cx: &mut Context<Self>,
12297        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12298    ) {
12299        if ranges.is_empty() {
12300            return;
12301        }
12302
12303        let mut buffers_affected = HashSet::default();
12304        let multi_buffer = self.buffer().read(cx);
12305        for range in ranges {
12306            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12307                buffers_affected.insert(buffer.read(cx).remote_id());
12308            };
12309        }
12310
12311        self.display_map.update(cx, update);
12312
12313        if auto_scroll {
12314            self.request_autoscroll(Autoscroll::fit(), cx);
12315        }
12316
12317        cx.notify();
12318        self.scrollbar_marker_state.dirty = true;
12319        self.active_indent_guides_state.dirty = true;
12320    }
12321
12322    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12323        self.display_map.read(cx).fold_placeholder.clone()
12324    }
12325
12326    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12327        self.buffer.update(cx, |buffer, cx| {
12328            buffer.set_all_diff_hunks_expanded(cx);
12329        });
12330    }
12331
12332    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12333        self.distinguish_unstaged_diff_hunks = true;
12334    }
12335
12336    pub fn expand_all_diff_hunks(
12337        &mut self,
12338        _: &ExpandAllHunkDiffs,
12339        _window: &mut Window,
12340        cx: &mut Context<Self>,
12341    ) {
12342        self.buffer.update(cx, |buffer, cx| {
12343            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12344        });
12345    }
12346
12347    pub fn toggle_selected_diff_hunks(
12348        &mut self,
12349        _: &ToggleSelectedDiffHunks,
12350        _window: &mut Window,
12351        cx: &mut Context<Self>,
12352    ) {
12353        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12354        self.toggle_diff_hunks_in_ranges(ranges, cx);
12355    }
12356
12357    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12358        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12359        self.buffer
12360            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12361    }
12362
12363    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12364        self.buffer.update(cx, |buffer, cx| {
12365            let ranges = vec![Anchor::min()..Anchor::max()];
12366            if !buffer.all_diff_hunks_expanded()
12367                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12368            {
12369                buffer.collapse_diff_hunks(ranges, cx);
12370                true
12371            } else {
12372                false
12373            }
12374        })
12375    }
12376
12377    fn toggle_diff_hunks_in_ranges(
12378        &mut self,
12379        ranges: Vec<Range<Anchor>>,
12380        cx: &mut Context<'_, Editor>,
12381    ) {
12382        self.buffer.update(cx, |buffer, cx| {
12383            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12384            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12385        })
12386    }
12387
12388    fn toggle_diff_hunks_in_ranges_narrow(
12389        &mut self,
12390        ranges: Vec<Range<Anchor>>,
12391        cx: &mut Context<'_, Editor>,
12392    ) {
12393        self.buffer.update(cx, |buffer, cx| {
12394            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12395            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12396        })
12397    }
12398
12399    pub(crate) fn apply_all_diff_hunks(
12400        &mut self,
12401        _: &ApplyAllDiffHunks,
12402        window: &mut Window,
12403        cx: &mut Context<Self>,
12404    ) {
12405        let buffers = self.buffer.read(cx).all_buffers();
12406        for branch_buffer in buffers {
12407            branch_buffer.update(cx, |branch_buffer, cx| {
12408                branch_buffer.merge_into_base(Vec::new(), cx);
12409            });
12410        }
12411
12412        if let Some(project) = self.project.clone() {
12413            self.save(true, project, window, cx).detach_and_log_err(cx);
12414        }
12415    }
12416
12417    pub(crate) fn apply_selected_diff_hunks(
12418        &mut self,
12419        _: &ApplyDiffHunk,
12420        window: &mut Window,
12421        cx: &mut Context<Self>,
12422    ) {
12423        let snapshot = self.snapshot(window, cx);
12424        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12425        let mut ranges_by_buffer = HashMap::default();
12426        self.transact(window, cx, |editor, _window, cx| {
12427            for hunk in hunks {
12428                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12429                    ranges_by_buffer
12430                        .entry(buffer.clone())
12431                        .or_insert_with(Vec::new)
12432                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12433                }
12434            }
12435
12436            for (buffer, ranges) in ranges_by_buffer {
12437                buffer.update(cx, |buffer, cx| {
12438                    buffer.merge_into_base(ranges, cx);
12439                });
12440            }
12441        });
12442
12443        if let Some(project) = self.project.clone() {
12444            self.save(true, project, window, cx).detach_and_log_err(cx);
12445        }
12446    }
12447
12448    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12449        if hovered != self.gutter_hovered {
12450            self.gutter_hovered = hovered;
12451            cx.notify();
12452        }
12453    }
12454
12455    pub fn insert_blocks(
12456        &mut self,
12457        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12458        autoscroll: Option<Autoscroll>,
12459        cx: &mut Context<Self>,
12460    ) -> Vec<CustomBlockId> {
12461        let blocks = self
12462            .display_map
12463            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12464        if let Some(autoscroll) = autoscroll {
12465            self.request_autoscroll(autoscroll, cx);
12466        }
12467        cx.notify();
12468        blocks
12469    }
12470
12471    pub fn resize_blocks(
12472        &mut self,
12473        heights: HashMap<CustomBlockId, u32>,
12474        autoscroll: Option<Autoscroll>,
12475        cx: &mut Context<Self>,
12476    ) {
12477        self.display_map
12478            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12479        if let Some(autoscroll) = autoscroll {
12480            self.request_autoscroll(autoscroll, cx);
12481        }
12482        cx.notify();
12483    }
12484
12485    pub fn replace_blocks(
12486        &mut self,
12487        renderers: HashMap<CustomBlockId, RenderBlock>,
12488        autoscroll: Option<Autoscroll>,
12489        cx: &mut Context<Self>,
12490    ) {
12491        self.display_map
12492            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12493        if let Some(autoscroll) = autoscroll {
12494            self.request_autoscroll(autoscroll, cx);
12495        }
12496        cx.notify();
12497    }
12498
12499    pub fn remove_blocks(
12500        &mut self,
12501        block_ids: HashSet<CustomBlockId>,
12502        autoscroll: Option<Autoscroll>,
12503        cx: &mut Context<Self>,
12504    ) {
12505        self.display_map.update(cx, |display_map, cx| {
12506            display_map.remove_blocks(block_ids, cx)
12507        });
12508        if let Some(autoscroll) = autoscroll {
12509            self.request_autoscroll(autoscroll, cx);
12510        }
12511        cx.notify();
12512    }
12513
12514    pub fn row_for_block(
12515        &self,
12516        block_id: CustomBlockId,
12517        cx: &mut Context<Self>,
12518    ) -> Option<DisplayRow> {
12519        self.display_map
12520            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12521    }
12522
12523    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12524        self.focused_block = Some(focused_block);
12525    }
12526
12527    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12528        self.focused_block.take()
12529    }
12530
12531    pub fn insert_creases(
12532        &mut self,
12533        creases: impl IntoIterator<Item = Crease<Anchor>>,
12534        cx: &mut Context<Self>,
12535    ) -> Vec<CreaseId> {
12536        self.display_map
12537            .update(cx, |map, cx| map.insert_creases(creases, cx))
12538    }
12539
12540    pub fn remove_creases(
12541        &mut self,
12542        ids: impl IntoIterator<Item = CreaseId>,
12543        cx: &mut Context<Self>,
12544    ) {
12545        self.display_map
12546            .update(cx, |map, cx| map.remove_creases(ids, cx));
12547    }
12548
12549    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12550        self.display_map
12551            .update(cx, |map, cx| map.snapshot(cx))
12552            .longest_row()
12553    }
12554
12555    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12556        self.display_map
12557            .update(cx, |map, cx| map.snapshot(cx))
12558            .max_point()
12559    }
12560
12561    pub fn text(&self, cx: &App) -> String {
12562        self.buffer.read(cx).read(cx).text()
12563    }
12564
12565    pub fn is_empty(&self, cx: &App) -> bool {
12566        self.buffer.read(cx).read(cx).is_empty()
12567    }
12568
12569    pub fn text_option(&self, cx: &App) -> Option<String> {
12570        let text = self.text(cx);
12571        let text = text.trim();
12572
12573        if text.is_empty() {
12574            return None;
12575        }
12576
12577        Some(text.to_string())
12578    }
12579
12580    pub fn set_text(
12581        &mut self,
12582        text: impl Into<Arc<str>>,
12583        window: &mut Window,
12584        cx: &mut Context<Self>,
12585    ) {
12586        self.transact(window, cx, |this, _, cx| {
12587            this.buffer
12588                .read(cx)
12589                .as_singleton()
12590                .expect("you can only call set_text on editors for singleton buffers")
12591                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12592        });
12593    }
12594
12595    pub fn display_text(&self, cx: &mut App) -> String {
12596        self.display_map
12597            .update(cx, |map, cx| map.snapshot(cx))
12598            .text()
12599    }
12600
12601    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12602        let mut wrap_guides = smallvec::smallvec![];
12603
12604        if self.show_wrap_guides == Some(false) {
12605            return wrap_guides;
12606        }
12607
12608        let settings = self.buffer.read(cx).settings_at(0, cx);
12609        if settings.show_wrap_guides {
12610            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12611                wrap_guides.push((soft_wrap as usize, true));
12612            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12613                wrap_guides.push((soft_wrap as usize, true));
12614            }
12615            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12616        }
12617
12618        wrap_guides
12619    }
12620
12621    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12622        let settings = self.buffer.read(cx).settings_at(0, cx);
12623        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12624        match mode {
12625            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12626                SoftWrap::None
12627            }
12628            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12629            language_settings::SoftWrap::PreferredLineLength => {
12630                SoftWrap::Column(settings.preferred_line_length)
12631            }
12632            language_settings::SoftWrap::Bounded => {
12633                SoftWrap::Bounded(settings.preferred_line_length)
12634            }
12635        }
12636    }
12637
12638    pub fn set_soft_wrap_mode(
12639        &mut self,
12640        mode: language_settings::SoftWrap,
12641
12642        cx: &mut Context<Self>,
12643    ) {
12644        self.soft_wrap_mode_override = Some(mode);
12645        cx.notify();
12646    }
12647
12648    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12649        self.text_style_refinement = Some(style);
12650    }
12651
12652    /// called by the Element so we know what style we were most recently rendered with.
12653    pub(crate) fn set_style(
12654        &mut self,
12655        style: EditorStyle,
12656        window: &mut Window,
12657        cx: &mut Context<Self>,
12658    ) {
12659        let rem_size = window.rem_size();
12660        self.display_map.update(cx, |map, cx| {
12661            map.set_font(
12662                style.text.font(),
12663                style.text.font_size.to_pixels(rem_size),
12664                cx,
12665            )
12666        });
12667        self.style = Some(style);
12668    }
12669
12670    pub fn style(&self) -> Option<&EditorStyle> {
12671        self.style.as_ref()
12672    }
12673
12674    // Called by the element. This method is not designed to be called outside of the editor
12675    // element's layout code because it does not notify when rewrapping is computed synchronously.
12676    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12677        self.display_map
12678            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12679    }
12680
12681    pub fn set_soft_wrap(&mut self) {
12682        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12683    }
12684
12685    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12686        if self.soft_wrap_mode_override.is_some() {
12687            self.soft_wrap_mode_override.take();
12688        } else {
12689            let soft_wrap = match self.soft_wrap_mode(cx) {
12690                SoftWrap::GitDiff => return,
12691                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12692                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12693                    language_settings::SoftWrap::None
12694                }
12695            };
12696            self.soft_wrap_mode_override = Some(soft_wrap);
12697        }
12698        cx.notify();
12699    }
12700
12701    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12702        let Some(workspace) = self.workspace() else {
12703            return;
12704        };
12705        let fs = workspace.read(cx).app_state().fs.clone();
12706        let current_show = TabBarSettings::get_global(cx).show;
12707        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12708            setting.show = Some(!current_show);
12709        });
12710    }
12711
12712    pub fn toggle_indent_guides(
12713        &mut self,
12714        _: &ToggleIndentGuides,
12715        _: &mut Window,
12716        cx: &mut Context<Self>,
12717    ) {
12718        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12719            self.buffer
12720                .read(cx)
12721                .settings_at(0, cx)
12722                .indent_guides
12723                .enabled
12724        });
12725        self.show_indent_guides = Some(!currently_enabled);
12726        cx.notify();
12727    }
12728
12729    fn should_show_indent_guides(&self) -> Option<bool> {
12730        self.show_indent_guides
12731    }
12732
12733    pub fn toggle_line_numbers(
12734        &mut self,
12735        _: &ToggleLineNumbers,
12736        _: &mut Window,
12737        cx: &mut Context<Self>,
12738    ) {
12739        let mut editor_settings = EditorSettings::get_global(cx).clone();
12740        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12741        EditorSettings::override_global(editor_settings, cx);
12742    }
12743
12744    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12745        self.use_relative_line_numbers
12746            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12747    }
12748
12749    pub fn toggle_relative_line_numbers(
12750        &mut self,
12751        _: &ToggleRelativeLineNumbers,
12752        _: &mut Window,
12753        cx: &mut Context<Self>,
12754    ) {
12755        let is_relative = self.should_use_relative_line_numbers(cx);
12756        self.set_relative_line_number(Some(!is_relative), cx)
12757    }
12758
12759    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12760        self.use_relative_line_numbers = is_relative;
12761        cx.notify();
12762    }
12763
12764    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12765        self.show_gutter = show_gutter;
12766        cx.notify();
12767    }
12768
12769    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12770        self.show_scrollbars = show_scrollbars;
12771        cx.notify();
12772    }
12773
12774    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12775        self.show_line_numbers = Some(show_line_numbers);
12776        cx.notify();
12777    }
12778
12779    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12780        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12781        cx.notify();
12782    }
12783
12784    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12785        self.show_code_actions = Some(show_code_actions);
12786        cx.notify();
12787    }
12788
12789    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12790        self.show_runnables = Some(show_runnables);
12791        cx.notify();
12792    }
12793
12794    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12795        if self.display_map.read(cx).masked != masked {
12796            self.display_map.update(cx, |map, _| map.masked = masked);
12797        }
12798        cx.notify()
12799    }
12800
12801    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12802        self.show_wrap_guides = Some(show_wrap_guides);
12803        cx.notify();
12804    }
12805
12806    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12807        self.show_indent_guides = Some(show_indent_guides);
12808        cx.notify();
12809    }
12810
12811    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12812        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12813            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12814                if let Some(dir) = file.abs_path(cx).parent() {
12815                    return Some(dir.to_owned());
12816                }
12817            }
12818
12819            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12820                return Some(project_path.path.to_path_buf());
12821            }
12822        }
12823
12824        None
12825    }
12826
12827    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12828        self.active_excerpt(cx)?
12829            .1
12830            .read(cx)
12831            .file()
12832            .and_then(|f| f.as_local())
12833    }
12834
12835    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12836        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12837            let project_path = buffer.read(cx).project_path(cx)?;
12838            let project = self.project.as_ref()?.read(cx);
12839            project.absolute_path(&project_path, cx)
12840        })
12841    }
12842
12843    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12844        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12845            let project_path = buffer.read(cx).project_path(cx)?;
12846            let project = self.project.as_ref()?.read(cx);
12847            let entry = project.entry_for_path(&project_path, cx)?;
12848            let path = entry.path.to_path_buf();
12849            Some(path)
12850        })
12851    }
12852
12853    pub fn reveal_in_finder(
12854        &mut self,
12855        _: &RevealInFileManager,
12856        _window: &mut Window,
12857        cx: &mut Context<Self>,
12858    ) {
12859        if let Some(target) = self.target_file(cx) {
12860            cx.reveal_path(&target.abs_path(cx));
12861        }
12862    }
12863
12864    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12865        if let Some(path) = self.target_file_abs_path(cx) {
12866            if let Some(path) = path.to_str() {
12867                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12868            }
12869        }
12870    }
12871
12872    pub fn copy_relative_path(
12873        &mut self,
12874        _: &CopyRelativePath,
12875        _window: &mut Window,
12876        cx: &mut Context<Self>,
12877    ) {
12878        if let Some(path) = self.target_file_path(cx) {
12879            if let Some(path) = path.to_str() {
12880                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12881            }
12882        }
12883    }
12884
12885    pub fn copy_file_name_without_extension(
12886        &mut self,
12887        _: &CopyFileNameWithoutExtension,
12888        _: &mut Window,
12889        cx: &mut Context<Self>,
12890    ) {
12891        if let Some(file) = self.target_file(cx) {
12892            if let Some(file_stem) = file.path().file_stem() {
12893                if let Some(name) = file_stem.to_str() {
12894                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12895                }
12896            }
12897        }
12898    }
12899
12900    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
12901        if let Some(file) = self.target_file(cx) {
12902            if let Some(file_name) = file.path().file_name() {
12903                if let Some(name) = file_name.to_str() {
12904                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12905                }
12906            }
12907        }
12908    }
12909
12910    pub fn toggle_git_blame(
12911        &mut self,
12912        _: &ToggleGitBlame,
12913        window: &mut Window,
12914        cx: &mut Context<Self>,
12915    ) {
12916        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12917
12918        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12919            self.start_git_blame(true, window, cx);
12920        }
12921
12922        cx.notify();
12923    }
12924
12925    pub fn toggle_git_blame_inline(
12926        &mut self,
12927        _: &ToggleGitBlameInline,
12928        window: &mut Window,
12929        cx: &mut Context<Self>,
12930    ) {
12931        self.toggle_git_blame_inline_internal(true, window, cx);
12932        cx.notify();
12933    }
12934
12935    pub fn git_blame_inline_enabled(&self) -> bool {
12936        self.git_blame_inline_enabled
12937    }
12938
12939    pub fn toggle_selection_menu(
12940        &mut self,
12941        _: &ToggleSelectionMenu,
12942        _: &mut Window,
12943        cx: &mut Context<Self>,
12944    ) {
12945        self.show_selection_menu = self
12946            .show_selection_menu
12947            .map(|show_selections_menu| !show_selections_menu)
12948            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12949
12950        cx.notify();
12951    }
12952
12953    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12954        self.show_selection_menu
12955            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12956    }
12957
12958    fn start_git_blame(
12959        &mut self,
12960        user_triggered: bool,
12961        window: &mut Window,
12962        cx: &mut Context<Self>,
12963    ) {
12964        if let Some(project) = self.project.as_ref() {
12965            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12966                return;
12967            };
12968
12969            if buffer.read(cx).file().is_none() {
12970                return;
12971            }
12972
12973            let focused = self.focus_handle(cx).contains_focused(window, cx);
12974
12975            let project = project.clone();
12976            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12977            self.blame_subscription =
12978                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12979            self.blame = Some(blame);
12980        }
12981    }
12982
12983    fn toggle_git_blame_inline_internal(
12984        &mut self,
12985        user_triggered: bool,
12986        window: &mut Window,
12987        cx: &mut Context<Self>,
12988    ) {
12989        if self.git_blame_inline_enabled {
12990            self.git_blame_inline_enabled = false;
12991            self.show_git_blame_inline = false;
12992            self.show_git_blame_inline_delay_task.take();
12993        } else {
12994            self.git_blame_inline_enabled = true;
12995            self.start_git_blame_inline(user_triggered, window, cx);
12996        }
12997
12998        cx.notify();
12999    }
13000
13001    fn start_git_blame_inline(
13002        &mut self,
13003        user_triggered: bool,
13004        window: &mut Window,
13005        cx: &mut Context<Self>,
13006    ) {
13007        self.start_git_blame(user_triggered, window, cx);
13008
13009        if ProjectSettings::get_global(cx)
13010            .git
13011            .inline_blame_delay()
13012            .is_some()
13013        {
13014            self.start_inline_blame_timer(window, cx);
13015        } else {
13016            self.show_git_blame_inline = true
13017        }
13018    }
13019
13020    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13021        self.blame.as_ref()
13022    }
13023
13024    pub fn show_git_blame_gutter(&self) -> bool {
13025        self.show_git_blame_gutter
13026    }
13027
13028    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13029        self.show_git_blame_gutter && self.has_blame_entries(cx)
13030    }
13031
13032    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13033        self.show_git_blame_inline
13034            && self.focus_handle.is_focused(window)
13035            && !self.newest_selection_head_on_empty_line(cx)
13036            && self.has_blame_entries(cx)
13037    }
13038
13039    fn has_blame_entries(&self, cx: &App) -> bool {
13040        self.blame()
13041            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13042    }
13043
13044    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13045        let cursor_anchor = self.selections.newest_anchor().head();
13046
13047        let snapshot = self.buffer.read(cx).snapshot(cx);
13048        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13049
13050        snapshot.line_len(buffer_row) == 0
13051    }
13052
13053    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13054        let buffer_and_selection = maybe!({
13055            let selection = self.selections.newest::<Point>(cx);
13056            let selection_range = selection.range();
13057
13058            let multi_buffer = self.buffer().read(cx);
13059            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13060            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13061
13062            let (buffer, range, _) = if selection.reversed {
13063                buffer_ranges.first()
13064            } else {
13065                buffer_ranges.last()
13066            }?;
13067
13068            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13069                ..text::ToPoint::to_point(&range.end, &buffer).row;
13070            Some((
13071                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13072                selection,
13073            ))
13074        });
13075
13076        let Some((buffer, selection)) = buffer_and_selection else {
13077            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13078        };
13079
13080        let Some(project) = self.project.as_ref() else {
13081            return Task::ready(Err(anyhow!("editor does not have project")));
13082        };
13083
13084        project.update(cx, |project, cx| {
13085            project.get_permalink_to_line(&buffer, selection, cx)
13086        })
13087    }
13088
13089    pub fn copy_permalink_to_line(
13090        &mut self,
13091        _: &CopyPermalinkToLine,
13092        window: &mut Window,
13093        cx: &mut Context<Self>,
13094    ) {
13095        let permalink_task = self.get_permalink_to_line(cx);
13096        let workspace = self.workspace();
13097
13098        cx.spawn_in(window, |_, mut cx| async move {
13099            match permalink_task.await {
13100                Ok(permalink) => {
13101                    cx.update(|_, cx| {
13102                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13103                    })
13104                    .ok();
13105                }
13106                Err(err) => {
13107                    let message = format!("Failed to copy permalink: {err}");
13108
13109                    Err::<(), anyhow::Error>(err).log_err();
13110
13111                    if let Some(workspace) = workspace {
13112                        workspace
13113                            .update_in(&mut cx, |workspace, _, cx| {
13114                                struct CopyPermalinkToLine;
13115
13116                                workspace.show_toast(
13117                                    Toast::new(
13118                                        NotificationId::unique::<CopyPermalinkToLine>(),
13119                                        message,
13120                                    ),
13121                                    cx,
13122                                )
13123                            })
13124                            .ok();
13125                    }
13126                }
13127            }
13128        })
13129        .detach();
13130    }
13131
13132    pub fn copy_file_location(
13133        &mut self,
13134        _: &CopyFileLocation,
13135        _: &mut Window,
13136        cx: &mut Context<Self>,
13137    ) {
13138        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13139        if let Some(file) = self.target_file(cx) {
13140            if let Some(path) = file.path().to_str() {
13141                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13142            }
13143        }
13144    }
13145
13146    pub fn open_permalink_to_line(
13147        &mut self,
13148        _: &OpenPermalinkToLine,
13149        window: &mut Window,
13150        cx: &mut Context<Self>,
13151    ) {
13152        let permalink_task = self.get_permalink_to_line(cx);
13153        let workspace = self.workspace();
13154
13155        cx.spawn_in(window, |_, mut cx| async move {
13156            match permalink_task.await {
13157                Ok(permalink) => {
13158                    cx.update(|_, cx| {
13159                        cx.open_url(permalink.as_ref());
13160                    })
13161                    .ok();
13162                }
13163                Err(err) => {
13164                    let message = format!("Failed to open permalink: {err}");
13165
13166                    Err::<(), anyhow::Error>(err).log_err();
13167
13168                    if let Some(workspace) = workspace {
13169                        workspace
13170                            .update(&mut cx, |workspace, cx| {
13171                                struct OpenPermalinkToLine;
13172
13173                                workspace.show_toast(
13174                                    Toast::new(
13175                                        NotificationId::unique::<OpenPermalinkToLine>(),
13176                                        message,
13177                                    ),
13178                                    cx,
13179                                )
13180                            })
13181                            .ok();
13182                    }
13183                }
13184            }
13185        })
13186        .detach();
13187    }
13188
13189    pub fn insert_uuid_v4(
13190        &mut self,
13191        _: &InsertUuidV4,
13192        window: &mut Window,
13193        cx: &mut Context<Self>,
13194    ) {
13195        self.insert_uuid(UuidVersion::V4, window, cx);
13196    }
13197
13198    pub fn insert_uuid_v7(
13199        &mut self,
13200        _: &InsertUuidV7,
13201        window: &mut Window,
13202        cx: &mut Context<Self>,
13203    ) {
13204        self.insert_uuid(UuidVersion::V7, window, cx);
13205    }
13206
13207    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13208        self.transact(window, cx, |this, window, cx| {
13209            let edits = this
13210                .selections
13211                .all::<Point>(cx)
13212                .into_iter()
13213                .map(|selection| {
13214                    let uuid = match version {
13215                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13216                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13217                    };
13218
13219                    (selection.range(), uuid.to_string())
13220                });
13221            this.edit(edits, cx);
13222            this.refresh_inline_completion(true, false, window, cx);
13223        });
13224    }
13225
13226    pub fn open_selections_in_multibuffer(
13227        &mut self,
13228        _: &OpenSelectionsInMultibuffer,
13229        window: &mut Window,
13230        cx: &mut Context<Self>,
13231    ) {
13232        let multibuffer = self.buffer.read(cx);
13233
13234        let Some(buffer) = multibuffer.as_singleton() else {
13235            return;
13236        };
13237
13238        let Some(workspace) = self.workspace() else {
13239            return;
13240        };
13241
13242        let locations = self
13243            .selections
13244            .disjoint_anchors()
13245            .iter()
13246            .map(|range| Location {
13247                buffer: buffer.clone(),
13248                range: range.start.text_anchor..range.end.text_anchor,
13249            })
13250            .collect::<Vec<_>>();
13251
13252        let title = multibuffer.title(cx).to_string();
13253
13254        cx.spawn_in(window, |_, mut cx| async move {
13255            workspace.update_in(&mut cx, |workspace, window, cx| {
13256                Self::open_locations_in_multibuffer(
13257                    workspace,
13258                    locations,
13259                    format!("Selections for '{title}'"),
13260                    false,
13261                    MultibufferSelectionMode::All,
13262                    window,
13263                    cx,
13264                );
13265            })
13266        })
13267        .detach();
13268    }
13269
13270    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13271    /// last highlight added will be used.
13272    ///
13273    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13274    pub fn highlight_rows<T: 'static>(
13275        &mut self,
13276        range: Range<Anchor>,
13277        color: Hsla,
13278        should_autoscroll: bool,
13279        cx: &mut Context<Self>,
13280    ) {
13281        let snapshot = self.buffer().read(cx).snapshot(cx);
13282        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13283        let ix = row_highlights.binary_search_by(|highlight| {
13284            Ordering::Equal
13285                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13286                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13287        });
13288
13289        if let Err(mut ix) = ix {
13290            let index = post_inc(&mut self.highlight_order);
13291
13292            // If this range intersects with the preceding highlight, then merge it with
13293            // the preceding highlight. Otherwise insert a new highlight.
13294            let mut merged = false;
13295            if ix > 0 {
13296                let prev_highlight = &mut row_highlights[ix - 1];
13297                if prev_highlight
13298                    .range
13299                    .end
13300                    .cmp(&range.start, &snapshot)
13301                    .is_ge()
13302                {
13303                    ix -= 1;
13304                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13305                        prev_highlight.range.end = range.end;
13306                    }
13307                    merged = true;
13308                    prev_highlight.index = index;
13309                    prev_highlight.color = color;
13310                    prev_highlight.should_autoscroll = should_autoscroll;
13311                }
13312            }
13313
13314            if !merged {
13315                row_highlights.insert(
13316                    ix,
13317                    RowHighlight {
13318                        range: range.clone(),
13319                        index,
13320                        color,
13321                        should_autoscroll,
13322                    },
13323                );
13324            }
13325
13326            // If any of the following highlights intersect with this one, merge them.
13327            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13328                let highlight = &row_highlights[ix];
13329                if next_highlight
13330                    .range
13331                    .start
13332                    .cmp(&highlight.range.end, &snapshot)
13333                    .is_le()
13334                {
13335                    if next_highlight
13336                        .range
13337                        .end
13338                        .cmp(&highlight.range.end, &snapshot)
13339                        .is_gt()
13340                    {
13341                        row_highlights[ix].range.end = next_highlight.range.end;
13342                    }
13343                    row_highlights.remove(ix + 1);
13344                } else {
13345                    break;
13346                }
13347            }
13348        }
13349    }
13350
13351    /// Remove any highlighted row ranges of the given type that intersect the
13352    /// given ranges.
13353    pub fn remove_highlighted_rows<T: 'static>(
13354        &mut self,
13355        ranges_to_remove: Vec<Range<Anchor>>,
13356        cx: &mut Context<Self>,
13357    ) {
13358        let snapshot = self.buffer().read(cx).snapshot(cx);
13359        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13360        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13361        row_highlights.retain(|highlight| {
13362            while let Some(range_to_remove) = ranges_to_remove.peek() {
13363                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13364                    Ordering::Less | Ordering::Equal => {
13365                        ranges_to_remove.next();
13366                    }
13367                    Ordering::Greater => {
13368                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13369                            Ordering::Less | Ordering::Equal => {
13370                                return false;
13371                            }
13372                            Ordering::Greater => break,
13373                        }
13374                    }
13375                }
13376            }
13377
13378            true
13379        })
13380    }
13381
13382    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13383    pub fn clear_row_highlights<T: 'static>(&mut self) {
13384        self.highlighted_rows.remove(&TypeId::of::<T>());
13385    }
13386
13387    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13388    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13389        self.highlighted_rows
13390            .get(&TypeId::of::<T>())
13391            .map_or(&[] as &[_], |vec| vec.as_slice())
13392            .iter()
13393            .map(|highlight| (highlight.range.clone(), highlight.color))
13394    }
13395
13396    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13397    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13398    /// Allows to ignore certain kinds of highlights.
13399    pub fn highlighted_display_rows(
13400        &self,
13401        window: &mut Window,
13402        cx: &mut App,
13403    ) -> BTreeMap<DisplayRow, Background> {
13404        let snapshot = self.snapshot(window, cx);
13405        let mut used_highlight_orders = HashMap::default();
13406        self.highlighted_rows
13407            .iter()
13408            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13409            .fold(
13410                BTreeMap::<DisplayRow, Background>::new(),
13411                |mut unique_rows, highlight| {
13412                    let start = highlight.range.start.to_display_point(&snapshot);
13413                    let end = highlight.range.end.to_display_point(&snapshot);
13414                    let start_row = start.row().0;
13415                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13416                        && end.column() == 0
13417                    {
13418                        end.row().0.saturating_sub(1)
13419                    } else {
13420                        end.row().0
13421                    };
13422                    for row in start_row..=end_row {
13423                        let used_index =
13424                            used_highlight_orders.entry(row).or_insert(highlight.index);
13425                        if highlight.index >= *used_index {
13426                            *used_index = highlight.index;
13427                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13428                        }
13429                    }
13430                    unique_rows
13431                },
13432            )
13433    }
13434
13435    pub fn highlighted_display_row_for_autoscroll(
13436        &self,
13437        snapshot: &DisplaySnapshot,
13438    ) -> Option<DisplayRow> {
13439        self.highlighted_rows
13440            .values()
13441            .flat_map(|highlighted_rows| highlighted_rows.iter())
13442            .filter_map(|highlight| {
13443                if highlight.should_autoscroll {
13444                    Some(highlight.range.start.to_display_point(snapshot).row())
13445                } else {
13446                    None
13447                }
13448            })
13449            .min()
13450    }
13451
13452    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13453        self.highlight_background::<SearchWithinRange>(
13454            ranges,
13455            |colors| colors.editor_document_highlight_read_background,
13456            cx,
13457        )
13458    }
13459
13460    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13461        self.breadcrumb_header = Some(new_header);
13462    }
13463
13464    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13465        self.clear_background_highlights::<SearchWithinRange>(cx);
13466    }
13467
13468    pub fn highlight_background<T: 'static>(
13469        &mut self,
13470        ranges: &[Range<Anchor>],
13471        color_fetcher: fn(&ThemeColors) -> Hsla,
13472        cx: &mut Context<Self>,
13473    ) {
13474        self.background_highlights
13475            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13476        self.scrollbar_marker_state.dirty = true;
13477        cx.notify();
13478    }
13479
13480    pub fn clear_background_highlights<T: 'static>(
13481        &mut self,
13482        cx: &mut Context<Self>,
13483    ) -> Option<BackgroundHighlight> {
13484        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13485        if !text_highlights.1.is_empty() {
13486            self.scrollbar_marker_state.dirty = true;
13487            cx.notify();
13488        }
13489        Some(text_highlights)
13490    }
13491
13492    pub fn highlight_gutter<T: 'static>(
13493        &mut self,
13494        ranges: &[Range<Anchor>],
13495        color_fetcher: fn(&App) -> Hsla,
13496        cx: &mut Context<Self>,
13497    ) {
13498        self.gutter_highlights
13499            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13500        cx.notify();
13501    }
13502
13503    pub fn clear_gutter_highlights<T: 'static>(
13504        &mut self,
13505        cx: &mut Context<Self>,
13506    ) -> Option<GutterHighlight> {
13507        cx.notify();
13508        self.gutter_highlights.remove(&TypeId::of::<T>())
13509    }
13510
13511    #[cfg(feature = "test-support")]
13512    pub fn all_text_background_highlights(
13513        &self,
13514        window: &mut Window,
13515        cx: &mut Context<Self>,
13516    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13517        let snapshot = self.snapshot(window, cx);
13518        let buffer = &snapshot.buffer_snapshot;
13519        let start = buffer.anchor_before(0);
13520        let end = buffer.anchor_after(buffer.len());
13521        let theme = cx.theme().colors();
13522        self.background_highlights_in_range(start..end, &snapshot, theme)
13523    }
13524
13525    #[cfg(feature = "test-support")]
13526    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13527        let snapshot = self.buffer().read(cx).snapshot(cx);
13528
13529        let highlights = self
13530            .background_highlights
13531            .get(&TypeId::of::<items::BufferSearchHighlights>());
13532
13533        if let Some((_color, ranges)) = highlights {
13534            ranges
13535                .iter()
13536                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13537                .collect_vec()
13538        } else {
13539            vec![]
13540        }
13541    }
13542
13543    fn document_highlights_for_position<'a>(
13544        &'a self,
13545        position: Anchor,
13546        buffer: &'a MultiBufferSnapshot,
13547    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13548        let read_highlights = self
13549            .background_highlights
13550            .get(&TypeId::of::<DocumentHighlightRead>())
13551            .map(|h| &h.1);
13552        let write_highlights = self
13553            .background_highlights
13554            .get(&TypeId::of::<DocumentHighlightWrite>())
13555            .map(|h| &h.1);
13556        let left_position = position.bias_left(buffer);
13557        let right_position = position.bias_right(buffer);
13558        read_highlights
13559            .into_iter()
13560            .chain(write_highlights)
13561            .flat_map(move |ranges| {
13562                let start_ix = match ranges.binary_search_by(|probe| {
13563                    let cmp = probe.end.cmp(&left_position, buffer);
13564                    if cmp.is_ge() {
13565                        Ordering::Greater
13566                    } else {
13567                        Ordering::Less
13568                    }
13569                }) {
13570                    Ok(i) | Err(i) => i,
13571                };
13572
13573                ranges[start_ix..]
13574                    .iter()
13575                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13576            })
13577    }
13578
13579    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13580        self.background_highlights
13581            .get(&TypeId::of::<T>())
13582            .map_or(false, |(_, highlights)| !highlights.is_empty())
13583    }
13584
13585    pub fn background_highlights_in_range(
13586        &self,
13587        search_range: Range<Anchor>,
13588        display_snapshot: &DisplaySnapshot,
13589        theme: &ThemeColors,
13590    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13591        let mut results = Vec::new();
13592        for (color_fetcher, ranges) in self.background_highlights.values() {
13593            let color = color_fetcher(theme);
13594            let start_ix = match ranges.binary_search_by(|probe| {
13595                let cmp = probe
13596                    .end
13597                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13598                if cmp.is_gt() {
13599                    Ordering::Greater
13600                } else {
13601                    Ordering::Less
13602                }
13603            }) {
13604                Ok(i) | Err(i) => i,
13605            };
13606            for range in &ranges[start_ix..] {
13607                if range
13608                    .start
13609                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13610                    .is_ge()
13611                {
13612                    break;
13613                }
13614
13615                let start = range.start.to_display_point(display_snapshot);
13616                let end = range.end.to_display_point(display_snapshot);
13617                results.push((start..end, color))
13618            }
13619        }
13620        results
13621    }
13622
13623    pub fn background_highlight_row_ranges<T: 'static>(
13624        &self,
13625        search_range: Range<Anchor>,
13626        display_snapshot: &DisplaySnapshot,
13627        count: usize,
13628    ) -> Vec<RangeInclusive<DisplayPoint>> {
13629        let mut results = Vec::new();
13630        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13631            return vec![];
13632        };
13633
13634        let start_ix = match ranges.binary_search_by(|probe| {
13635            let cmp = probe
13636                .end
13637                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13638            if cmp.is_gt() {
13639                Ordering::Greater
13640            } else {
13641                Ordering::Less
13642            }
13643        }) {
13644            Ok(i) | Err(i) => i,
13645        };
13646        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13647            if let (Some(start_display), Some(end_display)) = (start, end) {
13648                results.push(
13649                    start_display.to_display_point(display_snapshot)
13650                        ..=end_display.to_display_point(display_snapshot),
13651                );
13652            }
13653        };
13654        let mut start_row: Option<Point> = None;
13655        let mut end_row: Option<Point> = None;
13656        if ranges.len() > count {
13657            return Vec::new();
13658        }
13659        for range in &ranges[start_ix..] {
13660            if range
13661                .start
13662                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13663                .is_ge()
13664            {
13665                break;
13666            }
13667            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13668            if let Some(current_row) = &end_row {
13669                if end.row == current_row.row {
13670                    continue;
13671                }
13672            }
13673            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13674            if start_row.is_none() {
13675                assert_eq!(end_row, None);
13676                start_row = Some(start);
13677                end_row = Some(end);
13678                continue;
13679            }
13680            if let Some(current_end) = end_row.as_mut() {
13681                if start.row > current_end.row + 1 {
13682                    push_region(start_row, end_row);
13683                    start_row = Some(start);
13684                    end_row = Some(end);
13685                } else {
13686                    // Merge two hunks.
13687                    *current_end = end;
13688                }
13689            } else {
13690                unreachable!();
13691            }
13692        }
13693        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13694        push_region(start_row, end_row);
13695        results
13696    }
13697
13698    pub fn gutter_highlights_in_range(
13699        &self,
13700        search_range: Range<Anchor>,
13701        display_snapshot: &DisplaySnapshot,
13702        cx: &App,
13703    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13704        let mut results = Vec::new();
13705        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13706            let color = color_fetcher(cx);
13707            let start_ix = match ranges.binary_search_by(|probe| {
13708                let cmp = probe
13709                    .end
13710                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13711                if cmp.is_gt() {
13712                    Ordering::Greater
13713                } else {
13714                    Ordering::Less
13715                }
13716            }) {
13717                Ok(i) | Err(i) => i,
13718            };
13719            for range in &ranges[start_ix..] {
13720                if range
13721                    .start
13722                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13723                    .is_ge()
13724                {
13725                    break;
13726                }
13727
13728                let start = range.start.to_display_point(display_snapshot);
13729                let end = range.end.to_display_point(display_snapshot);
13730                results.push((start..end, color))
13731            }
13732        }
13733        results
13734    }
13735
13736    /// Get the text ranges corresponding to the redaction query
13737    pub fn redacted_ranges(
13738        &self,
13739        search_range: Range<Anchor>,
13740        display_snapshot: &DisplaySnapshot,
13741        cx: &App,
13742    ) -> Vec<Range<DisplayPoint>> {
13743        display_snapshot
13744            .buffer_snapshot
13745            .redacted_ranges(search_range, |file| {
13746                if let Some(file) = file {
13747                    file.is_private()
13748                        && EditorSettings::get(
13749                            Some(SettingsLocation {
13750                                worktree_id: file.worktree_id(cx),
13751                                path: file.path().as_ref(),
13752                            }),
13753                            cx,
13754                        )
13755                        .redact_private_values
13756                } else {
13757                    false
13758                }
13759            })
13760            .map(|range| {
13761                range.start.to_display_point(display_snapshot)
13762                    ..range.end.to_display_point(display_snapshot)
13763            })
13764            .collect()
13765    }
13766
13767    pub fn highlight_text<T: 'static>(
13768        &mut self,
13769        ranges: Vec<Range<Anchor>>,
13770        style: HighlightStyle,
13771        cx: &mut Context<Self>,
13772    ) {
13773        self.display_map.update(cx, |map, _| {
13774            map.highlight_text(TypeId::of::<T>(), ranges, style)
13775        });
13776        cx.notify();
13777    }
13778
13779    pub(crate) fn highlight_inlays<T: 'static>(
13780        &mut self,
13781        highlights: Vec<InlayHighlight>,
13782        style: HighlightStyle,
13783        cx: &mut Context<Self>,
13784    ) {
13785        self.display_map.update(cx, |map, _| {
13786            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13787        });
13788        cx.notify();
13789    }
13790
13791    pub fn text_highlights<'a, T: 'static>(
13792        &'a self,
13793        cx: &'a App,
13794    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13795        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13796    }
13797
13798    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13799        let cleared = self
13800            .display_map
13801            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13802        if cleared {
13803            cx.notify();
13804        }
13805    }
13806
13807    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13808        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13809            && self.focus_handle.is_focused(window)
13810    }
13811
13812    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13813        self.show_cursor_when_unfocused = is_enabled;
13814        cx.notify();
13815    }
13816
13817    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13818        self.project
13819            .as_ref()
13820            .map(|project| project.read(cx).lsp_store())
13821    }
13822
13823    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13824        cx.notify();
13825    }
13826
13827    fn on_buffer_event(
13828        &mut self,
13829        multibuffer: &Entity<MultiBuffer>,
13830        event: &multi_buffer::Event,
13831        window: &mut Window,
13832        cx: &mut Context<Self>,
13833    ) {
13834        match event {
13835            multi_buffer::Event::Edited {
13836                singleton_buffer_edited,
13837                edited_buffer: buffer_edited,
13838            } => {
13839                self.scrollbar_marker_state.dirty = true;
13840                self.active_indent_guides_state.dirty = true;
13841                self.refresh_active_diagnostics(cx);
13842                self.refresh_code_actions(window, cx);
13843                if self.has_active_inline_completion() {
13844                    self.update_visible_inline_completion(window, cx);
13845                }
13846                if let Some(buffer) = buffer_edited {
13847                    let buffer_id = buffer.read(cx).remote_id();
13848                    if !self.registered_buffers.contains_key(&buffer_id) {
13849                        if let Some(lsp_store) = self.lsp_store(cx) {
13850                            lsp_store.update(cx, |lsp_store, cx| {
13851                                self.registered_buffers.insert(
13852                                    buffer_id,
13853                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13854                                );
13855                            })
13856                        }
13857                    }
13858                }
13859                cx.emit(EditorEvent::BufferEdited);
13860                cx.emit(SearchEvent::MatchesInvalidated);
13861                if *singleton_buffer_edited {
13862                    if let Some(project) = &self.project {
13863                        let project = project.read(cx);
13864                        #[allow(clippy::mutable_key_type)]
13865                        let languages_affected = multibuffer
13866                            .read(cx)
13867                            .all_buffers()
13868                            .into_iter()
13869                            .filter_map(|buffer| {
13870                                let buffer = buffer.read(cx);
13871                                let language = buffer.language()?;
13872                                if project.is_local()
13873                                    && project
13874                                        .language_servers_for_local_buffer(buffer, cx)
13875                                        .count()
13876                                        == 0
13877                                {
13878                                    None
13879                                } else {
13880                                    Some(language)
13881                                }
13882                            })
13883                            .cloned()
13884                            .collect::<HashSet<_>>();
13885                        if !languages_affected.is_empty() {
13886                            self.refresh_inlay_hints(
13887                                InlayHintRefreshReason::BufferEdited(languages_affected),
13888                                cx,
13889                            );
13890                        }
13891                    }
13892                }
13893
13894                let Some(project) = &self.project else { return };
13895                let (telemetry, is_via_ssh) = {
13896                    let project = project.read(cx);
13897                    let telemetry = project.client().telemetry().clone();
13898                    let is_via_ssh = project.is_via_ssh();
13899                    (telemetry, is_via_ssh)
13900                };
13901                refresh_linked_ranges(self, window, cx);
13902                telemetry.log_edit_event("editor", is_via_ssh);
13903            }
13904            multi_buffer::Event::ExcerptsAdded {
13905                buffer,
13906                predecessor,
13907                excerpts,
13908            } => {
13909                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13910                let buffer_id = buffer.read(cx).remote_id();
13911                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13912                    if let Some(project) = &self.project {
13913                        get_uncommitted_diff_for_buffer(
13914                            project,
13915                            [buffer.clone()],
13916                            self.buffer.clone(),
13917                            cx,
13918                        );
13919                    }
13920                }
13921                cx.emit(EditorEvent::ExcerptsAdded {
13922                    buffer: buffer.clone(),
13923                    predecessor: *predecessor,
13924                    excerpts: excerpts.clone(),
13925                });
13926                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13927            }
13928            multi_buffer::Event::ExcerptsRemoved { ids } => {
13929                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13930                let buffer = self.buffer.read(cx);
13931                self.registered_buffers
13932                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13933                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13934            }
13935            multi_buffer::Event::ExcerptsEdited { ids } => {
13936                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13937            }
13938            multi_buffer::Event::ExcerptsExpanded { ids } => {
13939                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13940                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13941            }
13942            multi_buffer::Event::Reparsed(buffer_id) => {
13943                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13944
13945                cx.emit(EditorEvent::Reparsed(*buffer_id));
13946            }
13947            multi_buffer::Event::DiffHunksToggled => {
13948                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13949            }
13950            multi_buffer::Event::LanguageChanged(buffer_id) => {
13951                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13952                cx.emit(EditorEvent::Reparsed(*buffer_id));
13953                cx.notify();
13954            }
13955            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13956            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13957            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13958                cx.emit(EditorEvent::TitleChanged)
13959            }
13960            // multi_buffer::Event::DiffBaseChanged => {
13961            //     self.scrollbar_marker_state.dirty = true;
13962            //     cx.emit(EditorEvent::DiffBaseChanged);
13963            //     cx.notify();
13964            // }
13965            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13966            multi_buffer::Event::DiagnosticsUpdated => {
13967                self.refresh_active_diagnostics(cx);
13968                self.scrollbar_marker_state.dirty = true;
13969                cx.notify();
13970            }
13971            _ => {}
13972        };
13973    }
13974
13975    fn on_display_map_changed(
13976        &mut self,
13977        _: Entity<DisplayMap>,
13978        _: &mut Window,
13979        cx: &mut Context<Self>,
13980    ) {
13981        cx.notify();
13982    }
13983
13984    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13985        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13986        self.refresh_inline_completion(true, false, window, cx);
13987        self.refresh_inlay_hints(
13988            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13989                self.selections.newest_anchor().head(),
13990                &self.buffer.read(cx).snapshot(cx),
13991                cx,
13992            )),
13993            cx,
13994        );
13995
13996        let old_cursor_shape = self.cursor_shape;
13997
13998        {
13999            let editor_settings = EditorSettings::get_global(cx);
14000            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14001            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14002            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14003        }
14004
14005        if old_cursor_shape != self.cursor_shape {
14006            cx.emit(EditorEvent::CursorShapeChanged);
14007        }
14008
14009        let project_settings = ProjectSettings::get_global(cx);
14010        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14011
14012        if self.mode == EditorMode::Full {
14013            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14014            if self.git_blame_inline_enabled != inline_blame_enabled {
14015                self.toggle_git_blame_inline_internal(false, window, cx);
14016            }
14017        }
14018
14019        cx.notify();
14020    }
14021
14022    pub fn set_searchable(&mut self, searchable: bool) {
14023        self.searchable = searchable;
14024    }
14025
14026    pub fn searchable(&self) -> bool {
14027        self.searchable
14028    }
14029
14030    fn open_proposed_changes_editor(
14031        &mut self,
14032        _: &OpenProposedChangesEditor,
14033        window: &mut Window,
14034        cx: &mut Context<Self>,
14035    ) {
14036        let Some(workspace) = self.workspace() else {
14037            cx.propagate();
14038            return;
14039        };
14040
14041        let selections = self.selections.all::<usize>(cx);
14042        let multi_buffer = self.buffer.read(cx);
14043        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14044        let mut new_selections_by_buffer = HashMap::default();
14045        for selection in selections {
14046            for (buffer, range, _) in
14047                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14048            {
14049                let mut range = range.to_point(buffer);
14050                range.start.column = 0;
14051                range.end.column = buffer.line_len(range.end.row);
14052                new_selections_by_buffer
14053                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14054                    .or_insert(Vec::new())
14055                    .push(range)
14056            }
14057        }
14058
14059        let proposed_changes_buffers = new_selections_by_buffer
14060            .into_iter()
14061            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14062            .collect::<Vec<_>>();
14063        let proposed_changes_editor = cx.new(|cx| {
14064            ProposedChangesEditor::new(
14065                "Proposed changes",
14066                proposed_changes_buffers,
14067                self.project.clone(),
14068                window,
14069                cx,
14070            )
14071        });
14072
14073        window.defer(cx, move |window, cx| {
14074            workspace.update(cx, |workspace, cx| {
14075                workspace.active_pane().update(cx, |pane, cx| {
14076                    pane.add_item(
14077                        Box::new(proposed_changes_editor),
14078                        true,
14079                        true,
14080                        None,
14081                        window,
14082                        cx,
14083                    );
14084                });
14085            });
14086        });
14087    }
14088
14089    pub fn open_excerpts_in_split(
14090        &mut self,
14091        _: &OpenExcerptsSplit,
14092        window: &mut Window,
14093        cx: &mut Context<Self>,
14094    ) {
14095        self.open_excerpts_common(None, true, window, cx)
14096    }
14097
14098    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14099        self.open_excerpts_common(None, false, window, cx)
14100    }
14101
14102    fn open_excerpts_common(
14103        &mut self,
14104        jump_data: Option<JumpData>,
14105        split: bool,
14106        window: &mut Window,
14107        cx: &mut Context<Self>,
14108    ) {
14109        let Some(workspace) = self.workspace() else {
14110            cx.propagate();
14111            return;
14112        };
14113
14114        if self.buffer.read(cx).is_singleton() {
14115            cx.propagate();
14116            return;
14117        }
14118
14119        let mut new_selections_by_buffer = HashMap::default();
14120        match &jump_data {
14121            Some(JumpData::MultiBufferPoint {
14122                excerpt_id,
14123                position,
14124                anchor,
14125                line_offset_from_top,
14126            }) => {
14127                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14128                if let Some(buffer) = multi_buffer_snapshot
14129                    .buffer_id_for_excerpt(*excerpt_id)
14130                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14131                {
14132                    let buffer_snapshot = buffer.read(cx).snapshot();
14133                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14134                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14135                    } else {
14136                        buffer_snapshot.clip_point(*position, Bias::Left)
14137                    };
14138                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14139                    new_selections_by_buffer.insert(
14140                        buffer,
14141                        (
14142                            vec![jump_to_offset..jump_to_offset],
14143                            Some(*line_offset_from_top),
14144                        ),
14145                    );
14146                }
14147            }
14148            Some(JumpData::MultiBufferRow {
14149                row,
14150                line_offset_from_top,
14151            }) => {
14152                let point = MultiBufferPoint::new(row.0, 0);
14153                if let Some((buffer, buffer_point, _)) =
14154                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14155                {
14156                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14157                    new_selections_by_buffer
14158                        .entry(buffer)
14159                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14160                        .0
14161                        .push(buffer_offset..buffer_offset)
14162                }
14163            }
14164            None => {
14165                let selections = self.selections.all::<usize>(cx);
14166                let multi_buffer = self.buffer.read(cx);
14167                for selection in selections {
14168                    for (buffer, mut range, _) in multi_buffer
14169                        .snapshot(cx)
14170                        .range_to_buffer_ranges(selection.range())
14171                    {
14172                        // When editing branch buffers, jump to the corresponding location
14173                        // in their base buffer.
14174                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14175                        let buffer = buffer_handle.read(cx);
14176                        if let Some(base_buffer) = buffer.base_buffer() {
14177                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14178                            buffer_handle = base_buffer;
14179                        }
14180
14181                        if selection.reversed {
14182                            mem::swap(&mut range.start, &mut range.end);
14183                        }
14184                        new_selections_by_buffer
14185                            .entry(buffer_handle)
14186                            .or_insert((Vec::new(), None))
14187                            .0
14188                            .push(range)
14189                    }
14190                }
14191            }
14192        }
14193
14194        if new_selections_by_buffer.is_empty() {
14195            return;
14196        }
14197
14198        // We defer the pane interaction because we ourselves are a workspace item
14199        // and activating a new item causes the pane to call a method on us reentrantly,
14200        // which panics if we're on the stack.
14201        window.defer(cx, move |window, cx| {
14202            workspace.update(cx, |workspace, cx| {
14203                let pane = if split {
14204                    workspace.adjacent_pane(window, cx)
14205                } else {
14206                    workspace.active_pane().clone()
14207                };
14208
14209                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14210                    let editor = buffer
14211                        .read(cx)
14212                        .file()
14213                        .is_none()
14214                        .then(|| {
14215                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14216                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14217                            // Instead, we try to activate the existing editor in the pane first.
14218                            let (editor, pane_item_index) =
14219                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14220                                    let editor = item.downcast::<Editor>()?;
14221                                    let singleton_buffer =
14222                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14223                                    if singleton_buffer == buffer {
14224                                        Some((editor, i))
14225                                    } else {
14226                                        None
14227                                    }
14228                                })?;
14229                            pane.update(cx, |pane, cx| {
14230                                pane.activate_item(pane_item_index, true, true, window, cx)
14231                            });
14232                            Some(editor)
14233                        })
14234                        .flatten()
14235                        .unwrap_or_else(|| {
14236                            workspace.open_project_item::<Self>(
14237                                pane.clone(),
14238                                buffer,
14239                                true,
14240                                true,
14241                                window,
14242                                cx,
14243                            )
14244                        });
14245
14246                    editor.update(cx, |editor, cx| {
14247                        let autoscroll = match scroll_offset {
14248                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14249                            None => Autoscroll::newest(),
14250                        };
14251                        let nav_history = editor.nav_history.take();
14252                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14253                            s.select_ranges(ranges);
14254                        });
14255                        editor.nav_history = nav_history;
14256                    });
14257                }
14258            })
14259        });
14260    }
14261
14262    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14263        let snapshot = self.buffer.read(cx).read(cx);
14264        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14265        Some(
14266            ranges
14267                .iter()
14268                .map(move |range| {
14269                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14270                })
14271                .collect(),
14272        )
14273    }
14274
14275    fn selection_replacement_ranges(
14276        &self,
14277        range: Range<OffsetUtf16>,
14278        cx: &mut App,
14279    ) -> Vec<Range<OffsetUtf16>> {
14280        let selections = self.selections.all::<OffsetUtf16>(cx);
14281        let newest_selection = selections
14282            .iter()
14283            .max_by_key(|selection| selection.id)
14284            .unwrap();
14285        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14286        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14287        let snapshot = self.buffer.read(cx).read(cx);
14288        selections
14289            .into_iter()
14290            .map(|mut selection| {
14291                selection.start.0 =
14292                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14293                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14294                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14295                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14296            })
14297            .collect()
14298    }
14299
14300    fn report_editor_event(
14301        &self,
14302        event_type: &'static str,
14303        file_extension: Option<String>,
14304        cx: &App,
14305    ) {
14306        if cfg!(any(test, feature = "test-support")) {
14307            return;
14308        }
14309
14310        let Some(project) = &self.project else { return };
14311
14312        // If None, we are in a file without an extension
14313        let file = self
14314            .buffer
14315            .read(cx)
14316            .as_singleton()
14317            .and_then(|b| b.read(cx).file());
14318        let file_extension = file_extension.or(file
14319            .as_ref()
14320            .and_then(|file| Path::new(file.file_name(cx)).extension())
14321            .and_then(|e| e.to_str())
14322            .map(|a| a.to_string()));
14323
14324        let vim_mode = cx
14325            .global::<SettingsStore>()
14326            .raw_user_settings()
14327            .get("vim_mode")
14328            == Some(&serde_json::Value::Bool(true));
14329
14330        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14331        let copilot_enabled = edit_predictions_provider
14332            == language::language_settings::EditPredictionProvider::Copilot;
14333        let copilot_enabled_for_language = self
14334            .buffer
14335            .read(cx)
14336            .settings_at(0, cx)
14337            .show_edit_predictions;
14338
14339        let project = project.read(cx);
14340        telemetry::event!(
14341            event_type,
14342            file_extension,
14343            vim_mode,
14344            copilot_enabled,
14345            copilot_enabled_for_language,
14346            edit_predictions_provider,
14347            is_via_ssh = project.is_via_ssh(),
14348        );
14349    }
14350
14351    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14352    /// with each line being an array of {text, highlight} objects.
14353    fn copy_highlight_json(
14354        &mut self,
14355        _: &CopyHighlightJson,
14356        window: &mut Window,
14357        cx: &mut Context<Self>,
14358    ) {
14359        #[derive(Serialize)]
14360        struct Chunk<'a> {
14361            text: String,
14362            highlight: Option<&'a str>,
14363        }
14364
14365        let snapshot = self.buffer.read(cx).snapshot(cx);
14366        let range = self
14367            .selected_text_range(false, window, cx)
14368            .and_then(|selection| {
14369                if selection.range.is_empty() {
14370                    None
14371                } else {
14372                    Some(selection.range)
14373                }
14374            })
14375            .unwrap_or_else(|| 0..snapshot.len());
14376
14377        let chunks = snapshot.chunks(range, true);
14378        let mut lines = Vec::new();
14379        let mut line: VecDeque<Chunk> = VecDeque::new();
14380
14381        let Some(style) = self.style.as_ref() else {
14382            return;
14383        };
14384
14385        for chunk in chunks {
14386            let highlight = chunk
14387                .syntax_highlight_id
14388                .and_then(|id| id.name(&style.syntax));
14389            let mut chunk_lines = chunk.text.split('\n').peekable();
14390            while let Some(text) = chunk_lines.next() {
14391                let mut merged_with_last_token = false;
14392                if let Some(last_token) = line.back_mut() {
14393                    if last_token.highlight == highlight {
14394                        last_token.text.push_str(text);
14395                        merged_with_last_token = true;
14396                    }
14397                }
14398
14399                if !merged_with_last_token {
14400                    line.push_back(Chunk {
14401                        text: text.into(),
14402                        highlight,
14403                    });
14404                }
14405
14406                if chunk_lines.peek().is_some() {
14407                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14408                        line.pop_front();
14409                    }
14410                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14411                        line.pop_back();
14412                    }
14413
14414                    lines.push(mem::take(&mut line));
14415                }
14416            }
14417        }
14418
14419        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14420            return;
14421        };
14422        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14423    }
14424
14425    pub fn open_context_menu(
14426        &mut self,
14427        _: &OpenContextMenu,
14428        window: &mut Window,
14429        cx: &mut Context<Self>,
14430    ) {
14431        self.request_autoscroll(Autoscroll::newest(), cx);
14432        let position = self.selections.newest_display(cx).start;
14433        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14434    }
14435
14436    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14437        &self.inlay_hint_cache
14438    }
14439
14440    pub fn replay_insert_event(
14441        &mut self,
14442        text: &str,
14443        relative_utf16_range: Option<Range<isize>>,
14444        window: &mut Window,
14445        cx: &mut Context<Self>,
14446    ) {
14447        if !self.input_enabled {
14448            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14449            return;
14450        }
14451        if let Some(relative_utf16_range) = relative_utf16_range {
14452            let selections = self.selections.all::<OffsetUtf16>(cx);
14453            self.change_selections(None, window, cx, |s| {
14454                let new_ranges = selections.into_iter().map(|range| {
14455                    let start = OffsetUtf16(
14456                        range
14457                            .head()
14458                            .0
14459                            .saturating_add_signed(relative_utf16_range.start),
14460                    );
14461                    let end = OffsetUtf16(
14462                        range
14463                            .head()
14464                            .0
14465                            .saturating_add_signed(relative_utf16_range.end),
14466                    );
14467                    start..end
14468                });
14469                s.select_ranges(new_ranges);
14470            });
14471        }
14472
14473        self.handle_input(text, window, cx);
14474    }
14475
14476    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14477        let Some(provider) = self.semantics_provider.as_ref() else {
14478            return false;
14479        };
14480
14481        let mut supports = false;
14482        self.buffer().read(cx).for_each_buffer(|buffer| {
14483            supports |= provider.supports_inlay_hints(buffer, cx);
14484        });
14485        supports
14486    }
14487
14488    pub fn is_focused(&self, window: &Window) -> bool {
14489        self.focus_handle.is_focused(window)
14490    }
14491
14492    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14493        cx.emit(EditorEvent::Focused);
14494
14495        if let Some(descendant) = self
14496            .last_focused_descendant
14497            .take()
14498            .and_then(|descendant| descendant.upgrade())
14499        {
14500            window.focus(&descendant);
14501        } else {
14502            if let Some(blame) = self.blame.as_ref() {
14503                blame.update(cx, GitBlame::focus)
14504            }
14505
14506            self.blink_manager.update(cx, BlinkManager::enable);
14507            self.show_cursor_names(window, cx);
14508            self.buffer.update(cx, |buffer, cx| {
14509                buffer.finalize_last_transaction(cx);
14510                if self.leader_peer_id.is_none() {
14511                    buffer.set_active_selections(
14512                        &self.selections.disjoint_anchors(),
14513                        self.selections.line_mode,
14514                        self.cursor_shape,
14515                        cx,
14516                    );
14517                }
14518            });
14519        }
14520    }
14521
14522    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14523        cx.emit(EditorEvent::FocusedIn)
14524    }
14525
14526    fn handle_focus_out(
14527        &mut self,
14528        event: FocusOutEvent,
14529        _window: &mut Window,
14530        _cx: &mut Context<Self>,
14531    ) {
14532        if event.blurred != self.focus_handle {
14533            self.last_focused_descendant = Some(event.blurred);
14534        }
14535    }
14536
14537    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14538        self.blink_manager.update(cx, BlinkManager::disable);
14539        self.buffer
14540            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14541
14542        if let Some(blame) = self.blame.as_ref() {
14543            blame.update(cx, GitBlame::blur)
14544        }
14545        if !self.hover_state.focused(window, cx) {
14546            hide_hover(self, cx);
14547        }
14548
14549        self.hide_context_menu(window, cx);
14550        cx.emit(EditorEvent::Blurred);
14551        cx.notify();
14552    }
14553
14554    pub fn register_action<A: Action>(
14555        &mut self,
14556        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14557    ) -> Subscription {
14558        let id = self.next_editor_action_id.post_inc();
14559        let listener = Arc::new(listener);
14560        self.editor_actions.borrow_mut().insert(
14561            id,
14562            Box::new(move |window, _| {
14563                let listener = listener.clone();
14564                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14565                    let action = action.downcast_ref().unwrap();
14566                    if phase == DispatchPhase::Bubble {
14567                        listener(action, window, cx)
14568                    }
14569                })
14570            }),
14571        );
14572
14573        let editor_actions = self.editor_actions.clone();
14574        Subscription::new(move || {
14575            editor_actions.borrow_mut().remove(&id);
14576        })
14577    }
14578
14579    pub fn file_header_size(&self) -> u32 {
14580        FILE_HEADER_HEIGHT
14581    }
14582
14583    pub fn revert(
14584        &mut self,
14585        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14586        window: &mut Window,
14587        cx: &mut Context<Self>,
14588    ) {
14589        self.buffer().update(cx, |multi_buffer, cx| {
14590            for (buffer_id, changes) in revert_changes {
14591                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14592                    buffer.update(cx, |buffer, cx| {
14593                        buffer.edit(
14594                            changes.into_iter().map(|(range, text)| {
14595                                (range, text.to_string().map(Arc::<str>::from))
14596                            }),
14597                            None,
14598                            cx,
14599                        );
14600                    });
14601                }
14602            }
14603        });
14604        self.change_selections(None, window, cx, |selections| selections.refresh());
14605    }
14606
14607    pub fn to_pixel_point(
14608        &self,
14609        source: multi_buffer::Anchor,
14610        editor_snapshot: &EditorSnapshot,
14611        window: &mut Window,
14612    ) -> Option<gpui::Point<Pixels>> {
14613        let source_point = source.to_display_point(editor_snapshot);
14614        self.display_to_pixel_point(source_point, editor_snapshot, window)
14615    }
14616
14617    pub fn display_to_pixel_point(
14618        &self,
14619        source: DisplayPoint,
14620        editor_snapshot: &EditorSnapshot,
14621        window: &mut Window,
14622    ) -> Option<gpui::Point<Pixels>> {
14623        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14624        let text_layout_details = self.text_layout_details(window);
14625        let scroll_top = text_layout_details
14626            .scroll_anchor
14627            .scroll_position(editor_snapshot)
14628            .y;
14629
14630        if source.row().as_f32() < scroll_top.floor() {
14631            return None;
14632        }
14633        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14634        let source_y = line_height * (source.row().as_f32() - scroll_top);
14635        Some(gpui::Point::new(source_x, source_y))
14636    }
14637
14638    pub fn has_visible_completions_menu(&self) -> bool {
14639        !self.edit_prediction_preview_is_active()
14640            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14641                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14642            })
14643    }
14644
14645    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14646        self.addons
14647            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14648    }
14649
14650    pub fn unregister_addon<T: Addon>(&mut self) {
14651        self.addons.remove(&std::any::TypeId::of::<T>());
14652    }
14653
14654    pub fn addon<T: Addon>(&self) -> Option<&T> {
14655        let type_id = std::any::TypeId::of::<T>();
14656        self.addons
14657            .get(&type_id)
14658            .and_then(|item| item.to_any().downcast_ref::<T>())
14659    }
14660
14661    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14662        let text_layout_details = self.text_layout_details(window);
14663        let style = &text_layout_details.editor_style;
14664        let font_id = window.text_system().resolve_font(&style.text.font());
14665        let font_size = style.text.font_size.to_pixels(window.rem_size());
14666        let line_height = style.text.line_height_in_pixels(window.rem_size());
14667        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14668
14669        gpui::Size::new(em_width, line_height)
14670    }
14671}
14672
14673fn get_uncommitted_diff_for_buffer(
14674    project: &Entity<Project>,
14675    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14676    buffer: Entity<MultiBuffer>,
14677    cx: &mut App,
14678) {
14679    let mut tasks = Vec::new();
14680    project.update(cx, |project, cx| {
14681        for buffer in buffers {
14682            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14683        }
14684    });
14685    cx.spawn(|mut cx| async move {
14686        let diffs = futures::future::join_all(tasks).await;
14687        buffer
14688            .update(&mut cx, |buffer, cx| {
14689                for diff in diffs.into_iter().flatten() {
14690                    buffer.add_diff(diff, cx);
14691                }
14692            })
14693            .ok();
14694    })
14695    .detach();
14696}
14697
14698fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14699    let tab_size = tab_size.get() as usize;
14700    let mut width = offset;
14701
14702    for ch in text.chars() {
14703        width += if ch == '\t' {
14704            tab_size - (width % tab_size)
14705        } else {
14706            1
14707        };
14708    }
14709
14710    width - offset
14711}
14712
14713#[cfg(test)]
14714mod tests {
14715    use super::*;
14716
14717    #[test]
14718    fn test_string_size_with_expanded_tabs() {
14719        let nz = |val| NonZeroU32::new(val).unwrap();
14720        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14721        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14722        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14723        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14724        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14725        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14726        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14727        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14728    }
14729}
14730
14731/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14732struct WordBreakingTokenizer<'a> {
14733    input: &'a str,
14734}
14735
14736impl<'a> WordBreakingTokenizer<'a> {
14737    fn new(input: &'a str) -> Self {
14738        Self { input }
14739    }
14740}
14741
14742fn is_char_ideographic(ch: char) -> bool {
14743    use unicode_script::Script::*;
14744    use unicode_script::UnicodeScript;
14745    matches!(ch.script(), Han | Tangut | Yi)
14746}
14747
14748fn is_grapheme_ideographic(text: &str) -> bool {
14749    text.chars().any(is_char_ideographic)
14750}
14751
14752fn is_grapheme_whitespace(text: &str) -> bool {
14753    text.chars().any(|x| x.is_whitespace())
14754}
14755
14756fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14757    text.chars().next().map_or(false, |ch| {
14758        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14759    })
14760}
14761
14762#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14763struct WordBreakToken<'a> {
14764    token: &'a str,
14765    grapheme_len: usize,
14766    is_whitespace: bool,
14767}
14768
14769impl<'a> Iterator for WordBreakingTokenizer<'a> {
14770    /// Yields a span, the count of graphemes in the token, and whether it was
14771    /// whitespace. Note that it also breaks at word boundaries.
14772    type Item = WordBreakToken<'a>;
14773
14774    fn next(&mut self) -> Option<Self::Item> {
14775        use unicode_segmentation::UnicodeSegmentation;
14776        if self.input.is_empty() {
14777            return None;
14778        }
14779
14780        let mut iter = self.input.graphemes(true).peekable();
14781        let mut offset = 0;
14782        let mut graphemes = 0;
14783        if let Some(first_grapheme) = iter.next() {
14784            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14785            offset += first_grapheme.len();
14786            graphemes += 1;
14787            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14788                if let Some(grapheme) = iter.peek().copied() {
14789                    if should_stay_with_preceding_ideograph(grapheme) {
14790                        offset += grapheme.len();
14791                        graphemes += 1;
14792                    }
14793                }
14794            } else {
14795                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14796                let mut next_word_bound = words.peek().copied();
14797                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14798                    next_word_bound = words.next();
14799                }
14800                while let Some(grapheme) = iter.peek().copied() {
14801                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14802                        break;
14803                    };
14804                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14805                        break;
14806                    };
14807                    offset += grapheme.len();
14808                    graphemes += 1;
14809                    iter.next();
14810                }
14811            }
14812            let token = &self.input[..offset];
14813            self.input = &self.input[offset..];
14814            if is_whitespace {
14815                Some(WordBreakToken {
14816                    token: " ",
14817                    grapheme_len: 1,
14818                    is_whitespace: true,
14819                })
14820            } else {
14821                Some(WordBreakToken {
14822                    token,
14823                    grapheme_len: graphemes,
14824                    is_whitespace: false,
14825                })
14826            }
14827        } else {
14828            None
14829        }
14830    }
14831}
14832
14833#[test]
14834fn test_word_breaking_tokenizer() {
14835    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14836        ("", &[]),
14837        ("  ", &[(" ", 1, true)]),
14838        ("Ʒ", &[("Ʒ", 1, false)]),
14839        ("Ǽ", &[("Ǽ", 1, false)]),
14840        ("", &[("", 1, false)]),
14841        ("⋑⋑", &[("⋑⋑", 2, false)]),
14842        (
14843            "原理,进而",
14844            &[
14845                ("", 1, false),
14846                ("理,", 2, false),
14847                ("", 1, false),
14848                ("", 1, false),
14849            ],
14850        ),
14851        (
14852            "hello world",
14853            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14854        ),
14855        (
14856            "hello, world",
14857            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14858        ),
14859        (
14860            "  hello world",
14861            &[
14862                (" ", 1, true),
14863                ("hello", 5, false),
14864                (" ", 1, true),
14865                ("world", 5, false),
14866            ],
14867        ),
14868        (
14869            "这是什么 \n 钢笔",
14870            &[
14871                ("", 1, false),
14872                ("", 1, false),
14873                ("", 1, false),
14874                ("", 1, false),
14875                (" ", 1, true),
14876                ("", 1, false),
14877                ("", 1, false),
14878            ],
14879        ),
14880        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14881    ];
14882
14883    for (input, result) in tests {
14884        assert_eq!(
14885            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14886            result
14887                .iter()
14888                .copied()
14889                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14890                    token,
14891                    grapheme_len,
14892                    is_whitespace,
14893                })
14894                .collect::<Vec<_>>()
14895        );
14896    }
14897}
14898
14899fn wrap_with_prefix(
14900    line_prefix: String,
14901    unwrapped_text: String,
14902    wrap_column: usize,
14903    tab_size: NonZeroU32,
14904) -> String {
14905    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14906    let mut wrapped_text = String::new();
14907    let mut current_line = line_prefix.clone();
14908
14909    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14910    let mut current_line_len = line_prefix_len;
14911    for WordBreakToken {
14912        token,
14913        grapheme_len,
14914        is_whitespace,
14915    } in tokenizer
14916    {
14917        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14918            wrapped_text.push_str(current_line.trim_end());
14919            wrapped_text.push('\n');
14920            current_line.truncate(line_prefix.len());
14921            current_line_len = line_prefix_len;
14922            if !is_whitespace {
14923                current_line.push_str(token);
14924                current_line_len += grapheme_len;
14925            }
14926        } else if !is_whitespace {
14927            current_line.push_str(token);
14928            current_line_len += grapheme_len;
14929        } else if current_line_len != line_prefix_len {
14930            current_line.push(' ');
14931            current_line_len += 1;
14932        }
14933    }
14934
14935    if !current_line.is_empty() {
14936        wrapped_text.push_str(&current_line);
14937    }
14938    wrapped_text
14939}
14940
14941#[test]
14942fn test_wrap_with_prefix() {
14943    assert_eq!(
14944        wrap_with_prefix(
14945            "# ".to_string(),
14946            "abcdefg".to_string(),
14947            4,
14948            NonZeroU32::new(4).unwrap()
14949        ),
14950        "# abcdefg"
14951    );
14952    assert_eq!(
14953        wrap_with_prefix(
14954            "".to_string(),
14955            "\thello world".to_string(),
14956            8,
14957            NonZeroU32::new(4).unwrap()
14958        ),
14959        "hello\nworld"
14960    );
14961    assert_eq!(
14962        wrap_with_prefix(
14963            "// ".to_string(),
14964            "xx \nyy zz aa bb cc".to_string(),
14965            12,
14966            NonZeroU32::new(4).unwrap()
14967        ),
14968        "// xx yy zz\n// aa bb cc"
14969    );
14970    assert_eq!(
14971        wrap_with_prefix(
14972            String::new(),
14973            "这是什么 \n 钢笔".to_string(),
14974            3,
14975            NonZeroU32::new(4).unwrap()
14976        ),
14977        "这是什\n么 钢\n"
14978    );
14979}
14980
14981pub trait CollaborationHub {
14982    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14983    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14984    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14985}
14986
14987impl CollaborationHub for Entity<Project> {
14988    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14989        self.read(cx).collaborators()
14990    }
14991
14992    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14993        self.read(cx).user_store().read(cx).participant_indices()
14994    }
14995
14996    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14997        let this = self.read(cx);
14998        let user_ids = this.collaborators().values().map(|c| c.user_id);
14999        this.user_store().read_with(cx, |user_store, cx| {
15000            user_store.participant_names(user_ids, cx)
15001        })
15002    }
15003}
15004
15005pub trait SemanticsProvider {
15006    fn hover(
15007        &self,
15008        buffer: &Entity<Buffer>,
15009        position: text::Anchor,
15010        cx: &mut App,
15011    ) -> Option<Task<Vec<project::Hover>>>;
15012
15013    fn inlay_hints(
15014        &self,
15015        buffer_handle: Entity<Buffer>,
15016        range: Range<text::Anchor>,
15017        cx: &mut App,
15018    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15019
15020    fn resolve_inlay_hint(
15021        &self,
15022        hint: InlayHint,
15023        buffer_handle: Entity<Buffer>,
15024        server_id: LanguageServerId,
15025        cx: &mut App,
15026    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15027
15028    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15029
15030    fn document_highlights(
15031        &self,
15032        buffer: &Entity<Buffer>,
15033        position: text::Anchor,
15034        cx: &mut App,
15035    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15036
15037    fn definitions(
15038        &self,
15039        buffer: &Entity<Buffer>,
15040        position: text::Anchor,
15041        kind: GotoDefinitionKind,
15042        cx: &mut App,
15043    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15044
15045    fn range_for_rename(
15046        &self,
15047        buffer: &Entity<Buffer>,
15048        position: text::Anchor,
15049        cx: &mut App,
15050    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15051
15052    fn perform_rename(
15053        &self,
15054        buffer: &Entity<Buffer>,
15055        position: text::Anchor,
15056        new_name: String,
15057        cx: &mut App,
15058    ) -> Option<Task<Result<ProjectTransaction>>>;
15059}
15060
15061pub trait CompletionProvider {
15062    fn completions(
15063        &self,
15064        buffer: &Entity<Buffer>,
15065        buffer_position: text::Anchor,
15066        trigger: CompletionContext,
15067        window: &mut Window,
15068        cx: &mut Context<Editor>,
15069    ) -> Task<Result<Vec<Completion>>>;
15070
15071    fn resolve_completions(
15072        &self,
15073        buffer: Entity<Buffer>,
15074        completion_indices: Vec<usize>,
15075        completions: Rc<RefCell<Box<[Completion]>>>,
15076        cx: &mut Context<Editor>,
15077    ) -> Task<Result<bool>>;
15078
15079    fn apply_additional_edits_for_completion(
15080        &self,
15081        _buffer: Entity<Buffer>,
15082        _completions: Rc<RefCell<Box<[Completion]>>>,
15083        _completion_index: usize,
15084        _push_to_history: bool,
15085        _cx: &mut Context<Editor>,
15086    ) -> Task<Result<Option<language::Transaction>>> {
15087        Task::ready(Ok(None))
15088    }
15089
15090    fn is_completion_trigger(
15091        &self,
15092        buffer: &Entity<Buffer>,
15093        position: language::Anchor,
15094        text: &str,
15095        trigger_in_words: bool,
15096        cx: &mut Context<Editor>,
15097    ) -> bool;
15098
15099    fn sort_completions(&self) -> bool {
15100        true
15101    }
15102}
15103
15104pub trait CodeActionProvider {
15105    fn id(&self) -> Arc<str>;
15106
15107    fn code_actions(
15108        &self,
15109        buffer: &Entity<Buffer>,
15110        range: Range<text::Anchor>,
15111        window: &mut Window,
15112        cx: &mut App,
15113    ) -> Task<Result<Vec<CodeAction>>>;
15114
15115    fn apply_code_action(
15116        &self,
15117        buffer_handle: Entity<Buffer>,
15118        action: CodeAction,
15119        excerpt_id: ExcerptId,
15120        push_to_history: bool,
15121        window: &mut Window,
15122        cx: &mut App,
15123    ) -> Task<Result<ProjectTransaction>>;
15124}
15125
15126impl CodeActionProvider for Entity<Project> {
15127    fn id(&self) -> Arc<str> {
15128        "project".into()
15129    }
15130
15131    fn code_actions(
15132        &self,
15133        buffer: &Entity<Buffer>,
15134        range: Range<text::Anchor>,
15135        _window: &mut Window,
15136        cx: &mut App,
15137    ) -> Task<Result<Vec<CodeAction>>> {
15138        self.update(cx, |project, cx| {
15139            project.code_actions(buffer, range, None, cx)
15140        })
15141    }
15142
15143    fn apply_code_action(
15144        &self,
15145        buffer_handle: Entity<Buffer>,
15146        action: CodeAction,
15147        _excerpt_id: ExcerptId,
15148        push_to_history: bool,
15149        _window: &mut Window,
15150        cx: &mut App,
15151    ) -> Task<Result<ProjectTransaction>> {
15152        self.update(cx, |project, cx| {
15153            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15154        })
15155    }
15156}
15157
15158fn snippet_completions(
15159    project: &Project,
15160    buffer: &Entity<Buffer>,
15161    buffer_position: text::Anchor,
15162    cx: &mut App,
15163) -> Task<Result<Vec<Completion>>> {
15164    let language = buffer.read(cx).language_at(buffer_position);
15165    let language_name = language.as_ref().map(|language| language.lsp_id());
15166    let snippet_store = project.snippets().read(cx);
15167    let snippets = snippet_store.snippets_for(language_name, cx);
15168
15169    if snippets.is_empty() {
15170        return Task::ready(Ok(vec![]));
15171    }
15172    let snapshot = buffer.read(cx).text_snapshot();
15173    let chars: String = snapshot
15174        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15175        .collect();
15176
15177    let scope = language.map(|language| language.default_scope());
15178    let executor = cx.background_executor().clone();
15179
15180    cx.background_executor().spawn(async move {
15181        let classifier = CharClassifier::new(scope).for_completion(true);
15182        let mut last_word = chars
15183            .chars()
15184            .take_while(|c| classifier.is_word(*c))
15185            .collect::<String>();
15186        last_word = last_word.chars().rev().collect();
15187
15188        if last_word.is_empty() {
15189            return Ok(vec![]);
15190        }
15191
15192        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15193        let to_lsp = |point: &text::Anchor| {
15194            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15195            point_to_lsp(end)
15196        };
15197        let lsp_end = to_lsp(&buffer_position);
15198
15199        let candidates = snippets
15200            .iter()
15201            .enumerate()
15202            .flat_map(|(ix, snippet)| {
15203                snippet
15204                    .prefix
15205                    .iter()
15206                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15207            })
15208            .collect::<Vec<StringMatchCandidate>>();
15209
15210        let mut matches = fuzzy::match_strings(
15211            &candidates,
15212            &last_word,
15213            last_word.chars().any(|c| c.is_uppercase()),
15214            100,
15215            &Default::default(),
15216            executor,
15217        )
15218        .await;
15219
15220        // Remove all candidates where the query's start does not match the start of any word in the candidate
15221        if let Some(query_start) = last_word.chars().next() {
15222            matches.retain(|string_match| {
15223                split_words(&string_match.string).any(|word| {
15224                    // Check that the first codepoint of the word as lowercase matches the first
15225                    // codepoint of the query as lowercase
15226                    word.chars()
15227                        .flat_map(|codepoint| codepoint.to_lowercase())
15228                        .zip(query_start.to_lowercase())
15229                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15230                })
15231            });
15232        }
15233
15234        let matched_strings = matches
15235            .into_iter()
15236            .map(|m| m.string)
15237            .collect::<HashSet<_>>();
15238
15239        let result: Vec<Completion> = snippets
15240            .into_iter()
15241            .filter_map(|snippet| {
15242                let matching_prefix = snippet
15243                    .prefix
15244                    .iter()
15245                    .find(|prefix| matched_strings.contains(*prefix))?;
15246                let start = as_offset - last_word.len();
15247                let start = snapshot.anchor_before(start);
15248                let range = start..buffer_position;
15249                let lsp_start = to_lsp(&start);
15250                let lsp_range = lsp::Range {
15251                    start: lsp_start,
15252                    end: lsp_end,
15253                };
15254                Some(Completion {
15255                    old_range: range,
15256                    new_text: snippet.body.clone(),
15257                    resolved: false,
15258                    label: CodeLabel {
15259                        text: matching_prefix.clone(),
15260                        runs: vec![],
15261                        filter_range: 0..matching_prefix.len(),
15262                    },
15263                    server_id: LanguageServerId(usize::MAX),
15264                    documentation: snippet
15265                        .description
15266                        .clone()
15267                        .map(CompletionDocumentation::SingleLine),
15268                    lsp_completion: lsp::CompletionItem {
15269                        label: snippet.prefix.first().unwrap().clone(),
15270                        kind: Some(CompletionItemKind::SNIPPET),
15271                        label_details: snippet.description.as_ref().map(|description| {
15272                            lsp::CompletionItemLabelDetails {
15273                                detail: Some(description.clone()),
15274                                description: None,
15275                            }
15276                        }),
15277                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15278                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15279                            lsp::InsertReplaceEdit {
15280                                new_text: snippet.body.clone(),
15281                                insert: lsp_range,
15282                                replace: lsp_range,
15283                            },
15284                        )),
15285                        filter_text: Some(snippet.body.clone()),
15286                        sort_text: Some(char::MAX.to_string()),
15287                        ..Default::default()
15288                    },
15289                    confirm: None,
15290                })
15291            })
15292            .collect();
15293
15294        Ok(result)
15295    })
15296}
15297
15298impl CompletionProvider for Entity<Project> {
15299    fn completions(
15300        &self,
15301        buffer: &Entity<Buffer>,
15302        buffer_position: text::Anchor,
15303        options: CompletionContext,
15304        _window: &mut Window,
15305        cx: &mut Context<Editor>,
15306    ) -> Task<Result<Vec<Completion>>> {
15307        self.update(cx, |project, cx| {
15308            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15309            let project_completions = project.completions(buffer, buffer_position, options, cx);
15310            cx.background_executor().spawn(async move {
15311                let mut completions = project_completions.await?;
15312                let snippets_completions = snippets.await?;
15313                completions.extend(snippets_completions);
15314                Ok(completions)
15315            })
15316        })
15317    }
15318
15319    fn resolve_completions(
15320        &self,
15321        buffer: Entity<Buffer>,
15322        completion_indices: Vec<usize>,
15323        completions: Rc<RefCell<Box<[Completion]>>>,
15324        cx: &mut Context<Editor>,
15325    ) -> Task<Result<bool>> {
15326        self.update(cx, |project, cx| {
15327            project.lsp_store().update(cx, |lsp_store, cx| {
15328                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15329            })
15330        })
15331    }
15332
15333    fn apply_additional_edits_for_completion(
15334        &self,
15335        buffer: Entity<Buffer>,
15336        completions: Rc<RefCell<Box<[Completion]>>>,
15337        completion_index: usize,
15338        push_to_history: bool,
15339        cx: &mut Context<Editor>,
15340    ) -> Task<Result<Option<language::Transaction>>> {
15341        self.update(cx, |project, cx| {
15342            project.lsp_store().update(cx, |lsp_store, cx| {
15343                lsp_store.apply_additional_edits_for_completion(
15344                    buffer,
15345                    completions,
15346                    completion_index,
15347                    push_to_history,
15348                    cx,
15349                )
15350            })
15351        })
15352    }
15353
15354    fn is_completion_trigger(
15355        &self,
15356        buffer: &Entity<Buffer>,
15357        position: language::Anchor,
15358        text: &str,
15359        trigger_in_words: bool,
15360        cx: &mut Context<Editor>,
15361    ) -> bool {
15362        let mut chars = text.chars();
15363        let char = if let Some(char) = chars.next() {
15364            char
15365        } else {
15366            return false;
15367        };
15368        if chars.next().is_some() {
15369            return false;
15370        }
15371
15372        let buffer = buffer.read(cx);
15373        let snapshot = buffer.snapshot();
15374        if !snapshot.settings_at(position, cx).show_completions_on_input {
15375            return false;
15376        }
15377        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15378        if trigger_in_words && classifier.is_word(char) {
15379            return true;
15380        }
15381
15382        buffer.completion_triggers().contains(text)
15383    }
15384}
15385
15386impl SemanticsProvider for Entity<Project> {
15387    fn hover(
15388        &self,
15389        buffer: &Entity<Buffer>,
15390        position: text::Anchor,
15391        cx: &mut App,
15392    ) -> Option<Task<Vec<project::Hover>>> {
15393        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15394    }
15395
15396    fn document_highlights(
15397        &self,
15398        buffer: &Entity<Buffer>,
15399        position: text::Anchor,
15400        cx: &mut App,
15401    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15402        Some(self.update(cx, |project, cx| {
15403            project.document_highlights(buffer, position, cx)
15404        }))
15405    }
15406
15407    fn definitions(
15408        &self,
15409        buffer: &Entity<Buffer>,
15410        position: text::Anchor,
15411        kind: GotoDefinitionKind,
15412        cx: &mut App,
15413    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15414        Some(self.update(cx, |project, cx| match kind {
15415            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15416            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15417            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15418            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15419        }))
15420    }
15421
15422    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15423        // TODO: make this work for remote projects
15424        self.read(cx)
15425            .language_servers_for_local_buffer(buffer.read(cx), cx)
15426            .any(
15427                |(_, server)| match server.capabilities().inlay_hint_provider {
15428                    Some(lsp::OneOf::Left(enabled)) => enabled,
15429                    Some(lsp::OneOf::Right(_)) => true,
15430                    None => false,
15431                },
15432            )
15433    }
15434
15435    fn inlay_hints(
15436        &self,
15437        buffer_handle: Entity<Buffer>,
15438        range: Range<text::Anchor>,
15439        cx: &mut App,
15440    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15441        Some(self.update(cx, |project, cx| {
15442            project.inlay_hints(buffer_handle, range, cx)
15443        }))
15444    }
15445
15446    fn resolve_inlay_hint(
15447        &self,
15448        hint: InlayHint,
15449        buffer_handle: Entity<Buffer>,
15450        server_id: LanguageServerId,
15451        cx: &mut App,
15452    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15453        Some(self.update(cx, |project, cx| {
15454            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15455        }))
15456    }
15457
15458    fn range_for_rename(
15459        &self,
15460        buffer: &Entity<Buffer>,
15461        position: text::Anchor,
15462        cx: &mut App,
15463    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15464        Some(self.update(cx, |project, cx| {
15465            let buffer = buffer.clone();
15466            let task = project.prepare_rename(buffer.clone(), position, cx);
15467            cx.spawn(|_, mut cx| async move {
15468                Ok(match task.await? {
15469                    PrepareRenameResponse::Success(range) => Some(range),
15470                    PrepareRenameResponse::InvalidPosition => None,
15471                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15472                        // Fallback on using TreeSitter info to determine identifier range
15473                        buffer.update(&mut cx, |buffer, _| {
15474                            let snapshot = buffer.snapshot();
15475                            let (range, kind) = snapshot.surrounding_word(position);
15476                            if kind != Some(CharKind::Word) {
15477                                return None;
15478                            }
15479                            Some(
15480                                snapshot.anchor_before(range.start)
15481                                    ..snapshot.anchor_after(range.end),
15482                            )
15483                        })?
15484                    }
15485                })
15486            })
15487        }))
15488    }
15489
15490    fn perform_rename(
15491        &self,
15492        buffer: &Entity<Buffer>,
15493        position: text::Anchor,
15494        new_name: String,
15495        cx: &mut App,
15496    ) -> Option<Task<Result<ProjectTransaction>>> {
15497        Some(self.update(cx, |project, cx| {
15498            project.perform_rename(buffer.clone(), position, new_name, cx)
15499        }))
15500    }
15501}
15502
15503fn inlay_hint_settings(
15504    location: Anchor,
15505    snapshot: &MultiBufferSnapshot,
15506    cx: &mut Context<Editor>,
15507) -> InlayHintSettings {
15508    let file = snapshot.file_at(location);
15509    let language = snapshot.language_at(location).map(|l| l.name());
15510    language_settings(language, file, cx).inlay_hints
15511}
15512
15513fn consume_contiguous_rows(
15514    contiguous_row_selections: &mut Vec<Selection<Point>>,
15515    selection: &Selection<Point>,
15516    display_map: &DisplaySnapshot,
15517    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15518) -> (MultiBufferRow, MultiBufferRow) {
15519    contiguous_row_selections.push(selection.clone());
15520    let start_row = MultiBufferRow(selection.start.row);
15521    let mut end_row = ending_row(selection, display_map);
15522
15523    while let Some(next_selection) = selections.peek() {
15524        if next_selection.start.row <= end_row.0 {
15525            end_row = ending_row(next_selection, display_map);
15526            contiguous_row_selections.push(selections.next().unwrap().clone());
15527        } else {
15528            break;
15529        }
15530    }
15531    (start_row, end_row)
15532}
15533
15534fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15535    if next_selection.end.column > 0 || next_selection.is_empty() {
15536        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15537    } else {
15538        MultiBufferRow(next_selection.end.row)
15539    }
15540}
15541
15542impl EditorSnapshot {
15543    pub fn remote_selections_in_range<'a>(
15544        &'a self,
15545        range: &'a Range<Anchor>,
15546        collaboration_hub: &dyn CollaborationHub,
15547        cx: &'a App,
15548    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15549        let participant_names = collaboration_hub.user_names(cx);
15550        let participant_indices = collaboration_hub.user_participant_indices(cx);
15551        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15552        let collaborators_by_replica_id = collaborators_by_peer_id
15553            .iter()
15554            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15555            .collect::<HashMap<_, _>>();
15556        self.buffer_snapshot
15557            .selections_in_range(range, false)
15558            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15559                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15560                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15561                let user_name = participant_names.get(&collaborator.user_id).cloned();
15562                Some(RemoteSelection {
15563                    replica_id,
15564                    selection,
15565                    cursor_shape,
15566                    line_mode,
15567                    participant_index,
15568                    peer_id: collaborator.peer_id,
15569                    user_name,
15570                })
15571            })
15572    }
15573
15574    pub fn hunks_for_ranges(
15575        &self,
15576        ranges: impl Iterator<Item = Range<Point>>,
15577    ) -> Vec<MultiBufferDiffHunk> {
15578        let mut hunks = Vec::new();
15579        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15580            HashMap::default();
15581        for query_range in ranges {
15582            let query_rows =
15583                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15584            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15585                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15586            ) {
15587                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15588                // when the caret is just above or just below the deleted hunk.
15589                let allow_adjacent = hunk.status().is_removed();
15590                let related_to_selection = if allow_adjacent {
15591                    hunk.row_range.overlaps(&query_rows)
15592                        || hunk.row_range.start == query_rows.end
15593                        || hunk.row_range.end == query_rows.start
15594                } else {
15595                    hunk.row_range.overlaps(&query_rows)
15596                };
15597                if related_to_selection {
15598                    if !processed_buffer_rows
15599                        .entry(hunk.buffer_id)
15600                        .or_default()
15601                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15602                    {
15603                        continue;
15604                    }
15605                    hunks.push(hunk);
15606                }
15607            }
15608        }
15609
15610        hunks
15611    }
15612
15613    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15614        self.display_snapshot.buffer_snapshot.language_at(position)
15615    }
15616
15617    pub fn is_focused(&self) -> bool {
15618        self.is_focused
15619    }
15620
15621    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15622        self.placeholder_text.as_ref()
15623    }
15624
15625    pub fn scroll_position(&self) -> gpui::Point<f32> {
15626        self.scroll_anchor.scroll_position(&self.display_snapshot)
15627    }
15628
15629    fn gutter_dimensions(
15630        &self,
15631        font_id: FontId,
15632        font_size: Pixels,
15633        max_line_number_width: Pixels,
15634        cx: &App,
15635    ) -> Option<GutterDimensions> {
15636        if !self.show_gutter {
15637            return None;
15638        }
15639
15640        let descent = cx.text_system().descent(font_id, font_size);
15641        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15642        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15643
15644        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15645            matches!(
15646                ProjectSettings::get_global(cx).git.git_gutter,
15647                Some(GitGutterSetting::TrackedFiles)
15648            )
15649        });
15650        let gutter_settings = EditorSettings::get_global(cx).gutter;
15651        let show_line_numbers = self
15652            .show_line_numbers
15653            .unwrap_or(gutter_settings.line_numbers);
15654        let line_gutter_width = if show_line_numbers {
15655            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15656            let min_width_for_number_on_gutter = em_advance * 4.0;
15657            max_line_number_width.max(min_width_for_number_on_gutter)
15658        } else {
15659            0.0.into()
15660        };
15661
15662        let show_code_actions = self
15663            .show_code_actions
15664            .unwrap_or(gutter_settings.code_actions);
15665
15666        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15667
15668        let git_blame_entries_width =
15669            self.git_blame_gutter_max_author_length
15670                .map(|max_author_length| {
15671                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15672
15673                    /// The number of characters to dedicate to gaps and margins.
15674                    const SPACING_WIDTH: usize = 4;
15675
15676                    let max_char_count = max_author_length
15677                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15678                        + ::git::SHORT_SHA_LENGTH
15679                        + MAX_RELATIVE_TIMESTAMP.len()
15680                        + SPACING_WIDTH;
15681
15682                    em_advance * max_char_count
15683                });
15684
15685        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15686        left_padding += if show_code_actions || show_runnables {
15687            em_width * 3.0
15688        } else if show_git_gutter && show_line_numbers {
15689            em_width * 2.0
15690        } else if show_git_gutter || show_line_numbers {
15691            em_width
15692        } else {
15693            px(0.)
15694        };
15695
15696        let right_padding = if gutter_settings.folds && show_line_numbers {
15697            em_width * 4.0
15698        } else if gutter_settings.folds {
15699            em_width * 3.0
15700        } else if show_line_numbers {
15701            em_width
15702        } else {
15703            px(0.)
15704        };
15705
15706        Some(GutterDimensions {
15707            left_padding,
15708            right_padding,
15709            width: line_gutter_width + left_padding + right_padding,
15710            margin: -descent,
15711            git_blame_entries_width,
15712        })
15713    }
15714
15715    pub fn render_crease_toggle(
15716        &self,
15717        buffer_row: MultiBufferRow,
15718        row_contains_cursor: bool,
15719        editor: Entity<Editor>,
15720        window: &mut Window,
15721        cx: &mut App,
15722    ) -> Option<AnyElement> {
15723        let folded = self.is_line_folded(buffer_row);
15724        let mut is_foldable = false;
15725
15726        if let Some(crease) = self
15727            .crease_snapshot
15728            .query_row(buffer_row, &self.buffer_snapshot)
15729        {
15730            is_foldable = true;
15731            match crease {
15732                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15733                    if let Some(render_toggle) = render_toggle {
15734                        let toggle_callback =
15735                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15736                                if folded {
15737                                    editor.update(cx, |editor, cx| {
15738                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15739                                    });
15740                                } else {
15741                                    editor.update(cx, |editor, cx| {
15742                                        editor.unfold_at(
15743                                            &crate::UnfoldAt { buffer_row },
15744                                            window,
15745                                            cx,
15746                                        )
15747                                    });
15748                                }
15749                            });
15750                        return Some((render_toggle)(
15751                            buffer_row,
15752                            folded,
15753                            toggle_callback,
15754                            window,
15755                            cx,
15756                        ));
15757                    }
15758                }
15759            }
15760        }
15761
15762        is_foldable |= self.starts_indent(buffer_row);
15763
15764        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15765            Some(
15766                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15767                    .toggle_state(folded)
15768                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15769                        if folded {
15770                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15771                        } else {
15772                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15773                        }
15774                    }))
15775                    .into_any_element(),
15776            )
15777        } else {
15778            None
15779        }
15780    }
15781
15782    pub fn render_crease_trailer(
15783        &self,
15784        buffer_row: MultiBufferRow,
15785        window: &mut Window,
15786        cx: &mut App,
15787    ) -> Option<AnyElement> {
15788        let folded = self.is_line_folded(buffer_row);
15789        if let Crease::Inline { render_trailer, .. } = self
15790            .crease_snapshot
15791            .query_row(buffer_row, &self.buffer_snapshot)?
15792        {
15793            let render_trailer = render_trailer.as_ref()?;
15794            Some(render_trailer(buffer_row, folded, window, cx))
15795        } else {
15796            None
15797        }
15798    }
15799}
15800
15801impl Deref for EditorSnapshot {
15802    type Target = DisplaySnapshot;
15803
15804    fn deref(&self) -> &Self::Target {
15805        &self.display_snapshot
15806    }
15807}
15808
15809#[derive(Clone, Debug, PartialEq, Eq)]
15810pub enum EditorEvent {
15811    InputIgnored {
15812        text: Arc<str>,
15813    },
15814    InputHandled {
15815        utf16_range_to_replace: Option<Range<isize>>,
15816        text: Arc<str>,
15817    },
15818    ExcerptsAdded {
15819        buffer: Entity<Buffer>,
15820        predecessor: ExcerptId,
15821        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15822    },
15823    ExcerptsRemoved {
15824        ids: Vec<ExcerptId>,
15825    },
15826    BufferFoldToggled {
15827        ids: Vec<ExcerptId>,
15828        folded: bool,
15829    },
15830    ExcerptsEdited {
15831        ids: Vec<ExcerptId>,
15832    },
15833    ExcerptsExpanded {
15834        ids: Vec<ExcerptId>,
15835    },
15836    BufferEdited,
15837    Edited {
15838        transaction_id: clock::Lamport,
15839    },
15840    Reparsed(BufferId),
15841    Focused,
15842    FocusedIn,
15843    Blurred,
15844    DirtyChanged,
15845    Saved,
15846    TitleChanged,
15847    DiffBaseChanged,
15848    SelectionsChanged {
15849        local: bool,
15850    },
15851    ScrollPositionChanged {
15852        local: bool,
15853        autoscroll: bool,
15854    },
15855    Closed,
15856    TransactionUndone {
15857        transaction_id: clock::Lamport,
15858    },
15859    TransactionBegun {
15860        transaction_id: clock::Lamport,
15861    },
15862    Reloaded,
15863    CursorShapeChanged,
15864}
15865
15866impl EventEmitter<EditorEvent> for Editor {}
15867
15868impl Focusable for Editor {
15869    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15870        self.focus_handle.clone()
15871    }
15872}
15873
15874impl Render for Editor {
15875    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15876        let settings = ThemeSettings::get_global(cx);
15877
15878        let mut text_style = match self.mode {
15879            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15880                color: cx.theme().colors().editor_foreground,
15881                font_family: settings.ui_font.family.clone(),
15882                font_features: settings.ui_font.features.clone(),
15883                font_fallbacks: settings.ui_font.fallbacks.clone(),
15884                font_size: rems(0.875).into(),
15885                font_weight: settings.ui_font.weight,
15886                line_height: relative(settings.buffer_line_height.value()),
15887                ..Default::default()
15888            },
15889            EditorMode::Full => TextStyle {
15890                color: cx.theme().colors().editor_foreground,
15891                font_family: settings.buffer_font.family.clone(),
15892                font_features: settings.buffer_font.features.clone(),
15893                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15894                font_size: settings.buffer_font_size().into(),
15895                font_weight: settings.buffer_font.weight,
15896                line_height: relative(settings.buffer_line_height.value()),
15897                ..Default::default()
15898            },
15899        };
15900        if let Some(text_style_refinement) = &self.text_style_refinement {
15901            text_style.refine(text_style_refinement)
15902        }
15903
15904        let background = match self.mode {
15905            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15906            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15907            EditorMode::Full => cx.theme().colors().editor_background,
15908        };
15909
15910        EditorElement::new(
15911            &cx.entity(),
15912            EditorStyle {
15913                background,
15914                local_player: cx.theme().players().local(),
15915                text: text_style,
15916                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15917                syntax: cx.theme().syntax().clone(),
15918                status: cx.theme().status().clone(),
15919                inlay_hints_style: make_inlay_hints_style(cx),
15920                inline_completion_styles: make_suggestion_styles(cx),
15921                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15922            },
15923        )
15924    }
15925}
15926
15927impl EntityInputHandler for Editor {
15928    fn text_for_range(
15929        &mut self,
15930        range_utf16: Range<usize>,
15931        adjusted_range: &mut Option<Range<usize>>,
15932        _: &mut Window,
15933        cx: &mut Context<Self>,
15934    ) -> Option<String> {
15935        let snapshot = self.buffer.read(cx).read(cx);
15936        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15937        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15938        if (start.0..end.0) != range_utf16 {
15939            adjusted_range.replace(start.0..end.0);
15940        }
15941        Some(snapshot.text_for_range(start..end).collect())
15942    }
15943
15944    fn selected_text_range(
15945        &mut self,
15946        ignore_disabled_input: bool,
15947        _: &mut Window,
15948        cx: &mut Context<Self>,
15949    ) -> Option<UTF16Selection> {
15950        // Prevent the IME menu from appearing when holding down an alphabetic key
15951        // while input is disabled.
15952        if !ignore_disabled_input && !self.input_enabled {
15953            return None;
15954        }
15955
15956        let selection = self.selections.newest::<OffsetUtf16>(cx);
15957        let range = selection.range();
15958
15959        Some(UTF16Selection {
15960            range: range.start.0..range.end.0,
15961            reversed: selection.reversed,
15962        })
15963    }
15964
15965    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15966        let snapshot = self.buffer.read(cx).read(cx);
15967        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15968        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15969    }
15970
15971    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15972        self.clear_highlights::<InputComposition>(cx);
15973        self.ime_transaction.take();
15974    }
15975
15976    fn replace_text_in_range(
15977        &mut self,
15978        range_utf16: Option<Range<usize>>,
15979        text: &str,
15980        window: &mut Window,
15981        cx: &mut Context<Self>,
15982    ) {
15983        if !self.input_enabled {
15984            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15985            return;
15986        }
15987
15988        self.transact(window, cx, |this, window, cx| {
15989            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15990                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15991                Some(this.selection_replacement_ranges(range_utf16, cx))
15992            } else {
15993                this.marked_text_ranges(cx)
15994            };
15995
15996            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15997                let newest_selection_id = this.selections.newest_anchor().id;
15998                this.selections
15999                    .all::<OffsetUtf16>(cx)
16000                    .iter()
16001                    .zip(ranges_to_replace.iter())
16002                    .find_map(|(selection, range)| {
16003                        if selection.id == newest_selection_id {
16004                            Some(
16005                                (range.start.0 as isize - selection.head().0 as isize)
16006                                    ..(range.end.0 as isize - selection.head().0 as isize),
16007                            )
16008                        } else {
16009                            None
16010                        }
16011                    })
16012            });
16013
16014            cx.emit(EditorEvent::InputHandled {
16015                utf16_range_to_replace: range_to_replace,
16016                text: text.into(),
16017            });
16018
16019            if let Some(new_selected_ranges) = new_selected_ranges {
16020                this.change_selections(None, window, cx, |selections| {
16021                    selections.select_ranges(new_selected_ranges)
16022                });
16023                this.backspace(&Default::default(), window, cx);
16024            }
16025
16026            this.handle_input(text, window, cx);
16027        });
16028
16029        if let Some(transaction) = self.ime_transaction {
16030            self.buffer.update(cx, |buffer, cx| {
16031                buffer.group_until_transaction(transaction, cx);
16032            });
16033        }
16034
16035        self.unmark_text(window, cx);
16036    }
16037
16038    fn replace_and_mark_text_in_range(
16039        &mut self,
16040        range_utf16: Option<Range<usize>>,
16041        text: &str,
16042        new_selected_range_utf16: Option<Range<usize>>,
16043        window: &mut Window,
16044        cx: &mut Context<Self>,
16045    ) {
16046        if !self.input_enabled {
16047            return;
16048        }
16049
16050        let transaction = self.transact(window, cx, |this, window, cx| {
16051            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16052                let snapshot = this.buffer.read(cx).read(cx);
16053                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16054                    for marked_range in &mut marked_ranges {
16055                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16056                        marked_range.start.0 += relative_range_utf16.start;
16057                        marked_range.start =
16058                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16059                        marked_range.end =
16060                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16061                    }
16062                }
16063                Some(marked_ranges)
16064            } else if let Some(range_utf16) = range_utf16 {
16065                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16066                Some(this.selection_replacement_ranges(range_utf16, cx))
16067            } else {
16068                None
16069            };
16070
16071            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16072                let newest_selection_id = this.selections.newest_anchor().id;
16073                this.selections
16074                    .all::<OffsetUtf16>(cx)
16075                    .iter()
16076                    .zip(ranges_to_replace.iter())
16077                    .find_map(|(selection, range)| {
16078                        if selection.id == newest_selection_id {
16079                            Some(
16080                                (range.start.0 as isize - selection.head().0 as isize)
16081                                    ..(range.end.0 as isize - selection.head().0 as isize),
16082                            )
16083                        } else {
16084                            None
16085                        }
16086                    })
16087            });
16088
16089            cx.emit(EditorEvent::InputHandled {
16090                utf16_range_to_replace: range_to_replace,
16091                text: text.into(),
16092            });
16093
16094            if let Some(ranges) = ranges_to_replace {
16095                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16096            }
16097
16098            let marked_ranges = {
16099                let snapshot = this.buffer.read(cx).read(cx);
16100                this.selections
16101                    .disjoint_anchors()
16102                    .iter()
16103                    .map(|selection| {
16104                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16105                    })
16106                    .collect::<Vec<_>>()
16107            };
16108
16109            if text.is_empty() {
16110                this.unmark_text(window, cx);
16111            } else {
16112                this.highlight_text::<InputComposition>(
16113                    marked_ranges.clone(),
16114                    HighlightStyle {
16115                        underline: Some(UnderlineStyle {
16116                            thickness: px(1.),
16117                            color: None,
16118                            wavy: false,
16119                        }),
16120                        ..Default::default()
16121                    },
16122                    cx,
16123                );
16124            }
16125
16126            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16127            let use_autoclose = this.use_autoclose;
16128            let use_auto_surround = this.use_auto_surround;
16129            this.set_use_autoclose(false);
16130            this.set_use_auto_surround(false);
16131            this.handle_input(text, window, cx);
16132            this.set_use_autoclose(use_autoclose);
16133            this.set_use_auto_surround(use_auto_surround);
16134
16135            if let Some(new_selected_range) = new_selected_range_utf16 {
16136                let snapshot = this.buffer.read(cx).read(cx);
16137                let new_selected_ranges = marked_ranges
16138                    .into_iter()
16139                    .map(|marked_range| {
16140                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16141                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16142                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16143                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16144                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16145                    })
16146                    .collect::<Vec<_>>();
16147
16148                drop(snapshot);
16149                this.change_selections(None, window, cx, |selections| {
16150                    selections.select_ranges(new_selected_ranges)
16151                });
16152            }
16153        });
16154
16155        self.ime_transaction = self.ime_transaction.or(transaction);
16156        if let Some(transaction) = self.ime_transaction {
16157            self.buffer.update(cx, |buffer, cx| {
16158                buffer.group_until_transaction(transaction, cx);
16159            });
16160        }
16161
16162        if self.text_highlights::<InputComposition>(cx).is_none() {
16163            self.ime_transaction.take();
16164        }
16165    }
16166
16167    fn bounds_for_range(
16168        &mut self,
16169        range_utf16: Range<usize>,
16170        element_bounds: gpui::Bounds<Pixels>,
16171        window: &mut Window,
16172        cx: &mut Context<Self>,
16173    ) -> Option<gpui::Bounds<Pixels>> {
16174        let text_layout_details = self.text_layout_details(window);
16175        let gpui::Size {
16176            width: em_width,
16177            height: line_height,
16178        } = self.character_size(window);
16179
16180        let snapshot = self.snapshot(window, cx);
16181        let scroll_position = snapshot.scroll_position();
16182        let scroll_left = scroll_position.x * em_width;
16183
16184        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16185        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16186            + self.gutter_dimensions.width
16187            + self.gutter_dimensions.margin;
16188        let y = line_height * (start.row().as_f32() - scroll_position.y);
16189
16190        Some(Bounds {
16191            origin: element_bounds.origin + point(x, y),
16192            size: size(em_width, line_height),
16193        })
16194    }
16195
16196    fn character_index_for_point(
16197        &mut self,
16198        point: gpui::Point<Pixels>,
16199        _window: &mut Window,
16200        _cx: &mut Context<Self>,
16201    ) -> Option<usize> {
16202        let position_map = self.last_position_map.as_ref()?;
16203        if !position_map.text_hitbox.contains(&point) {
16204            return None;
16205        }
16206        let display_point = position_map.point_for_position(point).previous_valid;
16207        let anchor = position_map
16208            .snapshot
16209            .display_point_to_anchor(display_point, Bias::Left);
16210        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16211        Some(utf16_offset.0)
16212    }
16213}
16214
16215trait SelectionExt {
16216    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16217    fn spanned_rows(
16218        &self,
16219        include_end_if_at_line_start: bool,
16220        map: &DisplaySnapshot,
16221    ) -> Range<MultiBufferRow>;
16222}
16223
16224impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16225    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16226        let start = self
16227            .start
16228            .to_point(&map.buffer_snapshot)
16229            .to_display_point(map);
16230        let end = self
16231            .end
16232            .to_point(&map.buffer_snapshot)
16233            .to_display_point(map);
16234        if self.reversed {
16235            end..start
16236        } else {
16237            start..end
16238        }
16239    }
16240
16241    fn spanned_rows(
16242        &self,
16243        include_end_if_at_line_start: bool,
16244        map: &DisplaySnapshot,
16245    ) -> Range<MultiBufferRow> {
16246        let start = self.start.to_point(&map.buffer_snapshot);
16247        let mut end = self.end.to_point(&map.buffer_snapshot);
16248        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16249            end.row -= 1;
16250        }
16251
16252        let buffer_start = map.prev_line_boundary(start).0;
16253        let buffer_end = map.next_line_boundary(end).0;
16254        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16255    }
16256}
16257
16258impl<T: InvalidationRegion> InvalidationStack<T> {
16259    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16260    where
16261        S: Clone + ToOffset,
16262    {
16263        while let Some(region) = self.last() {
16264            let all_selections_inside_invalidation_ranges =
16265                if selections.len() == region.ranges().len() {
16266                    selections
16267                        .iter()
16268                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16269                        .all(|(selection, invalidation_range)| {
16270                            let head = selection.head().to_offset(buffer);
16271                            invalidation_range.start <= head && invalidation_range.end >= head
16272                        })
16273                } else {
16274                    false
16275                };
16276
16277            if all_selections_inside_invalidation_ranges {
16278                break;
16279            } else {
16280                self.pop();
16281            }
16282        }
16283    }
16284}
16285
16286impl<T> Default for InvalidationStack<T> {
16287    fn default() -> Self {
16288        Self(Default::default())
16289    }
16290}
16291
16292impl<T> Deref for InvalidationStack<T> {
16293    type Target = Vec<T>;
16294
16295    fn deref(&self) -> &Self::Target {
16296        &self.0
16297    }
16298}
16299
16300impl<T> DerefMut for InvalidationStack<T> {
16301    fn deref_mut(&mut self) -> &mut Self::Target {
16302        &mut self.0
16303    }
16304}
16305
16306impl InvalidationRegion for SnippetState {
16307    fn ranges(&self) -> &[Range<Anchor>] {
16308        &self.ranges[self.active_index]
16309    }
16310}
16311
16312pub fn diagnostic_block_renderer(
16313    diagnostic: Diagnostic,
16314    max_message_rows: Option<u8>,
16315    allow_closing: bool,
16316    _is_valid: bool,
16317) -> RenderBlock {
16318    let (text_without_backticks, code_ranges) =
16319        highlight_diagnostic_message(&diagnostic, max_message_rows);
16320
16321    Arc::new(move |cx: &mut BlockContext| {
16322        let group_id: SharedString = cx.block_id.to_string().into();
16323
16324        let mut text_style = cx.window.text_style().clone();
16325        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16326        let theme_settings = ThemeSettings::get_global(cx);
16327        text_style.font_family = theme_settings.buffer_font.family.clone();
16328        text_style.font_style = theme_settings.buffer_font.style;
16329        text_style.font_features = theme_settings.buffer_font.features.clone();
16330        text_style.font_weight = theme_settings.buffer_font.weight;
16331
16332        let multi_line_diagnostic = diagnostic.message.contains('\n');
16333
16334        let buttons = |diagnostic: &Diagnostic| {
16335            if multi_line_diagnostic {
16336                v_flex()
16337            } else {
16338                h_flex()
16339            }
16340            .when(allow_closing, |div| {
16341                div.children(diagnostic.is_primary.then(|| {
16342                    IconButton::new("close-block", IconName::XCircle)
16343                        .icon_color(Color::Muted)
16344                        .size(ButtonSize::Compact)
16345                        .style(ButtonStyle::Transparent)
16346                        .visible_on_hover(group_id.clone())
16347                        .on_click(move |_click, window, cx| {
16348                            window.dispatch_action(Box::new(Cancel), cx)
16349                        })
16350                        .tooltip(|window, cx| {
16351                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16352                        })
16353                }))
16354            })
16355            .child(
16356                IconButton::new("copy-block", IconName::Copy)
16357                    .icon_color(Color::Muted)
16358                    .size(ButtonSize::Compact)
16359                    .style(ButtonStyle::Transparent)
16360                    .visible_on_hover(group_id.clone())
16361                    .on_click({
16362                        let message = diagnostic.message.clone();
16363                        move |_click, _, cx| {
16364                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16365                        }
16366                    })
16367                    .tooltip(Tooltip::text("Copy diagnostic message")),
16368            )
16369        };
16370
16371        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16372            AvailableSpace::min_size(),
16373            cx.window,
16374            cx.app,
16375        );
16376
16377        h_flex()
16378            .id(cx.block_id)
16379            .group(group_id.clone())
16380            .relative()
16381            .size_full()
16382            .block_mouse_down()
16383            .pl(cx.gutter_dimensions.width)
16384            .w(cx.max_width - cx.gutter_dimensions.full_width())
16385            .child(
16386                div()
16387                    .flex()
16388                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16389                    .flex_shrink(),
16390            )
16391            .child(buttons(&diagnostic))
16392            .child(div().flex().flex_shrink_0().child(
16393                StyledText::new(text_without_backticks.clone()).with_highlights(
16394                    &text_style,
16395                    code_ranges.iter().map(|range| {
16396                        (
16397                            range.clone(),
16398                            HighlightStyle {
16399                                font_weight: Some(FontWeight::BOLD),
16400                                ..Default::default()
16401                            },
16402                        )
16403                    }),
16404                ),
16405            ))
16406            .into_any_element()
16407    })
16408}
16409
16410fn inline_completion_edit_text(
16411    current_snapshot: &BufferSnapshot,
16412    edits: &[(Range<Anchor>, String)],
16413    edit_preview: &EditPreview,
16414    include_deletions: bool,
16415    cx: &App,
16416) -> HighlightedText {
16417    let edits = edits
16418        .iter()
16419        .map(|(anchor, text)| {
16420            (
16421                anchor.start.text_anchor..anchor.end.text_anchor,
16422                text.clone(),
16423            )
16424        })
16425        .collect::<Vec<_>>();
16426
16427    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16428}
16429
16430pub fn highlight_diagnostic_message(
16431    diagnostic: &Diagnostic,
16432    mut max_message_rows: Option<u8>,
16433) -> (SharedString, Vec<Range<usize>>) {
16434    let mut text_without_backticks = String::new();
16435    let mut code_ranges = Vec::new();
16436
16437    if let Some(source) = &diagnostic.source {
16438        text_without_backticks.push_str(source);
16439        code_ranges.push(0..source.len());
16440        text_without_backticks.push_str(": ");
16441    }
16442
16443    let mut prev_offset = 0;
16444    let mut in_code_block = false;
16445    let has_row_limit = max_message_rows.is_some();
16446    let mut newline_indices = diagnostic
16447        .message
16448        .match_indices('\n')
16449        .filter(|_| has_row_limit)
16450        .map(|(ix, _)| ix)
16451        .fuse()
16452        .peekable();
16453
16454    for (quote_ix, _) in diagnostic
16455        .message
16456        .match_indices('`')
16457        .chain([(diagnostic.message.len(), "")])
16458    {
16459        let mut first_newline_ix = None;
16460        let mut last_newline_ix = None;
16461        while let Some(newline_ix) = newline_indices.peek() {
16462            if *newline_ix < quote_ix {
16463                if first_newline_ix.is_none() {
16464                    first_newline_ix = Some(*newline_ix);
16465                }
16466                last_newline_ix = Some(*newline_ix);
16467
16468                if let Some(rows_left) = &mut max_message_rows {
16469                    if *rows_left == 0 {
16470                        break;
16471                    } else {
16472                        *rows_left -= 1;
16473                    }
16474                }
16475                let _ = newline_indices.next();
16476            } else {
16477                break;
16478            }
16479        }
16480        let prev_len = text_without_backticks.len();
16481        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16482        text_without_backticks.push_str(new_text);
16483        if in_code_block {
16484            code_ranges.push(prev_len..text_without_backticks.len());
16485        }
16486        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16487        in_code_block = !in_code_block;
16488        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16489            text_without_backticks.push_str("...");
16490            break;
16491        }
16492    }
16493
16494    (text_without_backticks.into(), code_ranges)
16495}
16496
16497fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16498    match severity {
16499        DiagnosticSeverity::ERROR => colors.error,
16500        DiagnosticSeverity::WARNING => colors.warning,
16501        DiagnosticSeverity::INFORMATION => colors.info,
16502        DiagnosticSeverity::HINT => colors.info,
16503        _ => colors.ignored,
16504    }
16505}
16506
16507pub fn styled_runs_for_code_label<'a>(
16508    label: &'a CodeLabel,
16509    syntax_theme: &'a theme::SyntaxTheme,
16510) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16511    let fade_out = HighlightStyle {
16512        fade_out: Some(0.35),
16513        ..Default::default()
16514    };
16515
16516    let mut prev_end = label.filter_range.end;
16517    label
16518        .runs
16519        .iter()
16520        .enumerate()
16521        .flat_map(move |(ix, (range, highlight_id))| {
16522            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16523                style
16524            } else {
16525                return Default::default();
16526            };
16527            let mut muted_style = style;
16528            muted_style.highlight(fade_out);
16529
16530            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16531            if range.start >= label.filter_range.end {
16532                if range.start > prev_end {
16533                    runs.push((prev_end..range.start, fade_out));
16534                }
16535                runs.push((range.clone(), muted_style));
16536            } else if range.end <= label.filter_range.end {
16537                runs.push((range.clone(), style));
16538            } else {
16539                runs.push((range.start..label.filter_range.end, style));
16540                runs.push((label.filter_range.end..range.end, muted_style));
16541            }
16542            prev_end = cmp::max(prev_end, range.end);
16543
16544            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16545                runs.push((prev_end..label.text.len(), fade_out));
16546            }
16547
16548            runs
16549        })
16550}
16551
16552pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16553    let mut prev_index = 0;
16554    let mut prev_codepoint: Option<char> = None;
16555    text.char_indices()
16556        .chain([(text.len(), '\0')])
16557        .filter_map(move |(index, codepoint)| {
16558            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16559            let is_boundary = index == text.len()
16560                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16561                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16562            if is_boundary {
16563                let chunk = &text[prev_index..index];
16564                prev_index = index;
16565                Some(chunk)
16566            } else {
16567                None
16568            }
16569        })
16570}
16571
16572pub trait RangeToAnchorExt: Sized {
16573    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16574
16575    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16576        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16577        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16578    }
16579}
16580
16581impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16582    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16583        let start_offset = self.start.to_offset(snapshot);
16584        let end_offset = self.end.to_offset(snapshot);
16585        if start_offset == end_offset {
16586            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16587        } else {
16588            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16589        }
16590    }
16591}
16592
16593pub trait RowExt {
16594    fn as_f32(&self) -> f32;
16595
16596    fn next_row(&self) -> Self;
16597
16598    fn previous_row(&self) -> Self;
16599
16600    fn minus(&self, other: Self) -> u32;
16601}
16602
16603impl RowExt for DisplayRow {
16604    fn as_f32(&self) -> f32 {
16605        self.0 as f32
16606    }
16607
16608    fn next_row(&self) -> Self {
16609        Self(self.0 + 1)
16610    }
16611
16612    fn previous_row(&self) -> Self {
16613        Self(self.0.saturating_sub(1))
16614    }
16615
16616    fn minus(&self, other: Self) -> u32 {
16617        self.0 - other.0
16618    }
16619}
16620
16621impl RowExt for MultiBufferRow {
16622    fn as_f32(&self) -> f32 {
16623        self.0 as f32
16624    }
16625
16626    fn next_row(&self) -> Self {
16627        Self(self.0 + 1)
16628    }
16629
16630    fn previous_row(&self) -> Self {
16631        Self(self.0.saturating_sub(1))
16632    }
16633
16634    fn minus(&self, other: Self) -> u32 {
16635        self.0 - other.0
16636    }
16637}
16638
16639trait RowRangeExt {
16640    type Row;
16641
16642    fn len(&self) -> usize;
16643
16644    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16645}
16646
16647impl RowRangeExt for Range<MultiBufferRow> {
16648    type Row = MultiBufferRow;
16649
16650    fn len(&self) -> usize {
16651        (self.end.0 - self.start.0) as usize
16652    }
16653
16654    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16655        (self.start.0..self.end.0).map(MultiBufferRow)
16656    }
16657}
16658
16659impl RowRangeExt for Range<DisplayRow> {
16660    type Row = DisplayRow;
16661
16662    fn len(&self) -> usize {
16663        (self.end.0 - self.start.0) as usize
16664    }
16665
16666    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16667        (self.start.0..self.end.0).map(DisplayRow)
16668    }
16669}
16670
16671/// If select range has more than one line, we
16672/// just point the cursor to range.start.
16673fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16674    if range.start.row == range.end.row {
16675        range
16676    } else {
16677        range.start..range.start
16678    }
16679}
16680pub struct KillRing(ClipboardItem);
16681impl Global for KillRing {}
16682
16683const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16684
16685fn all_edits_insertions_or_deletions(
16686    edits: &Vec<(Range<Anchor>, String)>,
16687    snapshot: &MultiBufferSnapshot,
16688) -> bool {
16689    let mut all_insertions = true;
16690    let mut all_deletions = true;
16691
16692    for (range, new_text) in edits.iter() {
16693        let range_is_empty = range.to_offset(&snapshot).is_empty();
16694        let text_is_empty = new_text.is_empty();
16695
16696        if range_is_empty != text_is_empty {
16697            if range_is_empty {
16698                all_deletions = false;
16699            } else {
16700                all_insertions = false;
16701            }
16702        } else {
16703            return false;
16704        }
16705
16706        if !all_insertions && !all_deletions {
16707            return false;
16708        }
16709    }
16710    all_insertions || all_deletions
16711}