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    edit_prediction_cursor_on_leading_whitespace: bool,
  713    inline_completions_hidden_for_vim_mode: bool,
  714    show_inline_completions_override: Option<bool>,
  715    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  716    edit_prediction_preview: EditPredictionPreview,
  717    inlay_hint_cache: InlayHintCache,
  718    next_inlay_id: usize,
  719    _subscriptions: Vec<Subscription>,
  720    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  721    gutter_dimensions: GutterDimensions,
  722    style: Option<EditorStyle>,
  723    text_style_refinement: Option<TextStyleRefinement>,
  724    next_editor_action_id: EditorActionId,
  725    editor_actions:
  726        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  727    use_autoclose: bool,
  728    use_auto_surround: bool,
  729    auto_replace_emoji_shortcode: bool,
  730    show_git_blame_gutter: bool,
  731    show_git_blame_inline: bool,
  732    show_git_blame_inline_delay_task: Option<Task<()>>,
  733    distinguish_unstaged_diff_hunks: bool,
  734    git_blame_inline_enabled: bool,
  735    serialize_dirty_buffers: bool,
  736    show_selection_menu: Option<bool>,
  737    blame: Option<Entity<GitBlame>>,
  738    blame_subscription: Option<Subscription>,
  739    custom_context_menu: Option<
  740        Box<
  741            dyn 'static
  742                + Fn(
  743                    &mut Self,
  744                    DisplayPoint,
  745                    &mut Window,
  746                    &mut Context<Self>,
  747                ) -> Option<Entity<ui::ContextMenu>>,
  748        >,
  749    >,
  750    last_bounds: Option<Bounds<Pixels>>,
  751    last_position_map: Option<Rc<PositionMap>>,
  752    expect_bounds_change: Option<Bounds<Pixels>>,
  753    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  754    tasks_update_task: Option<Task<()>>,
  755    in_project_search: bool,
  756    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  757    breadcrumb_header: Option<String>,
  758    focused_block: Option<FocusedBlock>,
  759    next_scroll_position: NextScrollCursorCenterTopBottom,
  760    addons: HashMap<TypeId, Box<dyn Addon>>,
  761    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  762    selection_mark_mode: bool,
  763    toggle_fold_multiple_buffers: Task<()>,
  764    _scroll_cursor_center_top_bottom_task: Task<()>,
  765}
  766
  767#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  768enum NextScrollCursorCenterTopBottom {
  769    #[default]
  770    Center,
  771    Top,
  772    Bottom,
  773}
  774
  775impl NextScrollCursorCenterTopBottom {
  776    fn next(&self) -> Self {
  777        match self {
  778            Self::Center => Self::Top,
  779            Self::Top => Self::Bottom,
  780            Self::Bottom => Self::Center,
  781        }
  782    }
  783}
  784
  785#[derive(Clone)]
  786pub struct EditorSnapshot {
  787    pub mode: EditorMode,
  788    show_gutter: bool,
  789    show_line_numbers: Option<bool>,
  790    show_git_diff_gutter: Option<bool>,
  791    show_code_actions: Option<bool>,
  792    show_runnables: Option<bool>,
  793    git_blame_gutter_max_author_length: Option<usize>,
  794    pub display_snapshot: DisplaySnapshot,
  795    pub placeholder_text: Option<Arc<str>>,
  796    is_focused: bool,
  797    scroll_anchor: ScrollAnchor,
  798    ongoing_scroll: OngoingScroll,
  799    current_line_highlight: CurrentLineHighlight,
  800    gutter_hovered: bool,
  801}
  802
  803const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  804
  805#[derive(Default, Debug, Clone, Copy)]
  806pub struct GutterDimensions {
  807    pub left_padding: Pixels,
  808    pub right_padding: Pixels,
  809    pub width: Pixels,
  810    pub margin: Pixels,
  811    pub git_blame_entries_width: Option<Pixels>,
  812}
  813
  814impl GutterDimensions {
  815    /// The full width of the space taken up by the gutter.
  816    pub fn full_width(&self) -> Pixels {
  817        self.margin + self.width
  818    }
  819
  820    /// The width of the space reserved for the fold indicators,
  821    /// use alongside 'justify_end' and `gutter_width` to
  822    /// right align content with the line numbers
  823    pub fn fold_area_width(&self) -> Pixels {
  824        self.margin + self.right_padding
  825    }
  826}
  827
  828#[derive(Debug)]
  829pub struct RemoteSelection {
  830    pub replica_id: ReplicaId,
  831    pub selection: Selection<Anchor>,
  832    pub cursor_shape: CursorShape,
  833    pub peer_id: PeerId,
  834    pub line_mode: bool,
  835    pub participant_index: Option<ParticipantIndex>,
  836    pub user_name: Option<SharedString>,
  837}
  838
  839#[derive(Clone, Debug)]
  840struct SelectionHistoryEntry {
  841    selections: Arc<[Selection<Anchor>]>,
  842    select_next_state: Option<SelectNextState>,
  843    select_prev_state: Option<SelectNextState>,
  844    add_selections_state: Option<AddSelectionsState>,
  845}
  846
  847enum SelectionHistoryMode {
  848    Normal,
  849    Undoing,
  850    Redoing,
  851}
  852
  853#[derive(Clone, PartialEq, Eq, Hash)]
  854struct HoveredCursor {
  855    replica_id: u16,
  856    selection_id: usize,
  857}
  858
  859impl Default for SelectionHistoryMode {
  860    fn default() -> Self {
  861        Self::Normal
  862    }
  863}
  864
  865#[derive(Default)]
  866struct SelectionHistory {
  867    #[allow(clippy::type_complexity)]
  868    selections_by_transaction:
  869        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  870    mode: SelectionHistoryMode,
  871    undo_stack: VecDeque<SelectionHistoryEntry>,
  872    redo_stack: VecDeque<SelectionHistoryEntry>,
  873}
  874
  875impl SelectionHistory {
  876    fn insert_transaction(
  877        &mut self,
  878        transaction_id: TransactionId,
  879        selections: Arc<[Selection<Anchor>]>,
  880    ) {
  881        self.selections_by_transaction
  882            .insert(transaction_id, (selections, None));
  883    }
  884
  885    #[allow(clippy::type_complexity)]
  886    fn transaction(
  887        &self,
  888        transaction_id: TransactionId,
  889    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  890        self.selections_by_transaction.get(&transaction_id)
  891    }
  892
  893    #[allow(clippy::type_complexity)]
  894    fn transaction_mut(
  895        &mut self,
  896        transaction_id: TransactionId,
  897    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  898        self.selections_by_transaction.get_mut(&transaction_id)
  899    }
  900
  901    fn push(&mut self, entry: SelectionHistoryEntry) {
  902        if !entry.selections.is_empty() {
  903            match self.mode {
  904                SelectionHistoryMode::Normal => {
  905                    self.push_undo(entry);
  906                    self.redo_stack.clear();
  907                }
  908                SelectionHistoryMode::Undoing => self.push_redo(entry),
  909                SelectionHistoryMode::Redoing => self.push_undo(entry),
  910            }
  911        }
  912    }
  913
  914    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  915        if self
  916            .undo_stack
  917            .back()
  918            .map_or(true, |e| e.selections != entry.selections)
  919        {
  920            self.undo_stack.push_back(entry);
  921            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  922                self.undo_stack.pop_front();
  923            }
  924        }
  925    }
  926
  927    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  928        if self
  929            .redo_stack
  930            .back()
  931            .map_or(true, |e| e.selections != entry.selections)
  932        {
  933            self.redo_stack.push_back(entry);
  934            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  935                self.redo_stack.pop_front();
  936            }
  937        }
  938    }
  939}
  940
  941struct RowHighlight {
  942    index: usize,
  943    range: Range<Anchor>,
  944    color: Hsla,
  945    should_autoscroll: bool,
  946}
  947
  948#[derive(Clone, Debug)]
  949struct AddSelectionsState {
  950    above: bool,
  951    stack: Vec<usize>,
  952}
  953
  954#[derive(Clone)]
  955struct SelectNextState {
  956    query: AhoCorasick,
  957    wordwise: bool,
  958    done: bool,
  959}
  960
  961impl std::fmt::Debug for SelectNextState {
  962    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  963        f.debug_struct(std::any::type_name::<Self>())
  964            .field("wordwise", &self.wordwise)
  965            .field("done", &self.done)
  966            .finish()
  967    }
  968}
  969
  970#[derive(Debug)]
  971struct AutocloseRegion {
  972    selection_id: usize,
  973    range: Range<Anchor>,
  974    pair: BracketPair,
  975}
  976
  977#[derive(Debug)]
  978struct SnippetState {
  979    ranges: Vec<Vec<Range<Anchor>>>,
  980    active_index: usize,
  981    choices: Vec<Option<Vec<String>>>,
  982}
  983
  984#[doc(hidden)]
  985pub struct RenameState {
  986    pub range: Range<Anchor>,
  987    pub old_name: Arc<str>,
  988    pub editor: Entity<Editor>,
  989    block_id: CustomBlockId,
  990}
  991
  992struct InvalidationStack<T>(Vec<T>);
  993
  994struct RegisteredInlineCompletionProvider {
  995    provider: Arc<dyn InlineCompletionProviderHandle>,
  996    _subscription: Subscription,
  997}
  998
  999#[derive(Debug)]
 1000struct ActiveDiagnosticGroup {
 1001    primary_range: Range<Anchor>,
 1002    primary_message: String,
 1003    group_id: usize,
 1004    blocks: HashMap<CustomBlockId, Diagnostic>,
 1005    is_valid: bool,
 1006}
 1007
 1008#[derive(Serialize, Deserialize, Clone, Debug)]
 1009pub struct ClipboardSelection {
 1010    pub len: usize,
 1011    pub is_entire_line: bool,
 1012    pub first_line_indent: u32,
 1013}
 1014
 1015#[derive(Debug)]
 1016pub(crate) struct NavigationData {
 1017    cursor_anchor: Anchor,
 1018    cursor_position: Point,
 1019    scroll_anchor: ScrollAnchor,
 1020    scroll_top_row: u32,
 1021}
 1022
 1023#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1024pub enum GotoDefinitionKind {
 1025    Symbol,
 1026    Declaration,
 1027    Type,
 1028    Implementation,
 1029}
 1030
 1031#[derive(Debug, Clone)]
 1032enum InlayHintRefreshReason {
 1033    Toggle(bool),
 1034    SettingsChange(InlayHintSettings),
 1035    NewLinesShown,
 1036    BufferEdited(HashSet<Arc<Language>>),
 1037    RefreshRequested,
 1038    ExcerptsRemoved(Vec<ExcerptId>),
 1039}
 1040
 1041impl InlayHintRefreshReason {
 1042    fn description(&self) -> &'static str {
 1043        match self {
 1044            Self::Toggle(_) => "toggle",
 1045            Self::SettingsChange(_) => "settings change",
 1046            Self::NewLinesShown => "new lines shown",
 1047            Self::BufferEdited(_) => "buffer edited",
 1048            Self::RefreshRequested => "refresh requested",
 1049            Self::ExcerptsRemoved(_) => "excerpts removed",
 1050        }
 1051    }
 1052}
 1053
 1054pub enum FormatTarget {
 1055    Buffers,
 1056    Ranges(Vec<Range<MultiBufferPoint>>),
 1057}
 1058
 1059pub(crate) struct FocusedBlock {
 1060    id: BlockId,
 1061    focus_handle: WeakFocusHandle,
 1062}
 1063
 1064#[derive(Clone)]
 1065enum JumpData {
 1066    MultiBufferRow {
 1067        row: MultiBufferRow,
 1068        line_offset_from_top: u32,
 1069    },
 1070    MultiBufferPoint {
 1071        excerpt_id: ExcerptId,
 1072        position: Point,
 1073        anchor: text::Anchor,
 1074        line_offset_from_top: u32,
 1075    },
 1076}
 1077
 1078pub enum MultibufferSelectionMode {
 1079    First,
 1080    All,
 1081}
 1082
 1083impl Editor {
 1084    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1085        let buffer = cx.new(|cx| Buffer::local("", cx));
 1086        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1087        Self::new(
 1088            EditorMode::SingleLine { auto_width: false },
 1089            buffer,
 1090            None,
 1091            false,
 1092            window,
 1093            cx,
 1094        )
 1095    }
 1096
 1097    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1098        let buffer = cx.new(|cx| Buffer::local("", cx));
 1099        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1100        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1101    }
 1102
 1103    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1104        let buffer = cx.new(|cx| Buffer::local("", cx));
 1105        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1106        Self::new(
 1107            EditorMode::SingleLine { auto_width: true },
 1108            buffer,
 1109            None,
 1110            false,
 1111            window,
 1112            cx,
 1113        )
 1114    }
 1115
 1116    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1117        let buffer = cx.new(|cx| Buffer::local("", cx));
 1118        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1119        Self::new(
 1120            EditorMode::AutoHeight { max_lines },
 1121            buffer,
 1122            None,
 1123            false,
 1124            window,
 1125            cx,
 1126        )
 1127    }
 1128
 1129    pub fn for_buffer(
 1130        buffer: Entity<Buffer>,
 1131        project: Option<Entity<Project>>,
 1132        window: &mut Window,
 1133        cx: &mut Context<Self>,
 1134    ) -> Self {
 1135        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1136        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1137    }
 1138
 1139    pub fn for_multibuffer(
 1140        buffer: Entity<MultiBuffer>,
 1141        project: Option<Entity<Project>>,
 1142        show_excerpt_controls: bool,
 1143        window: &mut Window,
 1144        cx: &mut Context<Self>,
 1145    ) -> Self {
 1146        Self::new(
 1147            EditorMode::Full,
 1148            buffer,
 1149            project,
 1150            show_excerpt_controls,
 1151            window,
 1152            cx,
 1153        )
 1154    }
 1155
 1156    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1157        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1158        let mut clone = Self::new(
 1159            self.mode,
 1160            self.buffer.clone(),
 1161            self.project.clone(),
 1162            show_excerpt_controls,
 1163            window,
 1164            cx,
 1165        );
 1166        self.display_map.update(cx, |display_map, cx| {
 1167            let snapshot = display_map.snapshot(cx);
 1168            clone.display_map.update(cx, |display_map, cx| {
 1169                display_map.set_state(&snapshot, cx);
 1170            });
 1171        });
 1172        clone.selections.clone_state(&self.selections);
 1173        clone.scroll_manager.clone_state(&self.scroll_manager);
 1174        clone.searchable = self.searchable;
 1175        clone
 1176    }
 1177
 1178    pub fn new(
 1179        mode: EditorMode,
 1180        buffer: Entity<MultiBuffer>,
 1181        project: Option<Entity<Project>>,
 1182        show_excerpt_controls: bool,
 1183        window: &mut Window,
 1184        cx: &mut Context<Self>,
 1185    ) -> Self {
 1186        let style = window.text_style();
 1187        let font_size = style.font_size.to_pixels(window.rem_size());
 1188        let editor = cx.entity().downgrade();
 1189        let fold_placeholder = FoldPlaceholder {
 1190            constrain_width: true,
 1191            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1192                let editor = editor.clone();
 1193                div()
 1194                    .id(fold_id)
 1195                    .bg(cx.theme().colors().ghost_element_background)
 1196                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1197                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1198                    .rounded_sm()
 1199                    .size_full()
 1200                    .cursor_pointer()
 1201                    .child("")
 1202                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1203                    .on_click(move |_, _window, cx| {
 1204                        editor
 1205                            .update(cx, |editor, cx| {
 1206                                editor.unfold_ranges(
 1207                                    &[fold_range.start..fold_range.end],
 1208                                    true,
 1209                                    false,
 1210                                    cx,
 1211                                );
 1212                                cx.stop_propagation();
 1213                            })
 1214                            .ok();
 1215                    })
 1216                    .into_any()
 1217            }),
 1218            merge_adjacent: true,
 1219            ..Default::default()
 1220        };
 1221        let display_map = cx.new(|cx| {
 1222            DisplayMap::new(
 1223                buffer.clone(),
 1224                style.font(),
 1225                font_size,
 1226                None,
 1227                show_excerpt_controls,
 1228                FILE_HEADER_HEIGHT,
 1229                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1230                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1231                fold_placeholder,
 1232                cx,
 1233            )
 1234        });
 1235
 1236        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1237
 1238        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1239
 1240        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1241            .then(|| language_settings::SoftWrap::None);
 1242
 1243        let mut project_subscriptions = Vec::new();
 1244        if mode == EditorMode::Full {
 1245            if let Some(project) = project.as_ref() {
 1246                if buffer.read(cx).is_singleton() {
 1247                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1248                        cx.emit(EditorEvent::TitleChanged);
 1249                    }));
 1250                }
 1251                project_subscriptions.push(cx.subscribe_in(
 1252                    project,
 1253                    window,
 1254                    |editor, _, event, window, cx| {
 1255                        if let project::Event::RefreshInlayHints = event {
 1256                            editor
 1257                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1258                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1259                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1260                                let focus_handle = editor.focus_handle(cx);
 1261                                if focus_handle.is_focused(window) {
 1262                                    let snapshot = buffer.read(cx).snapshot();
 1263                                    for (range, snippet) in snippet_edits {
 1264                                        let editor_range =
 1265                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1266                                        editor
 1267                                            .insert_snippet(
 1268                                                &[editor_range],
 1269                                                snippet.clone(),
 1270                                                window,
 1271                                                cx,
 1272                                            )
 1273                                            .ok();
 1274                                    }
 1275                                }
 1276                            }
 1277                        }
 1278                    },
 1279                ));
 1280                if let Some(task_inventory) = project
 1281                    .read(cx)
 1282                    .task_store()
 1283                    .read(cx)
 1284                    .task_inventory()
 1285                    .cloned()
 1286                {
 1287                    project_subscriptions.push(cx.observe_in(
 1288                        &task_inventory,
 1289                        window,
 1290                        |editor, _, window, cx| {
 1291                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1292                        },
 1293                    ));
 1294                }
 1295            }
 1296        }
 1297
 1298        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1299
 1300        let inlay_hint_settings =
 1301            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1302        let focus_handle = cx.focus_handle();
 1303        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1304            .detach();
 1305        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1306            .detach();
 1307        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1308            .detach();
 1309        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1310            .detach();
 1311
 1312        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1313            Some(false)
 1314        } else {
 1315            None
 1316        };
 1317
 1318        let mut code_action_providers = Vec::new();
 1319        if let Some(project) = project.clone() {
 1320            get_uncommitted_diff_for_buffer(
 1321                &project,
 1322                buffer.read(cx).all_buffers(),
 1323                buffer.clone(),
 1324                cx,
 1325            );
 1326            code_action_providers.push(Rc::new(project) as Rc<_>);
 1327        }
 1328
 1329        let mut this = Self {
 1330            focus_handle,
 1331            show_cursor_when_unfocused: false,
 1332            last_focused_descendant: None,
 1333            buffer: buffer.clone(),
 1334            display_map: display_map.clone(),
 1335            selections,
 1336            scroll_manager: ScrollManager::new(cx),
 1337            columnar_selection_tail: None,
 1338            add_selections_state: None,
 1339            select_next_state: None,
 1340            select_prev_state: None,
 1341            selection_history: Default::default(),
 1342            autoclose_regions: Default::default(),
 1343            snippet_stack: Default::default(),
 1344            select_larger_syntax_node_stack: Vec::new(),
 1345            ime_transaction: Default::default(),
 1346            active_diagnostics: None,
 1347            soft_wrap_mode_override,
 1348            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1349            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1350            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1351            project,
 1352            blink_manager: blink_manager.clone(),
 1353            show_local_selections: true,
 1354            show_scrollbars: true,
 1355            mode,
 1356            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1357            show_gutter: mode == EditorMode::Full,
 1358            show_line_numbers: None,
 1359            use_relative_line_numbers: None,
 1360            show_git_diff_gutter: None,
 1361            show_code_actions: None,
 1362            show_runnables: None,
 1363            show_wrap_guides: None,
 1364            show_indent_guides,
 1365            placeholder_text: None,
 1366            highlight_order: 0,
 1367            highlighted_rows: HashMap::default(),
 1368            background_highlights: Default::default(),
 1369            gutter_highlights: TreeMap::default(),
 1370            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1371            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1372            nav_history: None,
 1373            context_menu: RefCell::new(None),
 1374            mouse_context_menu: None,
 1375            completion_tasks: Default::default(),
 1376            signature_help_state: SignatureHelpState::default(),
 1377            auto_signature_help: None,
 1378            find_all_references_task_sources: Vec::new(),
 1379            next_completion_id: 0,
 1380            next_inlay_id: 0,
 1381            code_action_providers,
 1382            available_code_actions: Default::default(),
 1383            code_actions_task: Default::default(),
 1384            document_highlights_task: Default::default(),
 1385            linked_editing_range_task: Default::default(),
 1386            pending_rename: Default::default(),
 1387            searchable: true,
 1388            cursor_shape: EditorSettings::get_global(cx)
 1389                .cursor_shape
 1390                .unwrap_or_default(),
 1391            current_line_highlight: None,
 1392            autoindent_mode: Some(AutoindentMode::EachLine),
 1393            collapse_matches: false,
 1394            workspace: None,
 1395            input_enabled: true,
 1396            use_modal_editing: mode == EditorMode::Full,
 1397            read_only: false,
 1398            use_autoclose: true,
 1399            use_auto_surround: true,
 1400            auto_replace_emoji_shortcode: false,
 1401            leader_peer_id: None,
 1402            remote_id: None,
 1403            hover_state: Default::default(),
 1404            pending_mouse_down: None,
 1405            hovered_link_state: Default::default(),
 1406            edit_prediction_provider: None,
 1407            active_inline_completion: None,
 1408            stale_inline_completion_in_menu: None,
 1409            edit_prediction_preview: EditPredictionPreview::Inactive,
 1410            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1411
 1412            gutter_hovered: false,
 1413            pixel_position_of_newest_cursor: None,
 1414            last_bounds: None,
 1415            last_position_map: None,
 1416            expect_bounds_change: None,
 1417            gutter_dimensions: GutterDimensions::default(),
 1418            style: None,
 1419            show_cursor_names: false,
 1420            hovered_cursors: Default::default(),
 1421            next_editor_action_id: EditorActionId::default(),
 1422            editor_actions: Rc::default(),
 1423            inline_completions_hidden_for_vim_mode: false,
 1424            show_inline_completions_override: None,
 1425            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1426            edit_prediction_settings: EditPredictionSettings::Disabled,
 1427            edit_prediction_cursor_on_leading_whitespace: false,
 1428            custom_context_menu: None,
 1429            show_git_blame_gutter: false,
 1430            show_git_blame_inline: false,
 1431            distinguish_unstaged_diff_hunks: false,
 1432            show_selection_menu: None,
 1433            show_git_blame_inline_delay_task: None,
 1434            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1435            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1436                .session
 1437                .restore_unsaved_buffers,
 1438            blame: None,
 1439            blame_subscription: None,
 1440            tasks: Default::default(),
 1441            _subscriptions: vec![
 1442                cx.observe(&buffer, Self::on_buffer_changed),
 1443                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1444                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1445                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1446                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1447                cx.observe_window_activation(window, |editor, window, cx| {
 1448                    let active = window.is_window_active();
 1449                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1450                        if active {
 1451                            blink_manager.enable(cx);
 1452                        } else {
 1453                            blink_manager.disable(cx);
 1454                        }
 1455                    });
 1456                }),
 1457            ],
 1458            tasks_update_task: None,
 1459            linked_edit_ranges: Default::default(),
 1460            in_project_search: false,
 1461            previous_search_ranges: None,
 1462            breadcrumb_header: None,
 1463            focused_block: None,
 1464            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1465            addons: HashMap::default(),
 1466            registered_buffers: HashMap::default(),
 1467            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1468            selection_mark_mode: false,
 1469            toggle_fold_multiple_buffers: Task::ready(()),
 1470            text_style_refinement: None,
 1471        };
 1472        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1473        this._subscriptions.extend(project_subscriptions);
 1474
 1475        this.end_selection(window, cx);
 1476        this.scroll_manager.show_scrollbar(window, cx);
 1477
 1478        if mode == EditorMode::Full {
 1479            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1480            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1481
 1482            if this.git_blame_inline_enabled {
 1483                this.git_blame_inline_enabled = true;
 1484                this.start_git_blame_inline(false, window, cx);
 1485            }
 1486
 1487            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1488                if let Some(project) = this.project.as_ref() {
 1489                    let lsp_store = project.read(cx).lsp_store();
 1490                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1491                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1492                    });
 1493                    this.registered_buffers
 1494                        .insert(buffer.read(cx).remote_id(), handle);
 1495                }
 1496            }
 1497        }
 1498
 1499        this.report_editor_event("Editor Opened", None, cx);
 1500        this
 1501    }
 1502
 1503    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1504        self.mouse_context_menu
 1505            .as_ref()
 1506            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1507    }
 1508
 1509    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1510        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1511    }
 1512
 1513    fn key_context_internal(
 1514        &self,
 1515        has_active_edit_prediction: bool,
 1516        window: &Window,
 1517        cx: &App,
 1518    ) -> KeyContext {
 1519        let mut key_context = KeyContext::new_with_defaults();
 1520        key_context.add("Editor");
 1521        let mode = match self.mode {
 1522            EditorMode::SingleLine { .. } => "single_line",
 1523            EditorMode::AutoHeight { .. } => "auto_height",
 1524            EditorMode::Full => "full",
 1525        };
 1526
 1527        if EditorSettings::jupyter_enabled(cx) {
 1528            key_context.add("jupyter");
 1529        }
 1530
 1531        key_context.set("mode", mode);
 1532        if self.pending_rename.is_some() {
 1533            key_context.add("renaming");
 1534        }
 1535
 1536        let mut showing_completions = false;
 1537
 1538        match self.context_menu.borrow().as_ref() {
 1539            Some(CodeContextMenu::Completions(_)) => {
 1540                key_context.add("menu");
 1541                key_context.add("showing_completions");
 1542                showing_completions = true;
 1543            }
 1544            Some(CodeContextMenu::CodeActions(_)) => {
 1545                key_context.add("menu");
 1546                key_context.add("showing_code_actions")
 1547            }
 1548            None => {}
 1549        }
 1550
 1551        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1552        if !self.focus_handle(cx).contains_focused(window, cx)
 1553            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1554        {
 1555            for addon in self.addons.values() {
 1556                addon.extend_key_context(&mut key_context, cx)
 1557            }
 1558        }
 1559
 1560        if let Some(extension) = self
 1561            .buffer
 1562            .read(cx)
 1563            .as_singleton()
 1564            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1565        {
 1566            key_context.set("extension", extension.to_string());
 1567        }
 1568
 1569        if has_active_edit_prediction {
 1570            key_context.add("copilot_suggestion");
 1571            key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1572            if showing_completions
 1573                || self.edit_prediction_requires_modifier()
 1574                // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1575                // bindings to insert tab characters.
 1576                || self.edit_prediction_cursor_on_leading_whitespace
 1577            {
 1578                key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
 1579            }
 1580        }
 1581
 1582        if self.selection_mark_mode {
 1583            key_context.add("selection_mode");
 1584        }
 1585
 1586        key_context
 1587    }
 1588
 1589    pub fn accept_edit_prediction_keybind(
 1590        &self,
 1591        window: &Window,
 1592        cx: &App,
 1593    ) -> AcceptEditPredictionBinding {
 1594        let key_context = self.key_context_internal(true, window, cx);
 1595        AcceptEditPredictionBinding(
 1596            window
 1597                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1598                .into_iter()
 1599                .rev()
 1600                .next(),
 1601        )
 1602    }
 1603
 1604    pub fn new_file(
 1605        workspace: &mut Workspace,
 1606        _: &workspace::NewFile,
 1607        window: &mut Window,
 1608        cx: &mut Context<Workspace>,
 1609    ) {
 1610        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1611            "Failed to create buffer",
 1612            window,
 1613            cx,
 1614            |e, _, _| match e.error_code() {
 1615                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1616                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1617                e.error_tag("required").unwrap_or("the latest version")
 1618            )),
 1619                _ => None,
 1620            },
 1621        );
 1622    }
 1623
 1624    pub fn new_in_workspace(
 1625        workspace: &mut Workspace,
 1626        window: &mut Window,
 1627        cx: &mut Context<Workspace>,
 1628    ) -> Task<Result<Entity<Editor>>> {
 1629        let project = workspace.project().clone();
 1630        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1631
 1632        cx.spawn_in(window, |workspace, mut cx| async move {
 1633            let buffer = create.await?;
 1634            workspace.update_in(&mut cx, |workspace, window, cx| {
 1635                let editor =
 1636                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1637                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1638                editor
 1639            })
 1640        })
 1641    }
 1642
 1643    fn new_file_vertical(
 1644        workspace: &mut Workspace,
 1645        _: &workspace::NewFileSplitVertical,
 1646        window: &mut Window,
 1647        cx: &mut Context<Workspace>,
 1648    ) {
 1649        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1650    }
 1651
 1652    fn new_file_horizontal(
 1653        workspace: &mut Workspace,
 1654        _: &workspace::NewFileSplitHorizontal,
 1655        window: &mut Window,
 1656        cx: &mut Context<Workspace>,
 1657    ) {
 1658        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1659    }
 1660
 1661    fn new_file_in_direction(
 1662        workspace: &mut Workspace,
 1663        direction: SplitDirection,
 1664        window: &mut Window,
 1665        cx: &mut Context<Workspace>,
 1666    ) {
 1667        let project = workspace.project().clone();
 1668        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1669
 1670        cx.spawn_in(window, |workspace, mut cx| async move {
 1671            let buffer = create.await?;
 1672            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1673                workspace.split_item(
 1674                    direction,
 1675                    Box::new(
 1676                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1677                    ),
 1678                    window,
 1679                    cx,
 1680                )
 1681            })?;
 1682            anyhow::Ok(())
 1683        })
 1684        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1685            match e.error_code() {
 1686                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1687                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1688                e.error_tag("required").unwrap_or("the latest version")
 1689            )),
 1690                _ => None,
 1691            }
 1692        });
 1693    }
 1694
 1695    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1696        self.leader_peer_id
 1697    }
 1698
 1699    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1700        &self.buffer
 1701    }
 1702
 1703    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1704        self.workspace.as_ref()?.0.upgrade()
 1705    }
 1706
 1707    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1708        self.buffer().read(cx).title(cx)
 1709    }
 1710
 1711    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1712        let git_blame_gutter_max_author_length = self
 1713            .render_git_blame_gutter(cx)
 1714            .then(|| {
 1715                if let Some(blame) = self.blame.as_ref() {
 1716                    let max_author_length =
 1717                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1718                    Some(max_author_length)
 1719                } else {
 1720                    None
 1721                }
 1722            })
 1723            .flatten();
 1724
 1725        EditorSnapshot {
 1726            mode: self.mode,
 1727            show_gutter: self.show_gutter,
 1728            show_line_numbers: self.show_line_numbers,
 1729            show_git_diff_gutter: self.show_git_diff_gutter,
 1730            show_code_actions: self.show_code_actions,
 1731            show_runnables: self.show_runnables,
 1732            git_blame_gutter_max_author_length,
 1733            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1734            scroll_anchor: self.scroll_manager.anchor(),
 1735            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1736            placeholder_text: self.placeholder_text.clone(),
 1737            is_focused: self.focus_handle.is_focused(window),
 1738            current_line_highlight: self
 1739                .current_line_highlight
 1740                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1741            gutter_hovered: self.gutter_hovered,
 1742        }
 1743    }
 1744
 1745    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1746        self.buffer.read(cx).language_at(point, cx)
 1747    }
 1748
 1749    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1750        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1751    }
 1752
 1753    pub fn active_excerpt(
 1754        &self,
 1755        cx: &App,
 1756    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1757        self.buffer
 1758            .read(cx)
 1759            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1760    }
 1761
 1762    pub fn mode(&self) -> EditorMode {
 1763        self.mode
 1764    }
 1765
 1766    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1767        self.collaboration_hub.as_deref()
 1768    }
 1769
 1770    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1771        self.collaboration_hub = Some(hub);
 1772    }
 1773
 1774    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1775        self.in_project_search = in_project_search;
 1776    }
 1777
 1778    pub fn set_custom_context_menu(
 1779        &mut self,
 1780        f: impl 'static
 1781            + Fn(
 1782                &mut Self,
 1783                DisplayPoint,
 1784                &mut Window,
 1785                &mut Context<Self>,
 1786            ) -> Option<Entity<ui::ContextMenu>>,
 1787    ) {
 1788        self.custom_context_menu = Some(Box::new(f))
 1789    }
 1790
 1791    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1792        self.completion_provider = provider;
 1793    }
 1794
 1795    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1796        self.semantics_provider.clone()
 1797    }
 1798
 1799    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1800        self.semantics_provider = provider;
 1801    }
 1802
 1803    pub fn set_edit_prediction_provider<T>(
 1804        &mut self,
 1805        provider: Option<Entity<T>>,
 1806        window: &mut Window,
 1807        cx: &mut Context<Self>,
 1808    ) where
 1809        T: EditPredictionProvider,
 1810    {
 1811        self.edit_prediction_provider =
 1812            provider.map(|provider| RegisteredInlineCompletionProvider {
 1813                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1814                    if this.focus_handle.is_focused(window) {
 1815                        this.update_visible_inline_completion(window, cx);
 1816                    }
 1817                }),
 1818                provider: Arc::new(provider),
 1819            });
 1820        self.refresh_inline_completion(false, false, window, cx);
 1821    }
 1822
 1823    pub fn placeholder_text(&self) -> Option<&str> {
 1824        self.placeholder_text.as_deref()
 1825    }
 1826
 1827    pub fn set_placeholder_text(
 1828        &mut self,
 1829        placeholder_text: impl Into<Arc<str>>,
 1830        cx: &mut Context<Self>,
 1831    ) {
 1832        let placeholder_text = Some(placeholder_text.into());
 1833        if self.placeholder_text != placeholder_text {
 1834            self.placeholder_text = placeholder_text;
 1835            cx.notify();
 1836        }
 1837    }
 1838
 1839    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1840        self.cursor_shape = cursor_shape;
 1841
 1842        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1843        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1844
 1845        cx.notify();
 1846    }
 1847
 1848    pub fn set_current_line_highlight(
 1849        &mut self,
 1850        current_line_highlight: Option<CurrentLineHighlight>,
 1851    ) {
 1852        self.current_line_highlight = current_line_highlight;
 1853    }
 1854
 1855    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1856        self.collapse_matches = collapse_matches;
 1857    }
 1858
 1859    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1860        let buffers = self.buffer.read(cx).all_buffers();
 1861        let Some(lsp_store) = self.lsp_store(cx) else {
 1862            return;
 1863        };
 1864        lsp_store.update(cx, |lsp_store, cx| {
 1865            for buffer in buffers {
 1866                self.registered_buffers
 1867                    .entry(buffer.read(cx).remote_id())
 1868                    .or_insert_with(|| {
 1869                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1870                    });
 1871            }
 1872        })
 1873    }
 1874
 1875    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1876        if self.collapse_matches {
 1877            return range.start..range.start;
 1878        }
 1879        range.clone()
 1880    }
 1881
 1882    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1883        if self.display_map.read(cx).clip_at_line_ends != clip {
 1884            self.display_map
 1885                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1886        }
 1887    }
 1888
 1889    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1890        self.input_enabled = input_enabled;
 1891    }
 1892
 1893    pub fn set_inline_completions_hidden_for_vim_mode(
 1894        &mut self,
 1895        hidden: bool,
 1896        window: &mut Window,
 1897        cx: &mut Context<Self>,
 1898    ) {
 1899        if hidden != self.inline_completions_hidden_for_vim_mode {
 1900            self.inline_completions_hidden_for_vim_mode = hidden;
 1901            if hidden {
 1902                self.update_visible_inline_completion(window, cx);
 1903            } else {
 1904                self.refresh_inline_completion(true, false, window, cx);
 1905            }
 1906        }
 1907    }
 1908
 1909    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1910        self.menu_inline_completions_policy = value;
 1911    }
 1912
 1913    pub fn set_autoindent(&mut self, autoindent: bool) {
 1914        if autoindent {
 1915            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1916        } else {
 1917            self.autoindent_mode = None;
 1918        }
 1919    }
 1920
 1921    pub fn read_only(&self, cx: &App) -> bool {
 1922        self.read_only || self.buffer.read(cx).read_only()
 1923    }
 1924
 1925    pub fn set_read_only(&mut self, read_only: bool) {
 1926        self.read_only = read_only;
 1927    }
 1928
 1929    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1930        self.use_autoclose = autoclose;
 1931    }
 1932
 1933    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1934        self.use_auto_surround = auto_surround;
 1935    }
 1936
 1937    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1938        self.auto_replace_emoji_shortcode = auto_replace;
 1939    }
 1940
 1941    pub fn toggle_inline_completions(
 1942        &mut self,
 1943        _: &ToggleEditPrediction,
 1944        window: &mut Window,
 1945        cx: &mut Context<Self>,
 1946    ) {
 1947        if self.show_inline_completions_override.is_some() {
 1948            self.set_show_edit_predictions(None, window, cx);
 1949        } else {
 1950            let show_edit_predictions = !self.edit_predictions_enabled();
 1951            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1952        }
 1953    }
 1954
 1955    pub fn set_show_edit_predictions(
 1956        &mut self,
 1957        show_edit_predictions: Option<bool>,
 1958        window: &mut Window,
 1959        cx: &mut Context<Self>,
 1960    ) {
 1961        self.show_inline_completions_override = show_edit_predictions;
 1962        self.refresh_inline_completion(false, true, window, cx);
 1963    }
 1964
 1965    fn inline_completions_disabled_in_scope(
 1966        &self,
 1967        buffer: &Entity<Buffer>,
 1968        buffer_position: language::Anchor,
 1969        cx: &App,
 1970    ) -> bool {
 1971        let snapshot = buffer.read(cx).snapshot();
 1972        let settings = snapshot.settings_at(buffer_position, cx);
 1973
 1974        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1975            return false;
 1976        };
 1977
 1978        scope.override_name().map_or(false, |scope_name| {
 1979            settings
 1980                .edit_predictions_disabled_in
 1981                .iter()
 1982                .any(|s| s == scope_name)
 1983        })
 1984    }
 1985
 1986    pub fn set_use_modal_editing(&mut self, to: bool) {
 1987        self.use_modal_editing = to;
 1988    }
 1989
 1990    pub fn use_modal_editing(&self) -> bool {
 1991        self.use_modal_editing
 1992    }
 1993
 1994    fn selections_did_change(
 1995        &mut self,
 1996        local: bool,
 1997        old_cursor_position: &Anchor,
 1998        show_completions: bool,
 1999        window: &mut Window,
 2000        cx: &mut Context<Self>,
 2001    ) {
 2002        window.invalidate_character_coordinates();
 2003
 2004        // Copy selections to primary selection buffer
 2005        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2006        if local {
 2007            let selections = self.selections.all::<usize>(cx);
 2008            let buffer_handle = self.buffer.read(cx).read(cx);
 2009
 2010            let mut text = String::new();
 2011            for (index, selection) in selections.iter().enumerate() {
 2012                let text_for_selection = buffer_handle
 2013                    .text_for_range(selection.start..selection.end)
 2014                    .collect::<String>();
 2015
 2016                text.push_str(&text_for_selection);
 2017                if index != selections.len() - 1 {
 2018                    text.push('\n');
 2019                }
 2020            }
 2021
 2022            if !text.is_empty() {
 2023                cx.write_to_primary(ClipboardItem::new_string(text));
 2024            }
 2025        }
 2026
 2027        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2028            self.buffer.update(cx, |buffer, cx| {
 2029                buffer.set_active_selections(
 2030                    &self.selections.disjoint_anchors(),
 2031                    self.selections.line_mode,
 2032                    self.cursor_shape,
 2033                    cx,
 2034                )
 2035            });
 2036        }
 2037        let display_map = self
 2038            .display_map
 2039            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2040        let buffer = &display_map.buffer_snapshot;
 2041        self.add_selections_state = None;
 2042        self.select_next_state = None;
 2043        self.select_prev_state = None;
 2044        self.select_larger_syntax_node_stack.clear();
 2045        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2046        self.snippet_stack
 2047            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2048        self.take_rename(false, window, cx);
 2049
 2050        let new_cursor_position = self.selections.newest_anchor().head();
 2051
 2052        self.push_to_nav_history(
 2053            *old_cursor_position,
 2054            Some(new_cursor_position.to_point(buffer)),
 2055            cx,
 2056        );
 2057
 2058        if local {
 2059            let new_cursor_position = self.selections.newest_anchor().head();
 2060            let mut context_menu = self.context_menu.borrow_mut();
 2061            let completion_menu = match context_menu.as_ref() {
 2062                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2063                _ => {
 2064                    *context_menu = None;
 2065                    None
 2066                }
 2067            };
 2068            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2069                if !self.registered_buffers.contains_key(&buffer_id) {
 2070                    if let Some(lsp_store) = self.lsp_store(cx) {
 2071                        lsp_store.update(cx, |lsp_store, cx| {
 2072                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2073                                return;
 2074                            };
 2075                            self.registered_buffers.insert(
 2076                                buffer_id,
 2077                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2078                            );
 2079                        })
 2080                    }
 2081                }
 2082            }
 2083
 2084            if let Some(completion_menu) = completion_menu {
 2085                let cursor_position = new_cursor_position.to_offset(buffer);
 2086                let (word_range, kind) =
 2087                    buffer.surrounding_word(completion_menu.initial_position, true);
 2088                if kind == Some(CharKind::Word)
 2089                    && word_range.to_inclusive().contains(&cursor_position)
 2090                {
 2091                    let mut completion_menu = completion_menu.clone();
 2092                    drop(context_menu);
 2093
 2094                    let query = Self::completion_query(buffer, cursor_position);
 2095                    cx.spawn(move |this, mut cx| async move {
 2096                        completion_menu
 2097                            .filter(query.as_deref(), cx.background_executor().clone())
 2098                            .await;
 2099
 2100                        this.update(&mut cx, |this, cx| {
 2101                            let mut context_menu = this.context_menu.borrow_mut();
 2102                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2103                            else {
 2104                                return;
 2105                            };
 2106
 2107                            if menu.id > completion_menu.id {
 2108                                return;
 2109                            }
 2110
 2111                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2112                            drop(context_menu);
 2113                            cx.notify();
 2114                        })
 2115                    })
 2116                    .detach();
 2117
 2118                    if show_completions {
 2119                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2120                    }
 2121                } else {
 2122                    drop(context_menu);
 2123                    self.hide_context_menu(window, cx);
 2124                }
 2125            } else {
 2126                drop(context_menu);
 2127            }
 2128
 2129            hide_hover(self, cx);
 2130
 2131            if old_cursor_position.to_display_point(&display_map).row()
 2132                != new_cursor_position.to_display_point(&display_map).row()
 2133            {
 2134                self.available_code_actions.take();
 2135            }
 2136            self.refresh_code_actions(window, cx);
 2137            self.refresh_document_highlights(cx);
 2138            refresh_matching_bracket_highlights(self, window, cx);
 2139            self.update_visible_inline_completion(window, cx);
 2140            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2141            if self.git_blame_inline_enabled {
 2142                self.start_inline_blame_timer(window, cx);
 2143            }
 2144        }
 2145
 2146        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2147        cx.emit(EditorEvent::SelectionsChanged { local });
 2148
 2149        if self.selections.disjoint_anchors().len() == 1 {
 2150            cx.emit(SearchEvent::ActiveMatchChanged)
 2151        }
 2152        cx.notify();
 2153    }
 2154
 2155    pub fn change_selections<R>(
 2156        &mut self,
 2157        autoscroll: Option<Autoscroll>,
 2158        window: &mut Window,
 2159        cx: &mut Context<Self>,
 2160        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2161    ) -> R {
 2162        self.change_selections_inner(autoscroll, true, window, cx, change)
 2163    }
 2164
 2165    pub fn change_selections_inner<R>(
 2166        &mut self,
 2167        autoscroll: Option<Autoscroll>,
 2168        request_completions: bool,
 2169        window: &mut Window,
 2170        cx: &mut Context<Self>,
 2171        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2172    ) -> R {
 2173        let old_cursor_position = self.selections.newest_anchor().head();
 2174        self.push_to_selection_history();
 2175
 2176        let (changed, result) = self.selections.change_with(cx, change);
 2177
 2178        if changed {
 2179            if let Some(autoscroll) = autoscroll {
 2180                self.request_autoscroll(autoscroll, cx);
 2181            }
 2182            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2183
 2184            if self.should_open_signature_help_automatically(
 2185                &old_cursor_position,
 2186                self.signature_help_state.backspace_pressed(),
 2187                cx,
 2188            ) {
 2189                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2190            }
 2191            self.signature_help_state.set_backspace_pressed(false);
 2192        }
 2193
 2194        result
 2195    }
 2196
 2197    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2198    where
 2199        I: IntoIterator<Item = (Range<S>, T)>,
 2200        S: ToOffset,
 2201        T: Into<Arc<str>>,
 2202    {
 2203        if self.read_only(cx) {
 2204            return;
 2205        }
 2206
 2207        self.buffer
 2208            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2209    }
 2210
 2211    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2212    where
 2213        I: IntoIterator<Item = (Range<S>, T)>,
 2214        S: ToOffset,
 2215        T: Into<Arc<str>>,
 2216    {
 2217        if self.read_only(cx) {
 2218            return;
 2219        }
 2220
 2221        self.buffer.update(cx, |buffer, cx| {
 2222            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2223        });
 2224    }
 2225
 2226    pub fn edit_with_block_indent<I, S, T>(
 2227        &mut self,
 2228        edits: I,
 2229        original_indent_columns: Vec<u32>,
 2230        cx: &mut Context<Self>,
 2231    ) where
 2232        I: IntoIterator<Item = (Range<S>, T)>,
 2233        S: ToOffset,
 2234        T: Into<Arc<str>>,
 2235    {
 2236        if self.read_only(cx) {
 2237            return;
 2238        }
 2239
 2240        self.buffer.update(cx, |buffer, cx| {
 2241            buffer.edit(
 2242                edits,
 2243                Some(AutoindentMode::Block {
 2244                    original_indent_columns,
 2245                }),
 2246                cx,
 2247            )
 2248        });
 2249    }
 2250
 2251    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2252        self.hide_context_menu(window, cx);
 2253
 2254        match phase {
 2255            SelectPhase::Begin {
 2256                position,
 2257                add,
 2258                click_count,
 2259            } => self.begin_selection(position, add, click_count, window, cx),
 2260            SelectPhase::BeginColumnar {
 2261                position,
 2262                goal_column,
 2263                reset,
 2264            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2265            SelectPhase::Extend {
 2266                position,
 2267                click_count,
 2268            } => self.extend_selection(position, click_count, window, cx),
 2269            SelectPhase::Update {
 2270                position,
 2271                goal_column,
 2272                scroll_delta,
 2273            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2274            SelectPhase::End => self.end_selection(window, cx),
 2275        }
 2276    }
 2277
 2278    fn extend_selection(
 2279        &mut self,
 2280        position: DisplayPoint,
 2281        click_count: usize,
 2282        window: &mut Window,
 2283        cx: &mut Context<Self>,
 2284    ) {
 2285        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2286        let tail = self.selections.newest::<usize>(cx).tail();
 2287        self.begin_selection(position, false, click_count, window, cx);
 2288
 2289        let position = position.to_offset(&display_map, Bias::Left);
 2290        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2291
 2292        let mut pending_selection = self
 2293            .selections
 2294            .pending_anchor()
 2295            .expect("extend_selection not called with pending selection");
 2296        if position >= tail {
 2297            pending_selection.start = tail_anchor;
 2298        } else {
 2299            pending_selection.end = tail_anchor;
 2300            pending_selection.reversed = true;
 2301        }
 2302
 2303        let mut pending_mode = self.selections.pending_mode().unwrap();
 2304        match &mut pending_mode {
 2305            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2306            _ => {}
 2307        }
 2308
 2309        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2310            s.set_pending(pending_selection, pending_mode)
 2311        });
 2312    }
 2313
 2314    fn begin_selection(
 2315        &mut self,
 2316        position: DisplayPoint,
 2317        add: bool,
 2318        click_count: usize,
 2319        window: &mut Window,
 2320        cx: &mut Context<Self>,
 2321    ) {
 2322        if !self.focus_handle.is_focused(window) {
 2323            self.last_focused_descendant = None;
 2324            window.focus(&self.focus_handle);
 2325        }
 2326
 2327        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2328        let buffer = &display_map.buffer_snapshot;
 2329        let newest_selection = self.selections.newest_anchor().clone();
 2330        let position = display_map.clip_point(position, Bias::Left);
 2331
 2332        let start;
 2333        let end;
 2334        let mode;
 2335        let mut auto_scroll;
 2336        match click_count {
 2337            1 => {
 2338                start = buffer.anchor_before(position.to_point(&display_map));
 2339                end = start;
 2340                mode = SelectMode::Character;
 2341                auto_scroll = true;
 2342            }
 2343            2 => {
 2344                let range = movement::surrounding_word(&display_map, position);
 2345                start = buffer.anchor_before(range.start.to_point(&display_map));
 2346                end = buffer.anchor_before(range.end.to_point(&display_map));
 2347                mode = SelectMode::Word(start..end);
 2348                auto_scroll = true;
 2349            }
 2350            3 => {
 2351                let position = display_map
 2352                    .clip_point(position, Bias::Left)
 2353                    .to_point(&display_map);
 2354                let line_start = display_map.prev_line_boundary(position).0;
 2355                let next_line_start = buffer.clip_point(
 2356                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2357                    Bias::Left,
 2358                );
 2359                start = buffer.anchor_before(line_start);
 2360                end = buffer.anchor_before(next_line_start);
 2361                mode = SelectMode::Line(start..end);
 2362                auto_scroll = true;
 2363            }
 2364            _ => {
 2365                start = buffer.anchor_before(0);
 2366                end = buffer.anchor_before(buffer.len());
 2367                mode = SelectMode::All;
 2368                auto_scroll = false;
 2369            }
 2370        }
 2371        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2372
 2373        let point_to_delete: Option<usize> = {
 2374            let selected_points: Vec<Selection<Point>> =
 2375                self.selections.disjoint_in_range(start..end, cx);
 2376
 2377            if !add || click_count > 1 {
 2378                None
 2379            } else if !selected_points.is_empty() {
 2380                Some(selected_points[0].id)
 2381            } else {
 2382                let clicked_point_already_selected =
 2383                    self.selections.disjoint.iter().find(|selection| {
 2384                        selection.start.to_point(buffer) == start.to_point(buffer)
 2385                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2386                    });
 2387
 2388                clicked_point_already_selected.map(|selection| selection.id)
 2389            }
 2390        };
 2391
 2392        let selections_count = self.selections.count();
 2393
 2394        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2395            if let Some(point_to_delete) = point_to_delete {
 2396                s.delete(point_to_delete);
 2397
 2398                if selections_count == 1 {
 2399                    s.set_pending_anchor_range(start..end, mode);
 2400                }
 2401            } else {
 2402                if !add {
 2403                    s.clear_disjoint();
 2404                } else if click_count > 1 {
 2405                    s.delete(newest_selection.id)
 2406                }
 2407
 2408                s.set_pending_anchor_range(start..end, mode);
 2409            }
 2410        });
 2411    }
 2412
 2413    fn begin_columnar_selection(
 2414        &mut self,
 2415        position: DisplayPoint,
 2416        goal_column: u32,
 2417        reset: bool,
 2418        window: &mut Window,
 2419        cx: &mut Context<Self>,
 2420    ) {
 2421        if !self.focus_handle.is_focused(window) {
 2422            self.last_focused_descendant = None;
 2423            window.focus(&self.focus_handle);
 2424        }
 2425
 2426        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2427
 2428        if reset {
 2429            let pointer_position = display_map
 2430                .buffer_snapshot
 2431                .anchor_before(position.to_point(&display_map));
 2432
 2433            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2434                s.clear_disjoint();
 2435                s.set_pending_anchor_range(
 2436                    pointer_position..pointer_position,
 2437                    SelectMode::Character,
 2438                );
 2439            });
 2440        }
 2441
 2442        let tail = self.selections.newest::<Point>(cx).tail();
 2443        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2444
 2445        if !reset {
 2446            self.select_columns(
 2447                tail.to_display_point(&display_map),
 2448                position,
 2449                goal_column,
 2450                &display_map,
 2451                window,
 2452                cx,
 2453            );
 2454        }
 2455    }
 2456
 2457    fn update_selection(
 2458        &mut self,
 2459        position: DisplayPoint,
 2460        goal_column: u32,
 2461        scroll_delta: gpui::Point<f32>,
 2462        window: &mut Window,
 2463        cx: &mut Context<Self>,
 2464    ) {
 2465        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2466
 2467        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2468            let tail = tail.to_display_point(&display_map);
 2469            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2470        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2471            let buffer = self.buffer.read(cx).snapshot(cx);
 2472            let head;
 2473            let tail;
 2474            let mode = self.selections.pending_mode().unwrap();
 2475            match &mode {
 2476                SelectMode::Character => {
 2477                    head = position.to_point(&display_map);
 2478                    tail = pending.tail().to_point(&buffer);
 2479                }
 2480                SelectMode::Word(original_range) => {
 2481                    let original_display_range = original_range.start.to_display_point(&display_map)
 2482                        ..original_range.end.to_display_point(&display_map);
 2483                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2484                        ..original_display_range.end.to_point(&display_map);
 2485                    if movement::is_inside_word(&display_map, position)
 2486                        || original_display_range.contains(&position)
 2487                    {
 2488                        let word_range = movement::surrounding_word(&display_map, position);
 2489                        if word_range.start < original_display_range.start {
 2490                            head = word_range.start.to_point(&display_map);
 2491                        } else {
 2492                            head = word_range.end.to_point(&display_map);
 2493                        }
 2494                    } else {
 2495                        head = position.to_point(&display_map);
 2496                    }
 2497
 2498                    if head <= original_buffer_range.start {
 2499                        tail = original_buffer_range.end;
 2500                    } else {
 2501                        tail = original_buffer_range.start;
 2502                    }
 2503                }
 2504                SelectMode::Line(original_range) => {
 2505                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2506
 2507                    let position = display_map
 2508                        .clip_point(position, Bias::Left)
 2509                        .to_point(&display_map);
 2510                    let line_start = display_map.prev_line_boundary(position).0;
 2511                    let next_line_start = buffer.clip_point(
 2512                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2513                        Bias::Left,
 2514                    );
 2515
 2516                    if line_start < original_range.start {
 2517                        head = line_start
 2518                    } else {
 2519                        head = next_line_start
 2520                    }
 2521
 2522                    if head <= original_range.start {
 2523                        tail = original_range.end;
 2524                    } else {
 2525                        tail = original_range.start;
 2526                    }
 2527                }
 2528                SelectMode::All => {
 2529                    return;
 2530                }
 2531            };
 2532
 2533            if head < tail {
 2534                pending.start = buffer.anchor_before(head);
 2535                pending.end = buffer.anchor_before(tail);
 2536                pending.reversed = true;
 2537            } else {
 2538                pending.start = buffer.anchor_before(tail);
 2539                pending.end = buffer.anchor_before(head);
 2540                pending.reversed = false;
 2541            }
 2542
 2543            self.change_selections(None, window, cx, |s| {
 2544                s.set_pending(pending, mode);
 2545            });
 2546        } else {
 2547            log::error!("update_selection dispatched with no pending selection");
 2548            return;
 2549        }
 2550
 2551        self.apply_scroll_delta(scroll_delta, window, cx);
 2552        cx.notify();
 2553    }
 2554
 2555    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2556        self.columnar_selection_tail.take();
 2557        if self.selections.pending_anchor().is_some() {
 2558            let selections = self.selections.all::<usize>(cx);
 2559            self.change_selections(None, window, cx, |s| {
 2560                s.select(selections);
 2561                s.clear_pending();
 2562            });
 2563        }
 2564    }
 2565
 2566    fn select_columns(
 2567        &mut self,
 2568        tail: DisplayPoint,
 2569        head: DisplayPoint,
 2570        goal_column: u32,
 2571        display_map: &DisplaySnapshot,
 2572        window: &mut Window,
 2573        cx: &mut Context<Self>,
 2574    ) {
 2575        let start_row = cmp::min(tail.row(), head.row());
 2576        let end_row = cmp::max(tail.row(), head.row());
 2577        let start_column = cmp::min(tail.column(), goal_column);
 2578        let end_column = cmp::max(tail.column(), goal_column);
 2579        let reversed = start_column < tail.column();
 2580
 2581        let selection_ranges = (start_row.0..=end_row.0)
 2582            .map(DisplayRow)
 2583            .filter_map(|row| {
 2584                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2585                    let start = display_map
 2586                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2587                        .to_point(display_map);
 2588                    let end = display_map
 2589                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2590                        .to_point(display_map);
 2591                    if reversed {
 2592                        Some(end..start)
 2593                    } else {
 2594                        Some(start..end)
 2595                    }
 2596                } else {
 2597                    None
 2598                }
 2599            })
 2600            .collect::<Vec<_>>();
 2601
 2602        self.change_selections(None, window, cx, |s| {
 2603            s.select_ranges(selection_ranges);
 2604        });
 2605        cx.notify();
 2606    }
 2607
 2608    pub fn has_pending_nonempty_selection(&self) -> bool {
 2609        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2610            Some(Selection { start, end, .. }) => start != end,
 2611            None => false,
 2612        };
 2613
 2614        pending_nonempty_selection
 2615            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2616    }
 2617
 2618    pub fn has_pending_selection(&self) -> bool {
 2619        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2620    }
 2621
 2622    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2623        self.selection_mark_mode = false;
 2624
 2625        if self.clear_expanded_diff_hunks(cx) {
 2626            cx.notify();
 2627            return;
 2628        }
 2629        if self.dismiss_menus_and_popups(true, window, cx) {
 2630            return;
 2631        }
 2632
 2633        if self.mode == EditorMode::Full
 2634            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2635        {
 2636            return;
 2637        }
 2638
 2639        cx.propagate();
 2640    }
 2641
 2642    pub fn dismiss_menus_and_popups(
 2643        &mut self,
 2644        is_user_requested: bool,
 2645        window: &mut Window,
 2646        cx: &mut Context<Self>,
 2647    ) -> bool {
 2648        if self.take_rename(false, window, cx).is_some() {
 2649            return true;
 2650        }
 2651
 2652        if hide_hover(self, cx) {
 2653            return true;
 2654        }
 2655
 2656        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2657            return true;
 2658        }
 2659
 2660        if self.hide_context_menu(window, cx).is_some() {
 2661            return true;
 2662        }
 2663
 2664        if self.mouse_context_menu.take().is_some() {
 2665            return true;
 2666        }
 2667
 2668        if is_user_requested && self.discard_inline_completion(true, cx) {
 2669            return true;
 2670        }
 2671
 2672        if self.snippet_stack.pop().is_some() {
 2673            return true;
 2674        }
 2675
 2676        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2677            self.dismiss_diagnostics(cx);
 2678            return true;
 2679        }
 2680
 2681        false
 2682    }
 2683
 2684    fn linked_editing_ranges_for(
 2685        &self,
 2686        selection: Range<text::Anchor>,
 2687        cx: &App,
 2688    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2689        if self.linked_edit_ranges.is_empty() {
 2690            return None;
 2691        }
 2692        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2693            selection.end.buffer_id.and_then(|end_buffer_id| {
 2694                if selection.start.buffer_id != Some(end_buffer_id) {
 2695                    return None;
 2696                }
 2697                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2698                let snapshot = buffer.read(cx).snapshot();
 2699                self.linked_edit_ranges
 2700                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2701                    .map(|ranges| (ranges, snapshot, buffer))
 2702            })?;
 2703        use text::ToOffset as TO;
 2704        // find offset from the start of current range to current cursor position
 2705        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2706
 2707        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2708        let start_difference = start_offset - start_byte_offset;
 2709        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2710        let end_difference = end_offset - start_byte_offset;
 2711        // Current range has associated linked ranges.
 2712        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2713        for range in linked_ranges.iter() {
 2714            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2715            let end_offset = start_offset + end_difference;
 2716            let start_offset = start_offset + start_difference;
 2717            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2718                continue;
 2719            }
 2720            if self.selections.disjoint_anchor_ranges().any(|s| {
 2721                if s.start.buffer_id != selection.start.buffer_id
 2722                    || s.end.buffer_id != selection.end.buffer_id
 2723                {
 2724                    return false;
 2725                }
 2726                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2727                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2728            }) {
 2729                continue;
 2730            }
 2731            let start = buffer_snapshot.anchor_after(start_offset);
 2732            let end = buffer_snapshot.anchor_after(end_offset);
 2733            linked_edits
 2734                .entry(buffer.clone())
 2735                .or_default()
 2736                .push(start..end);
 2737        }
 2738        Some(linked_edits)
 2739    }
 2740
 2741    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2742        let text: Arc<str> = text.into();
 2743
 2744        if self.read_only(cx) {
 2745            return;
 2746        }
 2747
 2748        let selections = self.selections.all_adjusted(cx);
 2749        let mut bracket_inserted = false;
 2750        let mut edits = Vec::new();
 2751        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2752        let mut new_selections = Vec::with_capacity(selections.len());
 2753        let mut new_autoclose_regions = Vec::new();
 2754        let snapshot = self.buffer.read(cx).read(cx);
 2755
 2756        for (selection, autoclose_region) in
 2757            self.selections_with_autoclose_regions(selections, &snapshot)
 2758        {
 2759            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2760                // Determine if the inserted text matches the opening or closing
 2761                // bracket of any of this language's bracket pairs.
 2762                let mut bracket_pair = None;
 2763                let mut is_bracket_pair_start = false;
 2764                let mut is_bracket_pair_end = false;
 2765                if !text.is_empty() {
 2766                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2767                    //  and they are removing the character that triggered IME popup.
 2768                    for (pair, enabled) in scope.brackets() {
 2769                        if !pair.close && !pair.surround {
 2770                            continue;
 2771                        }
 2772
 2773                        if enabled && pair.start.ends_with(text.as_ref()) {
 2774                            let prefix_len = pair.start.len() - text.len();
 2775                            let preceding_text_matches_prefix = prefix_len == 0
 2776                                || (selection.start.column >= (prefix_len as u32)
 2777                                    && snapshot.contains_str_at(
 2778                                        Point::new(
 2779                                            selection.start.row,
 2780                                            selection.start.column - (prefix_len as u32),
 2781                                        ),
 2782                                        &pair.start[..prefix_len],
 2783                                    ));
 2784                            if preceding_text_matches_prefix {
 2785                                bracket_pair = Some(pair.clone());
 2786                                is_bracket_pair_start = true;
 2787                                break;
 2788                            }
 2789                        }
 2790                        if pair.end.as_str() == text.as_ref() {
 2791                            bracket_pair = Some(pair.clone());
 2792                            is_bracket_pair_end = true;
 2793                            break;
 2794                        }
 2795                    }
 2796                }
 2797
 2798                if let Some(bracket_pair) = bracket_pair {
 2799                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2800                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2801                    let auto_surround =
 2802                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2803                    if selection.is_empty() {
 2804                        if is_bracket_pair_start {
 2805                            // If the inserted text is a suffix of an opening bracket and the
 2806                            // selection is preceded by the rest of the opening bracket, then
 2807                            // insert the closing bracket.
 2808                            let following_text_allows_autoclose = snapshot
 2809                                .chars_at(selection.start)
 2810                                .next()
 2811                                .map_or(true, |c| scope.should_autoclose_before(c));
 2812
 2813                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2814                                && bracket_pair.start.len() == 1
 2815                            {
 2816                                let target = bracket_pair.start.chars().next().unwrap();
 2817                                let current_line_count = snapshot
 2818                                    .reversed_chars_at(selection.start)
 2819                                    .take_while(|&c| c != '\n')
 2820                                    .filter(|&c| c == target)
 2821                                    .count();
 2822                                current_line_count % 2 == 1
 2823                            } else {
 2824                                false
 2825                            };
 2826
 2827                            if autoclose
 2828                                && bracket_pair.close
 2829                                && following_text_allows_autoclose
 2830                                && !is_closing_quote
 2831                            {
 2832                                let anchor = snapshot.anchor_before(selection.end);
 2833                                new_selections.push((selection.map(|_| anchor), text.len()));
 2834                                new_autoclose_regions.push((
 2835                                    anchor,
 2836                                    text.len(),
 2837                                    selection.id,
 2838                                    bracket_pair.clone(),
 2839                                ));
 2840                                edits.push((
 2841                                    selection.range(),
 2842                                    format!("{}{}", text, bracket_pair.end).into(),
 2843                                ));
 2844                                bracket_inserted = true;
 2845                                continue;
 2846                            }
 2847                        }
 2848
 2849                        if let Some(region) = autoclose_region {
 2850                            // If the selection is followed by an auto-inserted closing bracket,
 2851                            // then don't insert that closing bracket again; just move the selection
 2852                            // past the closing bracket.
 2853                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2854                                && text.as_ref() == region.pair.end.as_str();
 2855                            if should_skip {
 2856                                let anchor = snapshot.anchor_after(selection.end);
 2857                                new_selections
 2858                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2859                                continue;
 2860                            }
 2861                        }
 2862
 2863                        let always_treat_brackets_as_autoclosed = snapshot
 2864                            .settings_at(selection.start, cx)
 2865                            .always_treat_brackets_as_autoclosed;
 2866                        if always_treat_brackets_as_autoclosed
 2867                            && is_bracket_pair_end
 2868                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2869                        {
 2870                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2871                            // and the inserted text is a closing bracket and the selection is followed
 2872                            // by the closing bracket then move the selection past the closing bracket.
 2873                            let anchor = snapshot.anchor_after(selection.end);
 2874                            new_selections.push((selection.map(|_| anchor), text.len()));
 2875                            continue;
 2876                        }
 2877                    }
 2878                    // If an opening bracket is 1 character long and is typed while
 2879                    // text is selected, then surround that text with the bracket pair.
 2880                    else if auto_surround
 2881                        && bracket_pair.surround
 2882                        && is_bracket_pair_start
 2883                        && bracket_pair.start.chars().count() == 1
 2884                    {
 2885                        edits.push((selection.start..selection.start, text.clone()));
 2886                        edits.push((
 2887                            selection.end..selection.end,
 2888                            bracket_pair.end.as_str().into(),
 2889                        ));
 2890                        bracket_inserted = true;
 2891                        new_selections.push((
 2892                            Selection {
 2893                                id: selection.id,
 2894                                start: snapshot.anchor_after(selection.start),
 2895                                end: snapshot.anchor_before(selection.end),
 2896                                reversed: selection.reversed,
 2897                                goal: selection.goal,
 2898                            },
 2899                            0,
 2900                        ));
 2901                        continue;
 2902                    }
 2903                }
 2904            }
 2905
 2906            if self.auto_replace_emoji_shortcode
 2907                && selection.is_empty()
 2908                && text.as_ref().ends_with(':')
 2909            {
 2910                if let Some(possible_emoji_short_code) =
 2911                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2912                {
 2913                    if !possible_emoji_short_code.is_empty() {
 2914                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2915                            let emoji_shortcode_start = Point::new(
 2916                                selection.start.row,
 2917                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2918                            );
 2919
 2920                            // Remove shortcode from buffer
 2921                            edits.push((
 2922                                emoji_shortcode_start..selection.start,
 2923                                "".to_string().into(),
 2924                            ));
 2925                            new_selections.push((
 2926                                Selection {
 2927                                    id: selection.id,
 2928                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2929                                    end: snapshot.anchor_before(selection.start),
 2930                                    reversed: selection.reversed,
 2931                                    goal: selection.goal,
 2932                                },
 2933                                0,
 2934                            ));
 2935
 2936                            // Insert emoji
 2937                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2938                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2939                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2940
 2941                            continue;
 2942                        }
 2943                    }
 2944                }
 2945            }
 2946
 2947            // If not handling any auto-close operation, then just replace the selected
 2948            // text with the given input and move the selection to the end of the
 2949            // newly inserted text.
 2950            let anchor = snapshot.anchor_after(selection.end);
 2951            if !self.linked_edit_ranges.is_empty() {
 2952                let start_anchor = snapshot.anchor_before(selection.start);
 2953
 2954                let is_word_char = text.chars().next().map_or(true, |char| {
 2955                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2956                    classifier.is_word(char)
 2957                });
 2958
 2959                if is_word_char {
 2960                    if let Some(ranges) = self
 2961                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2962                    {
 2963                        for (buffer, edits) in ranges {
 2964                            linked_edits
 2965                                .entry(buffer.clone())
 2966                                .or_default()
 2967                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2968                        }
 2969                    }
 2970                }
 2971            }
 2972
 2973            new_selections.push((selection.map(|_| anchor), 0));
 2974            edits.push((selection.start..selection.end, text.clone()));
 2975        }
 2976
 2977        drop(snapshot);
 2978
 2979        self.transact(window, cx, |this, window, cx| {
 2980            this.buffer.update(cx, |buffer, cx| {
 2981                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2982            });
 2983            for (buffer, edits) in linked_edits {
 2984                buffer.update(cx, |buffer, cx| {
 2985                    let snapshot = buffer.snapshot();
 2986                    let edits = edits
 2987                        .into_iter()
 2988                        .map(|(range, text)| {
 2989                            use text::ToPoint as TP;
 2990                            let end_point = TP::to_point(&range.end, &snapshot);
 2991                            let start_point = TP::to_point(&range.start, &snapshot);
 2992                            (start_point..end_point, text)
 2993                        })
 2994                        .sorted_by_key(|(range, _)| range.start)
 2995                        .collect::<Vec<_>>();
 2996                    buffer.edit(edits, None, cx);
 2997                })
 2998            }
 2999            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3000            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3001            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3002            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3003                .zip(new_selection_deltas)
 3004                .map(|(selection, delta)| Selection {
 3005                    id: selection.id,
 3006                    start: selection.start + delta,
 3007                    end: selection.end + delta,
 3008                    reversed: selection.reversed,
 3009                    goal: SelectionGoal::None,
 3010                })
 3011                .collect::<Vec<_>>();
 3012
 3013            let mut i = 0;
 3014            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3015                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3016                let start = map.buffer_snapshot.anchor_before(position);
 3017                let end = map.buffer_snapshot.anchor_after(position);
 3018                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3019                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3020                        Ordering::Less => i += 1,
 3021                        Ordering::Greater => break,
 3022                        Ordering::Equal => {
 3023                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3024                                Ordering::Less => i += 1,
 3025                                Ordering::Equal => break,
 3026                                Ordering::Greater => break,
 3027                            }
 3028                        }
 3029                    }
 3030                }
 3031                this.autoclose_regions.insert(
 3032                    i,
 3033                    AutocloseRegion {
 3034                        selection_id,
 3035                        range: start..end,
 3036                        pair,
 3037                    },
 3038                );
 3039            }
 3040
 3041            let had_active_inline_completion = this.has_active_inline_completion();
 3042            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3043                s.select(new_selections)
 3044            });
 3045
 3046            if !bracket_inserted {
 3047                if let Some(on_type_format_task) =
 3048                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3049                {
 3050                    on_type_format_task.detach_and_log_err(cx);
 3051                }
 3052            }
 3053
 3054            let editor_settings = EditorSettings::get_global(cx);
 3055            if bracket_inserted
 3056                && (editor_settings.auto_signature_help
 3057                    || editor_settings.show_signature_help_after_edits)
 3058            {
 3059                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3060            }
 3061
 3062            let trigger_in_words =
 3063                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3064            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3065            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3066            this.refresh_inline_completion(true, false, window, cx);
 3067        });
 3068    }
 3069
 3070    fn find_possible_emoji_shortcode_at_position(
 3071        snapshot: &MultiBufferSnapshot,
 3072        position: Point,
 3073    ) -> Option<String> {
 3074        let mut chars = Vec::new();
 3075        let mut found_colon = false;
 3076        for char in snapshot.reversed_chars_at(position).take(100) {
 3077            // Found a possible emoji shortcode in the middle of the buffer
 3078            if found_colon {
 3079                if char.is_whitespace() {
 3080                    chars.reverse();
 3081                    return Some(chars.iter().collect());
 3082                }
 3083                // If the previous character is not a whitespace, we are in the middle of a word
 3084                // and we only want to complete the shortcode if the word is made up of other emojis
 3085                let mut containing_word = String::new();
 3086                for ch in snapshot
 3087                    .reversed_chars_at(position)
 3088                    .skip(chars.len() + 1)
 3089                    .take(100)
 3090                {
 3091                    if ch.is_whitespace() {
 3092                        break;
 3093                    }
 3094                    containing_word.push(ch);
 3095                }
 3096                let containing_word = containing_word.chars().rev().collect::<String>();
 3097                if util::word_consists_of_emojis(containing_word.as_str()) {
 3098                    chars.reverse();
 3099                    return Some(chars.iter().collect());
 3100                }
 3101            }
 3102
 3103            if char.is_whitespace() || !char.is_ascii() {
 3104                return None;
 3105            }
 3106            if char == ':' {
 3107                found_colon = true;
 3108            } else {
 3109                chars.push(char);
 3110            }
 3111        }
 3112        // Found a possible emoji shortcode at the beginning of the buffer
 3113        chars.reverse();
 3114        Some(chars.iter().collect())
 3115    }
 3116
 3117    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3118        self.transact(window, cx, |this, window, cx| {
 3119            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3120                let selections = this.selections.all::<usize>(cx);
 3121                let multi_buffer = this.buffer.read(cx);
 3122                let buffer = multi_buffer.snapshot(cx);
 3123                selections
 3124                    .iter()
 3125                    .map(|selection| {
 3126                        let start_point = selection.start.to_point(&buffer);
 3127                        let mut indent =
 3128                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3129                        indent.len = cmp::min(indent.len, start_point.column);
 3130                        let start = selection.start;
 3131                        let end = selection.end;
 3132                        let selection_is_empty = start == end;
 3133                        let language_scope = buffer.language_scope_at(start);
 3134                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3135                            &language_scope
 3136                        {
 3137                            let leading_whitespace_len = buffer
 3138                                .reversed_chars_at(start)
 3139                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3140                                .map(|c| c.len_utf8())
 3141                                .sum::<usize>();
 3142
 3143                            let trailing_whitespace_len = buffer
 3144                                .chars_at(end)
 3145                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3146                                .map(|c| c.len_utf8())
 3147                                .sum::<usize>();
 3148
 3149                            let insert_extra_newline =
 3150                                language.brackets().any(|(pair, enabled)| {
 3151                                    let pair_start = pair.start.trim_end();
 3152                                    let pair_end = pair.end.trim_start();
 3153
 3154                                    enabled
 3155                                        && pair.newline
 3156                                        && buffer.contains_str_at(
 3157                                            end + trailing_whitespace_len,
 3158                                            pair_end,
 3159                                        )
 3160                                        && buffer.contains_str_at(
 3161                                            (start - leading_whitespace_len)
 3162                                                .saturating_sub(pair_start.len()),
 3163                                            pair_start,
 3164                                        )
 3165                                });
 3166
 3167                            // Comment extension on newline is allowed only for cursor selections
 3168                            let comment_delimiter = maybe!({
 3169                                if !selection_is_empty {
 3170                                    return None;
 3171                                }
 3172
 3173                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3174                                    return None;
 3175                                }
 3176
 3177                                let delimiters = language.line_comment_prefixes();
 3178                                let max_len_of_delimiter =
 3179                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3180                                let (snapshot, range) =
 3181                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3182
 3183                                let mut index_of_first_non_whitespace = 0;
 3184                                let comment_candidate = snapshot
 3185                                    .chars_for_range(range)
 3186                                    .skip_while(|c| {
 3187                                        let should_skip = c.is_whitespace();
 3188                                        if should_skip {
 3189                                            index_of_first_non_whitespace += 1;
 3190                                        }
 3191                                        should_skip
 3192                                    })
 3193                                    .take(max_len_of_delimiter)
 3194                                    .collect::<String>();
 3195                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3196                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3197                                })?;
 3198                                let cursor_is_placed_after_comment_marker =
 3199                                    index_of_first_non_whitespace + comment_prefix.len()
 3200                                        <= start_point.column as usize;
 3201                                if cursor_is_placed_after_comment_marker {
 3202                                    Some(comment_prefix.clone())
 3203                                } else {
 3204                                    None
 3205                                }
 3206                            });
 3207                            (comment_delimiter, insert_extra_newline)
 3208                        } else {
 3209                            (None, false)
 3210                        };
 3211
 3212                        let capacity_for_delimiter = comment_delimiter
 3213                            .as_deref()
 3214                            .map(str::len)
 3215                            .unwrap_or_default();
 3216                        let mut new_text =
 3217                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3218                        new_text.push('\n');
 3219                        new_text.extend(indent.chars());
 3220                        if let Some(delimiter) = &comment_delimiter {
 3221                            new_text.push_str(delimiter);
 3222                        }
 3223                        if insert_extra_newline {
 3224                            new_text = new_text.repeat(2);
 3225                        }
 3226
 3227                        let anchor = buffer.anchor_after(end);
 3228                        let new_selection = selection.map(|_| anchor);
 3229                        (
 3230                            (start..end, new_text),
 3231                            (insert_extra_newline, new_selection),
 3232                        )
 3233                    })
 3234                    .unzip()
 3235            };
 3236
 3237            this.edit_with_autoindent(edits, cx);
 3238            let buffer = this.buffer.read(cx).snapshot(cx);
 3239            let new_selections = selection_fixup_info
 3240                .into_iter()
 3241                .map(|(extra_newline_inserted, new_selection)| {
 3242                    let mut cursor = new_selection.end.to_point(&buffer);
 3243                    if extra_newline_inserted {
 3244                        cursor.row -= 1;
 3245                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3246                    }
 3247                    new_selection.map(|_| cursor)
 3248                })
 3249                .collect();
 3250
 3251            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3252                s.select(new_selections)
 3253            });
 3254            this.refresh_inline_completion(true, false, window, cx);
 3255        });
 3256    }
 3257
 3258    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3259        let buffer = self.buffer.read(cx);
 3260        let snapshot = buffer.snapshot(cx);
 3261
 3262        let mut edits = Vec::new();
 3263        let mut rows = Vec::new();
 3264
 3265        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3266            let cursor = selection.head();
 3267            let row = cursor.row;
 3268
 3269            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3270
 3271            let newline = "\n".to_string();
 3272            edits.push((start_of_line..start_of_line, newline));
 3273
 3274            rows.push(row + rows_inserted as u32);
 3275        }
 3276
 3277        self.transact(window, cx, |editor, window, cx| {
 3278            editor.edit(edits, cx);
 3279
 3280            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3281                let mut index = 0;
 3282                s.move_cursors_with(|map, _, _| {
 3283                    let row = rows[index];
 3284                    index += 1;
 3285
 3286                    let point = Point::new(row, 0);
 3287                    let boundary = map.next_line_boundary(point).1;
 3288                    let clipped = map.clip_point(boundary, Bias::Left);
 3289
 3290                    (clipped, SelectionGoal::None)
 3291                });
 3292            });
 3293
 3294            let mut indent_edits = Vec::new();
 3295            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3296            for row in rows {
 3297                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3298                for (row, indent) in indents {
 3299                    if indent.len == 0 {
 3300                        continue;
 3301                    }
 3302
 3303                    let text = match indent.kind {
 3304                        IndentKind::Space => " ".repeat(indent.len as usize),
 3305                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3306                    };
 3307                    let point = Point::new(row.0, 0);
 3308                    indent_edits.push((point..point, text));
 3309                }
 3310            }
 3311            editor.edit(indent_edits, cx);
 3312        });
 3313    }
 3314
 3315    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3316        let buffer = self.buffer.read(cx);
 3317        let snapshot = buffer.snapshot(cx);
 3318
 3319        let mut edits = Vec::new();
 3320        let mut rows = Vec::new();
 3321        let mut rows_inserted = 0;
 3322
 3323        for selection in self.selections.all_adjusted(cx) {
 3324            let cursor = selection.head();
 3325            let row = cursor.row;
 3326
 3327            let point = Point::new(row + 1, 0);
 3328            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3329
 3330            let newline = "\n".to_string();
 3331            edits.push((start_of_line..start_of_line, newline));
 3332
 3333            rows_inserted += 1;
 3334            rows.push(row + rows_inserted);
 3335        }
 3336
 3337        self.transact(window, cx, |editor, window, cx| {
 3338            editor.edit(edits, cx);
 3339
 3340            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3341                let mut index = 0;
 3342                s.move_cursors_with(|map, _, _| {
 3343                    let row = rows[index];
 3344                    index += 1;
 3345
 3346                    let point = Point::new(row, 0);
 3347                    let boundary = map.next_line_boundary(point).1;
 3348                    let clipped = map.clip_point(boundary, Bias::Left);
 3349
 3350                    (clipped, SelectionGoal::None)
 3351                });
 3352            });
 3353
 3354            let mut indent_edits = Vec::new();
 3355            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3356            for row in rows {
 3357                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3358                for (row, indent) in indents {
 3359                    if indent.len == 0 {
 3360                        continue;
 3361                    }
 3362
 3363                    let text = match indent.kind {
 3364                        IndentKind::Space => " ".repeat(indent.len as usize),
 3365                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3366                    };
 3367                    let point = Point::new(row.0, 0);
 3368                    indent_edits.push((point..point, text));
 3369                }
 3370            }
 3371            editor.edit(indent_edits, cx);
 3372        });
 3373    }
 3374
 3375    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3376        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3377            original_indent_columns: Vec::new(),
 3378        });
 3379        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3380    }
 3381
 3382    fn insert_with_autoindent_mode(
 3383        &mut self,
 3384        text: &str,
 3385        autoindent_mode: Option<AutoindentMode>,
 3386        window: &mut Window,
 3387        cx: &mut Context<Self>,
 3388    ) {
 3389        if self.read_only(cx) {
 3390            return;
 3391        }
 3392
 3393        let text: Arc<str> = text.into();
 3394        self.transact(window, cx, |this, window, cx| {
 3395            let old_selections = this.selections.all_adjusted(cx);
 3396            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3397                let anchors = {
 3398                    let snapshot = buffer.read(cx);
 3399                    old_selections
 3400                        .iter()
 3401                        .map(|s| {
 3402                            let anchor = snapshot.anchor_after(s.head());
 3403                            s.map(|_| anchor)
 3404                        })
 3405                        .collect::<Vec<_>>()
 3406                };
 3407                buffer.edit(
 3408                    old_selections
 3409                        .iter()
 3410                        .map(|s| (s.start..s.end, text.clone())),
 3411                    autoindent_mode,
 3412                    cx,
 3413                );
 3414                anchors
 3415            });
 3416
 3417            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3418                s.select_anchors(selection_anchors);
 3419            });
 3420
 3421            cx.notify();
 3422        });
 3423    }
 3424
 3425    fn trigger_completion_on_input(
 3426        &mut self,
 3427        text: &str,
 3428        trigger_in_words: bool,
 3429        window: &mut Window,
 3430        cx: &mut Context<Self>,
 3431    ) {
 3432        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3433            self.show_completions(
 3434                &ShowCompletions {
 3435                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3436                },
 3437                window,
 3438                cx,
 3439            );
 3440        } else {
 3441            self.hide_context_menu(window, cx);
 3442        }
 3443    }
 3444
 3445    fn is_completion_trigger(
 3446        &self,
 3447        text: &str,
 3448        trigger_in_words: bool,
 3449        cx: &mut Context<Self>,
 3450    ) -> bool {
 3451        let position = self.selections.newest_anchor().head();
 3452        let multibuffer = self.buffer.read(cx);
 3453        let Some(buffer) = position
 3454            .buffer_id
 3455            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3456        else {
 3457            return false;
 3458        };
 3459
 3460        if let Some(completion_provider) = &self.completion_provider {
 3461            completion_provider.is_completion_trigger(
 3462                &buffer,
 3463                position.text_anchor,
 3464                text,
 3465                trigger_in_words,
 3466                cx,
 3467            )
 3468        } else {
 3469            false
 3470        }
 3471    }
 3472
 3473    /// If any empty selections is touching the start of its innermost containing autoclose
 3474    /// region, expand it to select the brackets.
 3475    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3476        let selections = self.selections.all::<usize>(cx);
 3477        let buffer = self.buffer.read(cx).read(cx);
 3478        let new_selections = self
 3479            .selections_with_autoclose_regions(selections, &buffer)
 3480            .map(|(mut selection, region)| {
 3481                if !selection.is_empty() {
 3482                    return selection;
 3483                }
 3484
 3485                if let Some(region) = region {
 3486                    let mut range = region.range.to_offset(&buffer);
 3487                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3488                        range.start -= region.pair.start.len();
 3489                        if buffer.contains_str_at(range.start, &region.pair.start)
 3490                            && buffer.contains_str_at(range.end, &region.pair.end)
 3491                        {
 3492                            range.end += region.pair.end.len();
 3493                            selection.start = range.start;
 3494                            selection.end = range.end;
 3495
 3496                            return selection;
 3497                        }
 3498                    }
 3499                }
 3500
 3501                let always_treat_brackets_as_autoclosed = buffer
 3502                    .settings_at(selection.start, cx)
 3503                    .always_treat_brackets_as_autoclosed;
 3504
 3505                if !always_treat_brackets_as_autoclosed {
 3506                    return selection;
 3507                }
 3508
 3509                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3510                    for (pair, enabled) in scope.brackets() {
 3511                        if !enabled || !pair.close {
 3512                            continue;
 3513                        }
 3514
 3515                        if buffer.contains_str_at(selection.start, &pair.end) {
 3516                            let pair_start_len = pair.start.len();
 3517                            if buffer.contains_str_at(
 3518                                selection.start.saturating_sub(pair_start_len),
 3519                                &pair.start,
 3520                            ) {
 3521                                selection.start -= pair_start_len;
 3522                                selection.end += pair.end.len();
 3523
 3524                                return selection;
 3525                            }
 3526                        }
 3527                    }
 3528                }
 3529
 3530                selection
 3531            })
 3532            .collect();
 3533
 3534        drop(buffer);
 3535        self.change_selections(None, window, cx, |selections| {
 3536            selections.select(new_selections)
 3537        });
 3538    }
 3539
 3540    /// Iterate the given selections, and for each one, find the smallest surrounding
 3541    /// autoclose region. This uses the ordering of the selections and the autoclose
 3542    /// regions to avoid repeated comparisons.
 3543    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3544        &'a self,
 3545        selections: impl IntoIterator<Item = Selection<D>>,
 3546        buffer: &'a MultiBufferSnapshot,
 3547    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3548        let mut i = 0;
 3549        let mut regions = self.autoclose_regions.as_slice();
 3550        selections.into_iter().map(move |selection| {
 3551            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3552
 3553            let mut enclosing = None;
 3554            while let Some(pair_state) = regions.get(i) {
 3555                if pair_state.range.end.to_offset(buffer) < range.start {
 3556                    regions = &regions[i + 1..];
 3557                    i = 0;
 3558                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3559                    break;
 3560                } else {
 3561                    if pair_state.selection_id == selection.id {
 3562                        enclosing = Some(pair_state);
 3563                    }
 3564                    i += 1;
 3565                }
 3566            }
 3567
 3568            (selection, enclosing)
 3569        })
 3570    }
 3571
 3572    /// Remove any autoclose regions that no longer contain their selection.
 3573    fn invalidate_autoclose_regions(
 3574        &mut self,
 3575        mut selections: &[Selection<Anchor>],
 3576        buffer: &MultiBufferSnapshot,
 3577    ) {
 3578        self.autoclose_regions.retain(|state| {
 3579            let mut i = 0;
 3580            while let Some(selection) = selections.get(i) {
 3581                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3582                    selections = &selections[1..];
 3583                    continue;
 3584                }
 3585                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3586                    break;
 3587                }
 3588                if selection.id == state.selection_id {
 3589                    return true;
 3590                } else {
 3591                    i += 1;
 3592                }
 3593            }
 3594            false
 3595        });
 3596    }
 3597
 3598    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3599        let offset = position.to_offset(buffer);
 3600        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3601        if offset > word_range.start && kind == Some(CharKind::Word) {
 3602            Some(
 3603                buffer
 3604                    .text_for_range(word_range.start..offset)
 3605                    .collect::<String>(),
 3606            )
 3607        } else {
 3608            None
 3609        }
 3610    }
 3611
 3612    pub fn toggle_inlay_hints(
 3613        &mut self,
 3614        _: &ToggleInlayHints,
 3615        _: &mut Window,
 3616        cx: &mut Context<Self>,
 3617    ) {
 3618        self.refresh_inlay_hints(
 3619            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3620            cx,
 3621        );
 3622    }
 3623
 3624    pub fn inlay_hints_enabled(&self) -> bool {
 3625        self.inlay_hint_cache.enabled
 3626    }
 3627
 3628    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3629        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3630            return;
 3631        }
 3632
 3633        let reason_description = reason.description();
 3634        let ignore_debounce = matches!(
 3635            reason,
 3636            InlayHintRefreshReason::SettingsChange(_)
 3637                | InlayHintRefreshReason::Toggle(_)
 3638                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3639        );
 3640        let (invalidate_cache, required_languages) = match reason {
 3641            InlayHintRefreshReason::Toggle(enabled) => {
 3642                self.inlay_hint_cache.enabled = enabled;
 3643                if enabled {
 3644                    (InvalidationStrategy::RefreshRequested, None)
 3645                } else {
 3646                    self.inlay_hint_cache.clear();
 3647                    self.splice_inlays(
 3648                        &self
 3649                            .visible_inlay_hints(cx)
 3650                            .iter()
 3651                            .map(|inlay| inlay.id)
 3652                            .collect::<Vec<InlayId>>(),
 3653                        Vec::new(),
 3654                        cx,
 3655                    );
 3656                    return;
 3657                }
 3658            }
 3659            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3660                match self.inlay_hint_cache.update_settings(
 3661                    &self.buffer,
 3662                    new_settings,
 3663                    self.visible_inlay_hints(cx),
 3664                    cx,
 3665                ) {
 3666                    ControlFlow::Break(Some(InlaySplice {
 3667                        to_remove,
 3668                        to_insert,
 3669                    })) => {
 3670                        self.splice_inlays(&to_remove, to_insert, cx);
 3671                        return;
 3672                    }
 3673                    ControlFlow::Break(None) => return,
 3674                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3675                }
 3676            }
 3677            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3678                if let Some(InlaySplice {
 3679                    to_remove,
 3680                    to_insert,
 3681                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3682                {
 3683                    self.splice_inlays(&to_remove, to_insert, cx);
 3684                }
 3685                return;
 3686            }
 3687            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3688            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3689                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3690            }
 3691            InlayHintRefreshReason::RefreshRequested => {
 3692                (InvalidationStrategy::RefreshRequested, None)
 3693            }
 3694        };
 3695
 3696        if let Some(InlaySplice {
 3697            to_remove,
 3698            to_insert,
 3699        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3700            reason_description,
 3701            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3702            invalidate_cache,
 3703            ignore_debounce,
 3704            cx,
 3705        ) {
 3706            self.splice_inlays(&to_remove, to_insert, cx);
 3707        }
 3708    }
 3709
 3710    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3711        self.display_map
 3712            .read(cx)
 3713            .current_inlays()
 3714            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3715            .cloned()
 3716            .collect()
 3717    }
 3718
 3719    pub fn excerpts_for_inlay_hints_query(
 3720        &self,
 3721        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3722        cx: &mut Context<Editor>,
 3723    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3724        let Some(project) = self.project.as_ref() else {
 3725            return HashMap::default();
 3726        };
 3727        let project = project.read(cx);
 3728        let multi_buffer = self.buffer().read(cx);
 3729        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3730        let multi_buffer_visible_start = self
 3731            .scroll_manager
 3732            .anchor()
 3733            .anchor
 3734            .to_point(&multi_buffer_snapshot);
 3735        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3736            multi_buffer_visible_start
 3737                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3738            Bias::Left,
 3739        );
 3740        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3741        multi_buffer_snapshot
 3742            .range_to_buffer_ranges(multi_buffer_visible_range)
 3743            .into_iter()
 3744            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3745            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3746                let buffer_file = project::File::from_dyn(buffer.file())?;
 3747                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3748                let worktree_entry = buffer_worktree
 3749                    .read(cx)
 3750                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3751                if worktree_entry.is_ignored {
 3752                    return None;
 3753                }
 3754
 3755                let language = buffer.language()?;
 3756                if let Some(restrict_to_languages) = restrict_to_languages {
 3757                    if !restrict_to_languages.contains(language) {
 3758                        return None;
 3759                    }
 3760                }
 3761                Some((
 3762                    excerpt_id,
 3763                    (
 3764                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3765                        buffer.version().clone(),
 3766                        excerpt_visible_range,
 3767                    ),
 3768                ))
 3769            })
 3770            .collect()
 3771    }
 3772
 3773    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3774        TextLayoutDetails {
 3775            text_system: window.text_system().clone(),
 3776            editor_style: self.style.clone().unwrap(),
 3777            rem_size: window.rem_size(),
 3778            scroll_anchor: self.scroll_manager.anchor(),
 3779            visible_rows: self.visible_line_count(),
 3780            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3781        }
 3782    }
 3783
 3784    pub fn splice_inlays(
 3785        &self,
 3786        to_remove: &[InlayId],
 3787        to_insert: Vec<Inlay>,
 3788        cx: &mut Context<Self>,
 3789    ) {
 3790        self.display_map.update(cx, |display_map, cx| {
 3791            display_map.splice_inlays(to_remove, to_insert, cx)
 3792        });
 3793        cx.notify();
 3794    }
 3795
 3796    fn trigger_on_type_formatting(
 3797        &self,
 3798        input: String,
 3799        window: &mut Window,
 3800        cx: &mut Context<Self>,
 3801    ) -> Option<Task<Result<()>>> {
 3802        if input.len() != 1 {
 3803            return None;
 3804        }
 3805
 3806        let project = self.project.as_ref()?;
 3807        let position = self.selections.newest_anchor().head();
 3808        let (buffer, buffer_position) = self
 3809            .buffer
 3810            .read(cx)
 3811            .text_anchor_for_position(position, cx)?;
 3812
 3813        let settings = language_settings::language_settings(
 3814            buffer
 3815                .read(cx)
 3816                .language_at(buffer_position)
 3817                .map(|l| l.name()),
 3818            buffer.read(cx).file(),
 3819            cx,
 3820        );
 3821        if !settings.use_on_type_format {
 3822            return None;
 3823        }
 3824
 3825        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3826        // hence we do LSP request & edit on host side only — add formats to host's history.
 3827        let push_to_lsp_host_history = true;
 3828        // If this is not the host, append its history with new edits.
 3829        let push_to_client_history = project.read(cx).is_via_collab();
 3830
 3831        let on_type_formatting = project.update(cx, |project, cx| {
 3832            project.on_type_format(
 3833                buffer.clone(),
 3834                buffer_position,
 3835                input,
 3836                push_to_lsp_host_history,
 3837                cx,
 3838            )
 3839        });
 3840        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3841            if let Some(transaction) = on_type_formatting.await? {
 3842                if push_to_client_history {
 3843                    buffer
 3844                        .update(&mut cx, |buffer, _| {
 3845                            buffer.push_transaction(transaction, Instant::now());
 3846                        })
 3847                        .ok();
 3848                }
 3849                editor.update(&mut cx, |editor, cx| {
 3850                    editor.refresh_document_highlights(cx);
 3851                })?;
 3852            }
 3853            Ok(())
 3854        }))
 3855    }
 3856
 3857    pub fn show_completions(
 3858        &mut self,
 3859        options: &ShowCompletions,
 3860        window: &mut Window,
 3861        cx: &mut Context<Self>,
 3862    ) {
 3863        if self.pending_rename.is_some() {
 3864            return;
 3865        }
 3866
 3867        let Some(provider) = self.completion_provider.as_ref() else {
 3868            return;
 3869        };
 3870
 3871        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3872            return;
 3873        }
 3874
 3875        let position = self.selections.newest_anchor().head();
 3876        if position.diff_base_anchor.is_some() {
 3877            return;
 3878        }
 3879        let (buffer, buffer_position) =
 3880            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3881                output
 3882            } else {
 3883                return;
 3884            };
 3885        let show_completion_documentation = buffer
 3886            .read(cx)
 3887            .snapshot()
 3888            .settings_at(buffer_position, cx)
 3889            .show_completion_documentation;
 3890
 3891        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3892
 3893        let trigger_kind = match &options.trigger {
 3894            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3895                CompletionTriggerKind::TRIGGER_CHARACTER
 3896            }
 3897            _ => CompletionTriggerKind::INVOKED,
 3898        };
 3899        let completion_context = CompletionContext {
 3900            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3901                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3902                    Some(String::from(trigger))
 3903                } else {
 3904                    None
 3905                }
 3906            }),
 3907            trigger_kind,
 3908        };
 3909        let completions =
 3910            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3911        let sort_completions = provider.sort_completions();
 3912
 3913        let id = post_inc(&mut self.next_completion_id);
 3914        let task = cx.spawn_in(window, |editor, mut cx| {
 3915            async move {
 3916                editor.update(&mut cx, |this, _| {
 3917                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3918                })?;
 3919                let completions = completions.await.log_err();
 3920                let menu = if let Some(completions) = completions {
 3921                    let mut menu = CompletionsMenu::new(
 3922                        id,
 3923                        sort_completions,
 3924                        show_completion_documentation,
 3925                        position,
 3926                        buffer.clone(),
 3927                        completions.into(),
 3928                    );
 3929
 3930                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3931                        .await;
 3932
 3933                    menu.visible().then_some(menu)
 3934                } else {
 3935                    None
 3936                };
 3937
 3938                editor.update_in(&mut cx, |editor, window, cx| {
 3939                    match editor.context_menu.borrow().as_ref() {
 3940                        None => {}
 3941                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3942                            if prev_menu.id > id {
 3943                                return;
 3944                            }
 3945                        }
 3946                        _ => return,
 3947                    }
 3948
 3949                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3950                        let mut menu = menu.unwrap();
 3951                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3952
 3953                        *editor.context_menu.borrow_mut() =
 3954                            Some(CodeContextMenu::Completions(menu));
 3955
 3956                        if editor.show_edit_predictions_in_menu() {
 3957                            editor.update_visible_inline_completion(window, cx);
 3958                        } else {
 3959                            editor.discard_inline_completion(false, cx);
 3960                        }
 3961
 3962                        cx.notify();
 3963                    } else if editor.completion_tasks.len() <= 1 {
 3964                        // If there are no more completion tasks and the last menu was
 3965                        // empty, we should hide it.
 3966                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3967                        // If it was already hidden and we don't show inline
 3968                        // completions in the menu, we should also show the
 3969                        // inline-completion when available.
 3970                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3971                            editor.update_visible_inline_completion(window, cx);
 3972                        }
 3973                    }
 3974                })?;
 3975
 3976                Ok::<_, anyhow::Error>(())
 3977            }
 3978            .log_err()
 3979        });
 3980
 3981        self.completion_tasks.push((id, task));
 3982    }
 3983
 3984    pub fn confirm_completion(
 3985        &mut self,
 3986        action: &ConfirmCompletion,
 3987        window: &mut Window,
 3988        cx: &mut Context<Self>,
 3989    ) -> Option<Task<Result<()>>> {
 3990        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3991    }
 3992
 3993    pub fn compose_completion(
 3994        &mut self,
 3995        action: &ComposeCompletion,
 3996        window: &mut Window,
 3997        cx: &mut Context<Self>,
 3998    ) -> Option<Task<Result<()>>> {
 3999        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4000    }
 4001
 4002    fn do_completion(
 4003        &mut self,
 4004        item_ix: Option<usize>,
 4005        intent: CompletionIntent,
 4006        window: &mut Window,
 4007        cx: &mut Context<Editor>,
 4008    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4009        use language::ToOffset as _;
 4010
 4011        let completions_menu =
 4012            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4013                menu
 4014            } else {
 4015                return None;
 4016            };
 4017
 4018        let entries = completions_menu.entries.borrow();
 4019        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4020        if self.show_edit_predictions_in_menu() {
 4021            self.discard_inline_completion(true, cx);
 4022        }
 4023        let candidate_id = mat.candidate_id;
 4024        drop(entries);
 4025
 4026        let buffer_handle = completions_menu.buffer;
 4027        let completion = completions_menu
 4028            .completions
 4029            .borrow()
 4030            .get(candidate_id)?
 4031            .clone();
 4032        cx.stop_propagation();
 4033
 4034        let snippet;
 4035        let text;
 4036
 4037        if completion.is_snippet() {
 4038            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4039            text = snippet.as_ref().unwrap().text.clone();
 4040        } else {
 4041            snippet = None;
 4042            text = completion.new_text.clone();
 4043        };
 4044        let selections = self.selections.all::<usize>(cx);
 4045        let buffer = buffer_handle.read(cx);
 4046        let old_range = completion.old_range.to_offset(buffer);
 4047        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4048
 4049        let newest_selection = self.selections.newest_anchor();
 4050        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4051            return None;
 4052        }
 4053
 4054        let lookbehind = newest_selection
 4055            .start
 4056            .text_anchor
 4057            .to_offset(buffer)
 4058            .saturating_sub(old_range.start);
 4059        let lookahead = old_range
 4060            .end
 4061            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4062        let mut common_prefix_len = old_text
 4063            .bytes()
 4064            .zip(text.bytes())
 4065            .take_while(|(a, b)| a == b)
 4066            .count();
 4067
 4068        let snapshot = self.buffer.read(cx).snapshot(cx);
 4069        let mut range_to_replace: Option<Range<isize>> = None;
 4070        let mut ranges = Vec::new();
 4071        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4072        for selection in &selections {
 4073            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4074                let start = selection.start.saturating_sub(lookbehind);
 4075                let end = selection.end + lookahead;
 4076                if selection.id == newest_selection.id {
 4077                    range_to_replace = Some(
 4078                        ((start + common_prefix_len) as isize - selection.start as isize)
 4079                            ..(end as isize - selection.start as isize),
 4080                    );
 4081                }
 4082                ranges.push(start + common_prefix_len..end);
 4083            } else {
 4084                common_prefix_len = 0;
 4085                ranges.clear();
 4086                ranges.extend(selections.iter().map(|s| {
 4087                    if s.id == newest_selection.id {
 4088                        range_to_replace = Some(
 4089                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4090                                - selection.start as isize
 4091                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4092                                    - selection.start as isize,
 4093                        );
 4094                        old_range.clone()
 4095                    } else {
 4096                        s.start..s.end
 4097                    }
 4098                }));
 4099                break;
 4100            }
 4101            if !self.linked_edit_ranges.is_empty() {
 4102                let start_anchor = snapshot.anchor_before(selection.head());
 4103                let end_anchor = snapshot.anchor_after(selection.tail());
 4104                if let Some(ranges) = self
 4105                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4106                {
 4107                    for (buffer, edits) in ranges {
 4108                        linked_edits.entry(buffer.clone()).or_default().extend(
 4109                            edits
 4110                                .into_iter()
 4111                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4112                        );
 4113                    }
 4114                }
 4115            }
 4116        }
 4117        let text = &text[common_prefix_len..];
 4118
 4119        cx.emit(EditorEvent::InputHandled {
 4120            utf16_range_to_replace: range_to_replace,
 4121            text: text.into(),
 4122        });
 4123
 4124        self.transact(window, cx, |this, window, cx| {
 4125            if let Some(mut snippet) = snippet {
 4126                snippet.text = text.to_string();
 4127                for tabstop in snippet
 4128                    .tabstops
 4129                    .iter_mut()
 4130                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4131                {
 4132                    tabstop.start -= common_prefix_len as isize;
 4133                    tabstop.end -= common_prefix_len as isize;
 4134                }
 4135
 4136                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4137            } else {
 4138                this.buffer.update(cx, |buffer, cx| {
 4139                    buffer.edit(
 4140                        ranges.iter().map(|range| (range.clone(), text)),
 4141                        this.autoindent_mode.clone(),
 4142                        cx,
 4143                    );
 4144                });
 4145            }
 4146            for (buffer, edits) in linked_edits {
 4147                buffer.update(cx, |buffer, cx| {
 4148                    let snapshot = buffer.snapshot();
 4149                    let edits = edits
 4150                        .into_iter()
 4151                        .map(|(range, text)| {
 4152                            use text::ToPoint as TP;
 4153                            let end_point = TP::to_point(&range.end, &snapshot);
 4154                            let start_point = TP::to_point(&range.start, &snapshot);
 4155                            (start_point..end_point, text)
 4156                        })
 4157                        .sorted_by_key(|(range, _)| range.start)
 4158                        .collect::<Vec<_>>();
 4159                    buffer.edit(edits, None, cx);
 4160                })
 4161            }
 4162
 4163            this.refresh_inline_completion(true, false, window, cx);
 4164        });
 4165
 4166        let show_new_completions_on_confirm = completion
 4167            .confirm
 4168            .as_ref()
 4169            .map_or(false, |confirm| confirm(intent, window, cx));
 4170        if show_new_completions_on_confirm {
 4171            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4172        }
 4173
 4174        let provider = self.completion_provider.as_ref()?;
 4175        drop(completion);
 4176        let apply_edits = provider.apply_additional_edits_for_completion(
 4177            buffer_handle,
 4178            completions_menu.completions.clone(),
 4179            candidate_id,
 4180            true,
 4181            cx,
 4182        );
 4183
 4184        let editor_settings = EditorSettings::get_global(cx);
 4185        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4186            // After the code completion is finished, users often want to know what signatures are needed.
 4187            // so we should automatically call signature_help
 4188            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4189        }
 4190
 4191        Some(cx.foreground_executor().spawn(async move {
 4192            apply_edits.await?;
 4193            Ok(())
 4194        }))
 4195    }
 4196
 4197    pub fn toggle_code_actions(
 4198        &mut self,
 4199        action: &ToggleCodeActions,
 4200        window: &mut Window,
 4201        cx: &mut Context<Self>,
 4202    ) {
 4203        let mut context_menu = self.context_menu.borrow_mut();
 4204        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4205            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4206                // Toggle if we're selecting the same one
 4207                *context_menu = None;
 4208                cx.notify();
 4209                return;
 4210            } else {
 4211                // Otherwise, clear it and start a new one
 4212                *context_menu = None;
 4213                cx.notify();
 4214            }
 4215        }
 4216        drop(context_menu);
 4217        let snapshot = self.snapshot(window, cx);
 4218        let deployed_from_indicator = action.deployed_from_indicator;
 4219        let mut task = self.code_actions_task.take();
 4220        let action = action.clone();
 4221        cx.spawn_in(window, |editor, mut cx| async move {
 4222            while let Some(prev_task) = task {
 4223                prev_task.await.log_err();
 4224                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4225            }
 4226
 4227            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4228                if editor.focus_handle.is_focused(window) {
 4229                    let multibuffer_point = action
 4230                        .deployed_from_indicator
 4231                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4232                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4233                    let (buffer, buffer_row) = snapshot
 4234                        .buffer_snapshot
 4235                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4236                        .and_then(|(buffer_snapshot, range)| {
 4237                            editor
 4238                                .buffer
 4239                                .read(cx)
 4240                                .buffer(buffer_snapshot.remote_id())
 4241                                .map(|buffer| (buffer, range.start.row))
 4242                        })?;
 4243                    let (_, code_actions) = editor
 4244                        .available_code_actions
 4245                        .clone()
 4246                        .and_then(|(location, code_actions)| {
 4247                            let snapshot = location.buffer.read(cx).snapshot();
 4248                            let point_range = location.range.to_point(&snapshot);
 4249                            let point_range = point_range.start.row..=point_range.end.row;
 4250                            if point_range.contains(&buffer_row) {
 4251                                Some((location, code_actions))
 4252                            } else {
 4253                                None
 4254                            }
 4255                        })
 4256                        .unzip();
 4257                    let buffer_id = buffer.read(cx).remote_id();
 4258                    let tasks = editor
 4259                        .tasks
 4260                        .get(&(buffer_id, buffer_row))
 4261                        .map(|t| Arc::new(t.to_owned()));
 4262                    if tasks.is_none() && code_actions.is_none() {
 4263                        return None;
 4264                    }
 4265
 4266                    editor.completion_tasks.clear();
 4267                    editor.discard_inline_completion(false, cx);
 4268                    let task_context =
 4269                        tasks
 4270                            .as_ref()
 4271                            .zip(editor.project.clone())
 4272                            .map(|(tasks, project)| {
 4273                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4274                            });
 4275
 4276                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4277                        let task_context = match task_context {
 4278                            Some(task_context) => task_context.await,
 4279                            None => None,
 4280                        };
 4281                        let resolved_tasks =
 4282                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4283                                Rc::new(ResolvedTasks {
 4284                                    templates: tasks.resolve(&task_context).collect(),
 4285                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4286                                        multibuffer_point.row,
 4287                                        tasks.column,
 4288                                    )),
 4289                                })
 4290                            });
 4291                        let spawn_straight_away = resolved_tasks
 4292                            .as_ref()
 4293                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4294                            && code_actions
 4295                                .as_ref()
 4296                                .map_or(true, |actions| actions.is_empty());
 4297                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4298                            *editor.context_menu.borrow_mut() =
 4299                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4300                                    buffer,
 4301                                    actions: CodeActionContents {
 4302                                        tasks: resolved_tasks,
 4303                                        actions: code_actions,
 4304                                    },
 4305                                    selected_item: Default::default(),
 4306                                    scroll_handle: UniformListScrollHandle::default(),
 4307                                    deployed_from_indicator,
 4308                                }));
 4309                            if spawn_straight_away {
 4310                                if let Some(task) = editor.confirm_code_action(
 4311                                    &ConfirmCodeAction { item_ix: Some(0) },
 4312                                    window,
 4313                                    cx,
 4314                                ) {
 4315                                    cx.notify();
 4316                                    return task;
 4317                                }
 4318                            }
 4319                            cx.notify();
 4320                            Task::ready(Ok(()))
 4321                        }) {
 4322                            task.await
 4323                        } else {
 4324                            Ok(())
 4325                        }
 4326                    }))
 4327                } else {
 4328                    Some(Task::ready(Ok(())))
 4329                }
 4330            })?;
 4331            if let Some(task) = spawned_test_task {
 4332                task.await?;
 4333            }
 4334
 4335            Ok::<_, anyhow::Error>(())
 4336        })
 4337        .detach_and_log_err(cx);
 4338    }
 4339
 4340    pub fn confirm_code_action(
 4341        &mut self,
 4342        action: &ConfirmCodeAction,
 4343        window: &mut Window,
 4344        cx: &mut Context<Self>,
 4345    ) -> Option<Task<Result<()>>> {
 4346        let actions_menu =
 4347            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4348                menu
 4349            } else {
 4350                return None;
 4351            };
 4352        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4353        let action = actions_menu.actions.get(action_ix)?;
 4354        let title = action.label();
 4355        let buffer = actions_menu.buffer;
 4356        let workspace = self.workspace()?;
 4357
 4358        match action {
 4359            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4360                workspace.update(cx, |workspace, cx| {
 4361                    workspace::tasks::schedule_resolved_task(
 4362                        workspace,
 4363                        task_source_kind,
 4364                        resolved_task,
 4365                        false,
 4366                        cx,
 4367                    );
 4368
 4369                    Some(Task::ready(Ok(())))
 4370                })
 4371            }
 4372            CodeActionsItem::CodeAction {
 4373                excerpt_id,
 4374                action,
 4375                provider,
 4376            } => {
 4377                let apply_code_action =
 4378                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4379                let workspace = workspace.downgrade();
 4380                Some(cx.spawn_in(window, |editor, cx| async move {
 4381                    let project_transaction = apply_code_action.await?;
 4382                    Self::open_project_transaction(
 4383                        &editor,
 4384                        workspace,
 4385                        project_transaction,
 4386                        title,
 4387                        cx,
 4388                    )
 4389                    .await
 4390                }))
 4391            }
 4392        }
 4393    }
 4394
 4395    pub async fn open_project_transaction(
 4396        this: &WeakEntity<Editor>,
 4397        workspace: WeakEntity<Workspace>,
 4398        transaction: ProjectTransaction,
 4399        title: String,
 4400        mut cx: AsyncWindowContext,
 4401    ) -> Result<()> {
 4402        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4403        cx.update(|_, cx| {
 4404            entries.sort_unstable_by_key(|(buffer, _)| {
 4405                buffer.read(cx).file().map(|f| f.path().clone())
 4406            });
 4407        })?;
 4408
 4409        // If the project transaction's edits are all contained within this editor, then
 4410        // avoid opening a new editor to display them.
 4411
 4412        if let Some((buffer, transaction)) = entries.first() {
 4413            if entries.len() == 1 {
 4414                let excerpt = this.update(&mut cx, |editor, cx| {
 4415                    editor
 4416                        .buffer()
 4417                        .read(cx)
 4418                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4419                })?;
 4420                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4421                    if excerpted_buffer == *buffer {
 4422                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4423                            let excerpt_range = excerpt_range.to_offset(buffer);
 4424                            buffer
 4425                                .edited_ranges_for_transaction::<usize>(transaction)
 4426                                .all(|range| {
 4427                                    excerpt_range.start <= range.start
 4428                                        && excerpt_range.end >= range.end
 4429                                })
 4430                        })?;
 4431
 4432                        if all_edits_within_excerpt {
 4433                            return Ok(());
 4434                        }
 4435                    }
 4436                }
 4437            }
 4438        } else {
 4439            return Ok(());
 4440        }
 4441
 4442        let mut ranges_to_highlight = Vec::new();
 4443        let excerpt_buffer = cx.new(|cx| {
 4444            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4445            for (buffer_handle, transaction) in &entries {
 4446                let buffer = buffer_handle.read(cx);
 4447                ranges_to_highlight.extend(
 4448                    multibuffer.push_excerpts_with_context_lines(
 4449                        buffer_handle.clone(),
 4450                        buffer
 4451                            .edited_ranges_for_transaction::<usize>(transaction)
 4452                            .collect(),
 4453                        DEFAULT_MULTIBUFFER_CONTEXT,
 4454                        cx,
 4455                    ),
 4456                );
 4457            }
 4458            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4459            multibuffer
 4460        })?;
 4461
 4462        workspace.update_in(&mut cx, |workspace, window, cx| {
 4463            let project = workspace.project().clone();
 4464            let editor = cx
 4465                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4466            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4467            editor.update(cx, |editor, cx| {
 4468                editor.highlight_background::<Self>(
 4469                    &ranges_to_highlight,
 4470                    |theme| theme.editor_highlighted_line_background,
 4471                    cx,
 4472                );
 4473            });
 4474        })?;
 4475
 4476        Ok(())
 4477    }
 4478
 4479    pub fn clear_code_action_providers(&mut self) {
 4480        self.code_action_providers.clear();
 4481        self.available_code_actions.take();
 4482    }
 4483
 4484    pub fn add_code_action_provider(
 4485        &mut self,
 4486        provider: Rc<dyn CodeActionProvider>,
 4487        window: &mut Window,
 4488        cx: &mut Context<Self>,
 4489    ) {
 4490        if self
 4491            .code_action_providers
 4492            .iter()
 4493            .any(|existing_provider| existing_provider.id() == provider.id())
 4494        {
 4495            return;
 4496        }
 4497
 4498        self.code_action_providers.push(provider);
 4499        self.refresh_code_actions(window, cx);
 4500    }
 4501
 4502    pub fn remove_code_action_provider(
 4503        &mut self,
 4504        id: Arc<str>,
 4505        window: &mut Window,
 4506        cx: &mut Context<Self>,
 4507    ) {
 4508        self.code_action_providers
 4509            .retain(|provider| provider.id() != id);
 4510        self.refresh_code_actions(window, cx);
 4511    }
 4512
 4513    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4514        let buffer = self.buffer.read(cx);
 4515        let newest_selection = self.selections.newest_anchor().clone();
 4516        if newest_selection.head().diff_base_anchor.is_some() {
 4517            return None;
 4518        }
 4519        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4520        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4521        if start_buffer != end_buffer {
 4522            return None;
 4523        }
 4524
 4525        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4526            cx.background_executor()
 4527                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4528                .await;
 4529
 4530            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4531                let providers = this.code_action_providers.clone();
 4532                let tasks = this
 4533                    .code_action_providers
 4534                    .iter()
 4535                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4536                    .collect::<Vec<_>>();
 4537                (providers, tasks)
 4538            })?;
 4539
 4540            let mut actions = Vec::new();
 4541            for (provider, provider_actions) in
 4542                providers.into_iter().zip(future::join_all(tasks).await)
 4543            {
 4544                if let Some(provider_actions) = provider_actions.log_err() {
 4545                    actions.extend(provider_actions.into_iter().map(|action| {
 4546                        AvailableCodeAction {
 4547                            excerpt_id: newest_selection.start.excerpt_id,
 4548                            action,
 4549                            provider: provider.clone(),
 4550                        }
 4551                    }));
 4552                }
 4553            }
 4554
 4555            this.update(&mut cx, |this, cx| {
 4556                this.available_code_actions = if actions.is_empty() {
 4557                    None
 4558                } else {
 4559                    Some((
 4560                        Location {
 4561                            buffer: start_buffer,
 4562                            range: start..end,
 4563                        },
 4564                        actions.into(),
 4565                    ))
 4566                };
 4567                cx.notify();
 4568            })
 4569        }));
 4570        None
 4571    }
 4572
 4573    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4574        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4575            self.show_git_blame_inline = false;
 4576
 4577            self.show_git_blame_inline_delay_task =
 4578                Some(cx.spawn_in(window, |this, mut cx| async move {
 4579                    cx.background_executor().timer(delay).await;
 4580
 4581                    this.update(&mut cx, |this, cx| {
 4582                        this.show_git_blame_inline = true;
 4583                        cx.notify();
 4584                    })
 4585                    .log_err();
 4586                }));
 4587        }
 4588    }
 4589
 4590    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4591        if self.pending_rename.is_some() {
 4592            return None;
 4593        }
 4594
 4595        let provider = self.semantics_provider.clone()?;
 4596        let buffer = self.buffer.read(cx);
 4597        let newest_selection = self.selections.newest_anchor().clone();
 4598        let cursor_position = newest_selection.head();
 4599        let (cursor_buffer, cursor_buffer_position) =
 4600            buffer.text_anchor_for_position(cursor_position, cx)?;
 4601        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4602        if cursor_buffer != tail_buffer {
 4603            return None;
 4604        }
 4605        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4606        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4607            cx.background_executor()
 4608                .timer(Duration::from_millis(debounce))
 4609                .await;
 4610
 4611            let highlights = if let Some(highlights) = cx
 4612                .update(|cx| {
 4613                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4614                })
 4615                .ok()
 4616                .flatten()
 4617            {
 4618                highlights.await.log_err()
 4619            } else {
 4620                None
 4621            };
 4622
 4623            if let Some(highlights) = highlights {
 4624                this.update(&mut cx, |this, cx| {
 4625                    if this.pending_rename.is_some() {
 4626                        return;
 4627                    }
 4628
 4629                    let buffer_id = cursor_position.buffer_id;
 4630                    let buffer = this.buffer.read(cx);
 4631                    if !buffer
 4632                        .text_anchor_for_position(cursor_position, cx)
 4633                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4634                    {
 4635                        return;
 4636                    }
 4637
 4638                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4639                    let mut write_ranges = Vec::new();
 4640                    let mut read_ranges = Vec::new();
 4641                    for highlight in highlights {
 4642                        for (excerpt_id, excerpt_range) in
 4643                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4644                        {
 4645                            let start = highlight
 4646                                .range
 4647                                .start
 4648                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4649                            let end = highlight
 4650                                .range
 4651                                .end
 4652                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4653                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4654                                continue;
 4655                            }
 4656
 4657                            let range = Anchor {
 4658                                buffer_id,
 4659                                excerpt_id,
 4660                                text_anchor: start,
 4661                                diff_base_anchor: None,
 4662                            }..Anchor {
 4663                                buffer_id,
 4664                                excerpt_id,
 4665                                text_anchor: end,
 4666                                diff_base_anchor: None,
 4667                            };
 4668                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4669                                write_ranges.push(range);
 4670                            } else {
 4671                                read_ranges.push(range);
 4672                            }
 4673                        }
 4674                    }
 4675
 4676                    this.highlight_background::<DocumentHighlightRead>(
 4677                        &read_ranges,
 4678                        |theme| theme.editor_document_highlight_read_background,
 4679                        cx,
 4680                    );
 4681                    this.highlight_background::<DocumentHighlightWrite>(
 4682                        &write_ranges,
 4683                        |theme| theme.editor_document_highlight_write_background,
 4684                        cx,
 4685                    );
 4686                    cx.notify();
 4687                })
 4688                .log_err();
 4689            }
 4690        }));
 4691        None
 4692    }
 4693
 4694    pub fn refresh_inline_completion(
 4695        &mut self,
 4696        debounce: bool,
 4697        user_requested: bool,
 4698        window: &mut Window,
 4699        cx: &mut Context<Self>,
 4700    ) -> Option<()> {
 4701        let provider = self.edit_prediction_provider()?;
 4702        let cursor = self.selections.newest_anchor().head();
 4703        let (buffer, cursor_buffer_position) =
 4704            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4705
 4706        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4707            self.discard_inline_completion(false, cx);
 4708            return None;
 4709        }
 4710
 4711        if !user_requested
 4712            && (!self.should_show_edit_predictions()
 4713                || !self.is_focused(window)
 4714                || buffer.read(cx).is_empty())
 4715        {
 4716            self.discard_inline_completion(false, cx);
 4717            return None;
 4718        }
 4719
 4720        self.update_visible_inline_completion(window, cx);
 4721        provider.refresh(
 4722            self.project.clone(),
 4723            buffer,
 4724            cursor_buffer_position,
 4725            debounce,
 4726            cx,
 4727        );
 4728        Some(())
 4729    }
 4730
 4731    fn show_edit_predictions_in_menu(&self) -> bool {
 4732        match self.edit_prediction_settings {
 4733            EditPredictionSettings::Disabled => false,
 4734            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4735        }
 4736    }
 4737
 4738    pub fn edit_predictions_enabled(&self) -> bool {
 4739        match self.edit_prediction_settings {
 4740            EditPredictionSettings::Disabled => false,
 4741            EditPredictionSettings::Enabled { .. } => true,
 4742        }
 4743    }
 4744
 4745    fn edit_prediction_requires_modifier(&self) -> bool {
 4746        match self.edit_prediction_settings {
 4747            EditPredictionSettings::Disabled => false,
 4748            EditPredictionSettings::Enabled {
 4749                preview_requires_modifier,
 4750                ..
 4751            } => preview_requires_modifier,
 4752        }
 4753    }
 4754
 4755    fn edit_prediction_settings_at_position(
 4756        &self,
 4757        buffer: &Entity<Buffer>,
 4758        buffer_position: language::Anchor,
 4759        cx: &App,
 4760    ) -> EditPredictionSettings {
 4761        if self.mode != EditorMode::Full
 4762            || !self.show_inline_completions_override.unwrap_or(true)
 4763            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4764        {
 4765            return EditPredictionSettings::Disabled;
 4766        }
 4767
 4768        let buffer = buffer.read(cx);
 4769
 4770        let file = buffer.file();
 4771
 4772        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4773            return EditPredictionSettings::Disabled;
 4774        };
 4775
 4776        let by_provider = matches!(
 4777            self.menu_inline_completions_policy,
 4778            MenuInlineCompletionsPolicy::ByProvider
 4779        );
 4780
 4781        let show_in_menu = by_provider
 4782            && self
 4783                .edit_prediction_provider
 4784                .as_ref()
 4785                .map_or(false, |provider| {
 4786                    provider.provider.show_completions_in_menu()
 4787                });
 4788
 4789        let preview_requires_modifier =
 4790            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4791
 4792        EditPredictionSettings::Enabled {
 4793            show_in_menu,
 4794            preview_requires_modifier,
 4795        }
 4796    }
 4797
 4798    fn should_show_edit_predictions(&self) -> bool {
 4799        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4800    }
 4801
 4802    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4803        matches!(
 4804            self.edit_prediction_preview,
 4805            EditPredictionPreview::Active { .. }
 4806        )
 4807    }
 4808
 4809    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4810        let cursor = self.selections.newest_anchor().head();
 4811        if let Some((buffer, cursor_position)) =
 4812            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4813        {
 4814            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4815        } else {
 4816            false
 4817        }
 4818    }
 4819
 4820    fn inline_completions_enabled_in_buffer(
 4821        &self,
 4822        buffer: &Entity<Buffer>,
 4823        buffer_position: language::Anchor,
 4824        cx: &App,
 4825    ) -> bool {
 4826        maybe!({
 4827            let provider = self.edit_prediction_provider()?;
 4828            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4829                return Some(false);
 4830            }
 4831            let buffer = buffer.read(cx);
 4832            let Some(file) = buffer.file() else {
 4833                return Some(true);
 4834            };
 4835            let settings = all_language_settings(Some(file), cx);
 4836            Some(settings.inline_completions_enabled_for_path(file.path()))
 4837        })
 4838        .unwrap_or(false)
 4839    }
 4840
 4841    fn cycle_inline_completion(
 4842        &mut self,
 4843        direction: Direction,
 4844        window: &mut Window,
 4845        cx: &mut Context<Self>,
 4846    ) -> Option<()> {
 4847        let provider = self.edit_prediction_provider()?;
 4848        let cursor = self.selections.newest_anchor().head();
 4849        let (buffer, cursor_buffer_position) =
 4850            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4851        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4852            return None;
 4853        }
 4854
 4855        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4856        self.update_visible_inline_completion(window, cx);
 4857
 4858        Some(())
 4859    }
 4860
 4861    pub fn show_inline_completion(
 4862        &mut self,
 4863        _: &ShowEditPrediction,
 4864        window: &mut Window,
 4865        cx: &mut Context<Self>,
 4866    ) {
 4867        if !self.has_active_inline_completion() {
 4868            self.refresh_inline_completion(false, true, window, cx);
 4869            return;
 4870        }
 4871
 4872        self.update_visible_inline_completion(window, cx);
 4873    }
 4874
 4875    pub fn display_cursor_names(
 4876        &mut self,
 4877        _: &DisplayCursorNames,
 4878        window: &mut Window,
 4879        cx: &mut Context<Self>,
 4880    ) {
 4881        self.show_cursor_names(window, cx);
 4882    }
 4883
 4884    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4885        self.show_cursor_names = true;
 4886        cx.notify();
 4887        cx.spawn_in(window, |this, mut cx| async move {
 4888            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4889            this.update(&mut cx, |this, cx| {
 4890                this.show_cursor_names = false;
 4891                cx.notify()
 4892            })
 4893            .ok()
 4894        })
 4895        .detach();
 4896    }
 4897
 4898    pub fn next_edit_prediction(
 4899        &mut self,
 4900        _: &NextEditPrediction,
 4901        window: &mut Window,
 4902        cx: &mut Context<Self>,
 4903    ) {
 4904        if self.has_active_inline_completion() {
 4905            self.cycle_inline_completion(Direction::Next, window, cx);
 4906        } else {
 4907            let is_copilot_disabled = self
 4908                .refresh_inline_completion(false, true, window, cx)
 4909                .is_none();
 4910            if is_copilot_disabled {
 4911                cx.propagate();
 4912            }
 4913        }
 4914    }
 4915
 4916    pub fn previous_edit_prediction(
 4917        &mut self,
 4918        _: &PreviousEditPrediction,
 4919        window: &mut Window,
 4920        cx: &mut Context<Self>,
 4921    ) {
 4922        if self.has_active_inline_completion() {
 4923            self.cycle_inline_completion(Direction::Prev, window, cx);
 4924        } else {
 4925            let is_copilot_disabled = self
 4926                .refresh_inline_completion(false, true, window, cx)
 4927                .is_none();
 4928            if is_copilot_disabled {
 4929                cx.propagate();
 4930            }
 4931        }
 4932    }
 4933
 4934    pub fn accept_edit_prediction(
 4935        &mut self,
 4936        _: &AcceptEditPrediction,
 4937        window: &mut Window,
 4938        cx: &mut Context<Self>,
 4939    ) {
 4940        if self.show_edit_predictions_in_menu() {
 4941            self.hide_context_menu(window, cx);
 4942        }
 4943
 4944        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4945            return;
 4946        };
 4947
 4948        self.report_inline_completion_event(
 4949            active_inline_completion.completion_id.clone(),
 4950            true,
 4951            cx,
 4952        );
 4953
 4954        match &active_inline_completion.completion {
 4955            InlineCompletion::Move { target, .. } => {
 4956                let target = *target;
 4957
 4958                if let Some(position_map) = &self.last_position_map {
 4959                    if position_map
 4960                        .visible_row_range
 4961                        .contains(&target.to_display_point(&position_map.snapshot).row())
 4962                        || !self.edit_prediction_requires_modifier()
 4963                    {
 4964                        // Note that this is also done in vim's handler of the Tab action.
 4965                        self.change_selections(
 4966                            Some(Autoscroll::newest()),
 4967                            window,
 4968                            cx,
 4969                            |selections| {
 4970                                selections.select_anchor_ranges([target..target]);
 4971                            },
 4972                        );
 4973                        self.clear_row_highlights::<EditPredictionPreview>();
 4974
 4975                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4976                            previous_scroll_position: None,
 4977                        };
 4978                    } else {
 4979                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4980                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 4981                        };
 4982                        self.highlight_rows::<EditPredictionPreview>(
 4983                            target..target,
 4984                            cx.theme().colors().editor_highlighted_line_background,
 4985                            true,
 4986                            cx,
 4987                        );
 4988                        self.request_autoscroll(Autoscroll::fit(), cx);
 4989                    }
 4990                }
 4991            }
 4992            InlineCompletion::Edit { edits, .. } => {
 4993                if let Some(provider) = self.edit_prediction_provider() {
 4994                    provider.accept(cx);
 4995                }
 4996
 4997                let snapshot = self.buffer.read(cx).snapshot(cx);
 4998                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4999
 5000                self.buffer.update(cx, |buffer, cx| {
 5001                    buffer.edit(edits.iter().cloned(), None, cx)
 5002                });
 5003
 5004                self.change_selections(None, window, cx, |s| {
 5005                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5006                });
 5007
 5008                self.update_visible_inline_completion(window, cx);
 5009                if self.active_inline_completion.is_none() {
 5010                    self.refresh_inline_completion(true, true, window, cx);
 5011                }
 5012
 5013                cx.notify();
 5014            }
 5015        }
 5016    }
 5017
 5018    pub fn accept_partial_inline_completion(
 5019        &mut self,
 5020        _: &AcceptPartialEditPrediction,
 5021        window: &mut Window,
 5022        cx: &mut Context<Self>,
 5023    ) {
 5024        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5025            return;
 5026        };
 5027        if self.selections.count() != 1 {
 5028            return;
 5029        }
 5030
 5031        self.report_inline_completion_event(
 5032            active_inline_completion.completion_id.clone(),
 5033            true,
 5034            cx,
 5035        );
 5036
 5037        match &active_inline_completion.completion {
 5038            InlineCompletion::Move { target, .. } => {
 5039                let target = *target;
 5040                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5041                    selections.select_anchor_ranges([target..target]);
 5042                });
 5043            }
 5044            InlineCompletion::Edit { edits, .. } => {
 5045                // Find an insertion that starts at the cursor position.
 5046                let snapshot = self.buffer.read(cx).snapshot(cx);
 5047                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5048                let insertion = edits.iter().find_map(|(range, text)| {
 5049                    let range = range.to_offset(&snapshot);
 5050                    if range.is_empty() && range.start == cursor_offset {
 5051                        Some(text)
 5052                    } else {
 5053                        None
 5054                    }
 5055                });
 5056
 5057                if let Some(text) = insertion {
 5058                    let mut partial_completion = text
 5059                        .chars()
 5060                        .by_ref()
 5061                        .take_while(|c| c.is_alphabetic())
 5062                        .collect::<String>();
 5063                    if partial_completion.is_empty() {
 5064                        partial_completion = text
 5065                            .chars()
 5066                            .by_ref()
 5067                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5068                            .collect::<String>();
 5069                    }
 5070
 5071                    cx.emit(EditorEvent::InputHandled {
 5072                        utf16_range_to_replace: None,
 5073                        text: partial_completion.clone().into(),
 5074                    });
 5075
 5076                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5077
 5078                    self.refresh_inline_completion(true, true, window, cx);
 5079                    cx.notify();
 5080                } else {
 5081                    self.accept_edit_prediction(&Default::default(), window, cx);
 5082                }
 5083            }
 5084        }
 5085    }
 5086
 5087    fn discard_inline_completion(
 5088        &mut self,
 5089        should_report_inline_completion_event: bool,
 5090        cx: &mut Context<Self>,
 5091    ) -> bool {
 5092        if should_report_inline_completion_event {
 5093            let completion_id = self
 5094                .active_inline_completion
 5095                .as_ref()
 5096                .and_then(|active_completion| active_completion.completion_id.clone());
 5097
 5098            self.report_inline_completion_event(completion_id, false, cx);
 5099        }
 5100
 5101        if let Some(provider) = self.edit_prediction_provider() {
 5102            provider.discard(cx);
 5103        }
 5104
 5105        self.take_active_inline_completion(cx)
 5106    }
 5107
 5108    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5109        let Some(provider) = self.edit_prediction_provider() else {
 5110            return;
 5111        };
 5112
 5113        let Some((_, buffer, _)) = self
 5114            .buffer
 5115            .read(cx)
 5116            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5117        else {
 5118            return;
 5119        };
 5120
 5121        let extension = buffer
 5122            .read(cx)
 5123            .file()
 5124            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5125
 5126        let event_type = match accepted {
 5127            true => "Edit Prediction Accepted",
 5128            false => "Edit Prediction Discarded",
 5129        };
 5130        telemetry::event!(
 5131            event_type,
 5132            provider = provider.name(),
 5133            prediction_id = id,
 5134            suggestion_accepted = accepted,
 5135            file_extension = extension,
 5136        );
 5137    }
 5138
 5139    pub fn has_active_inline_completion(&self) -> bool {
 5140        self.active_inline_completion.is_some()
 5141    }
 5142
 5143    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5144        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5145            return false;
 5146        };
 5147
 5148        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5149        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5150        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5151        true
 5152    }
 5153
 5154    /// Returns true when we're displaying the edit prediction popover below the cursor
 5155    /// like we are not previewing and the LSP autocomplete menu is visible
 5156    /// or we are in `when_holding_modifier` mode.
 5157    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5158        if self.edit_prediction_preview_is_active()
 5159            || !self.show_edit_predictions_in_menu()
 5160            || !self.edit_predictions_enabled()
 5161        {
 5162            return false;
 5163        }
 5164
 5165        if self.has_visible_completions_menu() {
 5166            return true;
 5167        }
 5168
 5169        has_completion && self.edit_prediction_requires_modifier()
 5170    }
 5171
 5172    fn handle_modifiers_changed(
 5173        &mut self,
 5174        modifiers: Modifiers,
 5175        position_map: &PositionMap,
 5176        window: &mut Window,
 5177        cx: &mut Context<Self>,
 5178    ) {
 5179        if self.show_edit_predictions_in_menu() {
 5180            self.update_edit_prediction_preview(&modifiers, window, cx);
 5181        }
 5182
 5183        let mouse_position = window.mouse_position();
 5184        if !position_map.text_hitbox.is_hovered(window) {
 5185            return;
 5186        }
 5187
 5188        self.update_hovered_link(
 5189            position_map.point_for_position(mouse_position),
 5190            &position_map.snapshot,
 5191            modifiers,
 5192            window,
 5193            cx,
 5194        )
 5195    }
 5196
 5197    fn update_edit_prediction_preview(
 5198        &mut self,
 5199        modifiers: &Modifiers,
 5200        window: &mut Window,
 5201        cx: &mut Context<Self>,
 5202    ) {
 5203        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5204        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5205            return;
 5206        };
 5207
 5208        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5209            if matches!(
 5210                self.edit_prediction_preview,
 5211                EditPredictionPreview::Inactive
 5212            ) {
 5213                self.edit_prediction_preview = EditPredictionPreview::Active {
 5214                    previous_scroll_position: None,
 5215                };
 5216
 5217                self.update_visible_inline_completion(window, cx);
 5218                cx.notify();
 5219            }
 5220        } else if let EditPredictionPreview::Active {
 5221            previous_scroll_position,
 5222        } = self.edit_prediction_preview
 5223        {
 5224            if let (Some(previous_scroll_position), Some(position_map)) =
 5225                (previous_scroll_position, self.last_position_map.as_ref())
 5226            {
 5227                self.set_scroll_position(
 5228                    previous_scroll_position
 5229                        .scroll_position(&position_map.snapshot.display_snapshot),
 5230                    window,
 5231                    cx,
 5232                );
 5233            }
 5234
 5235            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5236            self.clear_row_highlights::<EditPredictionPreview>();
 5237            self.update_visible_inline_completion(window, cx);
 5238            cx.notify();
 5239        }
 5240    }
 5241
 5242    fn update_visible_inline_completion(
 5243        &mut self,
 5244        _window: &mut Window,
 5245        cx: &mut Context<Self>,
 5246    ) -> Option<()> {
 5247        let selection = self.selections.newest_anchor();
 5248        let cursor = selection.head();
 5249        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5250        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5251        let excerpt_id = cursor.excerpt_id;
 5252
 5253        let show_in_menu = self.show_edit_predictions_in_menu();
 5254        let completions_menu_has_precedence = !show_in_menu
 5255            && (self.context_menu.borrow().is_some()
 5256                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5257
 5258        if completions_menu_has_precedence
 5259            || !offset_selection.is_empty()
 5260            || self
 5261                .active_inline_completion
 5262                .as_ref()
 5263                .map_or(false, |completion| {
 5264                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5265                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5266                    !invalidation_range.contains(&offset_selection.head())
 5267                })
 5268        {
 5269            self.discard_inline_completion(false, cx);
 5270            return None;
 5271        }
 5272
 5273        self.take_active_inline_completion(cx);
 5274        let Some(provider) = self.edit_prediction_provider() else {
 5275            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5276            return None;
 5277        };
 5278
 5279        let (buffer, cursor_buffer_position) =
 5280            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5281
 5282        self.edit_prediction_settings =
 5283            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5284
 5285        if !self.edit_prediction_settings.is_enabled() {
 5286            self.discard_inline_completion(false, cx);
 5287            return None;
 5288        }
 5289
 5290        self.edit_prediction_cursor_on_leading_whitespace =
 5291            multibuffer.is_line_whitespace_upto(cursor);
 5292
 5293        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5294        let edits = inline_completion
 5295            .edits
 5296            .into_iter()
 5297            .flat_map(|(range, new_text)| {
 5298                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5299                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5300                Some((start..end, new_text))
 5301            })
 5302            .collect::<Vec<_>>();
 5303        if edits.is_empty() {
 5304            return None;
 5305        }
 5306
 5307        let first_edit_start = edits.first().unwrap().0.start;
 5308        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5309        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5310
 5311        let last_edit_end = edits.last().unwrap().0.end;
 5312        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5313        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5314
 5315        let cursor_row = cursor.to_point(&multibuffer).row;
 5316
 5317        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5318
 5319        let mut inlay_ids = Vec::new();
 5320        let invalidation_row_range;
 5321        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5322            Some(cursor_row..edit_end_row)
 5323        } else if cursor_row > edit_end_row {
 5324            Some(edit_start_row..cursor_row)
 5325        } else {
 5326            None
 5327        };
 5328        let is_move =
 5329            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5330        let completion = if is_move {
 5331            invalidation_row_range =
 5332                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5333            let target = first_edit_start;
 5334            InlineCompletion::Move { target, snapshot }
 5335        } else {
 5336            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5337                && !self.inline_completions_hidden_for_vim_mode;
 5338
 5339            if show_completions_in_buffer {
 5340                if edits
 5341                    .iter()
 5342                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5343                {
 5344                    let mut inlays = Vec::new();
 5345                    for (range, new_text) in &edits {
 5346                        let inlay = Inlay::inline_completion(
 5347                            post_inc(&mut self.next_inlay_id),
 5348                            range.start,
 5349                            new_text.as_str(),
 5350                        );
 5351                        inlay_ids.push(inlay.id);
 5352                        inlays.push(inlay);
 5353                    }
 5354
 5355                    self.splice_inlays(&[], inlays, cx);
 5356                } else {
 5357                    let background_color = cx.theme().status().deleted_background;
 5358                    self.highlight_text::<InlineCompletionHighlight>(
 5359                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5360                        HighlightStyle {
 5361                            background_color: Some(background_color),
 5362                            ..Default::default()
 5363                        },
 5364                        cx,
 5365                    );
 5366                }
 5367            }
 5368
 5369            invalidation_row_range = edit_start_row..edit_end_row;
 5370
 5371            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5372                if provider.show_tab_accept_marker() {
 5373                    EditDisplayMode::TabAccept
 5374                } else {
 5375                    EditDisplayMode::Inline
 5376                }
 5377            } else {
 5378                EditDisplayMode::DiffPopover
 5379            };
 5380
 5381            InlineCompletion::Edit {
 5382                edits,
 5383                edit_preview: inline_completion.edit_preview,
 5384                display_mode,
 5385                snapshot,
 5386            }
 5387        };
 5388
 5389        let invalidation_range = multibuffer
 5390            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5391            ..multibuffer.anchor_after(Point::new(
 5392                invalidation_row_range.end,
 5393                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5394            ));
 5395
 5396        self.stale_inline_completion_in_menu = None;
 5397        self.active_inline_completion = Some(InlineCompletionState {
 5398            inlay_ids,
 5399            completion,
 5400            completion_id: inline_completion.id,
 5401            invalidation_range,
 5402        });
 5403
 5404        cx.notify();
 5405
 5406        Some(())
 5407    }
 5408
 5409    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5410        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5411    }
 5412
 5413    fn render_code_actions_indicator(
 5414        &self,
 5415        _style: &EditorStyle,
 5416        row: DisplayRow,
 5417        is_active: bool,
 5418        cx: &mut Context<Self>,
 5419    ) -> Option<IconButton> {
 5420        if self.available_code_actions.is_some() {
 5421            Some(
 5422                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5423                    .shape(ui::IconButtonShape::Square)
 5424                    .icon_size(IconSize::XSmall)
 5425                    .icon_color(Color::Muted)
 5426                    .toggle_state(is_active)
 5427                    .tooltip({
 5428                        let focus_handle = self.focus_handle.clone();
 5429                        move |window, cx| {
 5430                            Tooltip::for_action_in(
 5431                                "Toggle Code Actions",
 5432                                &ToggleCodeActions {
 5433                                    deployed_from_indicator: None,
 5434                                },
 5435                                &focus_handle,
 5436                                window,
 5437                                cx,
 5438                            )
 5439                        }
 5440                    })
 5441                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5442                        window.focus(&editor.focus_handle(cx));
 5443                        editor.toggle_code_actions(
 5444                            &ToggleCodeActions {
 5445                                deployed_from_indicator: Some(row),
 5446                            },
 5447                            window,
 5448                            cx,
 5449                        );
 5450                    })),
 5451            )
 5452        } else {
 5453            None
 5454        }
 5455    }
 5456
 5457    fn clear_tasks(&mut self) {
 5458        self.tasks.clear()
 5459    }
 5460
 5461    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5462        if self.tasks.insert(key, value).is_some() {
 5463            // This case should hopefully be rare, but just in case...
 5464            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5465        }
 5466    }
 5467
 5468    fn build_tasks_context(
 5469        project: &Entity<Project>,
 5470        buffer: &Entity<Buffer>,
 5471        buffer_row: u32,
 5472        tasks: &Arc<RunnableTasks>,
 5473        cx: &mut Context<Self>,
 5474    ) -> Task<Option<task::TaskContext>> {
 5475        let position = Point::new(buffer_row, tasks.column);
 5476        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5477        let location = Location {
 5478            buffer: buffer.clone(),
 5479            range: range_start..range_start,
 5480        };
 5481        // Fill in the environmental variables from the tree-sitter captures
 5482        let mut captured_task_variables = TaskVariables::default();
 5483        for (capture_name, value) in tasks.extra_variables.clone() {
 5484            captured_task_variables.insert(
 5485                task::VariableName::Custom(capture_name.into()),
 5486                value.clone(),
 5487            );
 5488        }
 5489        project.update(cx, |project, cx| {
 5490            project.task_store().update(cx, |task_store, cx| {
 5491                task_store.task_context_for_location(captured_task_variables, location, cx)
 5492            })
 5493        })
 5494    }
 5495
 5496    pub fn spawn_nearest_task(
 5497        &mut self,
 5498        action: &SpawnNearestTask,
 5499        window: &mut Window,
 5500        cx: &mut Context<Self>,
 5501    ) {
 5502        let Some((workspace, _)) = self.workspace.clone() else {
 5503            return;
 5504        };
 5505        let Some(project) = self.project.clone() else {
 5506            return;
 5507        };
 5508
 5509        // Try to find a closest, enclosing node using tree-sitter that has a
 5510        // task
 5511        let Some((buffer, buffer_row, tasks)) = self
 5512            .find_enclosing_node_task(cx)
 5513            // Or find the task that's closest in row-distance.
 5514            .or_else(|| self.find_closest_task(cx))
 5515        else {
 5516            return;
 5517        };
 5518
 5519        let reveal_strategy = action.reveal;
 5520        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5521        cx.spawn_in(window, |_, mut cx| async move {
 5522            let context = task_context.await?;
 5523            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5524
 5525            let resolved = resolved_task.resolved.as_mut()?;
 5526            resolved.reveal = reveal_strategy;
 5527
 5528            workspace
 5529                .update(&mut cx, |workspace, cx| {
 5530                    workspace::tasks::schedule_resolved_task(
 5531                        workspace,
 5532                        task_source_kind,
 5533                        resolved_task,
 5534                        false,
 5535                        cx,
 5536                    );
 5537                })
 5538                .ok()
 5539        })
 5540        .detach();
 5541    }
 5542
 5543    fn find_closest_task(
 5544        &mut self,
 5545        cx: &mut Context<Self>,
 5546    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5547        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5548
 5549        let ((buffer_id, row), tasks) = self
 5550            .tasks
 5551            .iter()
 5552            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5553
 5554        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5555        let tasks = Arc::new(tasks.to_owned());
 5556        Some((buffer, *row, tasks))
 5557    }
 5558
 5559    fn find_enclosing_node_task(
 5560        &mut self,
 5561        cx: &mut Context<Self>,
 5562    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5563        let snapshot = self.buffer.read(cx).snapshot(cx);
 5564        let offset = self.selections.newest::<usize>(cx).head();
 5565        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5566        let buffer_id = excerpt.buffer().remote_id();
 5567
 5568        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5569        let mut cursor = layer.node().walk();
 5570
 5571        while cursor.goto_first_child_for_byte(offset).is_some() {
 5572            if cursor.node().end_byte() == offset {
 5573                cursor.goto_next_sibling();
 5574            }
 5575        }
 5576
 5577        // Ascend to the smallest ancestor that contains the range and has a task.
 5578        loop {
 5579            let node = cursor.node();
 5580            let node_range = node.byte_range();
 5581            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5582
 5583            // Check if this node contains our offset
 5584            if node_range.start <= offset && node_range.end >= offset {
 5585                // If it contains offset, check for task
 5586                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5587                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5588                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5589                }
 5590            }
 5591
 5592            if !cursor.goto_parent() {
 5593                break;
 5594            }
 5595        }
 5596        None
 5597    }
 5598
 5599    fn render_run_indicator(
 5600        &self,
 5601        _style: &EditorStyle,
 5602        is_active: bool,
 5603        row: DisplayRow,
 5604        cx: &mut Context<Self>,
 5605    ) -> IconButton {
 5606        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5607            .shape(ui::IconButtonShape::Square)
 5608            .icon_size(IconSize::XSmall)
 5609            .icon_color(Color::Muted)
 5610            .toggle_state(is_active)
 5611            .on_click(cx.listener(move |editor, _e, window, cx| {
 5612                window.focus(&editor.focus_handle(cx));
 5613                editor.toggle_code_actions(
 5614                    &ToggleCodeActions {
 5615                        deployed_from_indicator: Some(row),
 5616                    },
 5617                    window,
 5618                    cx,
 5619                );
 5620            }))
 5621    }
 5622
 5623    pub fn context_menu_visible(&self) -> bool {
 5624        !self.edit_prediction_preview_is_active()
 5625            && self
 5626                .context_menu
 5627                .borrow()
 5628                .as_ref()
 5629                .map_or(false, |menu| menu.visible())
 5630    }
 5631
 5632    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5633        self.context_menu
 5634            .borrow()
 5635            .as_ref()
 5636            .map(|menu| menu.origin())
 5637    }
 5638
 5639    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5640        px(30.)
 5641    }
 5642
 5643    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5644        if self.read_only(cx) {
 5645            cx.theme().players().read_only()
 5646        } else {
 5647            self.style.as_ref().unwrap().local_player
 5648        }
 5649    }
 5650
 5651    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5652        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5653        let accept_keystroke = accept_binding.keystroke()?;
 5654        let colors = cx.theme().colors();
 5655        let accent_color = colors.text_accent;
 5656        let editor_bg_color = colors.editor_background;
 5657        let bg_color = editor_bg_color.blend(accent_color.opacity(0.1));
 5658
 5659        h_flex()
 5660            .px_0p5()
 5661            .gap_1()
 5662            .bg(bg_color)
 5663            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5664            .text_size(TextSize::XSmall.rems(cx))
 5665            .when(!self.edit_prediction_preview_is_active(), |parent| {
 5666                parent.children(ui::render_modifiers(
 5667                    &accept_keystroke.modifiers,
 5668                    PlatformStyle::platform(),
 5669                    Some(if accept_keystroke.modifiers == window.modifiers() {
 5670                        Color::Accent
 5671                    } else {
 5672                        Color::Muted
 5673                    }),
 5674                    Some(IconSize::XSmall.rems().into()),
 5675                    false,
 5676                ))
 5677            })
 5678            .child(accept_keystroke.key.clone())
 5679            .into()
 5680    }
 5681
 5682    fn render_edit_prediction_line_popover(
 5683        &self,
 5684        label: impl Into<SharedString>,
 5685        icon: Option<IconName>,
 5686        window: &mut Window,
 5687        cx: &App,
 5688    ) -> Option<Div> {
 5689        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5690
 5691        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5692
 5693        let result = h_flex()
 5694            .gap_1()
 5695            .border_1()
 5696            .rounded_lg()
 5697            .shadow_sm()
 5698            .bg(bg_color)
 5699            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5700            .py_0p5()
 5701            .pl_1()
 5702            .pr(padding_right)
 5703            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5704            .child(Label::new(label).size(LabelSize::Small))
 5705            .when_some(icon, |element, icon| {
 5706                element.child(
 5707                    div()
 5708                        .mt(px(1.5))
 5709                        .child(Icon::new(icon).size(IconSize::Small)),
 5710                )
 5711            });
 5712
 5713        Some(result)
 5714    }
 5715
 5716    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5717        let accent_color = cx.theme().colors().text_accent;
 5718        let editor_bg_color = cx.theme().colors().editor_background;
 5719        editor_bg_color.blend(accent_color.opacity(0.1))
 5720    }
 5721
 5722    #[allow(clippy::too_many_arguments)]
 5723    fn render_edit_prediction_cursor_popover(
 5724        &self,
 5725        min_width: Pixels,
 5726        max_width: Pixels,
 5727        cursor_point: Point,
 5728        style: &EditorStyle,
 5729        accept_keystroke: &gpui::Keystroke,
 5730        _window: &Window,
 5731        cx: &mut Context<Editor>,
 5732    ) -> Option<AnyElement> {
 5733        let provider = self.edit_prediction_provider.as_ref()?;
 5734
 5735        if provider.provider.needs_terms_acceptance(cx) {
 5736            return Some(
 5737                h_flex()
 5738                    .min_w(min_width)
 5739                    .flex_1()
 5740                    .px_2()
 5741                    .py_1()
 5742                    .gap_3()
 5743                    .elevation_2(cx)
 5744                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5745                    .id("accept-terms")
 5746                    .cursor_pointer()
 5747                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5748                    .on_click(cx.listener(|this, _event, window, cx| {
 5749                        cx.stop_propagation();
 5750                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5751                        window.dispatch_action(
 5752                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5753                            cx,
 5754                        );
 5755                    }))
 5756                    .child(
 5757                        h_flex()
 5758                            .flex_1()
 5759                            .gap_2()
 5760                            .child(Icon::new(IconName::ZedPredict))
 5761                            .child(Label::new("Accept Terms of Service"))
 5762                            .child(div().w_full())
 5763                            .child(
 5764                                Icon::new(IconName::ArrowUpRight)
 5765                                    .color(Color::Muted)
 5766                                    .size(IconSize::Small),
 5767                            )
 5768                            .into_any_element(),
 5769                    )
 5770                    .into_any(),
 5771            );
 5772        }
 5773
 5774        let is_refreshing = provider.provider.is_refreshing(cx);
 5775
 5776        fn pending_completion_container() -> Div {
 5777            h_flex()
 5778                .h_full()
 5779                .flex_1()
 5780                .gap_2()
 5781                .child(Icon::new(IconName::ZedPredict))
 5782        }
 5783
 5784        let completion = match &self.active_inline_completion {
 5785            Some(completion) => match &completion.completion {
 5786                InlineCompletion::Move {
 5787                    target, snapshot, ..
 5788                } if !self.has_visible_completions_menu() => {
 5789                    use text::ToPoint as _;
 5790
 5791                    return Some(
 5792                        h_flex()
 5793                            .px_2()
 5794                            .py_1()
 5795                            .elevation_2(cx)
 5796                            .border_color(cx.theme().colors().border)
 5797                            .rounded_tl(px(0.))
 5798                            .gap_2()
 5799                            .child(
 5800                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5801                                    Icon::new(IconName::ZedPredictDown)
 5802                                } else {
 5803                                    Icon::new(IconName::ZedPredictUp)
 5804                                },
 5805                            )
 5806                            .child(Label::new("Hold").size(LabelSize::Small))
 5807                            .children(ui::render_modifiers(
 5808                                &accept_keystroke.modifiers,
 5809                                PlatformStyle::platform(),
 5810                                Some(Color::Default),
 5811                                Some(IconSize::Small.rems().into()),
 5812                                true,
 5813                            ))
 5814                            .into_any(),
 5815                    );
 5816                }
 5817                _ => self.render_edit_prediction_cursor_popover_preview(
 5818                    completion,
 5819                    cursor_point,
 5820                    style,
 5821                    cx,
 5822                )?,
 5823            },
 5824
 5825            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5826                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5827                    stale_completion,
 5828                    cursor_point,
 5829                    style,
 5830                    cx,
 5831                )?,
 5832
 5833                None => {
 5834                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5835                }
 5836            },
 5837
 5838            None => pending_completion_container().child(Label::new("No Prediction")),
 5839        };
 5840
 5841        let completion = if is_refreshing {
 5842            completion
 5843                .with_animation(
 5844                    "loading-completion",
 5845                    Animation::new(Duration::from_secs(2))
 5846                        .repeat()
 5847                        .with_easing(pulsating_between(0.4, 0.8)),
 5848                    |label, delta| label.opacity(delta),
 5849                )
 5850                .into_any_element()
 5851        } else {
 5852            completion.into_any_element()
 5853        };
 5854
 5855        let has_completion = self.active_inline_completion.is_some();
 5856
 5857        Some(
 5858            h_flex()
 5859                .min_w(min_width)
 5860                .max_w(max_width)
 5861                .flex_1()
 5862                .elevation_2(cx)
 5863                .border_color(cx.theme().colors().border)
 5864                .child(
 5865                    div()
 5866                        .flex_1()
 5867                        .py_1()
 5868                        .px_2()
 5869                        .overflow_hidden()
 5870                        .child(completion),
 5871                )
 5872                .child(
 5873                    h_flex()
 5874                        .h_full()
 5875                        .border_l_1()
 5876                        .rounded_r_lg()
 5877                        .border_color(cx.theme().colors().border)
 5878                        .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5879                        .gap_1()
 5880                        .py_1()
 5881                        .px_2()
 5882                        .child(
 5883                            h_flex()
 5884                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5885                                .gap_1()
 5886                                .children(ui::render_modifiers(
 5887                                    &accept_keystroke.modifiers,
 5888                                    PlatformStyle::platform(),
 5889                                    Some(if !has_completion {
 5890                                        Color::Muted
 5891                                    } else {
 5892                                        Color::Default
 5893                                    }),
 5894                                    None,
 5895                                    true,
 5896                                )),
 5897                        )
 5898                        .child(Label::new("Preview").into_any_element())
 5899                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5900                )
 5901                .into_any(),
 5902        )
 5903    }
 5904
 5905    fn render_edit_prediction_cursor_popover_preview(
 5906        &self,
 5907        completion: &InlineCompletionState,
 5908        cursor_point: Point,
 5909        style: &EditorStyle,
 5910        cx: &mut Context<Editor>,
 5911    ) -> Option<Div> {
 5912        use text::ToPoint as _;
 5913
 5914        fn render_relative_row_jump(
 5915            prefix: impl Into<String>,
 5916            current_row: u32,
 5917            target_row: u32,
 5918        ) -> Div {
 5919            let (row_diff, arrow) = if target_row < current_row {
 5920                (current_row - target_row, IconName::ArrowUp)
 5921            } else {
 5922                (target_row - current_row, IconName::ArrowDown)
 5923            };
 5924
 5925            h_flex()
 5926                .child(
 5927                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5928                        .color(Color::Muted)
 5929                        .size(LabelSize::Small),
 5930                )
 5931                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5932        }
 5933
 5934        match &completion.completion {
 5935            InlineCompletion::Move {
 5936                target, snapshot, ..
 5937            } => Some(
 5938                h_flex()
 5939                    .px_2()
 5940                    .gap_2()
 5941                    .flex_1()
 5942                    .child(
 5943                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5944                            Icon::new(IconName::ZedPredictDown)
 5945                        } else {
 5946                            Icon::new(IconName::ZedPredictUp)
 5947                        },
 5948                    )
 5949                    .child(Label::new("Jump to Edit")),
 5950            ),
 5951
 5952            InlineCompletion::Edit {
 5953                edits,
 5954                edit_preview,
 5955                snapshot,
 5956                display_mode: _,
 5957            } => {
 5958                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5959
 5960                let highlighted_edits = crate::inline_completion_edit_text(
 5961                    &snapshot,
 5962                    &edits,
 5963                    edit_preview.as_ref()?,
 5964                    true,
 5965                    cx,
 5966                );
 5967
 5968                let len_total = highlighted_edits.text.len();
 5969                let first_line = &highlighted_edits.text
 5970                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5971                let first_line_len = first_line.len();
 5972
 5973                let first_highlight_start = highlighted_edits
 5974                    .highlights
 5975                    .first()
 5976                    .map_or(0, |(range, _)| range.start);
 5977                let drop_prefix_len = first_line
 5978                    .char_indices()
 5979                    .find(|(_, c)| !c.is_whitespace())
 5980                    .map_or(first_highlight_start, |(ix, _)| {
 5981                        ix.min(first_highlight_start)
 5982                    });
 5983
 5984                let preview_text = &first_line[drop_prefix_len..];
 5985                let preview_len = preview_text.len();
 5986                let highlights = highlighted_edits
 5987                    .highlights
 5988                    .into_iter()
 5989                    .take_until(|(range, _)| range.start > first_line_len)
 5990                    .map(|(range, style)| {
 5991                        (
 5992                            range.start - drop_prefix_len
 5993                                ..(range.end - drop_prefix_len).min(preview_len),
 5994                            style,
 5995                        )
 5996                    });
 5997
 5998                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5999                    .with_highlights(&style.text, highlights);
 6000
 6001                let preview = h_flex()
 6002                    .gap_1()
 6003                    .min_w_16()
 6004                    .child(styled_text)
 6005                    .when(len_total > first_line_len, |parent| parent.child(""));
 6006
 6007                let left = if first_edit_row != cursor_point.row {
 6008                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6009                        .into_any_element()
 6010                } else {
 6011                    Icon::new(IconName::ZedPredict).into_any_element()
 6012                };
 6013
 6014                Some(
 6015                    h_flex()
 6016                        .h_full()
 6017                        .flex_1()
 6018                        .gap_2()
 6019                        .pr_1()
 6020                        .overflow_x_hidden()
 6021                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6022                        .child(left)
 6023                        .child(preview),
 6024                )
 6025            }
 6026        }
 6027    }
 6028
 6029    fn render_context_menu(
 6030        &self,
 6031        style: &EditorStyle,
 6032        max_height_in_lines: u32,
 6033        y_flipped: bool,
 6034        window: &mut Window,
 6035        cx: &mut Context<Editor>,
 6036    ) -> Option<AnyElement> {
 6037        let menu = self.context_menu.borrow();
 6038        let menu = menu.as_ref()?;
 6039        if !menu.visible() {
 6040            return None;
 6041        };
 6042        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6043    }
 6044
 6045    fn render_context_menu_aside(
 6046        &self,
 6047        style: &EditorStyle,
 6048        max_size: Size<Pixels>,
 6049        cx: &mut Context<Editor>,
 6050    ) -> Option<AnyElement> {
 6051        self.context_menu.borrow().as_ref().and_then(|menu| {
 6052            if menu.visible() {
 6053                menu.render_aside(
 6054                    style,
 6055                    max_size,
 6056                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6057                    cx,
 6058                )
 6059            } else {
 6060                None
 6061            }
 6062        })
 6063    }
 6064
 6065    fn hide_context_menu(
 6066        &mut self,
 6067        window: &mut Window,
 6068        cx: &mut Context<Self>,
 6069    ) -> Option<CodeContextMenu> {
 6070        cx.notify();
 6071        self.completion_tasks.clear();
 6072        let context_menu = self.context_menu.borrow_mut().take();
 6073        self.stale_inline_completion_in_menu.take();
 6074        self.update_visible_inline_completion(window, cx);
 6075        context_menu
 6076    }
 6077
 6078    fn show_snippet_choices(
 6079        &mut self,
 6080        choices: &Vec<String>,
 6081        selection: Range<Anchor>,
 6082        cx: &mut Context<Self>,
 6083    ) {
 6084        if selection.start.buffer_id.is_none() {
 6085            return;
 6086        }
 6087        let buffer_id = selection.start.buffer_id.unwrap();
 6088        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6089        let id = post_inc(&mut self.next_completion_id);
 6090
 6091        if let Some(buffer) = buffer {
 6092            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6093                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6094            ));
 6095        }
 6096    }
 6097
 6098    pub fn insert_snippet(
 6099        &mut self,
 6100        insertion_ranges: &[Range<usize>],
 6101        snippet: Snippet,
 6102        window: &mut Window,
 6103        cx: &mut Context<Self>,
 6104    ) -> Result<()> {
 6105        struct Tabstop<T> {
 6106            is_end_tabstop: bool,
 6107            ranges: Vec<Range<T>>,
 6108            choices: Option<Vec<String>>,
 6109        }
 6110
 6111        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6112            let snippet_text: Arc<str> = snippet.text.clone().into();
 6113            buffer.edit(
 6114                insertion_ranges
 6115                    .iter()
 6116                    .cloned()
 6117                    .map(|range| (range, snippet_text.clone())),
 6118                Some(AutoindentMode::EachLine),
 6119                cx,
 6120            );
 6121
 6122            let snapshot = &*buffer.read(cx);
 6123            let snippet = &snippet;
 6124            snippet
 6125                .tabstops
 6126                .iter()
 6127                .map(|tabstop| {
 6128                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6129                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6130                    });
 6131                    let mut tabstop_ranges = tabstop
 6132                        .ranges
 6133                        .iter()
 6134                        .flat_map(|tabstop_range| {
 6135                            let mut delta = 0_isize;
 6136                            insertion_ranges.iter().map(move |insertion_range| {
 6137                                let insertion_start = insertion_range.start as isize + delta;
 6138                                delta +=
 6139                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6140
 6141                                let start = ((insertion_start + tabstop_range.start) as usize)
 6142                                    .min(snapshot.len());
 6143                                let end = ((insertion_start + tabstop_range.end) as usize)
 6144                                    .min(snapshot.len());
 6145                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6146                            })
 6147                        })
 6148                        .collect::<Vec<_>>();
 6149                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6150
 6151                    Tabstop {
 6152                        is_end_tabstop,
 6153                        ranges: tabstop_ranges,
 6154                        choices: tabstop.choices.clone(),
 6155                    }
 6156                })
 6157                .collect::<Vec<_>>()
 6158        });
 6159        if let Some(tabstop) = tabstops.first() {
 6160            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6161                s.select_ranges(tabstop.ranges.iter().cloned());
 6162            });
 6163
 6164            if let Some(choices) = &tabstop.choices {
 6165                if let Some(selection) = tabstop.ranges.first() {
 6166                    self.show_snippet_choices(choices, selection.clone(), cx)
 6167                }
 6168            }
 6169
 6170            // If we're already at the last tabstop and it's at the end of the snippet,
 6171            // we're done, we don't need to keep the state around.
 6172            if !tabstop.is_end_tabstop {
 6173                let choices = tabstops
 6174                    .iter()
 6175                    .map(|tabstop| tabstop.choices.clone())
 6176                    .collect();
 6177
 6178                let ranges = tabstops
 6179                    .into_iter()
 6180                    .map(|tabstop| tabstop.ranges)
 6181                    .collect::<Vec<_>>();
 6182
 6183                self.snippet_stack.push(SnippetState {
 6184                    active_index: 0,
 6185                    ranges,
 6186                    choices,
 6187                });
 6188            }
 6189
 6190            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6191            if self.autoclose_regions.is_empty() {
 6192                let snapshot = self.buffer.read(cx).snapshot(cx);
 6193                for selection in &mut self.selections.all::<Point>(cx) {
 6194                    let selection_head = selection.head();
 6195                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6196                        continue;
 6197                    };
 6198
 6199                    let mut bracket_pair = None;
 6200                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6201                    let prev_chars = snapshot
 6202                        .reversed_chars_at(selection_head)
 6203                        .collect::<String>();
 6204                    for (pair, enabled) in scope.brackets() {
 6205                        if enabled
 6206                            && pair.close
 6207                            && prev_chars.starts_with(pair.start.as_str())
 6208                            && next_chars.starts_with(pair.end.as_str())
 6209                        {
 6210                            bracket_pair = Some(pair.clone());
 6211                            break;
 6212                        }
 6213                    }
 6214                    if let Some(pair) = bracket_pair {
 6215                        let start = snapshot.anchor_after(selection_head);
 6216                        let end = snapshot.anchor_after(selection_head);
 6217                        self.autoclose_regions.push(AutocloseRegion {
 6218                            selection_id: selection.id,
 6219                            range: start..end,
 6220                            pair,
 6221                        });
 6222                    }
 6223                }
 6224            }
 6225        }
 6226        Ok(())
 6227    }
 6228
 6229    pub fn move_to_next_snippet_tabstop(
 6230        &mut self,
 6231        window: &mut Window,
 6232        cx: &mut Context<Self>,
 6233    ) -> bool {
 6234        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6235    }
 6236
 6237    pub fn move_to_prev_snippet_tabstop(
 6238        &mut self,
 6239        window: &mut Window,
 6240        cx: &mut Context<Self>,
 6241    ) -> bool {
 6242        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6243    }
 6244
 6245    pub fn move_to_snippet_tabstop(
 6246        &mut self,
 6247        bias: Bias,
 6248        window: &mut Window,
 6249        cx: &mut Context<Self>,
 6250    ) -> bool {
 6251        if let Some(mut snippet) = self.snippet_stack.pop() {
 6252            match bias {
 6253                Bias::Left => {
 6254                    if snippet.active_index > 0 {
 6255                        snippet.active_index -= 1;
 6256                    } else {
 6257                        self.snippet_stack.push(snippet);
 6258                        return false;
 6259                    }
 6260                }
 6261                Bias::Right => {
 6262                    if snippet.active_index + 1 < snippet.ranges.len() {
 6263                        snippet.active_index += 1;
 6264                    } else {
 6265                        self.snippet_stack.push(snippet);
 6266                        return false;
 6267                    }
 6268                }
 6269            }
 6270            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6271                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6272                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6273                });
 6274
 6275                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6276                    if let Some(selection) = current_ranges.first() {
 6277                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6278                    }
 6279                }
 6280
 6281                // If snippet state is not at the last tabstop, push it back on the stack
 6282                if snippet.active_index + 1 < snippet.ranges.len() {
 6283                    self.snippet_stack.push(snippet);
 6284                }
 6285                return true;
 6286            }
 6287        }
 6288
 6289        false
 6290    }
 6291
 6292    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6293        self.transact(window, cx, |this, window, cx| {
 6294            this.select_all(&SelectAll, window, cx);
 6295            this.insert("", window, cx);
 6296        });
 6297    }
 6298
 6299    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6300        self.transact(window, cx, |this, window, cx| {
 6301            this.select_autoclose_pair(window, cx);
 6302            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6303            if !this.linked_edit_ranges.is_empty() {
 6304                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6305                let snapshot = this.buffer.read(cx).snapshot(cx);
 6306
 6307                for selection in selections.iter() {
 6308                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6309                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6310                    if selection_start.buffer_id != selection_end.buffer_id {
 6311                        continue;
 6312                    }
 6313                    if let Some(ranges) =
 6314                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6315                    {
 6316                        for (buffer, entries) in ranges {
 6317                            linked_ranges.entry(buffer).or_default().extend(entries);
 6318                        }
 6319                    }
 6320                }
 6321            }
 6322
 6323            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6324            if !this.selections.line_mode {
 6325                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6326                for selection in &mut selections {
 6327                    if selection.is_empty() {
 6328                        let old_head = selection.head();
 6329                        let mut new_head =
 6330                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6331                                .to_point(&display_map);
 6332                        if let Some((buffer, line_buffer_range)) = display_map
 6333                            .buffer_snapshot
 6334                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6335                        {
 6336                            let indent_size =
 6337                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6338                            let indent_len = match indent_size.kind {
 6339                                IndentKind::Space => {
 6340                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6341                                }
 6342                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6343                            };
 6344                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6345                                let indent_len = indent_len.get();
 6346                                new_head = cmp::min(
 6347                                    new_head,
 6348                                    MultiBufferPoint::new(
 6349                                        old_head.row,
 6350                                        ((old_head.column - 1) / indent_len) * indent_len,
 6351                                    ),
 6352                                );
 6353                            }
 6354                        }
 6355
 6356                        selection.set_head(new_head, SelectionGoal::None);
 6357                    }
 6358                }
 6359            }
 6360
 6361            this.signature_help_state.set_backspace_pressed(true);
 6362            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6363                s.select(selections)
 6364            });
 6365            this.insert("", window, cx);
 6366            let empty_str: Arc<str> = Arc::from("");
 6367            for (buffer, edits) in linked_ranges {
 6368                let snapshot = buffer.read(cx).snapshot();
 6369                use text::ToPoint as TP;
 6370
 6371                let edits = edits
 6372                    .into_iter()
 6373                    .map(|range| {
 6374                        let end_point = TP::to_point(&range.end, &snapshot);
 6375                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6376
 6377                        if end_point == start_point {
 6378                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6379                                .saturating_sub(1);
 6380                            start_point =
 6381                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6382                        };
 6383
 6384                        (start_point..end_point, empty_str.clone())
 6385                    })
 6386                    .sorted_by_key(|(range, _)| range.start)
 6387                    .collect::<Vec<_>>();
 6388                buffer.update(cx, |this, cx| {
 6389                    this.edit(edits, None, cx);
 6390                })
 6391            }
 6392            this.refresh_inline_completion(true, false, window, cx);
 6393            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6394        });
 6395    }
 6396
 6397    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6398        self.transact(window, cx, |this, window, cx| {
 6399            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6400                let line_mode = s.line_mode;
 6401                s.move_with(|map, selection| {
 6402                    if selection.is_empty() && !line_mode {
 6403                        let cursor = movement::right(map, selection.head());
 6404                        selection.end = cursor;
 6405                        selection.reversed = true;
 6406                        selection.goal = SelectionGoal::None;
 6407                    }
 6408                })
 6409            });
 6410            this.insert("", window, cx);
 6411            this.refresh_inline_completion(true, false, window, cx);
 6412        });
 6413    }
 6414
 6415    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6416        if self.move_to_prev_snippet_tabstop(window, cx) {
 6417            return;
 6418        }
 6419
 6420        self.outdent(&Outdent, window, cx);
 6421    }
 6422
 6423    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6424        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6425            return;
 6426        }
 6427
 6428        let mut selections = self.selections.all_adjusted(cx);
 6429        let buffer = self.buffer.read(cx);
 6430        let snapshot = buffer.snapshot(cx);
 6431        let rows_iter = selections.iter().map(|s| s.head().row);
 6432        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6433
 6434        let mut edits = Vec::new();
 6435        let mut prev_edited_row = 0;
 6436        let mut row_delta = 0;
 6437        for selection in &mut selections {
 6438            if selection.start.row != prev_edited_row {
 6439                row_delta = 0;
 6440            }
 6441            prev_edited_row = selection.end.row;
 6442
 6443            // If the selection is non-empty, then increase the indentation of the selected lines.
 6444            if !selection.is_empty() {
 6445                row_delta =
 6446                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6447                continue;
 6448            }
 6449
 6450            // If the selection is empty and the cursor is in the leading whitespace before the
 6451            // suggested indentation, then auto-indent the line.
 6452            let cursor = selection.head();
 6453            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6454            if let Some(suggested_indent) =
 6455                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6456            {
 6457                if cursor.column < suggested_indent.len
 6458                    && cursor.column <= current_indent.len
 6459                    && current_indent.len <= suggested_indent.len
 6460                {
 6461                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6462                    selection.end = selection.start;
 6463                    if row_delta == 0 {
 6464                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6465                            cursor.row,
 6466                            current_indent,
 6467                            suggested_indent,
 6468                        ));
 6469                        row_delta = suggested_indent.len - current_indent.len;
 6470                    }
 6471                    continue;
 6472                }
 6473            }
 6474
 6475            // Otherwise, insert a hard or soft tab.
 6476            let settings = buffer.settings_at(cursor, cx);
 6477            let tab_size = if settings.hard_tabs {
 6478                IndentSize::tab()
 6479            } else {
 6480                let tab_size = settings.tab_size.get();
 6481                let char_column = snapshot
 6482                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6483                    .flat_map(str::chars)
 6484                    .count()
 6485                    + row_delta as usize;
 6486                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6487                IndentSize::spaces(chars_to_next_tab_stop)
 6488            };
 6489            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6490            selection.end = selection.start;
 6491            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6492            row_delta += tab_size.len;
 6493        }
 6494
 6495        self.transact(window, cx, |this, window, cx| {
 6496            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6497            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6498                s.select(selections)
 6499            });
 6500            this.refresh_inline_completion(true, false, window, cx);
 6501        });
 6502    }
 6503
 6504    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6505        if self.read_only(cx) {
 6506            return;
 6507        }
 6508        let mut selections = self.selections.all::<Point>(cx);
 6509        let mut prev_edited_row = 0;
 6510        let mut row_delta = 0;
 6511        let mut edits = Vec::new();
 6512        let buffer = self.buffer.read(cx);
 6513        let snapshot = buffer.snapshot(cx);
 6514        for selection in &mut selections {
 6515            if selection.start.row != prev_edited_row {
 6516                row_delta = 0;
 6517            }
 6518            prev_edited_row = selection.end.row;
 6519
 6520            row_delta =
 6521                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6522        }
 6523
 6524        self.transact(window, cx, |this, window, cx| {
 6525            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6526            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6527                s.select(selections)
 6528            });
 6529        });
 6530    }
 6531
 6532    fn indent_selection(
 6533        buffer: &MultiBuffer,
 6534        snapshot: &MultiBufferSnapshot,
 6535        selection: &mut Selection<Point>,
 6536        edits: &mut Vec<(Range<Point>, String)>,
 6537        delta_for_start_row: u32,
 6538        cx: &App,
 6539    ) -> u32 {
 6540        let settings = buffer.settings_at(selection.start, cx);
 6541        let tab_size = settings.tab_size.get();
 6542        let indent_kind = if settings.hard_tabs {
 6543            IndentKind::Tab
 6544        } else {
 6545            IndentKind::Space
 6546        };
 6547        let mut start_row = selection.start.row;
 6548        let mut end_row = selection.end.row + 1;
 6549
 6550        // If a selection ends at the beginning of a line, don't indent
 6551        // that last line.
 6552        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6553            end_row -= 1;
 6554        }
 6555
 6556        // Avoid re-indenting a row that has already been indented by a
 6557        // previous selection, but still update this selection's column
 6558        // to reflect that indentation.
 6559        if delta_for_start_row > 0 {
 6560            start_row += 1;
 6561            selection.start.column += delta_for_start_row;
 6562            if selection.end.row == selection.start.row {
 6563                selection.end.column += delta_for_start_row;
 6564            }
 6565        }
 6566
 6567        let mut delta_for_end_row = 0;
 6568        let has_multiple_rows = start_row + 1 != end_row;
 6569        for row in start_row..end_row {
 6570            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6571            let indent_delta = match (current_indent.kind, indent_kind) {
 6572                (IndentKind::Space, IndentKind::Space) => {
 6573                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6574                    IndentSize::spaces(columns_to_next_tab_stop)
 6575                }
 6576                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6577                (_, IndentKind::Tab) => IndentSize::tab(),
 6578            };
 6579
 6580            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6581                0
 6582            } else {
 6583                selection.start.column
 6584            };
 6585            let row_start = Point::new(row, start);
 6586            edits.push((
 6587                row_start..row_start,
 6588                indent_delta.chars().collect::<String>(),
 6589            ));
 6590
 6591            // Update this selection's endpoints to reflect the indentation.
 6592            if row == selection.start.row {
 6593                selection.start.column += indent_delta.len;
 6594            }
 6595            if row == selection.end.row {
 6596                selection.end.column += indent_delta.len;
 6597                delta_for_end_row = indent_delta.len;
 6598            }
 6599        }
 6600
 6601        if selection.start.row == selection.end.row {
 6602            delta_for_start_row + delta_for_end_row
 6603        } else {
 6604            delta_for_end_row
 6605        }
 6606    }
 6607
 6608    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6609        if self.read_only(cx) {
 6610            return;
 6611        }
 6612        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6613        let selections = self.selections.all::<Point>(cx);
 6614        let mut deletion_ranges = Vec::new();
 6615        let mut last_outdent = None;
 6616        {
 6617            let buffer = self.buffer.read(cx);
 6618            let snapshot = buffer.snapshot(cx);
 6619            for selection in &selections {
 6620                let settings = buffer.settings_at(selection.start, cx);
 6621                let tab_size = settings.tab_size.get();
 6622                let mut rows = selection.spanned_rows(false, &display_map);
 6623
 6624                // Avoid re-outdenting a row that has already been outdented by a
 6625                // previous selection.
 6626                if let Some(last_row) = last_outdent {
 6627                    if last_row == rows.start {
 6628                        rows.start = rows.start.next_row();
 6629                    }
 6630                }
 6631                let has_multiple_rows = rows.len() > 1;
 6632                for row in rows.iter_rows() {
 6633                    let indent_size = snapshot.indent_size_for_line(row);
 6634                    if indent_size.len > 0 {
 6635                        let deletion_len = match indent_size.kind {
 6636                            IndentKind::Space => {
 6637                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6638                                if columns_to_prev_tab_stop == 0 {
 6639                                    tab_size
 6640                                } else {
 6641                                    columns_to_prev_tab_stop
 6642                                }
 6643                            }
 6644                            IndentKind::Tab => 1,
 6645                        };
 6646                        let start = if has_multiple_rows
 6647                            || deletion_len > selection.start.column
 6648                            || indent_size.len < selection.start.column
 6649                        {
 6650                            0
 6651                        } else {
 6652                            selection.start.column - deletion_len
 6653                        };
 6654                        deletion_ranges.push(
 6655                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6656                        );
 6657                        last_outdent = Some(row);
 6658                    }
 6659                }
 6660            }
 6661        }
 6662
 6663        self.transact(window, cx, |this, window, cx| {
 6664            this.buffer.update(cx, |buffer, cx| {
 6665                let empty_str: Arc<str> = Arc::default();
 6666                buffer.edit(
 6667                    deletion_ranges
 6668                        .into_iter()
 6669                        .map(|range| (range, empty_str.clone())),
 6670                    None,
 6671                    cx,
 6672                );
 6673            });
 6674            let selections = this.selections.all::<usize>(cx);
 6675            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6676                s.select(selections)
 6677            });
 6678        });
 6679    }
 6680
 6681    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6682        if self.read_only(cx) {
 6683            return;
 6684        }
 6685        let selections = self
 6686            .selections
 6687            .all::<usize>(cx)
 6688            .into_iter()
 6689            .map(|s| s.range());
 6690
 6691        self.transact(window, cx, |this, window, cx| {
 6692            this.buffer.update(cx, |buffer, cx| {
 6693                buffer.autoindent_ranges(selections, cx);
 6694            });
 6695            let selections = this.selections.all::<usize>(cx);
 6696            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6697                s.select(selections)
 6698            });
 6699        });
 6700    }
 6701
 6702    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6703        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6704        let selections = self.selections.all::<Point>(cx);
 6705
 6706        let mut new_cursors = Vec::new();
 6707        let mut edit_ranges = Vec::new();
 6708        let mut selections = selections.iter().peekable();
 6709        while let Some(selection) = selections.next() {
 6710            let mut rows = selection.spanned_rows(false, &display_map);
 6711            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6712
 6713            // Accumulate contiguous regions of rows that we want to delete.
 6714            while let Some(next_selection) = selections.peek() {
 6715                let next_rows = next_selection.spanned_rows(false, &display_map);
 6716                if next_rows.start <= rows.end {
 6717                    rows.end = next_rows.end;
 6718                    selections.next().unwrap();
 6719                } else {
 6720                    break;
 6721                }
 6722            }
 6723
 6724            let buffer = &display_map.buffer_snapshot;
 6725            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6726            let edit_end;
 6727            let cursor_buffer_row;
 6728            if buffer.max_point().row >= rows.end.0 {
 6729                // If there's a line after the range, delete the \n from the end of the row range
 6730                // and position the cursor on the next line.
 6731                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6732                cursor_buffer_row = rows.end;
 6733            } else {
 6734                // If there isn't a line after the range, delete the \n from the line before the
 6735                // start of the row range and position the cursor there.
 6736                edit_start = edit_start.saturating_sub(1);
 6737                edit_end = buffer.len();
 6738                cursor_buffer_row = rows.start.previous_row();
 6739            }
 6740
 6741            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6742            *cursor.column_mut() =
 6743                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6744
 6745            new_cursors.push((
 6746                selection.id,
 6747                buffer.anchor_after(cursor.to_point(&display_map)),
 6748            ));
 6749            edit_ranges.push(edit_start..edit_end);
 6750        }
 6751
 6752        self.transact(window, cx, |this, window, cx| {
 6753            let buffer = this.buffer.update(cx, |buffer, cx| {
 6754                let empty_str: Arc<str> = Arc::default();
 6755                buffer.edit(
 6756                    edit_ranges
 6757                        .into_iter()
 6758                        .map(|range| (range, empty_str.clone())),
 6759                    None,
 6760                    cx,
 6761                );
 6762                buffer.snapshot(cx)
 6763            });
 6764            let new_selections = new_cursors
 6765                .into_iter()
 6766                .map(|(id, cursor)| {
 6767                    let cursor = cursor.to_point(&buffer);
 6768                    Selection {
 6769                        id,
 6770                        start: cursor,
 6771                        end: cursor,
 6772                        reversed: false,
 6773                        goal: SelectionGoal::None,
 6774                    }
 6775                })
 6776                .collect();
 6777
 6778            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6779                s.select(new_selections);
 6780            });
 6781        });
 6782    }
 6783
 6784    pub fn join_lines_impl(
 6785        &mut self,
 6786        insert_whitespace: bool,
 6787        window: &mut Window,
 6788        cx: &mut Context<Self>,
 6789    ) {
 6790        if self.read_only(cx) {
 6791            return;
 6792        }
 6793        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6794        for selection in self.selections.all::<Point>(cx) {
 6795            let start = MultiBufferRow(selection.start.row);
 6796            // Treat single line selections as if they include the next line. Otherwise this action
 6797            // would do nothing for single line selections individual cursors.
 6798            let end = if selection.start.row == selection.end.row {
 6799                MultiBufferRow(selection.start.row + 1)
 6800            } else {
 6801                MultiBufferRow(selection.end.row)
 6802            };
 6803
 6804            if let Some(last_row_range) = row_ranges.last_mut() {
 6805                if start <= last_row_range.end {
 6806                    last_row_range.end = end;
 6807                    continue;
 6808                }
 6809            }
 6810            row_ranges.push(start..end);
 6811        }
 6812
 6813        let snapshot = self.buffer.read(cx).snapshot(cx);
 6814        let mut cursor_positions = Vec::new();
 6815        for row_range in &row_ranges {
 6816            let anchor = snapshot.anchor_before(Point::new(
 6817                row_range.end.previous_row().0,
 6818                snapshot.line_len(row_range.end.previous_row()),
 6819            ));
 6820            cursor_positions.push(anchor..anchor);
 6821        }
 6822
 6823        self.transact(window, cx, |this, window, cx| {
 6824            for row_range in row_ranges.into_iter().rev() {
 6825                for row in row_range.iter_rows().rev() {
 6826                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6827                    let next_line_row = row.next_row();
 6828                    let indent = snapshot.indent_size_for_line(next_line_row);
 6829                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6830
 6831                    let replace =
 6832                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6833                            " "
 6834                        } else {
 6835                            ""
 6836                        };
 6837
 6838                    this.buffer.update(cx, |buffer, cx| {
 6839                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6840                    });
 6841                }
 6842            }
 6843
 6844            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6845                s.select_anchor_ranges(cursor_positions)
 6846            });
 6847        });
 6848    }
 6849
 6850    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6851        self.join_lines_impl(true, window, cx);
 6852    }
 6853
 6854    pub fn sort_lines_case_sensitive(
 6855        &mut self,
 6856        _: &SortLinesCaseSensitive,
 6857        window: &mut Window,
 6858        cx: &mut Context<Self>,
 6859    ) {
 6860        self.manipulate_lines(window, cx, |lines| lines.sort())
 6861    }
 6862
 6863    pub fn sort_lines_case_insensitive(
 6864        &mut self,
 6865        _: &SortLinesCaseInsensitive,
 6866        window: &mut Window,
 6867        cx: &mut Context<Self>,
 6868    ) {
 6869        self.manipulate_lines(window, cx, |lines| {
 6870            lines.sort_by_key(|line| line.to_lowercase())
 6871        })
 6872    }
 6873
 6874    pub fn unique_lines_case_insensitive(
 6875        &mut self,
 6876        _: &UniqueLinesCaseInsensitive,
 6877        window: &mut Window,
 6878        cx: &mut Context<Self>,
 6879    ) {
 6880        self.manipulate_lines(window, cx, |lines| {
 6881            let mut seen = HashSet::default();
 6882            lines.retain(|line| seen.insert(line.to_lowercase()));
 6883        })
 6884    }
 6885
 6886    pub fn unique_lines_case_sensitive(
 6887        &mut self,
 6888        _: &UniqueLinesCaseSensitive,
 6889        window: &mut Window,
 6890        cx: &mut Context<Self>,
 6891    ) {
 6892        self.manipulate_lines(window, cx, |lines| {
 6893            let mut seen = HashSet::default();
 6894            lines.retain(|line| seen.insert(*line));
 6895        })
 6896    }
 6897
 6898    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6899        let mut revert_changes = HashMap::default();
 6900        let snapshot = self.snapshot(window, cx);
 6901        for hunk in snapshot
 6902            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6903        {
 6904            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6905        }
 6906        if !revert_changes.is_empty() {
 6907            self.transact(window, cx, |editor, window, cx| {
 6908                editor.revert(revert_changes, window, cx);
 6909            });
 6910        }
 6911    }
 6912
 6913    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6914        let Some(project) = self.project.clone() else {
 6915            return;
 6916        };
 6917        self.reload(project, window, cx)
 6918            .detach_and_notify_err(window, cx);
 6919    }
 6920
 6921    pub fn revert_selected_hunks(
 6922        &mut self,
 6923        _: &RevertSelectedHunks,
 6924        window: &mut Window,
 6925        cx: &mut Context<Self>,
 6926    ) {
 6927        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6928        self.revert_hunks_in_ranges(selections, window, cx);
 6929    }
 6930
 6931    fn revert_hunks_in_ranges(
 6932        &mut self,
 6933        ranges: impl Iterator<Item = Range<Point>>,
 6934        window: &mut Window,
 6935        cx: &mut Context<Editor>,
 6936    ) {
 6937        let mut revert_changes = HashMap::default();
 6938        let snapshot = self.snapshot(window, cx);
 6939        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6940            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6941        }
 6942        if !revert_changes.is_empty() {
 6943            self.transact(window, cx, |editor, window, cx| {
 6944                editor.revert(revert_changes, window, cx);
 6945            });
 6946        }
 6947    }
 6948
 6949    pub fn open_active_item_in_terminal(
 6950        &mut self,
 6951        _: &OpenInTerminal,
 6952        window: &mut Window,
 6953        cx: &mut Context<Self>,
 6954    ) {
 6955        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6956            let project_path = buffer.read(cx).project_path(cx)?;
 6957            let project = self.project.as_ref()?.read(cx);
 6958            let entry = project.entry_for_path(&project_path, cx)?;
 6959            let parent = match &entry.canonical_path {
 6960                Some(canonical_path) => canonical_path.to_path_buf(),
 6961                None => project.absolute_path(&project_path, cx)?,
 6962            }
 6963            .parent()?
 6964            .to_path_buf();
 6965            Some(parent)
 6966        }) {
 6967            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6968        }
 6969    }
 6970
 6971    pub fn prepare_revert_change(
 6972        &self,
 6973        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6974        hunk: &MultiBufferDiffHunk,
 6975        cx: &mut App,
 6976    ) -> Option<()> {
 6977        let buffer = self.buffer.read(cx);
 6978        let diff = buffer.diff_for(hunk.buffer_id)?;
 6979        let buffer = buffer.buffer(hunk.buffer_id)?;
 6980        let buffer = buffer.read(cx);
 6981        let original_text = diff
 6982            .read(cx)
 6983            .base_text()
 6984            .as_ref()?
 6985            .as_rope()
 6986            .slice(hunk.diff_base_byte_range.clone());
 6987        let buffer_snapshot = buffer.snapshot();
 6988        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6989        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6990            probe
 6991                .0
 6992                .start
 6993                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6994                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6995        }) {
 6996            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6997            Some(())
 6998        } else {
 6999            None
 7000        }
 7001    }
 7002
 7003    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7004        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7005    }
 7006
 7007    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7008        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7009    }
 7010
 7011    fn manipulate_lines<Fn>(
 7012        &mut self,
 7013        window: &mut Window,
 7014        cx: &mut Context<Self>,
 7015        mut callback: Fn,
 7016    ) where
 7017        Fn: FnMut(&mut Vec<&str>),
 7018    {
 7019        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7020        let buffer = self.buffer.read(cx).snapshot(cx);
 7021
 7022        let mut edits = Vec::new();
 7023
 7024        let selections = self.selections.all::<Point>(cx);
 7025        let mut selections = selections.iter().peekable();
 7026        let mut contiguous_row_selections = Vec::new();
 7027        let mut new_selections = Vec::new();
 7028        let mut added_lines = 0;
 7029        let mut removed_lines = 0;
 7030
 7031        while let Some(selection) = selections.next() {
 7032            let (start_row, end_row) = consume_contiguous_rows(
 7033                &mut contiguous_row_selections,
 7034                selection,
 7035                &display_map,
 7036                &mut selections,
 7037            );
 7038
 7039            let start_point = Point::new(start_row.0, 0);
 7040            let end_point = Point::new(
 7041                end_row.previous_row().0,
 7042                buffer.line_len(end_row.previous_row()),
 7043            );
 7044            let text = buffer
 7045                .text_for_range(start_point..end_point)
 7046                .collect::<String>();
 7047
 7048            let mut lines = text.split('\n').collect_vec();
 7049
 7050            let lines_before = lines.len();
 7051            callback(&mut lines);
 7052            let lines_after = lines.len();
 7053
 7054            edits.push((start_point..end_point, lines.join("\n")));
 7055
 7056            // Selections must change based on added and removed line count
 7057            let start_row =
 7058                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7059            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7060            new_selections.push(Selection {
 7061                id: selection.id,
 7062                start: start_row,
 7063                end: end_row,
 7064                goal: SelectionGoal::None,
 7065                reversed: selection.reversed,
 7066            });
 7067
 7068            if lines_after > lines_before {
 7069                added_lines += lines_after - lines_before;
 7070            } else if lines_before > lines_after {
 7071                removed_lines += lines_before - lines_after;
 7072            }
 7073        }
 7074
 7075        self.transact(window, cx, |this, window, cx| {
 7076            let buffer = this.buffer.update(cx, |buffer, cx| {
 7077                buffer.edit(edits, None, cx);
 7078                buffer.snapshot(cx)
 7079            });
 7080
 7081            // Recalculate offsets on newly edited buffer
 7082            let new_selections = new_selections
 7083                .iter()
 7084                .map(|s| {
 7085                    let start_point = Point::new(s.start.0, 0);
 7086                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7087                    Selection {
 7088                        id: s.id,
 7089                        start: buffer.point_to_offset(start_point),
 7090                        end: buffer.point_to_offset(end_point),
 7091                        goal: s.goal,
 7092                        reversed: s.reversed,
 7093                    }
 7094                })
 7095                .collect();
 7096
 7097            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7098                s.select(new_selections);
 7099            });
 7100
 7101            this.request_autoscroll(Autoscroll::fit(), cx);
 7102        });
 7103    }
 7104
 7105    pub fn convert_to_upper_case(
 7106        &mut self,
 7107        _: &ConvertToUpperCase,
 7108        window: &mut Window,
 7109        cx: &mut Context<Self>,
 7110    ) {
 7111        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7112    }
 7113
 7114    pub fn convert_to_lower_case(
 7115        &mut self,
 7116        _: &ConvertToLowerCase,
 7117        window: &mut Window,
 7118        cx: &mut Context<Self>,
 7119    ) {
 7120        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7121    }
 7122
 7123    pub fn convert_to_title_case(
 7124        &mut self,
 7125        _: &ConvertToTitleCase,
 7126        window: &mut Window,
 7127        cx: &mut Context<Self>,
 7128    ) {
 7129        self.manipulate_text(window, cx, |text| {
 7130            text.split('\n')
 7131                .map(|line| line.to_case(Case::Title))
 7132                .join("\n")
 7133        })
 7134    }
 7135
 7136    pub fn convert_to_snake_case(
 7137        &mut self,
 7138        _: &ConvertToSnakeCase,
 7139        window: &mut Window,
 7140        cx: &mut Context<Self>,
 7141    ) {
 7142        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7143    }
 7144
 7145    pub fn convert_to_kebab_case(
 7146        &mut self,
 7147        _: &ConvertToKebabCase,
 7148        window: &mut Window,
 7149        cx: &mut Context<Self>,
 7150    ) {
 7151        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7152    }
 7153
 7154    pub fn convert_to_upper_camel_case(
 7155        &mut self,
 7156        _: &ConvertToUpperCamelCase,
 7157        window: &mut Window,
 7158        cx: &mut Context<Self>,
 7159    ) {
 7160        self.manipulate_text(window, cx, |text| {
 7161            text.split('\n')
 7162                .map(|line| line.to_case(Case::UpperCamel))
 7163                .join("\n")
 7164        })
 7165    }
 7166
 7167    pub fn convert_to_lower_camel_case(
 7168        &mut self,
 7169        _: &ConvertToLowerCamelCase,
 7170        window: &mut Window,
 7171        cx: &mut Context<Self>,
 7172    ) {
 7173        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7174    }
 7175
 7176    pub fn convert_to_opposite_case(
 7177        &mut self,
 7178        _: &ConvertToOppositeCase,
 7179        window: &mut Window,
 7180        cx: &mut Context<Self>,
 7181    ) {
 7182        self.manipulate_text(window, cx, |text| {
 7183            text.chars()
 7184                .fold(String::with_capacity(text.len()), |mut t, c| {
 7185                    if c.is_uppercase() {
 7186                        t.extend(c.to_lowercase());
 7187                    } else {
 7188                        t.extend(c.to_uppercase());
 7189                    }
 7190                    t
 7191                })
 7192        })
 7193    }
 7194
 7195    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7196    where
 7197        Fn: FnMut(&str) -> String,
 7198    {
 7199        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7200        let buffer = self.buffer.read(cx).snapshot(cx);
 7201
 7202        let mut new_selections = Vec::new();
 7203        let mut edits = Vec::new();
 7204        let mut selection_adjustment = 0i32;
 7205
 7206        for selection in self.selections.all::<usize>(cx) {
 7207            let selection_is_empty = selection.is_empty();
 7208
 7209            let (start, end) = if selection_is_empty {
 7210                let word_range = movement::surrounding_word(
 7211                    &display_map,
 7212                    selection.start.to_display_point(&display_map),
 7213                );
 7214                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7215                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7216                (start, end)
 7217            } else {
 7218                (selection.start, selection.end)
 7219            };
 7220
 7221            let text = buffer.text_for_range(start..end).collect::<String>();
 7222            let old_length = text.len() as i32;
 7223            let text = callback(&text);
 7224
 7225            new_selections.push(Selection {
 7226                start: (start as i32 - selection_adjustment) as usize,
 7227                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7228                goal: SelectionGoal::None,
 7229                ..selection
 7230            });
 7231
 7232            selection_adjustment += old_length - text.len() as i32;
 7233
 7234            edits.push((start..end, text));
 7235        }
 7236
 7237        self.transact(window, cx, |this, window, cx| {
 7238            this.buffer.update(cx, |buffer, cx| {
 7239                buffer.edit(edits, None, cx);
 7240            });
 7241
 7242            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7243                s.select(new_selections);
 7244            });
 7245
 7246            this.request_autoscroll(Autoscroll::fit(), cx);
 7247        });
 7248    }
 7249
 7250    pub fn duplicate(
 7251        &mut self,
 7252        upwards: bool,
 7253        whole_lines: bool,
 7254        window: &mut Window,
 7255        cx: &mut Context<Self>,
 7256    ) {
 7257        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7258        let buffer = &display_map.buffer_snapshot;
 7259        let selections = self.selections.all::<Point>(cx);
 7260
 7261        let mut edits = Vec::new();
 7262        let mut selections_iter = selections.iter().peekable();
 7263        while let Some(selection) = selections_iter.next() {
 7264            let mut rows = selection.spanned_rows(false, &display_map);
 7265            // duplicate line-wise
 7266            if whole_lines || selection.start == selection.end {
 7267                // Avoid duplicating the same lines twice.
 7268                while let Some(next_selection) = selections_iter.peek() {
 7269                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7270                    if next_rows.start < rows.end {
 7271                        rows.end = next_rows.end;
 7272                        selections_iter.next().unwrap();
 7273                    } else {
 7274                        break;
 7275                    }
 7276                }
 7277
 7278                // Copy the text from the selected row region and splice it either at the start
 7279                // or end of the region.
 7280                let start = Point::new(rows.start.0, 0);
 7281                let end = Point::new(
 7282                    rows.end.previous_row().0,
 7283                    buffer.line_len(rows.end.previous_row()),
 7284                );
 7285                let text = buffer
 7286                    .text_for_range(start..end)
 7287                    .chain(Some("\n"))
 7288                    .collect::<String>();
 7289                let insert_location = if upwards {
 7290                    Point::new(rows.end.0, 0)
 7291                } else {
 7292                    start
 7293                };
 7294                edits.push((insert_location..insert_location, text));
 7295            } else {
 7296                // duplicate character-wise
 7297                let start = selection.start;
 7298                let end = selection.end;
 7299                let text = buffer.text_for_range(start..end).collect::<String>();
 7300                edits.push((selection.end..selection.end, text));
 7301            }
 7302        }
 7303
 7304        self.transact(window, cx, |this, _, cx| {
 7305            this.buffer.update(cx, |buffer, cx| {
 7306                buffer.edit(edits, None, cx);
 7307            });
 7308
 7309            this.request_autoscroll(Autoscroll::fit(), cx);
 7310        });
 7311    }
 7312
 7313    pub fn duplicate_line_up(
 7314        &mut self,
 7315        _: &DuplicateLineUp,
 7316        window: &mut Window,
 7317        cx: &mut Context<Self>,
 7318    ) {
 7319        self.duplicate(true, true, window, cx);
 7320    }
 7321
 7322    pub fn duplicate_line_down(
 7323        &mut self,
 7324        _: &DuplicateLineDown,
 7325        window: &mut Window,
 7326        cx: &mut Context<Self>,
 7327    ) {
 7328        self.duplicate(false, true, window, cx);
 7329    }
 7330
 7331    pub fn duplicate_selection(
 7332        &mut self,
 7333        _: &DuplicateSelection,
 7334        window: &mut Window,
 7335        cx: &mut Context<Self>,
 7336    ) {
 7337        self.duplicate(false, false, window, cx);
 7338    }
 7339
 7340    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7341        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7342        let buffer = self.buffer.read(cx).snapshot(cx);
 7343
 7344        let mut edits = Vec::new();
 7345        let mut unfold_ranges = Vec::new();
 7346        let mut refold_creases = Vec::new();
 7347
 7348        let selections = self.selections.all::<Point>(cx);
 7349        let mut selections = selections.iter().peekable();
 7350        let mut contiguous_row_selections = Vec::new();
 7351        let mut new_selections = Vec::new();
 7352
 7353        while let Some(selection) = selections.next() {
 7354            // Find all the selections that span a contiguous row range
 7355            let (start_row, end_row) = consume_contiguous_rows(
 7356                &mut contiguous_row_selections,
 7357                selection,
 7358                &display_map,
 7359                &mut selections,
 7360            );
 7361
 7362            // Move the text spanned by the row range to be before the line preceding the row range
 7363            if start_row.0 > 0 {
 7364                let range_to_move = Point::new(
 7365                    start_row.previous_row().0,
 7366                    buffer.line_len(start_row.previous_row()),
 7367                )
 7368                    ..Point::new(
 7369                        end_row.previous_row().0,
 7370                        buffer.line_len(end_row.previous_row()),
 7371                    );
 7372                let insertion_point = display_map
 7373                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7374                    .0;
 7375
 7376                // Don't move lines across excerpts
 7377                if buffer
 7378                    .excerpt_containing(insertion_point..range_to_move.end)
 7379                    .is_some()
 7380                {
 7381                    let text = buffer
 7382                        .text_for_range(range_to_move.clone())
 7383                        .flat_map(|s| s.chars())
 7384                        .skip(1)
 7385                        .chain(['\n'])
 7386                        .collect::<String>();
 7387
 7388                    edits.push((
 7389                        buffer.anchor_after(range_to_move.start)
 7390                            ..buffer.anchor_before(range_to_move.end),
 7391                        String::new(),
 7392                    ));
 7393                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7394                    edits.push((insertion_anchor..insertion_anchor, text));
 7395
 7396                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7397
 7398                    // Move selections up
 7399                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7400                        |mut selection| {
 7401                            selection.start.row -= row_delta;
 7402                            selection.end.row -= row_delta;
 7403                            selection
 7404                        },
 7405                    ));
 7406
 7407                    // Move folds up
 7408                    unfold_ranges.push(range_to_move.clone());
 7409                    for fold in display_map.folds_in_range(
 7410                        buffer.anchor_before(range_to_move.start)
 7411                            ..buffer.anchor_after(range_to_move.end),
 7412                    ) {
 7413                        let mut start = fold.range.start.to_point(&buffer);
 7414                        let mut end = fold.range.end.to_point(&buffer);
 7415                        start.row -= row_delta;
 7416                        end.row -= row_delta;
 7417                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7418                    }
 7419                }
 7420            }
 7421
 7422            // If we didn't move line(s), preserve the existing selections
 7423            new_selections.append(&mut contiguous_row_selections);
 7424        }
 7425
 7426        self.transact(window, cx, |this, window, cx| {
 7427            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7428            this.buffer.update(cx, |buffer, cx| {
 7429                for (range, text) in edits {
 7430                    buffer.edit([(range, text)], None, cx);
 7431                }
 7432            });
 7433            this.fold_creases(refold_creases, true, window, cx);
 7434            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7435                s.select(new_selections);
 7436            })
 7437        });
 7438    }
 7439
 7440    pub fn move_line_down(
 7441        &mut self,
 7442        _: &MoveLineDown,
 7443        window: &mut Window,
 7444        cx: &mut Context<Self>,
 7445    ) {
 7446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7447        let buffer = self.buffer.read(cx).snapshot(cx);
 7448
 7449        let mut edits = Vec::new();
 7450        let mut unfold_ranges = Vec::new();
 7451        let mut refold_creases = Vec::new();
 7452
 7453        let selections = self.selections.all::<Point>(cx);
 7454        let mut selections = selections.iter().peekable();
 7455        let mut contiguous_row_selections = Vec::new();
 7456        let mut new_selections = Vec::new();
 7457
 7458        while let Some(selection) = selections.next() {
 7459            // Find all the selections that span a contiguous row range
 7460            let (start_row, end_row) = consume_contiguous_rows(
 7461                &mut contiguous_row_selections,
 7462                selection,
 7463                &display_map,
 7464                &mut selections,
 7465            );
 7466
 7467            // Move the text spanned by the row range to be after the last line of the row range
 7468            if end_row.0 <= buffer.max_point().row {
 7469                let range_to_move =
 7470                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7471                let insertion_point = display_map
 7472                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7473                    .0;
 7474
 7475                // Don't move lines across excerpt boundaries
 7476                if buffer
 7477                    .excerpt_containing(range_to_move.start..insertion_point)
 7478                    .is_some()
 7479                {
 7480                    let mut text = String::from("\n");
 7481                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7482                    text.pop(); // Drop trailing newline
 7483                    edits.push((
 7484                        buffer.anchor_after(range_to_move.start)
 7485                            ..buffer.anchor_before(range_to_move.end),
 7486                        String::new(),
 7487                    ));
 7488                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7489                    edits.push((insertion_anchor..insertion_anchor, text));
 7490
 7491                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7492
 7493                    // Move selections down
 7494                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7495                        |mut selection| {
 7496                            selection.start.row += row_delta;
 7497                            selection.end.row += row_delta;
 7498                            selection
 7499                        },
 7500                    ));
 7501
 7502                    // Move folds down
 7503                    unfold_ranges.push(range_to_move.clone());
 7504                    for fold in display_map.folds_in_range(
 7505                        buffer.anchor_before(range_to_move.start)
 7506                            ..buffer.anchor_after(range_to_move.end),
 7507                    ) {
 7508                        let mut start = fold.range.start.to_point(&buffer);
 7509                        let mut end = fold.range.end.to_point(&buffer);
 7510                        start.row += row_delta;
 7511                        end.row += row_delta;
 7512                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7513                    }
 7514                }
 7515            }
 7516
 7517            // If we didn't move line(s), preserve the existing selections
 7518            new_selections.append(&mut contiguous_row_selections);
 7519        }
 7520
 7521        self.transact(window, cx, |this, window, cx| {
 7522            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7523            this.buffer.update(cx, |buffer, cx| {
 7524                for (range, text) in edits {
 7525                    buffer.edit([(range, text)], None, cx);
 7526                }
 7527            });
 7528            this.fold_creases(refold_creases, true, window, cx);
 7529            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7530                s.select(new_selections)
 7531            });
 7532        });
 7533    }
 7534
 7535    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7536        let text_layout_details = &self.text_layout_details(window);
 7537        self.transact(window, cx, |this, window, cx| {
 7538            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7539                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7540                let line_mode = s.line_mode;
 7541                s.move_with(|display_map, selection| {
 7542                    if !selection.is_empty() || line_mode {
 7543                        return;
 7544                    }
 7545
 7546                    let mut head = selection.head();
 7547                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7548                    if head.column() == display_map.line_len(head.row()) {
 7549                        transpose_offset = display_map
 7550                            .buffer_snapshot
 7551                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7552                    }
 7553
 7554                    if transpose_offset == 0 {
 7555                        return;
 7556                    }
 7557
 7558                    *head.column_mut() += 1;
 7559                    head = display_map.clip_point(head, Bias::Right);
 7560                    let goal = SelectionGoal::HorizontalPosition(
 7561                        display_map
 7562                            .x_for_display_point(head, text_layout_details)
 7563                            .into(),
 7564                    );
 7565                    selection.collapse_to(head, goal);
 7566
 7567                    let transpose_start = display_map
 7568                        .buffer_snapshot
 7569                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7570                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7571                        let transpose_end = display_map
 7572                            .buffer_snapshot
 7573                            .clip_offset(transpose_offset + 1, Bias::Right);
 7574                        if let Some(ch) =
 7575                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7576                        {
 7577                            edits.push((transpose_start..transpose_offset, String::new()));
 7578                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7579                        }
 7580                    }
 7581                });
 7582                edits
 7583            });
 7584            this.buffer
 7585                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7586            let selections = this.selections.all::<usize>(cx);
 7587            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7588                s.select(selections);
 7589            });
 7590        });
 7591    }
 7592
 7593    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7594        self.rewrap_impl(IsVimMode::No, cx)
 7595    }
 7596
 7597    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7598        let buffer = self.buffer.read(cx).snapshot(cx);
 7599        let selections = self.selections.all::<Point>(cx);
 7600        let mut selections = selections.iter().peekable();
 7601
 7602        let mut edits = Vec::new();
 7603        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7604
 7605        while let Some(selection) = selections.next() {
 7606            let mut start_row = selection.start.row;
 7607            let mut end_row = selection.end.row;
 7608
 7609            // Skip selections that overlap with a range that has already been rewrapped.
 7610            let selection_range = start_row..end_row;
 7611            if rewrapped_row_ranges
 7612                .iter()
 7613                .any(|range| range.overlaps(&selection_range))
 7614            {
 7615                continue;
 7616            }
 7617
 7618            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7619
 7620            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7621                match language_scope.language_name().as_ref() {
 7622                    "Markdown" | "Plain Text" => {
 7623                        should_rewrap = true;
 7624                    }
 7625                    _ => {}
 7626                }
 7627            }
 7628
 7629            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7630
 7631            // Since not all lines in the selection may be at the same indent
 7632            // level, choose the indent size that is the most common between all
 7633            // of the lines.
 7634            //
 7635            // If there is a tie, we use the deepest indent.
 7636            let (indent_size, indent_end) = {
 7637                let mut indent_size_occurrences = HashMap::default();
 7638                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7639
 7640                for row in start_row..=end_row {
 7641                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7642                    rows_by_indent_size.entry(indent).or_default().push(row);
 7643                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7644                }
 7645
 7646                let indent_size = indent_size_occurrences
 7647                    .into_iter()
 7648                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7649                    .map(|(indent, _)| indent)
 7650                    .unwrap_or_default();
 7651                let row = rows_by_indent_size[&indent_size][0];
 7652                let indent_end = Point::new(row, indent_size.len);
 7653
 7654                (indent_size, indent_end)
 7655            };
 7656
 7657            let mut line_prefix = indent_size.chars().collect::<String>();
 7658
 7659            if let Some(comment_prefix) =
 7660                buffer
 7661                    .language_scope_at(selection.head())
 7662                    .and_then(|language| {
 7663                        language
 7664                            .line_comment_prefixes()
 7665                            .iter()
 7666                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7667                            .cloned()
 7668                    })
 7669            {
 7670                line_prefix.push_str(&comment_prefix);
 7671                should_rewrap = true;
 7672            }
 7673
 7674            if !should_rewrap {
 7675                continue;
 7676            }
 7677
 7678            if selection.is_empty() {
 7679                'expand_upwards: while start_row > 0 {
 7680                    let prev_row = start_row - 1;
 7681                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7682                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7683                    {
 7684                        start_row = prev_row;
 7685                    } else {
 7686                        break 'expand_upwards;
 7687                    }
 7688                }
 7689
 7690                'expand_downwards: while end_row < buffer.max_point().row {
 7691                    let next_row = end_row + 1;
 7692                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7693                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7694                    {
 7695                        end_row = next_row;
 7696                    } else {
 7697                        break 'expand_downwards;
 7698                    }
 7699                }
 7700            }
 7701
 7702            let start = Point::new(start_row, 0);
 7703            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7704            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7705            let Some(lines_without_prefixes) = selection_text
 7706                .lines()
 7707                .map(|line| {
 7708                    line.strip_prefix(&line_prefix)
 7709                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7710                        .ok_or_else(|| {
 7711                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7712                        })
 7713                })
 7714                .collect::<Result<Vec<_>, _>>()
 7715                .log_err()
 7716            else {
 7717                continue;
 7718            };
 7719
 7720            let wrap_column = buffer
 7721                .settings_at(Point::new(start_row, 0), cx)
 7722                .preferred_line_length as usize;
 7723            let wrapped_text = wrap_with_prefix(
 7724                line_prefix,
 7725                lines_without_prefixes.join(" "),
 7726                wrap_column,
 7727                tab_size,
 7728            );
 7729
 7730            // TODO: should always use char-based diff while still supporting cursor behavior that
 7731            // matches vim.
 7732            let diff = match is_vim_mode {
 7733                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7734                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7735            };
 7736            let mut offset = start.to_offset(&buffer);
 7737            let mut moved_since_edit = true;
 7738
 7739            for change in diff.iter_all_changes() {
 7740                let value = change.value();
 7741                match change.tag() {
 7742                    ChangeTag::Equal => {
 7743                        offset += value.len();
 7744                        moved_since_edit = true;
 7745                    }
 7746                    ChangeTag::Delete => {
 7747                        let start = buffer.anchor_after(offset);
 7748                        let end = buffer.anchor_before(offset + value.len());
 7749
 7750                        if moved_since_edit {
 7751                            edits.push((start..end, String::new()));
 7752                        } else {
 7753                            edits.last_mut().unwrap().0.end = end;
 7754                        }
 7755
 7756                        offset += value.len();
 7757                        moved_since_edit = false;
 7758                    }
 7759                    ChangeTag::Insert => {
 7760                        if moved_since_edit {
 7761                            let anchor = buffer.anchor_after(offset);
 7762                            edits.push((anchor..anchor, value.to_string()));
 7763                        } else {
 7764                            edits.last_mut().unwrap().1.push_str(value);
 7765                        }
 7766
 7767                        moved_since_edit = false;
 7768                    }
 7769                }
 7770            }
 7771
 7772            rewrapped_row_ranges.push(start_row..=end_row);
 7773        }
 7774
 7775        self.buffer
 7776            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7777    }
 7778
 7779    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7780        let mut text = String::new();
 7781        let buffer = self.buffer.read(cx).snapshot(cx);
 7782        let mut selections = self.selections.all::<Point>(cx);
 7783        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7784        {
 7785            let max_point = buffer.max_point();
 7786            let mut is_first = true;
 7787            for selection in &mut selections {
 7788                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7789                if is_entire_line {
 7790                    selection.start = Point::new(selection.start.row, 0);
 7791                    if !selection.is_empty() && selection.end.column == 0 {
 7792                        selection.end = cmp::min(max_point, selection.end);
 7793                    } else {
 7794                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7795                    }
 7796                    selection.goal = SelectionGoal::None;
 7797                }
 7798                if is_first {
 7799                    is_first = false;
 7800                } else {
 7801                    text += "\n";
 7802                }
 7803                let mut len = 0;
 7804                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7805                    text.push_str(chunk);
 7806                    len += chunk.len();
 7807                }
 7808                clipboard_selections.push(ClipboardSelection {
 7809                    len,
 7810                    is_entire_line,
 7811                    first_line_indent: buffer
 7812                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7813                        .len,
 7814                });
 7815            }
 7816        }
 7817
 7818        self.transact(window, cx, |this, window, cx| {
 7819            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7820                s.select(selections);
 7821            });
 7822            this.insert("", window, cx);
 7823        });
 7824        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7825    }
 7826
 7827    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7828        let item = self.cut_common(window, cx);
 7829        cx.write_to_clipboard(item);
 7830    }
 7831
 7832    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7833        self.change_selections(None, window, cx, |s| {
 7834            s.move_with(|snapshot, sel| {
 7835                if sel.is_empty() {
 7836                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7837                }
 7838            });
 7839        });
 7840        let item = self.cut_common(window, cx);
 7841        cx.set_global(KillRing(item))
 7842    }
 7843
 7844    pub fn kill_ring_yank(
 7845        &mut self,
 7846        _: &KillRingYank,
 7847        window: &mut Window,
 7848        cx: &mut Context<Self>,
 7849    ) {
 7850        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7851            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7852                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7853            } else {
 7854                return;
 7855            }
 7856        } else {
 7857            return;
 7858        };
 7859        self.do_paste(&text, metadata, false, window, cx);
 7860    }
 7861
 7862    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7863        let selections = self.selections.all::<Point>(cx);
 7864        let buffer = self.buffer.read(cx).read(cx);
 7865        let mut text = String::new();
 7866
 7867        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7868        {
 7869            let max_point = buffer.max_point();
 7870            let mut is_first = true;
 7871            for selection in selections.iter() {
 7872                let mut start = selection.start;
 7873                let mut end = selection.end;
 7874                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7875                if is_entire_line {
 7876                    start = Point::new(start.row, 0);
 7877                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7878                }
 7879                if is_first {
 7880                    is_first = false;
 7881                } else {
 7882                    text += "\n";
 7883                }
 7884                let mut len = 0;
 7885                for chunk in buffer.text_for_range(start..end) {
 7886                    text.push_str(chunk);
 7887                    len += chunk.len();
 7888                }
 7889                clipboard_selections.push(ClipboardSelection {
 7890                    len,
 7891                    is_entire_line,
 7892                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7893                });
 7894            }
 7895        }
 7896
 7897        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7898            text,
 7899            clipboard_selections,
 7900        ));
 7901    }
 7902
 7903    pub fn do_paste(
 7904        &mut self,
 7905        text: &String,
 7906        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7907        handle_entire_lines: bool,
 7908        window: &mut Window,
 7909        cx: &mut Context<Self>,
 7910    ) {
 7911        if self.read_only(cx) {
 7912            return;
 7913        }
 7914
 7915        let clipboard_text = Cow::Borrowed(text);
 7916
 7917        self.transact(window, cx, |this, window, cx| {
 7918            if let Some(mut clipboard_selections) = clipboard_selections {
 7919                let old_selections = this.selections.all::<usize>(cx);
 7920                let all_selections_were_entire_line =
 7921                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7922                let first_selection_indent_column =
 7923                    clipboard_selections.first().map(|s| s.first_line_indent);
 7924                if clipboard_selections.len() != old_selections.len() {
 7925                    clipboard_selections.drain(..);
 7926                }
 7927                let cursor_offset = this.selections.last::<usize>(cx).head();
 7928                let mut auto_indent_on_paste = true;
 7929
 7930                this.buffer.update(cx, |buffer, cx| {
 7931                    let snapshot = buffer.read(cx);
 7932                    auto_indent_on_paste =
 7933                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7934
 7935                    let mut start_offset = 0;
 7936                    let mut edits = Vec::new();
 7937                    let mut original_indent_columns = Vec::new();
 7938                    for (ix, selection) in old_selections.iter().enumerate() {
 7939                        let to_insert;
 7940                        let entire_line;
 7941                        let original_indent_column;
 7942                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7943                            let end_offset = start_offset + clipboard_selection.len;
 7944                            to_insert = &clipboard_text[start_offset..end_offset];
 7945                            entire_line = clipboard_selection.is_entire_line;
 7946                            start_offset = end_offset + 1;
 7947                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7948                        } else {
 7949                            to_insert = clipboard_text.as_str();
 7950                            entire_line = all_selections_were_entire_line;
 7951                            original_indent_column = first_selection_indent_column
 7952                        }
 7953
 7954                        // If the corresponding selection was empty when this slice of the
 7955                        // clipboard text was written, then the entire line containing the
 7956                        // selection was copied. If this selection is also currently empty,
 7957                        // then paste the line before the current line of the buffer.
 7958                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7959                            let column = selection.start.to_point(&snapshot).column as usize;
 7960                            let line_start = selection.start - column;
 7961                            line_start..line_start
 7962                        } else {
 7963                            selection.range()
 7964                        };
 7965
 7966                        edits.push((range, to_insert));
 7967                        original_indent_columns.extend(original_indent_column);
 7968                    }
 7969                    drop(snapshot);
 7970
 7971                    buffer.edit(
 7972                        edits,
 7973                        if auto_indent_on_paste {
 7974                            Some(AutoindentMode::Block {
 7975                                original_indent_columns,
 7976                            })
 7977                        } else {
 7978                            None
 7979                        },
 7980                        cx,
 7981                    );
 7982                });
 7983
 7984                let selections = this.selections.all::<usize>(cx);
 7985                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7986                    s.select(selections)
 7987                });
 7988            } else {
 7989                this.insert(&clipboard_text, window, cx);
 7990            }
 7991        });
 7992    }
 7993
 7994    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7995        if let Some(item) = cx.read_from_clipboard() {
 7996            let entries = item.entries();
 7997
 7998            match entries.first() {
 7999                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8000                // of all the pasted entries.
 8001                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8002                    .do_paste(
 8003                        clipboard_string.text(),
 8004                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8005                        true,
 8006                        window,
 8007                        cx,
 8008                    ),
 8009                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8010            }
 8011        }
 8012    }
 8013
 8014    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8015        if self.read_only(cx) {
 8016            return;
 8017        }
 8018
 8019        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8020            if let Some((selections, _)) =
 8021                self.selection_history.transaction(transaction_id).cloned()
 8022            {
 8023                self.change_selections(None, window, cx, |s| {
 8024                    s.select_anchors(selections.to_vec());
 8025                });
 8026            }
 8027            self.request_autoscroll(Autoscroll::fit(), cx);
 8028            self.unmark_text(window, cx);
 8029            self.refresh_inline_completion(true, false, window, cx);
 8030            cx.emit(EditorEvent::Edited { transaction_id });
 8031            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8032        }
 8033    }
 8034
 8035    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8036        if self.read_only(cx) {
 8037            return;
 8038        }
 8039
 8040        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8041            if let Some((_, Some(selections))) =
 8042                self.selection_history.transaction(transaction_id).cloned()
 8043            {
 8044                self.change_selections(None, window, cx, |s| {
 8045                    s.select_anchors(selections.to_vec());
 8046                });
 8047            }
 8048            self.request_autoscroll(Autoscroll::fit(), cx);
 8049            self.unmark_text(window, cx);
 8050            self.refresh_inline_completion(true, false, window, cx);
 8051            cx.emit(EditorEvent::Edited { transaction_id });
 8052        }
 8053    }
 8054
 8055    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8056        self.buffer
 8057            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8058    }
 8059
 8060    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8061        self.buffer
 8062            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8063    }
 8064
 8065    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8066        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8067            let line_mode = s.line_mode;
 8068            s.move_with(|map, selection| {
 8069                let cursor = if selection.is_empty() && !line_mode {
 8070                    movement::left(map, selection.start)
 8071                } else {
 8072                    selection.start
 8073                };
 8074                selection.collapse_to(cursor, SelectionGoal::None);
 8075            });
 8076        })
 8077    }
 8078
 8079    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8080        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8081            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8082        })
 8083    }
 8084
 8085    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8086        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8087            let line_mode = s.line_mode;
 8088            s.move_with(|map, selection| {
 8089                let cursor = if selection.is_empty() && !line_mode {
 8090                    movement::right(map, selection.end)
 8091                } else {
 8092                    selection.end
 8093                };
 8094                selection.collapse_to(cursor, SelectionGoal::None)
 8095            });
 8096        })
 8097    }
 8098
 8099    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8100        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8101            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8102        })
 8103    }
 8104
 8105    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8106        if self.take_rename(true, window, cx).is_some() {
 8107            return;
 8108        }
 8109
 8110        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8111            cx.propagate();
 8112            return;
 8113        }
 8114
 8115        let text_layout_details = &self.text_layout_details(window);
 8116        let selection_count = self.selections.count();
 8117        let first_selection = self.selections.first_anchor();
 8118
 8119        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8120            let line_mode = s.line_mode;
 8121            s.move_with(|map, selection| {
 8122                if !selection.is_empty() && !line_mode {
 8123                    selection.goal = SelectionGoal::None;
 8124                }
 8125                let (cursor, goal) = movement::up(
 8126                    map,
 8127                    selection.start,
 8128                    selection.goal,
 8129                    false,
 8130                    text_layout_details,
 8131                );
 8132                selection.collapse_to(cursor, goal);
 8133            });
 8134        });
 8135
 8136        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8137        {
 8138            cx.propagate();
 8139        }
 8140    }
 8141
 8142    pub fn move_up_by_lines(
 8143        &mut self,
 8144        action: &MoveUpByLines,
 8145        window: &mut Window,
 8146        cx: &mut Context<Self>,
 8147    ) {
 8148        if self.take_rename(true, window, cx).is_some() {
 8149            return;
 8150        }
 8151
 8152        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8153            cx.propagate();
 8154            return;
 8155        }
 8156
 8157        let text_layout_details = &self.text_layout_details(window);
 8158
 8159        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8160            let line_mode = s.line_mode;
 8161            s.move_with(|map, selection| {
 8162                if !selection.is_empty() && !line_mode {
 8163                    selection.goal = SelectionGoal::None;
 8164                }
 8165                let (cursor, goal) = movement::up_by_rows(
 8166                    map,
 8167                    selection.start,
 8168                    action.lines,
 8169                    selection.goal,
 8170                    false,
 8171                    text_layout_details,
 8172                );
 8173                selection.collapse_to(cursor, goal);
 8174            });
 8175        })
 8176    }
 8177
 8178    pub fn move_down_by_lines(
 8179        &mut self,
 8180        action: &MoveDownByLines,
 8181        window: &mut Window,
 8182        cx: &mut Context<Self>,
 8183    ) {
 8184        if self.take_rename(true, window, cx).is_some() {
 8185            return;
 8186        }
 8187
 8188        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8189            cx.propagate();
 8190            return;
 8191        }
 8192
 8193        let text_layout_details = &self.text_layout_details(window);
 8194
 8195        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8196            let line_mode = s.line_mode;
 8197            s.move_with(|map, selection| {
 8198                if !selection.is_empty() && !line_mode {
 8199                    selection.goal = SelectionGoal::None;
 8200                }
 8201                let (cursor, goal) = movement::down_by_rows(
 8202                    map,
 8203                    selection.start,
 8204                    action.lines,
 8205                    selection.goal,
 8206                    false,
 8207                    text_layout_details,
 8208                );
 8209                selection.collapse_to(cursor, goal);
 8210            });
 8211        })
 8212    }
 8213
 8214    pub fn select_down_by_lines(
 8215        &mut self,
 8216        action: &SelectDownByLines,
 8217        window: &mut Window,
 8218        cx: &mut Context<Self>,
 8219    ) {
 8220        let text_layout_details = &self.text_layout_details(window);
 8221        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8222            s.move_heads_with(|map, head, goal| {
 8223                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8224            })
 8225        })
 8226    }
 8227
 8228    pub fn select_up_by_lines(
 8229        &mut self,
 8230        action: &SelectUpByLines,
 8231        window: &mut Window,
 8232        cx: &mut Context<Self>,
 8233    ) {
 8234        let text_layout_details = &self.text_layout_details(window);
 8235        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8236            s.move_heads_with(|map, head, goal| {
 8237                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8238            })
 8239        })
 8240    }
 8241
 8242    pub fn select_page_up(
 8243        &mut self,
 8244        _: &SelectPageUp,
 8245        window: &mut Window,
 8246        cx: &mut Context<Self>,
 8247    ) {
 8248        let Some(row_count) = self.visible_row_count() else {
 8249            return;
 8250        };
 8251
 8252        let text_layout_details = &self.text_layout_details(window);
 8253
 8254        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8255            s.move_heads_with(|map, head, goal| {
 8256                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8257            })
 8258        })
 8259    }
 8260
 8261    pub fn move_page_up(
 8262        &mut self,
 8263        action: &MovePageUp,
 8264        window: &mut Window,
 8265        cx: &mut Context<Self>,
 8266    ) {
 8267        if self.take_rename(true, window, cx).is_some() {
 8268            return;
 8269        }
 8270
 8271        if self
 8272            .context_menu
 8273            .borrow_mut()
 8274            .as_mut()
 8275            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8276            .unwrap_or(false)
 8277        {
 8278            return;
 8279        }
 8280
 8281        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8282            cx.propagate();
 8283            return;
 8284        }
 8285
 8286        let Some(row_count) = self.visible_row_count() else {
 8287            return;
 8288        };
 8289
 8290        let autoscroll = if action.center_cursor {
 8291            Autoscroll::center()
 8292        } else {
 8293            Autoscroll::fit()
 8294        };
 8295
 8296        let text_layout_details = &self.text_layout_details(window);
 8297
 8298        self.change_selections(Some(autoscroll), window, cx, |s| {
 8299            let line_mode = s.line_mode;
 8300            s.move_with(|map, selection| {
 8301                if !selection.is_empty() && !line_mode {
 8302                    selection.goal = SelectionGoal::None;
 8303                }
 8304                let (cursor, goal) = movement::up_by_rows(
 8305                    map,
 8306                    selection.end,
 8307                    row_count,
 8308                    selection.goal,
 8309                    false,
 8310                    text_layout_details,
 8311                );
 8312                selection.collapse_to(cursor, goal);
 8313            });
 8314        });
 8315    }
 8316
 8317    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8318        let text_layout_details = &self.text_layout_details(window);
 8319        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8320            s.move_heads_with(|map, head, goal| {
 8321                movement::up(map, head, goal, false, text_layout_details)
 8322            })
 8323        })
 8324    }
 8325
 8326    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8327        self.take_rename(true, window, cx);
 8328
 8329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8330            cx.propagate();
 8331            return;
 8332        }
 8333
 8334        let text_layout_details = &self.text_layout_details(window);
 8335        let selection_count = self.selections.count();
 8336        let first_selection = self.selections.first_anchor();
 8337
 8338        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8339            let line_mode = s.line_mode;
 8340            s.move_with(|map, selection| {
 8341                if !selection.is_empty() && !line_mode {
 8342                    selection.goal = SelectionGoal::None;
 8343                }
 8344                let (cursor, goal) = movement::down(
 8345                    map,
 8346                    selection.end,
 8347                    selection.goal,
 8348                    false,
 8349                    text_layout_details,
 8350                );
 8351                selection.collapse_to(cursor, goal);
 8352            });
 8353        });
 8354
 8355        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8356        {
 8357            cx.propagate();
 8358        }
 8359    }
 8360
 8361    pub fn select_page_down(
 8362        &mut self,
 8363        _: &SelectPageDown,
 8364        window: &mut Window,
 8365        cx: &mut Context<Self>,
 8366    ) {
 8367        let Some(row_count) = self.visible_row_count() else {
 8368            return;
 8369        };
 8370
 8371        let text_layout_details = &self.text_layout_details(window);
 8372
 8373        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8374            s.move_heads_with(|map, head, goal| {
 8375                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8376            })
 8377        })
 8378    }
 8379
 8380    pub fn move_page_down(
 8381        &mut self,
 8382        action: &MovePageDown,
 8383        window: &mut Window,
 8384        cx: &mut Context<Self>,
 8385    ) {
 8386        if self.take_rename(true, window, cx).is_some() {
 8387            return;
 8388        }
 8389
 8390        if self
 8391            .context_menu
 8392            .borrow_mut()
 8393            .as_mut()
 8394            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8395            .unwrap_or(false)
 8396        {
 8397            return;
 8398        }
 8399
 8400        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8401            cx.propagate();
 8402            return;
 8403        }
 8404
 8405        let Some(row_count) = self.visible_row_count() else {
 8406            return;
 8407        };
 8408
 8409        let autoscroll = if action.center_cursor {
 8410            Autoscroll::center()
 8411        } else {
 8412            Autoscroll::fit()
 8413        };
 8414
 8415        let text_layout_details = &self.text_layout_details(window);
 8416        self.change_selections(Some(autoscroll), window, cx, |s| {
 8417            let line_mode = s.line_mode;
 8418            s.move_with(|map, selection| {
 8419                if !selection.is_empty() && !line_mode {
 8420                    selection.goal = SelectionGoal::None;
 8421                }
 8422                let (cursor, goal) = movement::down_by_rows(
 8423                    map,
 8424                    selection.end,
 8425                    row_count,
 8426                    selection.goal,
 8427                    false,
 8428                    text_layout_details,
 8429                );
 8430                selection.collapse_to(cursor, goal);
 8431            });
 8432        });
 8433    }
 8434
 8435    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8436        let text_layout_details = &self.text_layout_details(window);
 8437        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8438            s.move_heads_with(|map, head, goal| {
 8439                movement::down(map, head, goal, false, text_layout_details)
 8440            })
 8441        });
 8442    }
 8443
 8444    pub fn context_menu_first(
 8445        &mut self,
 8446        _: &ContextMenuFirst,
 8447        _window: &mut Window,
 8448        cx: &mut Context<Self>,
 8449    ) {
 8450        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8451            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8452        }
 8453    }
 8454
 8455    pub fn context_menu_prev(
 8456        &mut self,
 8457        _: &ContextMenuPrev,
 8458        _window: &mut Window,
 8459        cx: &mut Context<Self>,
 8460    ) {
 8461        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8462            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8463        }
 8464    }
 8465
 8466    pub fn context_menu_next(
 8467        &mut self,
 8468        _: &ContextMenuNext,
 8469        _window: &mut Window,
 8470        cx: &mut Context<Self>,
 8471    ) {
 8472        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8473            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8474        }
 8475    }
 8476
 8477    pub fn context_menu_last(
 8478        &mut self,
 8479        _: &ContextMenuLast,
 8480        _window: &mut Window,
 8481        cx: &mut Context<Self>,
 8482    ) {
 8483        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8484            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8485        }
 8486    }
 8487
 8488    pub fn move_to_previous_word_start(
 8489        &mut self,
 8490        _: &MoveToPreviousWordStart,
 8491        window: &mut Window,
 8492        cx: &mut Context<Self>,
 8493    ) {
 8494        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8495            s.move_cursors_with(|map, head, _| {
 8496                (
 8497                    movement::previous_word_start(map, head),
 8498                    SelectionGoal::None,
 8499                )
 8500            });
 8501        })
 8502    }
 8503
 8504    pub fn move_to_previous_subword_start(
 8505        &mut self,
 8506        _: &MoveToPreviousSubwordStart,
 8507        window: &mut Window,
 8508        cx: &mut Context<Self>,
 8509    ) {
 8510        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8511            s.move_cursors_with(|map, head, _| {
 8512                (
 8513                    movement::previous_subword_start(map, head),
 8514                    SelectionGoal::None,
 8515                )
 8516            });
 8517        })
 8518    }
 8519
 8520    pub fn select_to_previous_word_start(
 8521        &mut self,
 8522        _: &SelectToPreviousWordStart,
 8523        window: &mut Window,
 8524        cx: &mut Context<Self>,
 8525    ) {
 8526        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8527            s.move_heads_with(|map, head, _| {
 8528                (
 8529                    movement::previous_word_start(map, head),
 8530                    SelectionGoal::None,
 8531                )
 8532            });
 8533        })
 8534    }
 8535
 8536    pub fn select_to_previous_subword_start(
 8537        &mut self,
 8538        _: &SelectToPreviousSubwordStart,
 8539        window: &mut Window,
 8540        cx: &mut Context<Self>,
 8541    ) {
 8542        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8543            s.move_heads_with(|map, head, _| {
 8544                (
 8545                    movement::previous_subword_start(map, head),
 8546                    SelectionGoal::None,
 8547                )
 8548            });
 8549        })
 8550    }
 8551
 8552    pub fn delete_to_previous_word_start(
 8553        &mut self,
 8554        action: &DeleteToPreviousWordStart,
 8555        window: &mut Window,
 8556        cx: &mut Context<Self>,
 8557    ) {
 8558        self.transact(window, cx, |this, window, cx| {
 8559            this.select_autoclose_pair(window, cx);
 8560            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8561                let line_mode = s.line_mode;
 8562                s.move_with(|map, selection| {
 8563                    if selection.is_empty() && !line_mode {
 8564                        let cursor = if action.ignore_newlines {
 8565                            movement::previous_word_start(map, selection.head())
 8566                        } else {
 8567                            movement::previous_word_start_or_newline(map, selection.head())
 8568                        };
 8569                        selection.set_head(cursor, SelectionGoal::None);
 8570                    }
 8571                });
 8572            });
 8573            this.insert("", window, cx);
 8574        });
 8575    }
 8576
 8577    pub fn delete_to_previous_subword_start(
 8578        &mut self,
 8579        _: &DeleteToPreviousSubwordStart,
 8580        window: &mut Window,
 8581        cx: &mut Context<Self>,
 8582    ) {
 8583        self.transact(window, cx, |this, window, cx| {
 8584            this.select_autoclose_pair(window, cx);
 8585            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8586                let line_mode = s.line_mode;
 8587                s.move_with(|map, selection| {
 8588                    if selection.is_empty() && !line_mode {
 8589                        let cursor = movement::previous_subword_start(map, selection.head());
 8590                        selection.set_head(cursor, SelectionGoal::None);
 8591                    }
 8592                });
 8593            });
 8594            this.insert("", window, cx);
 8595        });
 8596    }
 8597
 8598    pub fn move_to_next_word_end(
 8599        &mut self,
 8600        _: &MoveToNextWordEnd,
 8601        window: &mut Window,
 8602        cx: &mut Context<Self>,
 8603    ) {
 8604        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8605            s.move_cursors_with(|map, head, _| {
 8606                (movement::next_word_end(map, head), SelectionGoal::None)
 8607            });
 8608        })
 8609    }
 8610
 8611    pub fn move_to_next_subword_end(
 8612        &mut self,
 8613        _: &MoveToNextSubwordEnd,
 8614        window: &mut Window,
 8615        cx: &mut Context<Self>,
 8616    ) {
 8617        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8618            s.move_cursors_with(|map, head, _| {
 8619                (movement::next_subword_end(map, head), SelectionGoal::None)
 8620            });
 8621        })
 8622    }
 8623
 8624    pub fn select_to_next_word_end(
 8625        &mut self,
 8626        _: &SelectToNextWordEnd,
 8627        window: &mut Window,
 8628        cx: &mut Context<Self>,
 8629    ) {
 8630        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8631            s.move_heads_with(|map, head, _| {
 8632                (movement::next_word_end(map, head), SelectionGoal::None)
 8633            });
 8634        })
 8635    }
 8636
 8637    pub fn select_to_next_subword_end(
 8638        &mut self,
 8639        _: &SelectToNextSubwordEnd,
 8640        window: &mut Window,
 8641        cx: &mut Context<Self>,
 8642    ) {
 8643        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8644            s.move_heads_with(|map, head, _| {
 8645                (movement::next_subword_end(map, head), SelectionGoal::None)
 8646            });
 8647        })
 8648    }
 8649
 8650    pub fn delete_to_next_word_end(
 8651        &mut self,
 8652        action: &DeleteToNextWordEnd,
 8653        window: &mut Window,
 8654        cx: &mut Context<Self>,
 8655    ) {
 8656        self.transact(window, cx, |this, window, cx| {
 8657            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8658                let line_mode = s.line_mode;
 8659                s.move_with(|map, selection| {
 8660                    if selection.is_empty() && !line_mode {
 8661                        let cursor = if action.ignore_newlines {
 8662                            movement::next_word_end(map, selection.head())
 8663                        } else {
 8664                            movement::next_word_end_or_newline(map, selection.head())
 8665                        };
 8666                        selection.set_head(cursor, SelectionGoal::None);
 8667                    }
 8668                });
 8669            });
 8670            this.insert("", window, cx);
 8671        });
 8672    }
 8673
 8674    pub fn delete_to_next_subword_end(
 8675        &mut self,
 8676        _: &DeleteToNextSubwordEnd,
 8677        window: &mut Window,
 8678        cx: &mut Context<Self>,
 8679    ) {
 8680        self.transact(window, cx, |this, window, cx| {
 8681            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8682                s.move_with(|map, selection| {
 8683                    if selection.is_empty() {
 8684                        let cursor = movement::next_subword_end(map, selection.head());
 8685                        selection.set_head(cursor, SelectionGoal::None);
 8686                    }
 8687                });
 8688            });
 8689            this.insert("", window, cx);
 8690        });
 8691    }
 8692
 8693    pub fn move_to_beginning_of_line(
 8694        &mut self,
 8695        action: &MoveToBeginningOfLine,
 8696        window: &mut Window,
 8697        cx: &mut Context<Self>,
 8698    ) {
 8699        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8700            s.move_cursors_with(|map, head, _| {
 8701                (
 8702                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8703                    SelectionGoal::None,
 8704                )
 8705            });
 8706        })
 8707    }
 8708
 8709    pub fn select_to_beginning_of_line(
 8710        &mut self,
 8711        action: &SelectToBeginningOfLine,
 8712        window: &mut Window,
 8713        cx: &mut Context<Self>,
 8714    ) {
 8715        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8716            s.move_heads_with(|map, head, _| {
 8717                (
 8718                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8719                    SelectionGoal::None,
 8720                )
 8721            });
 8722        });
 8723    }
 8724
 8725    pub fn delete_to_beginning_of_line(
 8726        &mut self,
 8727        _: &DeleteToBeginningOfLine,
 8728        window: &mut Window,
 8729        cx: &mut Context<Self>,
 8730    ) {
 8731        self.transact(window, cx, |this, window, cx| {
 8732            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8733                s.move_with(|_, selection| {
 8734                    selection.reversed = true;
 8735                });
 8736            });
 8737
 8738            this.select_to_beginning_of_line(
 8739                &SelectToBeginningOfLine {
 8740                    stop_at_soft_wraps: false,
 8741                },
 8742                window,
 8743                cx,
 8744            );
 8745            this.backspace(&Backspace, window, cx);
 8746        });
 8747    }
 8748
 8749    pub fn move_to_end_of_line(
 8750        &mut self,
 8751        action: &MoveToEndOfLine,
 8752        window: &mut Window,
 8753        cx: &mut Context<Self>,
 8754    ) {
 8755        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8756            s.move_cursors_with(|map, head, _| {
 8757                (
 8758                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8759                    SelectionGoal::None,
 8760                )
 8761            });
 8762        })
 8763    }
 8764
 8765    pub fn select_to_end_of_line(
 8766        &mut self,
 8767        action: &SelectToEndOfLine,
 8768        window: &mut Window,
 8769        cx: &mut Context<Self>,
 8770    ) {
 8771        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8772            s.move_heads_with(|map, head, _| {
 8773                (
 8774                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8775                    SelectionGoal::None,
 8776                )
 8777            });
 8778        })
 8779    }
 8780
 8781    pub fn delete_to_end_of_line(
 8782        &mut self,
 8783        _: &DeleteToEndOfLine,
 8784        window: &mut Window,
 8785        cx: &mut Context<Self>,
 8786    ) {
 8787        self.transact(window, cx, |this, window, cx| {
 8788            this.select_to_end_of_line(
 8789                &SelectToEndOfLine {
 8790                    stop_at_soft_wraps: false,
 8791                },
 8792                window,
 8793                cx,
 8794            );
 8795            this.delete(&Delete, window, cx);
 8796        });
 8797    }
 8798
 8799    pub fn cut_to_end_of_line(
 8800        &mut self,
 8801        _: &CutToEndOfLine,
 8802        window: &mut Window,
 8803        cx: &mut Context<Self>,
 8804    ) {
 8805        self.transact(window, cx, |this, window, cx| {
 8806            this.select_to_end_of_line(
 8807                &SelectToEndOfLine {
 8808                    stop_at_soft_wraps: false,
 8809                },
 8810                window,
 8811                cx,
 8812            );
 8813            this.cut(&Cut, window, cx);
 8814        });
 8815    }
 8816
 8817    pub fn move_to_start_of_paragraph(
 8818        &mut self,
 8819        _: &MoveToStartOfParagraph,
 8820        window: &mut Window,
 8821        cx: &mut Context<Self>,
 8822    ) {
 8823        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8824            cx.propagate();
 8825            return;
 8826        }
 8827
 8828        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8829            s.move_with(|map, selection| {
 8830                selection.collapse_to(
 8831                    movement::start_of_paragraph(map, selection.head(), 1),
 8832                    SelectionGoal::None,
 8833                )
 8834            });
 8835        })
 8836    }
 8837
 8838    pub fn move_to_end_of_paragraph(
 8839        &mut self,
 8840        _: &MoveToEndOfParagraph,
 8841        window: &mut Window,
 8842        cx: &mut Context<Self>,
 8843    ) {
 8844        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8845            cx.propagate();
 8846            return;
 8847        }
 8848
 8849        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8850            s.move_with(|map, selection| {
 8851                selection.collapse_to(
 8852                    movement::end_of_paragraph(map, selection.head(), 1),
 8853                    SelectionGoal::None,
 8854                )
 8855            });
 8856        })
 8857    }
 8858
 8859    pub fn select_to_start_of_paragraph(
 8860        &mut self,
 8861        _: &SelectToStartOfParagraph,
 8862        window: &mut Window,
 8863        cx: &mut Context<Self>,
 8864    ) {
 8865        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8866            cx.propagate();
 8867            return;
 8868        }
 8869
 8870        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8871            s.move_heads_with(|map, head, _| {
 8872                (
 8873                    movement::start_of_paragraph(map, head, 1),
 8874                    SelectionGoal::None,
 8875                )
 8876            });
 8877        })
 8878    }
 8879
 8880    pub fn select_to_end_of_paragraph(
 8881        &mut self,
 8882        _: &SelectToEndOfParagraph,
 8883        window: &mut Window,
 8884        cx: &mut Context<Self>,
 8885    ) {
 8886        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8887            cx.propagate();
 8888            return;
 8889        }
 8890
 8891        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8892            s.move_heads_with(|map, head, _| {
 8893                (
 8894                    movement::end_of_paragraph(map, head, 1),
 8895                    SelectionGoal::None,
 8896                )
 8897            });
 8898        })
 8899    }
 8900
 8901    pub fn move_to_beginning(
 8902        &mut self,
 8903        _: &MoveToBeginning,
 8904        window: &mut Window,
 8905        cx: &mut Context<Self>,
 8906    ) {
 8907        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8908            cx.propagate();
 8909            return;
 8910        }
 8911
 8912        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8913            s.select_ranges(vec![0..0]);
 8914        });
 8915    }
 8916
 8917    pub fn select_to_beginning(
 8918        &mut self,
 8919        _: &SelectToBeginning,
 8920        window: &mut Window,
 8921        cx: &mut Context<Self>,
 8922    ) {
 8923        let mut selection = self.selections.last::<Point>(cx);
 8924        selection.set_head(Point::zero(), SelectionGoal::None);
 8925
 8926        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8927            s.select(vec![selection]);
 8928        });
 8929    }
 8930
 8931    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8932        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8933            cx.propagate();
 8934            return;
 8935        }
 8936
 8937        let cursor = self.buffer.read(cx).read(cx).len();
 8938        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8939            s.select_ranges(vec![cursor..cursor])
 8940        });
 8941    }
 8942
 8943    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8944        self.nav_history = nav_history;
 8945    }
 8946
 8947    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8948        self.nav_history.as_ref()
 8949    }
 8950
 8951    fn push_to_nav_history(
 8952        &mut self,
 8953        cursor_anchor: Anchor,
 8954        new_position: Option<Point>,
 8955        cx: &mut Context<Self>,
 8956    ) {
 8957        if let Some(nav_history) = self.nav_history.as_mut() {
 8958            let buffer = self.buffer.read(cx).read(cx);
 8959            let cursor_position = cursor_anchor.to_point(&buffer);
 8960            let scroll_state = self.scroll_manager.anchor();
 8961            let scroll_top_row = scroll_state.top_row(&buffer);
 8962            drop(buffer);
 8963
 8964            if let Some(new_position) = new_position {
 8965                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8966                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8967                    return;
 8968                }
 8969            }
 8970
 8971            nav_history.push(
 8972                Some(NavigationData {
 8973                    cursor_anchor,
 8974                    cursor_position,
 8975                    scroll_anchor: scroll_state,
 8976                    scroll_top_row,
 8977                }),
 8978                cx,
 8979            );
 8980        }
 8981    }
 8982
 8983    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8984        let buffer = self.buffer.read(cx).snapshot(cx);
 8985        let mut selection = self.selections.first::<usize>(cx);
 8986        selection.set_head(buffer.len(), SelectionGoal::None);
 8987        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8988            s.select(vec![selection]);
 8989        });
 8990    }
 8991
 8992    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8993        let end = self.buffer.read(cx).read(cx).len();
 8994        self.change_selections(None, window, cx, |s| {
 8995            s.select_ranges(vec![0..end]);
 8996        });
 8997    }
 8998
 8999    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9000        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9001        let mut selections = self.selections.all::<Point>(cx);
 9002        let max_point = display_map.buffer_snapshot.max_point();
 9003        for selection in &mut selections {
 9004            let rows = selection.spanned_rows(true, &display_map);
 9005            selection.start = Point::new(rows.start.0, 0);
 9006            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9007            selection.reversed = false;
 9008        }
 9009        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9010            s.select(selections);
 9011        });
 9012    }
 9013
 9014    pub fn split_selection_into_lines(
 9015        &mut self,
 9016        _: &SplitSelectionIntoLines,
 9017        window: &mut Window,
 9018        cx: &mut Context<Self>,
 9019    ) {
 9020        let mut to_unfold = Vec::new();
 9021        let mut new_selection_ranges = Vec::new();
 9022        {
 9023            let selections = self.selections.all::<Point>(cx);
 9024            let buffer = self.buffer.read(cx).read(cx);
 9025            for selection in selections {
 9026                for row in selection.start.row..selection.end.row {
 9027                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9028                    new_selection_ranges.push(cursor..cursor);
 9029                }
 9030                new_selection_ranges.push(selection.end..selection.end);
 9031                to_unfold.push(selection.start..selection.end);
 9032            }
 9033        }
 9034        self.unfold_ranges(&to_unfold, true, true, cx);
 9035        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9036            s.select_ranges(new_selection_ranges);
 9037        });
 9038    }
 9039
 9040    pub fn add_selection_above(
 9041        &mut self,
 9042        _: &AddSelectionAbove,
 9043        window: &mut Window,
 9044        cx: &mut Context<Self>,
 9045    ) {
 9046        self.add_selection(true, window, cx);
 9047    }
 9048
 9049    pub fn add_selection_below(
 9050        &mut self,
 9051        _: &AddSelectionBelow,
 9052        window: &mut Window,
 9053        cx: &mut Context<Self>,
 9054    ) {
 9055        self.add_selection(false, window, cx);
 9056    }
 9057
 9058    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9059        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9060        let mut selections = self.selections.all::<Point>(cx);
 9061        let text_layout_details = self.text_layout_details(window);
 9062        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9063            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9064            let range = oldest_selection.display_range(&display_map).sorted();
 9065
 9066            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9067            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9068            let positions = start_x.min(end_x)..start_x.max(end_x);
 9069
 9070            selections.clear();
 9071            let mut stack = Vec::new();
 9072            for row in range.start.row().0..=range.end.row().0 {
 9073                if let Some(selection) = self.selections.build_columnar_selection(
 9074                    &display_map,
 9075                    DisplayRow(row),
 9076                    &positions,
 9077                    oldest_selection.reversed,
 9078                    &text_layout_details,
 9079                ) {
 9080                    stack.push(selection.id);
 9081                    selections.push(selection);
 9082                }
 9083            }
 9084
 9085            if above {
 9086                stack.reverse();
 9087            }
 9088
 9089            AddSelectionsState { above, stack }
 9090        });
 9091
 9092        let last_added_selection = *state.stack.last().unwrap();
 9093        let mut new_selections = Vec::new();
 9094        if above == state.above {
 9095            let end_row = if above {
 9096                DisplayRow(0)
 9097            } else {
 9098                display_map.max_point().row()
 9099            };
 9100
 9101            'outer: for selection in selections {
 9102                if selection.id == last_added_selection {
 9103                    let range = selection.display_range(&display_map).sorted();
 9104                    debug_assert_eq!(range.start.row(), range.end.row());
 9105                    let mut row = range.start.row();
 9106                    let positions =
 9107                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9108                            px(start)..px(end)
 9109                        } else {
 9110                            let start_x =
 9111                                display_map.x_for_display_point(range.start, &text_layout_details);
 9112                            let end_x =
 9113                                display_map.x_for_display_point(range.end, &text_layout_details);
 9114                            start_x.min(end_x)..start_x.max(end_x)
 9115                        };
 9116
 9117                    while row != end_row {
 9118                        if above {
 9119                            row.0 -= 1;
 9120                        } else {
 9121                            row.0 += 1;
 9122                        }
 9123
 9124                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9125                            &display_map,
 9126                            row,
 9127                            &positions,
 9128                            selection.reversed,
 9129                            &text_layout_details,
 9130                        ) {
 9131                            state.stack.push(new_selection.id);
 9132                            if above {
 9133                                new_selections.push(new_selection);
 9134                                new_selections.push(selection);
 9135                            } else {
 9136                                new_selections.push(selection);
 9137                                new_selections.push(new_selection);
 9138                            }
 9139
 9140                            continue 'outer;
 9141                        }
 9142                    }
 9143                }
 9144
 9145                new_selections.push(selection);
 9146            }
 9147        } else {
 9148            new_selections = selections;
 9149            new_selections.retain(|s| s.id != last_added_selection);
 9150            state.stack.pop();
 9151        }
 9152
 9153        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9154            s.select(new_selections);
 9155        });
 9156        if state.stack.len() > 1 {
 9157            self.add_selections_state = Some(state);
 9158        }
 9159    }
 9160
 9161    pub fn select_next_match_internal(
 9162        &mut self,
 9163        display_map: &DisplaySnapshot,
 9164        replace_newest: bool,
 9165        autoscroll: Option<Autoscroll>,
 9166        window: &mut Window,
 9167        cx: &mut Context<Self>,
 9168    ) -> Result<()> {
 9169        fn select_next_match_ranges(
 9170            this: &mut Editor,
 9171            range: Range<usize>,
 9172            replace_newest: bool,
 9173            auto_scroll: Option<Autoscroll>,
 9174            window: &mut Window,
 9175            cx: &mut Context<Editor>,
 9176        ) {
 9177            this.unfold_ranges(&[range.clone()], false, true, cx);
 9178            this.change_selections(auto_scroll, window, cx, |s| {
 9179                if replace_newest {
 9180                    s.delete(s.newest_anchor().id);
 9181                }
 9182                s.insert_range(range.clone());
 9183            });
 9184        }
 9185
 9186        let buffer = &display_map.buffer_snapshot;
 9187        let mut selections = self.selections.all::<usize>(cx);
 9188        if let Some(mut select_next_state) = self.select_next_state.take() {
 9189            let query = &select_next_state.query;
 9190            if !select_next_state.done {
 9191                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9192                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9193                let mut next_selected_range = None;
 9194
 9195                let bytes_after_last_selection =
 9196                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9197                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9198                let query_matches = query
 9199                    .stream_find_iter(bytes_after_last_selection)
 9200                    .map(|result| (last_selection.end, result))
 9201                    .chain(
 9202                        query
 9203                            .stream_find_iter(bytes_before_first_selection)
 9204                            .map(|result| (0, result)),
 9205                    );
 9206
 9207                for (start_offset, query_match) in query_matches {
 9208                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9209                    let offset_range =
 9210                        start_offset + query_match.start()..start_offset + query_match.end();
 9211                    let display_range = offset_range.start.to_display_point(display_map)
 9212                        ..offset_range.end.to_display_point(display_map);
 9213
 9214                    if !select_next_state.wordwise
 9215                        || (!movement::is_inside_word(display_map, display_range.start)
 9216                            && !movement::is_inside_word(display_map, display_range.end))
 9217                    {
 9218                        // TODO: This is n^2, because we might check all the selections
 9219                        if !selections
 9220                            .iter()
 9221                            .any(|selection| selection.range().overlaps(&offset_range))
 9222                        {
 9223                            next_selected_range = Some(offset_range);
 9224                            break;
 9225                        }
 9226                    }
 9227                }
 9228
 9229                if let Some(next_selected_range) = next_selected_range {
 9230                    select_next_match_ranges(
 9231                        self,
 9232                        next_selected_range,
 9233                        replace_newest,
 9234                        autoscroll,
 9235                        window,
 9236                        cx,
 9237                    );
 9238                } else {
 9239                    select_next_state.done = true;
 9240                }
 9241            }
 9242
 9243            self.select_next_state = Some(select_next_state);
 9244        } else {
 9245            let mut only_carets = true;
 9246            let mut same_text_selected = true;
 9247            let mut selected_text = None;
 9248
 9249            let mut selections_iter = selections.iter().peekable();
 9250            while let Some(selection) = selections_iter.next() {
 9251                if selection.start != selection.end {
 9252                    only_carets = false;
 9253                }
 9254
 9255                if same_text_selected {
 9256                    if selected_text.is_none() {
 9257                        selected_text =
 9258                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9259                    }
 9260
 9261                    if let Some(next_selection) = selections_iter.peek() {
 9262                        if next_selection.range().len() == selection.range().len() {
 9263                            let next_selected_text = buffer
 9264                                .text_for_range(next_selection.range())
 9265                                .collect::<String>();
 9266                            if Some(next_selected_text) != selected_text {
 9267                                same_text_selected = false;
 9268                                selected_text = None;
 9269                            }
 9270                        } else {
 9271                            same_text_selected = false;
 9272                            selected_text = None;
 9273                        }
 9274                    }
 9275                }
 9276            }
 9277
 9278            if only_carets {
 9279                for selection in &mut selections {
 9280                    let word_range = movement::surrounding_word(
 9281                        display_map,
 9282                        selection.start.to_display_point(display_map),
 9283                    );
 9284                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9285                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9286                    selection.goal = SelectionGoal::None;
 9287                    selection.reversed = false;
 9288                    select_next_match_ranges(
 9289                        self,
 9290                        selection.start..selection.end,
 9291                        replace_newest,
 9292                        autoscroll,
 9293                        window,
 9294                        cx,
 9295                    );
 9296                }
 9297
 9298                if selections.len() == 1 {
 9299                    let selection = selections
 9300                        .last()
 9301                        .expect("ensured that there's only one selection");
 9302                    let query = buffer
 9303                        .text_for_range(selection.start..selection.end)
 9304                        .collect::<String>();
 9305                    let is_empty = query.is_empty();
 9306                    let select_state = SelectNextState {
 9307                        query: AhoCorasick::new(&[query])?,
 9308                        wordwise: true,
 9309                        done: is_empty,
 9310                    };
 9311                    self.select_next_state = Some(select_state);
 9312                } else {
 9313                    self.select_next_state = None;
 9314                }
 9315            } else if let Some(selected_text) = selected_text {
 9316                self.select_next_state = Some(SelectNextState {
 9317                    query: AhoCorasick::new(&[selected_text])?,
 9318                    wordwise: false,
 9319                    done: false,
 9320                });
 9321                self.select_next_match_internal(
 9322                    display_map,
 9323                    replace_newest,
 9324                    autoscroll,
 9325                    window,
 9326                    cx,
 9327                )?;
 9328            }
 9329        }
 9330        Ok(())
 9331    }
 9332
 9333    pub fn select_all_matches(
 9334        &mut self,
 9335        _action: &SelectAllMatches,
 9336        window: &mut Window,
 9337        cx: &mut Context<Self>,
 9338    ) -> Result<()> {
 9339        self.push_to_selection_history();
 9340        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9341
 9342        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9343        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9344            return Ok(());
 9345        };
 9346        if select_next_state.done {
 9347            return Ok(());
 9348        }
 9349
 9350        let mut new_selections = self.selections.all::<usize>(cx);
 9351
 9352        let buffer = &display_map.buffer_snapshot;
 9353        let query_matches = select_next_state
 9354            .query
 9355            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9356
 9357        for query_match in query_matches {
 9358            let query_match = query_match.unwrap(); // can only fail due to I/O
 9359            let offset_range = query_match.start()..query_match.end();
 9360            let display_range = offset_range.start.to_display_point(&display_map)
 9361                ..offset_range.end.to_display_point(&display_map);
 9362
 9363            if !select_next_state.wordwise
 9364                || (!movement::is_inside_word(&display_map, display_range.start)
 9365                    && !movement::is_inside_word(&display_map, display_range.end))
 9366            {
 9367                self.selections.change_with(cx, |selections| {
 9368                    new_selections.push(Selection {
 9369                        id: selections.new_selection_id(),
 9370                        start: offset_range.start,
 9371                        end: offset_range.end,
 9372                        reversed: false,
 9373                        goal: SelectionGoal::None,
 9374                    });
 9375                });
 9376            }
 9377        }
 9378
 9379        new_selections.sort_by_key(|selection| selection.start);
 9380        let mut ix = 0;
 9381        while ix + 1 < new_selections.len() {
 9382            let current_selection = &new_selections[ix];
 9383            let next_selection = &new_selections[ix + 1];
 9384            if current_selection.range().overlaps(&next_selection.range()) {
 9385                if current_selection.id < next_selection.id {
 9386                    new_selections.remove(ix + 1);
 9387                } else {
 9388                    new_selections.remove(ix);
 9389                }
 9390            } else {
 9391                ix += 1;
 9392            }
 9393        }
 9394
 9395        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9396
 9397        for selection in new_selections.iter_mut() {
 9398            selection.reversed = reversed;
 9399        }
 9400
 9401        select_next_state.done = true;
 9402        self.unfold_ranges(
 9403            &new_selections
 9404                .iter()
 9405                .map(|selection| selection.range())
 9406                .collect::<Vec<_>>(),
 9407            false,
 9408            false,
 9409            cx,
 9410        );
 9411        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9412            selections.select(new_selections)
 9413        });
 9414
 9415        Ok(())
 9416    }
 9417
 9418    pub fn select_next(
 9419        &mut self,
 9420        action: &SelectNext,
 9421        window: &mut Window,
 9422        cx: &mut Context<Self>,
 9423    ) -> Result<()> {
 9424        self.push_to_selection_history();
 9425        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9426        self.select_next_match_internal(
 9427            &display_map,
 9428            action.replace_newest,
 9429            Some(Autoscroll::newest()),
 9430            window,
 9431            cx,
 9432        )?;
 9433        Ok(())
 9434    }
 9435
 9436    pub fn select_previous(
 9437        &mut self,
 9438        action: &SelectPrevious,
 9439        window: &mut Window,
 9440        cx: &mut Context<Self>,
 9441    ) -> Result<()> {
 9442        self.push_to_selection_history();
 9443        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9444        let buffer = &display_map.buffer_snapshot;
 9445        let mut selections = self.selections.all::<usize>(cx);
 9446        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9447            let query = &select_prev_state.query;
 9448            if !select_prev_state.done {
 9449                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9450                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9451                let mut next_selected_range = None;
 9452                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9453                let bytes_before_last_selection =
 9454                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9455                let bytes_after_first_selection =
 9456                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9457                let query_matches = query
 9458                    .stream_find_iter(bytes_before_last_selection)
 9459                    .map(|result| (last_selection.start, result))
 9460                    .chain(
 9461                        query
 9462                            .stream_find_iter(bytes_after_first_selection)
 9463                            .map(|result| (buffer.len(), result)),
 9464                    );
 9465                for (end_offset, query_match) in query_matches {
 9466                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9467                    let offset_range =
 9468                        end_offset - query_match.end()..end_offset - query_match.start();
 9469                    let display_range = offset_range.start.to_display_point(&display_map)
 9470                        ..offset_range.end.to_display_point(&display_map);
 9471
 9472                    if !select_prev_state.wordwise
 9473                        || (!movement::is_inside_word(&display_map, display_range.start)
 9474                            && !movement::is_inside_word(&display_map, display_range.end))
 9475                    {
 9476                        next_selected_range = Some(offset_range);
 9477                        break;
 9478                    }
 9479                }
 9480
 9481                if let Some(next_selected_range) = next_selected_range {
 9482                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9483                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9484                        if action.replace_newest {
 9485                            s.delete(s.newest_anchor().id);
 9486                        }
 9487                        s.insert_range(next_selected_range);
 9488                    });
 9489                } else {
 9490                    select_prev_state.done = true;
 9491                }
 9492            }
 9493
 9494            self.select_prev_state = Some(select_prev_state);
 9495        } else {
 9496            let mut only_carets = true;
 9497            let mut same_text_selected = true;
 9498            let mut selected_text = None;
 9499
 9500            let mut selections_iter = selections.iter().peekable();
 9501            while let Some(selection) = selections_iter.next() {
 9502                if selection.start != selection.end {
 9503                    only_carets = false;
 9504                }
 9505
 9506                if same_text_selected {
 9507                    if selected_text.is_none() {
 9508                        selected_text =
 9509                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9510                    }
 9511
 9512                    if let Some(next_selection) = selections_iter.peek() {
 9513                        if next_selection.range().len() == selection.range().len() {
 9514                            let next_selected_text = buffer
 9515                                .text_for_range(next_selection.range())
 9516                                .collect::<String>();
 9517                            if Some(next_selected_text) != selected_text {
 9518                                same_text_selected = false;
 9519                                selected_text = None;
 9520                            }
 9521                        } else {
 9522                            same_text_selected = false;
 9523                            selected_text = None;
 9524                        }
 9525                    }
 9526                }
 9527            }
 9528
 9529            if only_carets {
 9530                for selection in &mut selections {
 9531                    let word_range = movement::surrounding_word(
 9532                        &display_map,
 9533                        selection.start.to_display_point(&display_map),
 9534                    );
 9535                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9536                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9537                    selection.goal = SelectionGoal::None;
 9538                    selection.reversed = false;
 9539                }
 9540                if selections.len() == 1 {
 9541                    let selection = selections
 9542                        .last()
 9543                        .expect("ensured that there's only one selection");
 9544                    let query = buffer
 9545                        .text_for_range(selection.start..selection.end)
 9546                        .collect::<String>();
 9547                    let is_empty = query.is_empty();
 9548                    let select_state = SelectNextState {
 9549                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9550                        wordwise: true,
 9551                        done: is_empty,
 9552                    };
 9553                    self.select_prev_state = Some(select_state);
 9554                } else {
 9555                    self.select_prev_state = None;
 9556                }
 9557
 9558                self.unfold_ranges(
 9559                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9560                    false,
 9561                    true,
 9562                    cx,
 9563                );
 9564                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9565                    s.select(selections);
 9566                });
 9567            } else if let Some(selected_text) = selected_text {
 9568                self.select_prev_state = Some(SelectNextState {
 9569                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9570                    wordwise: false,
 9571                    done: false,
 9572                });
 9573                self.select_previous(action, window, cx)?;
 9574            }
 9575        }
 9576        Ok(())
 9577    }
 9578
 9579    pub fn toggle_comments(
 9580        &mut self,
 9581        action: &ToggleComments,
 9582        window: &mut Window,
 9583        cx: &mut Context<Self>,
 9584    ) {
 9585        if self.read_only(cx) {
 9586            return;
 9587        }
 9588        let text_layout_details = &self.text_layout_details(window);
 9589        self.transact(window, cx, |this, window, cx| {
 9590            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9591            let mut edits = Vec::new();
 9592            let mut selection_edit_ranges = Vec::new();
 9593            let mut last_toggled_row = None;
 9594            let snapshot = this.buffer.read(cx).read(cx);
 9595            let empty_str: Arc<str> = Arc::default();
 9596            let mut suffixes_inserted = Vec::new();
 9597            let ignore_indent = action.ignore_indent;
 9598
 9599            fn comment_prefix_range(
 9600                snapshot: &MultiBufferSnapshot,
 9601                row: MultiBufferRow,
 9602                comment_prefix: &str,
 9603                comment_prefix_whitespace: &str,
 9604                ignore_indent: bool,
 9605            ) -> Range<Point> {
 9606                let indent_size = if ignore_indent {
 9607                    0
 9608                } else {
 9609                    snapshot.indent_size_for_line(row).len
 9610                };
 9611
 9612                let start = Point::new(row.0, indent_size);
 9613
 9614                let mut line_bytes = snapshot
 9615                    .bytes_in_range(start..snapshot.max_point())
 9616                    .flatten()
 9617                    .copied();
 9618
 9619                // If this line currently begins with the line comment prefix, then record
 9620                // the range containing the prefix.
 9621                if line_bytes
 9622                    .by_ref()
 9623                    .take(comment_prefix.len())
 9624                    .eq(comment_prefix.bytes())
 9625                {
 9626                    // Include any whitespace that matches the comment prefix.
 9627                    let matching_whitespace_len = line_bytes
 9628                        .zip(comment_prefix_whitespace.bytes())
 9629                        .take_while(|(a, b)| a == b)
 9630                        .count() as u32;
 9631                    let end = Point::new(
 9632                        start.row,
 9633                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9634                    );
 9635                    start..end
 9636                } else {
 9637                    start..start
 9638                }
 9639            }
 9640
 9641            fn comment_suffix_range(
 9642                snapshot: &MultiBufferSnapshot,
 9643                row: MultiBufferRow,
 9644                comment_suffix: &str,
 9645                comment_suffix_has_leading_space: bool,
 9646            ) -> Range<Point> {
 9647                let end = Point::new(row.0, snapshot.line_len(row));
 9648                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9649
 9650                let mut line_end_bytes = snapshot
 9651                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9652                    .flatten()
 9653                    .copied();
 9654
 9655                let leading_space_len = if suffix_start_column > 0
 9656                    && line_end_bytes.next() == Some(b' ')
 9657                    && comment_suffix_has_leading_space
 9658                {
 9659                    1
 9660                } else {
 9661                    0
 9662                };
 9663
 9664                // If this line currently begins with the line comment prefix, then record
 9665                // the range containing the prefix.
 9666                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9667                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9668                    start..end
 9669                } else {
 9670                    end..end
 9671                }
 9672            }
 9673
 9674            // TODO: Handle selections that cross excerpts
 9675            for selection in &mut selections {
 9676                let start_column = snapshot
 9677                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9678                    .len;
 9679                let language = if let Some(language) =
 9680                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9681                {
 9682                    language
 9683                } else {
 9684                    continue;
 9685                };
 9686
 9687                selection_edit_ranges.clear();
 9688
 9689                // If multiple selections contain a given row, avoid processing that
 9690                // row more than once.
 9691                let mut start_row = MultiBufferRow(selection.start.row);
 9692                if last_toggled_row == Some(start_row) {
 9693                    start_row = start_row.next_row();
 9694                }
 9695                let end_row =
 9696                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9697                        MultiBufferRow(selection.end.row - 1)
 9698                    } else {
 9699                        MultiBufferRow(selection.end.row)
 9700                    };
 9701                last_toggled_row = Some(end_row);
 9702
 9703                if start_row > end_row {
 9704                    continue;
 9705                }
 9706
 9707                // If the language has line comments, toggle those.
 9708                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9709
 9710                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9711                if ignore_indent {
 9712                    full_comment_prefixes = full_comment_prefixes
 9713                        .into_iter()
 9714                        .map(|s| Arc::from(s.trim_end()))
 9715                        .collect();
 9716                }
 9717
 9718                if !full_comment_prefixes.is_empty() {
 9719                    let first_prefix = full_comment_prefixes
 9720                        .first()
 9721                        .expect("prefixes is non-empty");
 9722                    let prefix_trimmed_lengths = full_comment_prefixes
 9723                        .iter()
 9724                        .map(|p| p.trim_end_matches(' ').len())
 9725                        .collect::<SmallVec<[usize; 4]>>();
 9726
 9727                    let mut all_selection_lines_are_comments = true;
 9728
 9729                    for row in start_row.0..=end_row.0 {
 9730                        let row = MultiBufferRow(row);
 9731                        if start_row < end_row && snapshot.is_line_blank(row) {
 9732                            continue;
 9733                        }
 9734
 9735                        let prefix_range = full_comment_prefixes
 9736                            .iter()
 9737                            .zip(prefix_trimmed_lengths.iter().copied())
 9738                            .map(|(prefix, trimmed_prefix_len)| {
 9739                                comment_prefix_range(
 9740                                    snapshot.deref(),
 9741                                    row,
 9742                                    &prefix[..trimmed_prefix_len],
 9743                                    &prefix[trimmed_prefix_len..],
 9744                                    ignore_indent,
 9745                                )
 9746                            })
 9747                            .max_by_key(|range| range.end.column - range.start.column)
 9748                            .expect("prefixes is non-empty");
 9749
 9750                        if prefix_range.is_empty() {
 9751                            all_selection_lines_are_comments = false;
 9752                        }
 9753
 9754                        selection_edit_ranges.push(prefix_range);
 9755                    }
 9756
 9757                    if all_selection_lines_are_comments {
 9758                        edits.extend(
 9759                            selection_edit_ranges
 9760                                .iter()
 9761                                .cloned()
 9762                                .map(|range| (range, empty_str.clone())),
 9763                        );
 9764                    } else {
 9765                        let min_column = selection_edit_ranges
 9766                            .iter()
 9767                            .map(|range| range.start.column)
 9768                            .min()
 9769                            .unwrap_or(0);
 9770                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9771                            let position = Point::new(range.start.row, min_column);
 9772                            (position..position, first_prefix.clone())
 9773                        }));
 9774                    }
 9775                } else if let Some((full_comment_prefix, comment_suffix)) =
 9776                    language.block_comment_delimiters()
 9777                {
 9778                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9779                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9780                    let prefix_range = comment_prefix_range(
 9781                        snapshot.deref(),
 9782                        start_row,
 9783                        comment_prefix,
 9784                        comment_prefix_whitespace,
 9785                        ignore_indent,
 9786                    );
 9787                    let suffix_range = comment_suffix_range(
 9788                        snapshot.deref(),
 9789                        end_row,
 9790                        comment_suffix.trim_start_matches(' '),
 9791                        comment_suffix.starts_with(' '),
 9792                    );
 9793
 9794                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9795                        edits.push((
 9796                            prefix_range.start..prefix_range.start,
 9797                            full_comment_prefix.clone(),
 9798                        ));
 9799                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9800                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9801                    } else {
 9802                        edits.push((prefix_range, empty_str.clone()));
 9803                        edits.push((suffix_range, empty_str.clone()));
 9804                    }
 9805                } else {
 9806                    continue;
 9807                }
 9808            }
 9809
 9810            drop(snapshot);
 9811            this.buffer.update(cx, |buffer, cx| {
 9812                buffer.edit(edits, None, cx);
 9813            });
 9814
 9815            // Adjust selections so that they end before any comment suffixes that
 9816            // were inserted.
 9817            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9818            let mut selections = this.selections.all::<Point>(cx);
 9819            let snapshot = this.buffer.read(cx).read(cx);
 9820            for selection in &mut selections {
 9821                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9822                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9823                        Ordering::Less => {
 9824                            suffixes_inserted.next();
 9825                            continue;
 9826                        }
 9827                        Ordering::Greater => break,
 9828                        Ordering::Equal => {
 9829                            if selection.end.column == snapshot.line_len(row) {
 9830                                if selection.is_empty() {
 9831                                    selection.start.column -= suffix_len as u32;
 9832                                }
 9833                                selection.end.column -= suffix_len as u32;
 9834                            }
 9835                            break;
 9836                        }
 9837                    }
 9838                }
 9839            }
 9840
 9841            drop(snapshot);
 9842            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9843                s.select(selections)
 9844            });
 9845
 9846            let selections = this.selections.all::<Point>(cx);
 9847            let selections_on_single_row = selections.windows(2).all(|selections| {
 9848                selections[0].start.row == selections[1].start.row
 9849                    && selections[0].end.row == selections[1].end.row
 9850                    && selections[0].start.row == selections[0].end.row
 9851            });
 9852            let selections_selecting = selections
 9853                .iter()
 9854                .any(|selection| selection.start != selection.end);
 9855            let advance_downwards = action.advance_downwards
 9856                && selections_on_single_row
 9857                && !selections_selecting
 9858                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9859
 9860            if advance_downwards {
 9861                let snapshot = this.buffer.read(cx).snapshot(cx);
 9862
 9863                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9864                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9865                        let mut point = display_point.to_point(display_snapshot);
 9866                        point.row += 1;
 9867                        point = snapshot.clip_point(point, Bias::Left);
 9868                        let display_point = point.to_display_point(display_snapshot);
 9869                        let goal = SelectionGoal::HorizontalPosition(
 9870                            display_snapshot
 9871                                .x_for_display_point(display_point, text_layout_details)
 9872                                .into(),
 9873                        );
 9874                        (display_point, goal)
 9875                    })
 9876                });
 9877            }
 9878        });
 9879    }
 9880
 9881    pub fn select_enclosing_symbol(
 9882        &mut self,
 9883        _: &SelectEnclosingSymbol,
 9884        window: &mut Window,
 9885        cx: &mut Context<Self>,
 9886    ) {
 9887        let buffer = self.buffer.read(cx).snapshot(cx);
 9888        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9889
 9890        fn update_selection(
 9891            selection: &Selection<usize>,
 9892            buffer_snap: &MultiBufferSnapshot,
 9893        ) -> Option<Selection<usize>> {
 9894            let cursor = selection.head();
 9895            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9896            for symbol in symbols.iter().rev() {
 9897                let start = symbol.range.start.to_offset(buffer_snap);
 9898                let end = symbol.range.end.to_offset(buffer_snap);
 9899                let new_range = start..end;
 9900                if start < selection.start || end > selection.end {
 9901                    return Some(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            }
 9910            None
 9911        }
 9912
 9913        let mut selected_larger_symbol = false;
 9914        let new_selections = old_selections
 9915            .iter()
 9916            .map(|selection| match update_selection(selection, &buffer) {
 9917                Some(new_selection) => {
 9918                    if new_selection.range() != selection.range() {
 9919                        selected_larger_symbol = true;
 9920                    }
 9921                    new_selection
 9922                }
 9923                None => selection.clone(),
 9924            })
 9925            .collect::<Vec<_>>();
 9926
 9927        if selected_larger_symbol {
 9928            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9929                s.select(new_selections);
 9930            });
 9931        }
 9932    }
 9933
 9934    pub fn select_larger_syntax_node(
 9935        &mut self,
 9936        _: &SelectLargerSyntaxNode,
 9937        window: &mut Window,
 9938        cx: &mut Context<Self>,
 9939    ) {
 9940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9941        let buffer = self.buffer.read(cx).snapshot(cx);
 9942        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9943
 9944        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9945        let mut selected_larger_node = false;
 9946        let new_selections = old_selections
 9947            .iter()
 9948            .map(|selection| {
 9949                let old_range = selection.start..selection.end;
 9950                let mut new_range = old_range.clone();
 9951                let mut new_node = None;
 9952                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9953                {
 9954                    new_node = Some(node);
 9955                    new_range = containing_range;
 9956                    if !display_map.intersects_fold(new_range.start)
 9957                        && !display_map.intersects_fold(new_range.end)
 9958                    {
 9959                        break;
 9960                    }
 9961                }
 9962
 9963                if let Some(node) = new_node {
 9964                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9965                    // nodes. Parent and grandparent are also logged because this operation will not
 9966                    // visit nodes that have the same range as their parent.
 9967                    log::info!("Node: {node:?}");
 9968                    let parent = node.parent();
 9969                    log::info!("Parent: {parent:?}");
 9970                    let grandparent = parent.and_then(|x| x.parent());
 9971                    log::info!("Grandparent: {grandparent:?}");
 9972                }
 9973
 9974                selected_larger_node |= new_range != old_range;
 9975                Selection {
 9976                    id: selection.id,
 9977                    start: new_range.start,
 9978                    end: new_range.end,
 9979                    goal: SelectionGoal::None,
 9980                    reversed: selection.reversed,
 9981                }
 9982            })
 9983            .collect::<Vec<_>>();
 9984
 9985        if selected_larger_node {
 9986            stack.push(old_selections);
 9987            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9988                s.select(new_selections);
 9989            });
 9990        }
 9991        self.select_larger_syntax_node_stack = stack;
 9992    }
 9993
 9994    pub fn select_smaller_syntax_node(
 9995        &mut self,
 9996        _: &SelectSmallerSyntaxNode,
 9997        window: &mut Window,
 9998        cx: &mut Context<Self>,
 9999    ) {
10000        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10001        if let Some(selections) = stack.pop() {
10002            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10003                s.select(selections.to_vec());
10004            });
10005        }
10006        self.select_larger_syntax_node_stack = stack;
10007    }
10008
10009    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10010        if !EditorSettings::get_global(cx).gutter.runnables {
10011            self.clear_tasks();
10012            return Task::ready(());
10013        }
10014        let project = self.project.as_ref().map(Entity::downgrade);
10015        cx.spawn_in(window, |this, mut cx| async move {
10016            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10017            let Some(project) = project.and_then(|p| p.upgrade()) else {
10018                return;
10019            };
10020            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10021                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10022            }) else {
10023                return;
10024            };
10025
10026            let hide_runnables = project
10027                .update(&mut cx, |project, cx| {
10028                    // Do not display any test indicators in non-dev server remote projects.
10029                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10030                })
10031                .unwrap_or(true);
10032            if hide_runnables {
10033                return;
10034            }
10035            let new_rows =
10036                cx.background_executor()
10037                    .spawn({
10038                        let snapshot = display_snapshot.clone();
10039                        async move {
10040                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10041                        }
10042                    })
10043                    .await;
10044
10045            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10046            this.update(&mut cx, |this, _| {
10047                this.clear_tasks();
10048                for (key, value) in rows {
10049                    this.insert_tasks(key, value);
10050                }
10051            })
10052            .ok();
10053        })
10054    }
10055    fn fetch_runnable_ranges(
10056        snapshot: &DisplaySnapshot,
10057        range: Range<Anchor>,
10058    ) -> Vec<language::RunnableRange> {
10059        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10060    }
10061
10062    fn runnable_rows(
10063        project: Entity<Project>,
10064        snapshot: DisplaySnapshot,
10065        runnable_ranges: Vec<RunnableRange>,
10066        mut cx: AsyncWindowContext,
10067    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10068        runnable_ranges
10069            .into_iter()
10070            .filter_map(|mut runnable| {
10071                let tasks = cx
10072                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10073                    .ok()?;
10074                if tasks.is_empty() {
10075                    return None;
10076                }
10077
10078                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10079
10080                let row = snapshot
10081                    .buffer_snapshot
10082                    .buffer_line_for_row(MultiBufferRow(point.row))?
10083                    .1
10084                    .start
10085                    .row;
10086
10087                let context_range =
10088                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10089                Some((
10090                    (runnable.buffer_id, row),
10091                    RunnableTasks {
10092                        templates: tasks,
10093                        offset: MultiBufferOffset(runnable.run_range.start),
10094                        context_range,
10095                        column: point.column,
10096                        extra_variables: runnable.extra_captures,
10097                    },
10098                ))
10099            })
10100            .collect()
10101    }
10102
10103    fn templates_with_tags(
10104        project: &Entity<Project>,
10105        runnable: &mut Runnable,
10106        cx: &mut App,
10107    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10108        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10109            let (worktree_id, file) = project
10110                .buffer_for_id(runnable.buffer, cx)
10111                .and_then(|buffer| buffer.read(cx).file())
10112                .map(|file| (file.worktree_id(cx), file.clone()))
10113                .unzip();
10114
10115            (
10116                project.task_store().read(cx).task_inventory().cloned(),
10117                worktree_id,
10118                file,
10119            )
10120        });
10121
10122        let tags = mem::take(&mut runnable.tags);
10123        let mut tags: Vec<_> = tags
10124            .into_iter()
10125            .flat_map(|tag| {
10126                let tag = tag.0.clone();
10127                inventory
10128                    .as_ref()
10129                    .into_iter()
10130                    .flat_map(|inventory| {
10131                        inventory.read(cx).list_tasks(
10132                            file.clone(),
10133                            Some(runnable.language.clone()),
10134                            worktree_id,
10135                            cx,
10136                        )
10137                    })
10138                    .filter(move |(_, template)| {
10139                        template.tags.iter().any(|source_tag| source_tag == &tag)
10140                    })
10141            })
10142            .sorted_by_key(|(kind, _)| kind.to_owned())
10143            .collect();
10144        if let Some((leading_tag_source, _)) = tags.first() {
10145            // Strongest source wins; if we have worktree tag binding, prefer that to
10146            // global and language bindings;
10147            // if we have a global binding, prefer that to language binding.
10148            let first_mismatch = tags
10149                .iter()
10150                .position(|(tag_source, _)| tag_source != leading_tag_source);
10151            if let Some(index) = first_mismatch {
10152                tags.truncate(index);
10153            }
10154        }
10155
10156        tags
10157    }
10158
10159    pub fn move_to_enclosing_bracket(
10160        &mut self,
10161        _: &MoveToEnclosingBracket,
10162        window: &mut Window,
10163        cx: &mut Context<Self>,
10164    ) {
10165        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10166            s.move_offsets_with(|snapshot, selection| {
10167                let Some(enclosing_bracket_ranges) =
10168                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10169                else {
10170                    return;
10171                };
10172
10173                let mut best_length = usize::MAX;
10174                let mut best_inside = false;
10175                let mut best_in_bracket_range = false;
10176                let mut best_destination = None;
10177                for (open, close) in enclosing_bracket_ranges {
10178                    let close = close.to_inclusive();
10179                    let length = close.end() - open.start;
10180                    let inside = selection.start >= open.end && selection.end <= *close.start();
10181                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10182                        || close.contains(&selection.head());
10183
10184                    // If best is next to a bracket and current isn't, skip
10185                    if !in_bracket_range && best_in_bracket_range {
10186                        continue;
10187                    }
10188
10189                    // Prefer smaller lengths unless best is inside and current isn't
10190                    if length > best_length && (best_inside || !inside) {
10191                        continue;
10192                    }
10193
10194                    best_length = length;
10195                    best_inside = inside;
10196                    best_in_bracket_range = in_bracket_range;
10197                    best_destination = Some(
10198                        if close.contains(&selection.start) && close.contains(&selection.end) {
10199                            if inside {
10200                                open.end
10201                            } else {
10202                                open.start
10203                            }
10204                        } else if inside {
10205                            *close.start()
10206                        } else {
10207                            *close.end()
10208                        },
10209                    );
10210                }
10211
10212                if let Some(destination) = best_destination {
10213                    selection.collapse_to(destination, SelectionGoal::None);
10214                }
10215            })
10216        });
10217    }
10218
10219    pub fn undo_selection(
10220        &mut self,
10221        _: &UndoSelection,
10222        window: &mut Window,
10223        cx: &mut Context<Self>,
10224    ) {
10225        self.end_selection(window, cx);
10226        self.selection_history.mode = SelectionHistoryMode::Undoing;
10227        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10228            self.change_selections(None, window, cx, |s| {
10229                s.select_anchors(entry.selections.to_vec())
10230            });
10231            self.select_next_state = entry.select_next_state;
10232            self.select_prev_state = entry.select_prev_state;
10233            self.add_selections_state = entry.add_selections_state;
10234            self.request_autoscroll(Autoscroll::newest(), cx);
10235        }
10236        self.selection_history.mode = SelectionHistoryMode::Normal;
10237    }
10238
10239    pub fn redo_selection(
10240        &mut self,
10241        _: &RedoSelection,
10242        window: &mut Window,
10243        cx: &mut Context<Self>,
10244    ) {
10245        self.end_selection(window, cx);
10246        self.selection_history.mode = SelectionHistoryMode::Redoing;
10247        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10248            self.change_selections(None, window, cx, |s| {
10249                s.select_anchors(entry.selections.to_vec())
10250            });
10251            self.select_next_state = entry.select_next_state;
10252            self.select_prev_state = entry.select_prev_state;
10253            self.add_selections_state = entry.add_selections_state;
10254            self.request_autoscroll(Autoscroll::newest(), cx);
10255        }
10256        self.selection_history.mode = SelectionHistoryMode::Normal;
10257    }
10258
10259    pub fn expand_excerpts(
10260        &mut self,
10261        action: &ExpandExcerpts,
10262        _: &mut Window,
10263        cx: &mut Context<Self>,
10264    ) {
10265        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10266    }
10267
10268    pub fn expand_excerpts_down(
10269        &mut self,
10270        action: &ExpandExcerptsDown,
10271        _: &mut Window,
10272        cx: &mut Context<Self>,
10273    ) {
10274        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10275    }
10276
10277    pub fn expand_excerpts_up(
10278        &mut self,
10279        action: &ExpandExcerptsUp,
10280        _: &mut Window,
10281        cx: &mut Context<Self>,
10282    ) {
10283        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10284    }
10285
10286    pub fn expand_excerpts_for_direction(
10287        &mut self,
10288        lines: u32,
10289        direction: ExpandExcerptDirection,
10290
10291        cx: &mut Context<Self>,
10292    ) {
10293        let selections = self.selections.disjoint_anchors();
10294
10295        let lines = if lines == 0 {
10296            EditorSettings::get_global(cx).expand_excerpt_lines
10297        } else {
10298            lines
10299        };
10300
10301        self.buffer.update(cx, |buffer, cx| {
10302            let snapshot = buffer.snapshot(cx);
10303            let mut excerpt_ids = selections
10304                .iter()
10305                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10306                .collect::<Vec<_>>();
10307            excerpt_ids.sort();
10308            excerpt_ids.dedup();
10309            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10310        })
10311    }
10312
10313    pub fn expand_excerpt(
10314        &mut self,
10315        excerpt: ExcerptId,
10316        direction: ExpandExcerptDirection,
10317        cx: &mut Context<Self>,
10318    ) {
10319        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10320        self.buffer.update(cx, |buffer, cx| {
10321            buffer.expand_excerpts([excerpt], lines, direction, cx)
10322        })
10323    }
10324
10325    pub fn go_to_singleton_buffer_point(
10326        &mut self,
10327        point: Point,
10328        window: &mut Window,
10329        cx: &mut Context<Self>,
10330    ) {
10331        self.go_to_singleton_buffer_range(point..point, window, cx);
10332    }
10333
10334    pub fn go_to_singleton_buffer_range(
10335        &mut self,
10336        range: Range<Point>,
10337        window: &mut Window,
10338        cx: &mut Context<Self>,
10339    ) {
10340        let multibuffer = self.buffer().read(cx);
10341        let Some(buffer) = multibuffer.as_singleton() else {
10342            return;
10343        };
10344        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10345            return;
10346        };
10347        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10348            return;
10349        };
10350        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10351            s.select_anchor_ranges([start..end])
10352        });
10353    }
10354
10355    fn go_to_diagnostic(
10356        &mut self,
10357        _: &GoToDiagnostic,
10358        window: &mut Window,
10359        cx: &mut Context<Self>,
10360    ) {
10361        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10362    }
10363
10364    fn go_to_prev_diagnostic(
10365        &mut self,
10366        _: &GoToPrevDiagnostic,
10367        window: &mut Window,
10368        cx: &mut Context<Self>,
10369    ) {
10370        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10371    }
10372
10373    pub fn go_to_diagnostic_impl(
10374        &mut self,
10375        direction: Direction,
10376        window: &mut Window,
10377        cx: &mut Context<Self>,
10378    ) {
10379        let buffer = self.buffer.read(cx).snapshot(cx);
10380        let selection = self.selections.newest::<usize>(cx);
10381
10382        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10383        if direction == Direction::Next {
10384            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10385                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10386                    return;
10387                };
10388                self.activate_diagnostics(
10389                    buffer_id,
10390                    popover.local_diagnostic.diagnostic.group_id,
10391                    window,
10392                    cx,
10393                );
10394                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10395                    let primary_range_start = active_diagnostics.primary_range.start;
10396                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10397                        let mut new_selection = s.newest_anchor().clone();
10398                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10399                        s.select_anchors(vec![new_selection.clone()]);
10400                    });
10401                    self.refresh_inline_completion(false, true, window, cx);
10402                }
10403                return;
10404            }
10405        }
10406
10407        let active_group_id = self
10408            .active_diagnostics
10409            .as_ref()
10410            .map(|active_group| active_group.group_id);
10411        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10412            active_diagnostics
10413                .primary_range
10414                .to_offset(&buffer)
10415                .to_inclusive()
10416        });
10417        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10418            if active_primary_range.contains(&selection.head()) {
10419                *active_primary_range.start()
10420            } else {
10421                selection.head()
10422            }
10423        } else {
10424            selection.head()
10425        };
10426
10427        let snapshot = self.snapshot(window, cx);
10428        let primary_diagnostics_before = buffer
10429            .diagnostics_in_range::<usize>(0..search_start)
10430            .filter(|entry| entry.diagnostic.is_primary)
10431            .filter(|entry| entry.range.start != entry.range.end)
10432            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10433            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10434            .collect::<Vec<_>>();
10435        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10436            primary_diagnostics_before
10437                .iter()
10438                .position(|entry| entry.diagnostic.group_id == active_group_id)
10439        });
10440
10441        let primary_diagnostics_after = buffer
10442            .diagnostics_in_range::<usize>(search_start..buffer.len())
10443            .filter(|entry| entry.diagnostic.is_primary)
10444            .filter(|entry| entry.range.start != entry.range.end)
10445            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10446            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10447            .collect::<Vec<_>>();
10448        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10449            primary_diagnostics_after
10450                .iter()
10451                .enumerate()
10452                .rev()
10453                .find_map(|(i, entry)| {
10454                    if entry.diagnostic.group_id == active_group_id {
10455                        Some(i)
10456                    } else {
10457                        None
10458                    }
10459                })
10460        });
10461
10462        let next_primary_diagnostic = match direction {
10463            Direction::Prev => primary_diagnostics_before
10464                .iter()
10465                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10466                .rev()
10467                .next(),
10468            Direction::Next => primary_diagnostics_after
10469                .iter()
10470                .skip(
10471                    last_same_group_diagnostic_after
10472                        .map(|index| index + 1)
10473                        .unwrap_or(0),
10474                )
10475                .next(),
10476        };
10477
10478        // Cycle around to the start of the buffer, potentially moving back to the start of
10479        // the currently active diagnostic.
10480        let cycle_around = || match direction {
10481            Direction::Prev => primary_diagnostics_after
10482                .iter()
10483                .rev()
10484                .chain(primary_diagnostics_before.iter().rev())
10485                .next(),
10486            Direction::Next => primary_diagnostics_before
10487                .iter()
10488                .chain(primary_diagnostics_after.iter())
10489                .next(),
10490        };
10491
10492        if let Some((primary_range, group_id)) = next_primary_diagnostic
10493            .or_else(cycle_around)
10494            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10495        {
10496            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10497                return;
10498            };
10499            self.activate_diagnostics(buffer_id, group_id, window, cx);
10500            if self.active_diagnostics.is_some() {
10501                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10502                    s.select(vec![Selection {
10503                        id: selection.id,
10504                        start: primary_range.start,
10505                        end: primary_range.start,
10506                        reversed: false,
10507                        goal: SelectionGoal::None,
10508                    }]);
10509                });
10510                self.refresh_inline_completion(false, true, window, cx);
10511            }
10512        }
10513    }
10514
10515    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10516        let snapshot = self.snapshot(window, cx);
10517        let selection = self.selections.newest::<Point>(cx);
10518        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10519    }
10520
10521    fn go_to_hunk_after_position(
10522        &mut self,
10523        snapshot: &EditorSnapshot,
10524        position: Point,
10525        window: &mut Window,
10526        cx: &mut Context<Editor>,
10527    ) -> Option<MultiBufferDiffHunk> {
10528        let mut hunk = snapshot
10529            .buffer_snapshot
10530            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10531            .find(|hunk| hunk.row_range.start.0 > position.row);
10532        if hunk.is_none() {
10533            hunk = snapshot
10534                .buffer_snapshot
10535                .diff_hunks_in_range(Point::zero()..position)
10536                .find(|hunk| hunk.row_range.end.0 < position.row)
10537        }
10538        if let Some(hunk) = &hunk {
10539            let destination = Point::new(hunk.row_range.start.0, 0);
10540            self.unfold_ranges(&[destination..destination], false, false, cx);
10541            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10542                s.select_ranges(vec![destination..destination]);
10543            });
10544        }
10545
10546        hunk
10547    }
10548
10549    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10550        let snapshot = self.snapshot(window, cx);
10551        let selection = self.selections.newest::<Point>(cx);
10552        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10553    }
10554
10555    fn go_to_hunk_before_position(
10556        &mut self,
10557        snapshot: &EditorSnapshot,
10558        position: Point,
10559        window: &mut Window,
10560        cx: &mut Context<Editor>,
10561    ) -> Option<MultiBufferDiffHunk> {
10562        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10563        if hunk.is_none() {
10564            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10565        }
10566        if let Some(hunk) = &hunk {
10567            let destination = Point::new(hunk.row_range.start.0, 0);
10568            self.unfold_ranges(&[destination..destination], false, false, cx);
10569            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10570                s.select_ranges(vec![destination..destination]);
10571            });
10572        }
10573
10574        hunk
10575    }
10576
10577    pub fn go_to_definition(
10578        &mut self,
10579        _: &GoToDefinition,
10580        window: &mut Window,
10581        cx: &mut Context<Self>,
10582    ) -> Task<Result<Navigated>> {
10583        let definition =
10584            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10585        cx.spawn_in(window, |editor, mut cx| async move {
10586            if definition.await? == Navigated::Yes {
10587                return Ok(Navigated::Yes);
10588            }
10589            match editor.update_in(&mut cx, |editor, window, cx| {
10590                editor.find_all_references(&FindAllReferences, window, cx)
10591            })? {
10592                Some(references) => references.await,
10593                None => Ok(Navigated::No),
10594            }
10595        })
10596    }
10597
10598    pub fn go_to_declaration(
10599        &mut self,
10600        _: &GoToDeclaration,
10601        window: &mut Window,
10602        cx: &mut Context<Self>,
10603    ) -> Task<Result<Navigated>> {
10604        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10605    }
10606
10607    pub fn go_to_declaration_split(
10608        &mut self,
10609        _: &GoToDeclaration,
10610        window: &mut Window,
10611        cx: &mut Context<Self>,
10612    ) -> Task<Result<Navigated>> {
10613        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10614    }
10615
10616    pub fn go_to_implementation(
10617        &mut self,
10618        _: &GoToImplementation,
10619        window: &mut Window,
10620        cx: &mut Context<Self>,
10621    ) -> Task<Result<Navigated>> {
10622        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10623    }
10624
10625    pub fn go_to_implementation_split(
10626        &mut self,
10627        _: &GoToImplementationSplit,
10628        window: &mut Window,
10629        cx: &mut Context<Self>,
10630    ) -> Task<Result<Navigated>> {
10631        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10632    }
10633
10634    pub fn go_to_type_definition(
10635        &mut self,
10636        _: &GoToTypeDefinition,
10637        window: &mut Window,
10638        cx: &mut Context<Self>,
10639    ) -> Task<Result<Navigated>> {
10640        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10641    }
10642
10643    pub fn go_to_definition_split(
10644        &mut self,
10645        _: &GoToDefinitionSplit,
10646        window: &mut Window,
10647        cx: &mut Context<Self>,
10648    ) -> Task<Result<Navigated>> {
10649        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10650    }
10651
10652    pub fn go_to_type_definition_split(
10653        &mut self,
10654        _: &GoToTypeDefinitionSplit,
10655        window: &mut Window,
10656        cx: &mut Context<Self>,
10657    ) -> Task<Result<Navigated>> {
10658        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10659    }
10660
10661    fn go_to_definition_of_kind(
10662        &mut self,
10663        kind: GotoDefinitionKind,
10664        split: bool,
10665        window: &mut Window,
10666        cx: &mut Context<Self>,
10667    ) -> Task<Result<Navigated>> {
10668        let Some(provider) = self.semantics_provider.clone() else {
10669            return Task::ready(Ok(Navigated::No));
10670        };
10671        let head = self.selections.newest::<usize>(cx).head();
10672        let buffer = self.buffer.read(cx);
10673        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10674            text_anchor
10675        } else {
10676            return Task::ready(Ok(Navigated::No));
10677        };
10678
10679        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10680            return Task::ready(Ok(Navigated::No));
10681        };
10682
10683        cx.spawn_in(window, |editor, mut cx| async move {
10684            let definitions = definitions.await?;
10685            let navigated = editor
10686                .update_in(&mut cx, |editor, window, cx| {
10687                    editor.navigate_to_hover_links(
10688                        Some(kind),
10689                        definitions
10690                            .into_iter()
10691                            .filter(|location| {
10692                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10693                            })
10694                            .map(HoverLink::Text)
10695                            .collect::<Vec<_>>(),
10696                        split,
10697                        window,
10698                        cx,
10699                    )
10700                })?
10701                .await?;
10702            anyhow::Ok(navigated)
10703        })
10704    }
10705
10706    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10707        let selection = self.selections.newest_anchor();
10708        let head = selection.head();
10709        let tail = selection.tail();
10710
10711        let Some((buffer, start_position)) =
10712            self.buffer.read(cx).text_anchor_for_position(head, cx)
10713        else {
10714            return;
10715        };
10716
10717        let end_position = if head != tail {
10718            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10719                return;
10720            };
10721            Some(pos)
10722        } else {
10723            None
10724        };
10725
10726        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10727            let url = if let Some(end_pos) = end_position {
10728                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10729            } else {
10730                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10731            };
10732
10733            if let Some(url) = url {
10734                editor.update(&mut cx, |_, cx| {
10735                    cx.open_url(&url);
10736                })
10737            } else {
10738                Ok(())
10739            }
10740        });
10741
10742        url_finder.detach();
10743    }
10744
10745    pub fn open_selected_filename(
10746        &mut self,
10747        _: &OpenSelectedFilename,
10748        window: &mut Window,
10749        cx: &mut Context<Self>,
10750    ) {
10751        let Some(workspace) = self.workspace() else {
10752            return;
10753        };
10754
10755        let position = self.selections.newest_anchor().head();
10756
10757        let Some((buffer, buffer_position)) =
10758            self.buffer.read(cx).text_anchor_for_position(position, cx)
10759        else {
10760            return;
10761        };
10762
10763        let project = self.project.clone();
10764
10765        cx.spawn_in(window, |_, mut cx| async move {
10766            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10767
10768            if let Some((_, path)) = result {
10769                workspace
10770                    .update_in(&mut cx, |workspace, window, cx| {
10771                        workspace.open_resolved_path(path, window, cx)
10772                    })?
10773                    .await?;
10774            }
10775            anyhow::Ok(())
10776        })
10777        .detach();
10778    }
10779
10780    pub(crate) fn navigate_to_hover_links(
10781        &mut self,
10782        kind: Option<GotoDefinitionKind>,
10783        mut definitions: Vec<HoverLink>,
10784        split: bool,
10785        window: &mut Window,
10786        cx: &mut Context<Editor>,
10787    ) -> Task<Result<Navigated>> {
10788        // If there is one definition, just open it directly
10789        if definitions.len() == 1 {
10790            let definition = definitions.pop().unwrap();
10791
10792            enum TargetTaskResult {
10793                Location(Option<Location>),
10794                AlreadyNavigated,
10795            }
10796
10797            let target_task = match definition {
10798                HoverLink::Text(link) => {
10799                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10800                }
10801                HoverLink::InlayHint(lsp_location, server_id) => {
10802                    let computation =
10803                        self.compute_target_location(lsp_location, server_id, window, cx);
10804                    cx.background_executor().spawn(async move {
10805                        let location = computation.await?;
10806                        Ok(TargetTaskResult::Location(location))
10807                    })
10808                }
10809                HoverLink::Url(url) => {
10810                    cx.open_url(&url);
10811                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10812                }
10813                HoverLink::File(path) => {
10814                    if let Some(workspace) = self.workspace() {
10815                        cx.spawn_in(window, |_, mut cx| async move {
10816                            workspace
10817                                .update_in(&mut cx, |workspace, window, cx| {
10818                                    workspace.open_resolved_path(path, window, cx)
10819                                })?
10820                                .await
10821                                .map(|_| TargetTaskResult::AlreadyNavigated)
10822                        })
10823                    } else {
10824                        Task::ready(Ok(TargetTaskResult::Location(None)))
10825                    }
10826                }
10827            };
10828            cx.spawn_in(window, |editor, mut cx| async move {
10829                let target = match target_task.await.context("target resolution task")? {
10830                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10831                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10832                    TargetTaskResult::Location(Some(target)) => target,
10833                };
10834
10835                editor.update_in(&mut cx, |editor, window, cx| {
10836                    let Some(workspace) = editor.workspace() else {
10837                        return Navigated::No;
10838                    };
10839                    let pane = workspace.read(cx).active_pane().clone();
10840
10841                    let range = target.range.to_point(target.buffer.read(cx));
10842                    let range = editor.range_for_match(&range);
10843                    let range = collapse_multiline_range(range);
10844
10845                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10846                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10847                    } else {
10848                        window.defer(cx, move |window, cx| {
10849                            let target_editor: Entity<Self> =
10850                                workspace.update(cx, |workspace, cx| {
10851                                    let pane = if split {
10852                                        workspace.adjacent_pane(window, cx)
10853                                    } else {
10854                                        workspace.active_pane().clone()
10855                                    };
10856
10857                                    workspace.open_project_item(
10858                                        pane,
10859                                        target.buffer.clone(),
10860                                        true,
10861                                        true,
10862                                        window,
10863                                        cx,
10864                                    )
10865                                });
10866                            target_editor.update(cx, |target_editor, cx| {
10867                                // When selecting a definition in a different buffer, disable the nav history
10868                                // to avoid creating a history entry at the previous cursor location.
10869                                pane.update(cx, |pane, _| pane.disable_history());
10870                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10871                                pane.update(cx, |pane, _| pane.enable_history());
10872                            });
10873                        });
10874                    }
10875                    Navigated::Yes
10876                })
10877            })
10878        } else if !definitions.is_empty() {
10879            cx.spawn_in(window, |editor, mut cx| async move {
10880                let (title, location_tasks, workspace) = editor
10881                    .update_in(&mut cx, |editor, window, cx| {
10882                        let tab_kind = match kind {
10883                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10884                            _ => "Definitions",
10885                        };
10886                        let title = definitions
10887                            .iter()
10888                            .find_map(|definition| match definition {
10889                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10890                                    let buffer = origin.buffer.read(cx);
10891                                    format!(
10892                                        "{} for {}",
10893                                        tab_kind,
10894                                        buffer
10895                                            .text_for_range(origin.range.clone())
10896                                            .collect::<String>()
10897                                    )
10898                                }),
10899                                HoverLink::InlayHint(_, _) => None,
10900                                HoverLink::Url(_) => None,
10901                                HoverLink::File(_) => None,
10902                            })
10903                            .unwrap_or(tab_kind.to_string());
10904                        let location_tasks = definitions
10905                            .into_iter()
10906                            .map(|definition| match definition {
10907                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10908                                HoverLink::InlayHint(lsp_location, server_id) => editor
10909                                    .compute_target_location(lsp_location, server_id, window, cx),
10910                                HoverLink::Url(_) => Task::ready(Ok(None)),
10911                                HoverLink::File(_) => Task::ready(Ok(None)),
10912                            })
10913                            .collect::<Vec<_>>();
10914                        (title, location_tasks, editor.workspace().clone())
10915                    })
10916                    .context("location tasks preparation")?;
10917
10918                let locations = future::join_all(location_tasks)
10919                    .await
10920                    .into_iter()
10921                    .filter_map(|location| location.transpose())
10922                    .collect::<Result<_>>()
10923                    .context("location tasks")?;
10924
10925                let Some(workspace) = workspace else {
10926                    return Ok(Navigated::No);
10927                };
10928                let opened = workspace
10929                    .update_in(&mut cx, |workspace, window, cx| {
10930                        Self::open_locations_in_multibuffer(
10931                            workspace,
10932                            locations,
10933                            title,
10934                            split,
10935                            MultibufferSelectionMode::First,
10936                            window,
10937                            cx,
10938                        )
10939                    })
10940                    .ok();
10941
10942                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10943            })
10944        } else {
10945            Task::ready(Ok(Navigated::No))
10946        }
10947    }
10948
10949    fn compute_target_location(
10950        &self,
10951        lsp_location: lsp::Location,
10952        server_id: LanguageServerId,
10953        window: &mut Window,
10954        cx: &mut Context<Self>,
10955    ) -> Task<anyhow::Result<Option<Location>>> {
10956        let Some(project) = self.project.clone() else {
10957            return Task::ready(Ok(None));
10958        };
10959
10960        cx.spawn_in(window, move |editor, mut cx| async move {
10961            let location_task = editor.update(&mut cx, |_, cx| {
10962                project.update(cx, |project, cx| {
10963                    let language_server_name = project
10964                        .language_server_statuses(cx)
10965                        .find(|(id, _)| server_id == *id)
10966                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10967                    language_server_name.map(|language_server_name| {
10968                        project.open_local_buffer_via_lsp(
10969                            lsp_location.uri.clone(),
10970                            server_id,
10971                            language_server_name,
10972                            cx,
10973                        )
10974                    })
10975                })
10976            })?;
10977            let location = match location_task {
10978                Some(task) => Some({
10979                    let target_buffer_handle = task.await.context("open local buffer")?;
10980                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10981                        let target_start = target_buffer
10982                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10983                        let target_end = target_buffer
10984                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10985                        target_buffer.anchor_after(target_start)
10986                            ..target_buffer.anchor_before(target_end)
10987                    })?;
10988                    Location {
10989                        buffer: target_buffer_handle,
10990                        range,
10991                    }
10992                }),
10993                None => None,
10994            };
10995            Ok(location)
10996        })
10997    }
10998
10999    pub fn find_all_references(
11000        &mut self,
11001        _: &FindAllReferences,
11002        window: &mut Window,
11003        cx: &mut Context<Self>,
11004    ) -> Option<Task<Result<Navigated>>> {
11005        let selection = self.selections.newest::<usize>(cx);
11006        let multi_buffer = self.buffer.read(cx);
11007        let head = selection.head();
11008
11009        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11010        let head_anchor = multi_buffer_snapshot.anchor_at(
11011            head,
11012            if head < selection.tail() {
11013                Bias::Right
11014            } else {
11015                Bias::Left
11016            },
11017        );
11018
11019        match self
11020            .find_all_references_task_sources
11021            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11022        {
11023            Ok(_) => {
11024                log::info!(
11025                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11026                );
11027                return None;
11028            }
11029            Err(i) => {
11030                self.find_all_references_task_sources.insert(i, head_anchor);
11031            }
11032        }
11033
11034        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11035        let workspace = self.workspace()?;
11036        let project = workspace.read(cx).project().clone();
11037        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11038        Some(cx.spawn_in(window, |editor, mut cx| async move {
11039            let _cleanup = defer({
11040                let mut cx = cx.clone();
11041                move || {
11042                    let _ = editor.update(&mut cx, |editor, _| {
11043                        if let Ok(i) =
11044                            editor
11045                                .find_all_references_task_sources
11046                                .binary_search_by(|anchor| {
11047                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11048                                })
11049                        {
11050                            editor.find_all_references_task_sources.remove(i);
11051                        }
11052                    });
11053                }
11054            });
11055
11056            let locations = references.await?;
11057            if locations.is_empty() {
11058                return anyhow::Ok(Navigated::No);
11059            }
11060
11061            workspace.update_in(&mut cx, |workspace, window, cx| {
11062                let title = locations
11063                    .first()
11064                    .as_ref()
11065                    .map(|location| {
11066                        let buffer = location.buffer.read(cx);
11067                        format!(
11068                            "References to `{}`",
11069                            buffer
11070                                .text_for_range(location.range.clone())
11071                                .collect::<String>()
11072                        )
11073                    })
11074                    .unwrap();
11075                Self::open_locations_in_multibuffer(
11076                    workspace,
11077                    locations,
11078                    title,
11079                    false,
11080                    MultibufferSelectionMode::First,
11081                    window,
11082                    cx,
11083                );
11084                Navigated::Yes
11085            })
11086        }))
11087    }
11088
11089    /// Opens a multibuffer with the given project locations in it
11090    pub fn open_locations_in_multibuffer(
11091        workspace: &mut Workspace,
11092        mut locations: Vec<Location>,
11093        title: String,
11094        split: bool,
11095        multibuffer_selection_mode: MultibufferSelectionMode,
11096        window: &mut Window,
11097        cx: &mut Context<Workspace>,
11098    ) {
11099        // If there are multiple definitions, open them in a multibuffer
11100        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11101        let mut locations = locations.into_iter().peekable();
11102        let mut ranges = Vec::new();
11103        let capability = workspace.project().read(cx).capability();
11104
11105        let excerpt_buffer = cx.new(|cx| {
11106            let mut multibuffer = MultiBuffer::new(capability);
11107            while let Some(location) = locations.next() {
11108                let buffer = location.buffer.read(cx);
11109                let mut ranges_for_buffer = Vec::new();
11110                let range = location.range.to_offset(buffer);
11111                ranges_for_buffer.push(range.clone());
11112
11113                while let Some(next_location) = locations.peek() {
11114                    if next_location.buffer == location.buffer {
11115                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11116                        locations.next();
11117                    } else {
11118                        break;
11119                    }
11120                }
11121
11122                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11123                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11124                    location.buffer.clone(),
11125                    ranges_for_buffer,
11126                    DEFAULT_MULTIBUFFER_CONTEXT,
11127                    cx,
11128                ))
11129            }
11130
11131            multibuffer.with_title(title)
11132        });
11133
11134        let editor = cx.new(|cx| {
11135            Editor::for_multibuffer(
11136                excerpt_buffer,
11137                Some(workspace.project().clone()),
11138                true,
11139                window,
11140                cx,
11141            )
11142        });
11143        editor.update(cx, |editor, cx| {
11144            match multibuffer_selection_mode {
11145                MultibufferSelectionMode::First => {
11146                    if let Some(first_range) = ranges.first() {
11147                        editor.change_selections(None, window, cx, |selections| {
11148                            selections.clear_disjoint();
11149                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11150                        });
11151                    }
11152                    editor.highlight_background::<Self>(
11153                        &ranges,
11154                        |theme| theme.editor_highlighted_line_background,
11155                        cx,
11156                    );
11157                }
11158                MultibufferSelectionMode::All => {
11159                    editor.change_selections(None, window, cx, |selections| {
11160                        selections.clear_disjoint();
11161                        selections.select_anchor_ranges(ranges);
11162                    });
11163                }
11164            }
11165            editor.register_buffers_with_language_servers(cx);
11166        });
11167
11168        let item = Box::new(editor);
11169        let item_id = item.item_id();
11170
11171        if split {
11172            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11173        } else {
11174            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11175                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11176                    pane.close_current_preview_item(window, cx)
11177                } else {
11178                    None
11179                }
11180            });
11181            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11182        }
11183        workspace.active_pane().update(cx, |pane, cx| {
11184            pane.set_preview_item_id(Some(item_id), cx);
11185        });
11186    }
11187
11188    pub fn rename(
11189        &mut self,
11190        _: &Rename,
11191        window: &mut Window,
11192        cx: &mut Context<Self>,
11193    ) -> Option<Task<Result<()>>> {
11194        use language::ToOffset as _;
11195
11196        let provider = self.semantics_provider.clone()?;
11197        let selection = self.selections.newest_anchor().clone();
11198        let (cursor_buffer, cursor_buffer_position) = self
11199            .buffer
11200            .read(cx)
11201            .text_anchor_for_position(selection.head(), cx)?;
11202        let (tail_buffer, cursor_buffer_position_end) = self
11203            .buffer
11204            .read(cx)
11205            .text_anchor_for_position(selection.tail(), cx)?;
11206        if tail_buffer != cursor_buffer {
11207            return None;
11208        }
11209
11210        let snapshot = cursor_buffer.read(cx).snapshot();
11211        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11212        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11213        let prepare_rename = provider
11214            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11215            .unwrap_or_else(|| Task::ready(Ok(None)));
11216        drop(snapshot);
11217
11218        Some(cx.spawn_in(window, |this, mut cx| async move {
11219            let rename_range = if let Some(range) = prepare_rename.await? {
11220                Some(range)
11221            } else {
11222                this.update(&mut cx, |this, cx| {
11223                    let buffer = this.buffer.read(cx).snapshot(cx);
11224                    let mut buffer_highlights = this
11225                        .document_highlights_for_position(selection.head(), &buffer)
11226                        .filter(|highlight| {
11227                            highlight.start.excerpt_id == selection.head().excerpt_id
11228                                && highlight.end.excerpt_id == selection.head().excerpt_id
11229                        });
11230                    buffer_highlights
11231                        .next()
11232                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11233                })?
11234            };
11235            if let Some(rename_range) = rename_range {
11236                this.update_in(&mut cx, |this, window, cx| {
11237                    let snapshot = cursor_buffer.read(cx).snapshot();
11238                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11239                    let cursor_offset_in_rename_range =
11240                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11241                    let cursor_offset_in_rename_range_end =
11242                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11243
11244                    this.take_rename(false, window, cx);
11245                    let buffer = this.buffer.read(cx).read(cx);
11246                    let cursor_offset = selection.head().to_offset(&buffer);
11247                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11248                    let rename_end = rename_start + rename_buffer_range.len();
11249                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11250                    let mut old_highlight_id = None;
11251                    let old_name: Arc<str> = buffer
11252                        .chunks(rename_start..rename_end, true)
11253                        .map(|chunk| {
11254                            if old_highlight_id.is_none() {
11255                                old_highlight_id = chunk.syntax_highlight_id;
11256                            }
11257                            chunk.text
11258                        })
11259                        .collect::<String>()
11260                        .into();
11261
11262                    drop(buffer);
11263
11264                    // Position the selection in the rename editor so that it matches the current selection.
11265                    this.show_local_selections = false;
11266                    let rename_editor = cx.new(|cx| {
11267                        let mut editor = Editor::single_line(window, cx);
11268                        editor.buffer.update(cx, |buffer, cx| {
11269                            buffer.edit([(0..0, old_name.clone())], None, cx)
11270                        });
11271                        let rename_selection_range = match cursor_offset_in_rename_range
11272                            .cmp(&cursor_offset_in_rename_range_end)
11273                        {
11274                            Ordering::Equal => {
11275                                editor.select_all(&SelectAll, window, cx);
11276                                return editor;
11277                            }
11278                            Ordering::Less => {
11279                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11280                            }
11281                            Ordering::Greater => {
11282                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11283                            }
11284                        };
11285                        if rename_selection_range.end > old_name.len() {
11286                            editor.select_all(&SelectAll, window, cx);
11287                        } else {
11288                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11289                                s.select_ranges([rename_selection_range]);
11290                            });
11291                        }
11292                        editor
11293                    });
11294                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11295                        if e == &EditorEvent::Focused {
11296                            cx.emit(EditorEvent::FocusedIn)
11297                        }
11298                    })
11299                    .detach();
11300
11301                    let write_highlights =
11302                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11303                    let read_highlights =
11304                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11305                    let ranges = write_highlights
11306                        .iter()
11307                        .flat_map(|(_, ranges)| ranges.iter())
11308                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11309                        .cloned()
11310                        .collect();
11311
11312                    this.highlight_text::<Rename>(
11313                        ranges,
11314                        HighlightStyle {
11315                            fade_out: Some(0.6),
11316                            ..Default::default()
11317                        },
11318                        cx,
11319                    );
11320                    let rename_focus_handle = rename_editor.focus_handle(cx);
11321                    window.focus(&rename_focus_handle);
11322                    let block_id = this.insert_blocks(
11323                        [BlockProperties {
11324                            style: BlockStyle::Flex,
11325                            placement: BlockPlacement::Below(range.start),
11326                            height: 1,
11327                            render: Arc::new({
11328                                let rename_editor = rename_editor.clone();
11329                                move |cx: &mut BlockContext| {
11330                                    let mut text_style = cx.editor_style.text.clone();
11331                                    if let Some(highlight_style) = old_highlight_id
11332                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11333                                    {
11334                                        text_style = text_style.highlight(highlight_style);
11335                                    }
11336                                    div()
11337                                        .block_mouse_down()
11338                                        .pl(cx.anchor_x)
11339                                        .child(EditorElement::new(
11340                                            &rename_editor,
11341                                            EditorStyle {
11342                                                background: cx.theme().system().transparent,
11343                                                local_player: cx.editor_style.local_player,
11344                                                text: text_style,
11345                                                scrollbar_width: cx.editor_style.scrollbar_width,
11346                                                syntax: cx.editor_style.syntax.clone(),
11347                                                status: cx.editor_style.status.clone(),
11348                                                inlay_hints_style: HighlightStyle {
11349                                                    font_weight: Some(FontWeight::BOLD),
11350                                                    ..make_inlay_hints_style(cx.app)
11351                                                },
11352                                                inline_completion_styles: make_suggestion_styles(
11353                                                    cx.app,
11354                                                ),
11355                                                ..EditorStyle::default()
11356                                            },
11357                                        ))
11358                                        .into_any_element()
11359                                }
11360                            }),
11361                            priority: 0,
11362                        }],
11363                        Some(Autoscroll::fit()),
11364                        cx,
11365                    )[0];
11366                    this.pending_rename = Some(RenameState {
11367                        range,
11368                        old_name,
11369                        editor: rename_editor,
11370                        block_id,
11371                    });
11372                })?;
11373            }
11374
11375            Ok(())
11376        }))
11377    }
11378
11379    pub fn confirm_rename(
11380        &mut self,
11381        _: &ConfirmRename,
11382        window: &mut Window,
11383        cx: &mut Context<Self>,
11384    ) -> Option<Task<Result<()>>> {
11385        let rename = self.take_rename(false, window, cx)?;
11386        let workspace = self.workspace()?.downgrade();
11387        let (buffer, start) = self
11388            .buffer
11389            .read(cx)
11390            .text_anchor_for_position(rename.range.start, cx)?;
11391        let (end_buffer, _) = self
11392            .buffer
11393            .read(cx)
11394            .text_anchor_for_position(rename.range.end, cx)?;
11395        if buffer != end_buffer {
11396            return None;
11397        }
11398
11399        let old_name = rename.old_name;
11400        let new_name = rename.editor.read(cx).text(cx);
11401
11402        let rename = self.semantics_provider.as_ref()?.perform_rename(
11403            &buffer,
11404            start,
11405            new_name.clone(),
11406            cx,
11407        )?;
11408
11409        Some(cx.spawn_in(window, |editor, mut cx| async move {
11410            let project_transaction = rename.await?;
11411            Self::open_project_transaction(
11412                &editor,
11413                workspace,
11414                project_transaction,
11415                format!("Rename: {}{}", old_name, new_name),
11416                cx.clone(),
11417            )
11418            .await?;
11419
11420            editor.update(&mut cx, |editor, cx| {
11421                editor.refresh_document_highlights(cx);
11422            })?;
11423            Ok(())
11424        }))
11425    }
11426
11427    fn take_rename(
11428        &mut self,
11429        moving_cursor: bool,
11430        window: &mut Window,
11431        cx: &mut Context<Self>,
11432    ) -> Option<RenameState> {
11433        let rename = self.pending_rename.take()?;
11434        if rename.editor.focus_handle(cx).is_focused(window) {
11435            window.focus(&self.focus_handle);
11436        }
11437
11438        self.remove_blocks(
11439            [rename.block_id].into_iter().collect(),
11440            Some(Autoscroll::fit()),
11441            cx,
11442        );
11443        self.clear_highlights::<Rename>(cx);
11444        self.show_local_selections = true;
11445
11446        if moving_cursor {
11447            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11448                editor.selections.newest::<usize>(cx).head()
11449            });
11450
11451            // Update the selection to match the position of the selection inside
11452            // the rename editor.
11453            let snapshot = self.buffer.read(cx).read(cx);
11454            let rename_range = rename.range.to_offset(&snapshot);
11455            let cursor_in_editor = snapshot
11456                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11457                .min(rename_range.end);
11458            drop(snapshot);
11459
11460            self.change_selections(None, window, cx, |s| {
11461                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11462            });
11463        } else {
11464            self.refresh_document_highlights(cx);
11465        }
11466
11467        Some(rename)
11468    }
11469
11470    pub fn pending_rename(&self) -> Option<&RenameState> {
11471        self.pending_rename.as_ref()
11472    }
11473
11474    fn format(
11475        &mut self,
11476        _: &Format,
11477        window: &mut Window,
11478        cx: &mut Context<Self>,
11479    ) -> Option<Task<Result<()>>> {
11480        let project = match &self.project {
11481            Some(project) => project.clone(),
11482            None => return None,
11483        };
11484
11485        Some(self.perform_format(
11486            project,
11487            FormatTrigger::Manual,
11488            FormatTarget::Buffers,
11489            window,
11490            cx,
11491        ))
11492    }
11493
11494    fn format_selections(
11495        &mut self,
11496        _: &FormatSelections,
11497        window: &mut Window,
11498        cx: &mut Context<Self>,
11499    ) -> Option<Task<Result<()>>> {
11500        let project = match &self.project {
11501            Some(project) => project.clone(),
11502            None => return None,
11503        };
11504
11505        let ranges = self
11506            .selections
11507            .all_adjusted(cx)
11508            .into_iter()
11509            .map(|selection| selection.range())
11510            .collect_vec();
11511
11512        Some(self.perform_format(
11513            project,
11514            FormatTrigger::Manual,
11515            FormatTarget::Ranges(ranges),
11516            window,
11517            cx,
11518        ))
11519    }
11520
11521    fn perform_format(
11522        &mut self,
11523        project: Entity<Project>,
11524        trigger: FormatTrigger,
11525        target: FormatTarget,
11526        window: &mut Window,
11527        cx: &mut Context<Self>,
11528    ) -> Task<Result<()>> {
11529        let buffer = self.buffer.clone();
11530        let (buffers, target) = match target {
11531            FormatTarget::Buffers => {
11532                let mut buffers = buffer.read(cx).all_buffers();
11533                if trigger == FormatTrigger::Save {
11534                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11535                }
11536                (buffers, LspFormatTarget::Buffers)
11537            }
11538            FormatTarget::Ranges(selection_ranges) => {
11539                let multi_buffer = buffer.read(cx);
11540                let snapshot = multi_buffer.read(cx);
11541                let mut buffers = HashSet::default();
11542                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11543                    BTreeMap::new();
11544                for selection_range in selection_ranges {
11545                    for (buffer, buffer_range, _) in
11546                        snapshot.range_to_buffer_ranges(selection_range)
11547                    {
11548                        let buffer_id = buffer.remote_id();
11549                        let start = buffer.anchor_before(buffer_range.start);
11550                        let end = buffer.anchor_after(buffer_range.end);
11551                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11552                        buffer_id_to_ranges
11553                            .entry(buffer_id)
11554                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11555                            .or_insert_with(|| vec![start..end]);
11556                    }
11557                }
11558                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11559            }
11560        };
11561
11562        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11563        let format = project.update(cx, |project, cx| {
11564            project.format(buffers, target, true, trigger, cx)
11565        });
11566
11567        cx.spawn_in(window, |_, mut cx| async move {
11568            let transaction = futures::select_biased! {
11569                () = timeout => {
11570                    log::warn!("timed out waiting for formatting");
11571                    None
11572                }
11573                transaction = format.log_err().fuse() => transaction,
11574            };
11575
11576            buffer
11577                .update(&mut cx, |buffer, cx| {
11578                    if let Some(transaction) = transaction {
11579                        if !buffer.is_singleton() {
11580                            buffer.push_transaction(&transaction.0, cx);
11581                        }
11582                    }
11583
11584                    cx.notify();
11585                })
11586                .ok();
11587
11588            Ok(())
11589        })
11590    }
11591
11592    fn restart_language_server(
11593        &mut self,
11594        _: &RestartLanguageServer,
11595        _: &mut Window,
11596        cx: &mut Context<Self>,
11597    ) {
11598        if let Some(project) = self.project.clone() {
11599            self.buffer.update(cx, |multi_buffer, cx| {
11600                project.update(cx, |project, cx| {
11601                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11602                });
11603            })
11604        }
11605    }
11606
11607    fn cancel_language_server_work(
11608        workspace: &mut Workspace,
11609        _: &actions::CancelLanguageServerWork,
11610        _: &mut Window,
11611        cx: &mut Context<Workspace>,
11612    ) {
11613        let project = workspace.project();
11614        let buffers = workspace
11615            .active_item(cx)
11616            .and_then(|item| item.act_as::<Editor>(cx))
11617            .map_or(HashSet::default(), |editor| {
11618                editor.read(cx).buffer.read(cx).all_buffers()
11619            });
11620        project.update(cx, |project, cx| {
11621            project.cancel_language_server_work_for_buffers(buffers, cx);
11622        });
11623    }
11624
11625    fn show_character_palette(
11626        &mut self,
11627        _: &ShowCharacterPalette,
11628        window: &mut Window,
11629        _: &mut Context<Self>,
11630    ) {
11631        window.show_character_palette();
11632    }
11633
11634    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11635        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11636            let buffer = self.buffer.read(cx).snapshot(cx);
11637            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11638            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11639            let is_valid = buffer
11640                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11641                .any(|entry| {
11642                    entry.diagnostic.is_primary
11643                        && !entry.range.is_empty()
11644                        && entry.range.start == primary_range_start
11645                        && entry.diagnostic.message == active_diagnostics.primary_message
11646                });
11647
11648            if is_valid != active_diagnostics.is_valid {
11649                active_diagnostics.is_valid = is_valid;
11650                let mut new_styles = HashMap::default();
11651                for (block_id, diagnostic) in &active_diagnostics.blocks {
11652                    new_styles.insert(
11653                        *block_id,
11654                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11655                    );
11656                }
11657                self.display_map.update(cx, |display_map, _cx| {
11658                    display_map.replace_blocks(new_styles)
11659                });
11660            }
11661        }
11662    }
11663
11664    fn activate_diagnostics(
11665        &mut self,
11666        buffer_id: BufferId,
11667        group_id: usize,
11668        window: &mut Window,
11669        cx: &mut Context<Self>,
11670    ) {
11671        self.dismiss_diagnostics(cx);
11672        let snapshot = self.snapshot(window, cx);
11673        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11674            let buffer = self.buffer.read(cx).snapshot(cx);
11675
11676            let mut primary_range = None;
11677            let mut primary_message = None;
11678            let diagnostic_group = buffer
11679                .diagnostic_group(buffer_id, group_id)
11680                .filter_map(|entry| {
11681                    let start = entry.range.start;
11682                    let end = entry.range.end;
11683                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11684                        && (start.row == end.row
11685                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11686                    {
11687                        return None;
11688                    }
11689                    if entry.diagnostic.is_primary {
11690                        primary_range = Some(entry.range.clone());
11691                        primary_message = Some(entry.diagnostic.message.clone());
11692                    }
11693                    Some(entry)
11694                })
11695                .collect::<Vec<_>>();
11696            let primary_range = primary_range?;
11697            let primary_message = primary_message?;
11698
11699            let blocks = display_map
11700                .insert_blocks(
11701                    diagnostic_group.iter().map(|entry| {
11702                        let diagnostic = entry.diagnostic.clone();
11703                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11704                        BlockProperties {
11705                            style: BlockStyle::Fixed,
11706                            placement: BlockPlacement::Below(
11707                                buffer.anchor_after(entry.range.start),
11708                            ),
11709                            height: message_height,
11710                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11711                            priority: 0,
11712                        }
11713                    }),
11714                    cx,
11715                )
11716                .into_iter()
11717                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11718                .collect();
11719
11720            Some(ActiveDiagnosticGroup {
11721                primary_range: buffer.anchor_before(primary_range.start)
11722                    ..buffer.anchor_after(primary_range.end),
11723                primary_message,
11724                group_id,
11725                blocks,
11726                is_valid: true,
11727            })
11728        });
11729    }
11730
11731    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11732        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11733            self.display_map.update(cx, |display_map, cx| {
11734                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11735            });
11736            cx.notify();
11737        }
11738    }
11739
11740    pub fn set_selections_from_remote(
11741        &mut self,
11742        selections: Vec<Selection<Anchor>>,
11743        pending_selection: Option<Selection<Anchor>>,
11744        window: &mut Window,
11745        cx: &mut Context<Self>,
11746    ) {
11747        let old_cursor_position = self.selections.newest_anchor().head();
11748        self.selections.change_with(cx, |s| {
11749            s.select_anchors(selections);
11750            if let Some(pending_selection) = pending_selection {
11751                s.set_pending(pending_selection, SelectMode::Character);
11752            } else {
11753                s.clear_pending();
11754            }
11755        });
11756        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11757    }
11758
11759    fn push_to_selection_history(&mut self) {
11760        self.selection_history.push(SelectionHistoryEntry {
11761            selections: self.selections.disjoint_anchors(),
11762            select_next_state: self.select_next_state.clone(),
11763            select_prev_state: self.select_prev_state.clone(),
11764            add_selections_state: self.add_selections_state.clone(),
11765        });
11766    }
11767
11768    pub fn transact(
11769        &mut self,
11770        window: &mut Window,
11771        cx: &mut Context<Self>,
11772        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11773    ) -> Option<TransactionId> {
11774        self.start_transaction_at(Instant::now(), window, cx);
11775        update(self, window, cx);
11776        self.end_transaction_at(Instant::now(), cx)
11777    }
11778
11779    pub fn start_transaction_at(
11780        &mut self,
11781        now: Instant,
11782        window: &mut Window,
11783        cx: &mut Context<Self>,
11784    ) {
11785        self.end_selection(window, cx);
11786        if let Some(tx_id) = self
11787            .buffer
11788            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11789        {
11790            self.selection_history
11791                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11792            cx.emit(EditorEvent::TransactionBegun {
11793                transaction_id: tx_id,
11794            })
11795        }
11796    }
11797
11798    pub fn end_transaction_at(
11799        &mut self,
11800        now: Instant,
11801        cx: &mut Context<Self>,
11802    ) -> Option<TransactionId> {
11803        if let Some(transaction_id) = self
11804            .buffer
11805            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11806        {
11807            if let Some((_, end_selections)) =
11808                self.selection_history.transaction_mut(transaction_id)
11809            {
11810                *end_selections = Some(self.selections.disjoint_anchors());
11811            } else {
11812                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11813            }
11814
11815            cx.emit(EditorEvent::Edited { transaction_id });
11816            Some(transaction_id)
11817        } else {
11818            None
11819        }
11820    }
11821
11822    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11823        if self.selection_mark_mode {
11824            self.change_selections(None, window, cx, |s| {
11825                s.move_with(|_, sel| {
11826                    sel.collapse_to(sel.head(), SelectionGoal::None);
11827                });
11828            })
11829        }
11830        self.selection_mark_mode = true;
11831        cx.notify();
11832    }
11833
11834    pub fn swap_selection_ends(
11835        &mut self,
11836        _: &actions::SwapSelectionEnds,
11837        window: &mut Window,
11838        cx: &mut Context<Self>,
11839    ) {
11840        self.change_selections(None, window, cx, |s| {
11841            s.move_with(|_, sel| {
11842                if sel.start != sel.end {
11843                    sel.reversed = !sel.reversed
11844                }
11845            });
11846        });
11847        self.request_autoscroll(Autoscroll::newest(), cx);
11848        cx.notify();
11849    }
11850
11851    pub fn toggle_fold(
11852        &mut self,
11853        _: &actions::ToggleFold,
11854        window: &mut Window,
11855        cx: &mut Context<Self>,
11856    ) {
11857        if self.is_singleton(cx) {
11858            let selection = self.selections.newest::<Point>(cx);
11859
11860            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11861            let range = if selection.is_empty() {
11862                let point = selection.head().to_display_point(&display_map);
11863                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11864                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11865                    .to_point(&display_map);
11866                start..end
11867            } else {
11868                selection.range()
11869            };
11870            if display_map.folds_in_range(range).next().is_some() {
11871                self.unfold_lines(&Default::default(), window, cx)
11872            } else {
11873                self.fold(&Default::default(), window, cx)
11874            }
11875        } else {
11876            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11877            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11878                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11879                .map(|(snapshot, _, _)| snapshot.remote_id())
11880                .collect();
11881
11882            for buffer_id in buffer_ids {
11883                if self.is_buffer_folded(buffer_id, cx) {
11884                    self.unfold_buffer(buffer_id, cx);
11885                } else {
11886                    self.fold_buffer(buffer_id, cx);
11887                }
11888            }
11889        }
11890    }
11891
11892    pub fn toggle_fold_recursive(
11893        &mut self,
11894        _: &actions::ToggleFoldRecursive,
11895        window: &mut Window,
11896        cx: &mut Context<Self>,
11897    ) {
11898        let selection = self.selections.newest::<Point>(cx);
11899
11900        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11901        let range = if selection.is_empty() {
11902            let point = selection.head().to_display_point(&display_map);
11903            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11904            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11905                .to_point(&display_map);
11906            start..end
11907        } else {
11908            selection.range()
11909        };
11910        if display_map.folds_in_range(range).next().is_some() {
11911            self.unfold_recursive(&Default::default(), window, cx)
11912        } else {
11913            self.fold_recursive(&Default::default(), window, cx)
11914        }
11915    }
11916
11917    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11918        if self.is_singleton(cx) {
11919            let mut to_fold = Vec::new();
11920            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11921            let selections = self.selections.all_adjusted(cx);
11922
11923            for selection in selections {
11924                let range = selection.range().sorted();
11925                let buffer_start_row = range.start.row;
11926
11927                if range.start.row != range.end.row {
11928                    let mut found = false;
11929                    let mut row = range.start.row;
11930                    while row <= range.end.row {
11931                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11932                        {
11933                            found = true;
11934                            row = crease.range().end.row + 1;
11935                            to_fold.push(crease);
11936                        } else {
11937                            row += 1
11938                        }
11939                    }
11940                    if found {
11941                        continue;
11942                    }
11943                }
11944
11945                for row in (0..=range.start.row).rev() {
11946                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11947                        if crease.range().end.row >= buffer_start_row {
11948                            to_fold.push(crease);
11949                            if row <= range.start.row {
11950                                break;
11951                            }
11952                        }
11953                    }
11954                }
11955            }
11956
11957            self.fold_creases(to_fold, true, window, cx);
11958        } else {
11959            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11960
11961            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11962                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11963                .map(|(snapshot, _, _)| snapshot.remote_id())
11964                .collect();
11965            for buffer_id in buffer_ids {
11966                self.fold_buffer(buffer_id, cx);
11967            }
11968        }
11969    }
11970
11971    fn fold_at_level(
11972        &mut self,
11973        fold_at: &FoldAtLevel,
11974        window: &mut Window,
11975        cx: &mut Context<Self>,
11976    ) {
11977        if !self.buffer.read(cx).is_singleton() {
11978            return;
11979        }
11980
11981        let fold_at_level = fold_at.0;
11982        let snapshot = self.buffer.read(cx).snapshot(cx);
11983        let mut to_fold = Vec::new();
11984        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11985
11986        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11987            while start_row < end_row {
11988                match self
11989                    .snapshot(window, cx)
11990                    .crease_for_buffer_row(MultiBufferRow(start_row))
11991                {
11992                    Some(crease) => {
11993                        let nested_start_row = crease.range().start.row + 1;
11994                        let nested_end_row = crease.range().end.row;
11995
11996                        if current_level < fold_at_level {
11997                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11998                        } else if current_level == fold_at_level {
11999                            to_fold.push(crease);
12000                        }
12001
12002                        start_row = nested_end_row + 1;
12003                    }
12004                    None => start_row += 1,
12005                }
12006            }
12007        }
12008
12009        self.fold_creases(to_fold, true, window, cx);
12010    }
12011
12012    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12013        if self.buffer.read(cx).is_singleton() {
12014            let mut fold_ranges = Vec::new();
12015            let snapshot = self.buffer.read(cx).snapshot(cx);
12016
12017            for row in 0..snapshot.max_row().0 {
12018                if let Some(foldable_range) = self
12019                    .snapshot(window, cx)
12020                    .crease_for_buffer_row(MultiBufferRow(row))
12021                {
12022                    fold_ranges.push(foldable_range);
12023                }
12024            }
12025
12026            self.fold_creases(fold_ranges, true, window, cx);
12027        } else {
12028            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12029                editor
12030                    .update_in(&mut cx, |editor, _, cx| {
12031                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12032                            editor.fold_buffer(buffer_id, cx);
12033                        }
12034                    })
12035                    .ok();
12036            });
12037        }
12038    }
12039
12040    pub fn fold_function_bodies(
12041        &mut self,
12042        _: &actions::FoldFunctionBodies,
12043        window: &mut Window,
12044        cx: &mut Context<Self>,
12045    ) {
12046        let snapshot = self.buffer.read(cx).snapshot(cx);
12047
12048        let ranges = snapshot
12049            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12050            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12051            .collect::<Vec<_>>();
12052
12053        let creases = ranges
12054            .into_iter()
12055            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12056            .collect();
12057
12058        self.fold_creases(creases, true, window, cx);
12059    }
12060
12061    pub fn fold_recursive(
12062        &mut self,
12063        _: &actions::FoldRecursive,
12064        window: &mut Window,
12065        cx: &mut Context<Self>,
12066    ) {
12067        let mut to_fold = Vec::new();
12068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12069        let selections = self.selections.all_adjusted(cx);
12070
12071        for selection in selections {
12072            let range = selection.range().sorted();
12073            let buffer_start_row = range.start.row;
12074
12075            if range.start.row != range.end.row {
12076                let mut found = false;
12077                for row in range.start.row..=range.end.row {
12078                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12079                        found = true;
12080                        to_fold.push(crease);
12081                    }
12082                }
12083                if found {
12084                    continue;
12085                }
12086            }
12087
12088            for row in (0..=range.start.row).rev() {
12089                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12090                    if crease.range().end.row >= buffer_start_row {
12091                        to_fold.push(crease);
12092                    } else {
12093                        break;
12094                    }
12095                }
12096            }
12097        }
12098
12099        self.fold_creases(to_fold, true, window, cx);
12100    }
12101
12102    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12103        let buffer_row = fold_at.buffer_row;
12104        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12105
12106        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12107            let autoscroll = self
12108                .selections
12109                .all::<Point>(cx)
12110                .iter()
12111                .any(|selection| crease.range().overlaps(&selection.range()));
12112
12113            self.fold_creases(vec![crease], autoscroll, window, cx);
12114        }
12115    }
12116
12117    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12118        if self.is_singleton(cx) {
12119            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12120            let buffer = &display_map.buffer_snapshot;
12121            let selections = self.selections.all::<Point>(cx);
12122            let ranges = selections
12123                .iter()
12124                .map(|s| {
12125                    let range = s.display_range(&display_map).sorted();
12126                    let mut start = range.start.to_point(&display_map);
12127                    let mut end = range.end.to_point(&display_map);
12128                    start.column = 0;
12129                    end.column = buffer.line_len(MultiBufferRow(end.row));
12130                    start..end
12131                })
12132                .collect::<Vec<_>>();
12133
12134            self.unfold_ranges(&ranges, true, true, cx);
12135        } else {
12136            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12137            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12138                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12139                .map(|(snapshot, _, _)| snapshot.remote_id())
12140                .collect();
12141            for buffer_id in buffer_ids {
12142                self.unfold_buffer(buffer_id, cx);
12143            }
12144        }
12145    }
12146
12147    pub fn unfold_recursive(
12148        &mut self,
12149        _: &UnfoldRecursive,
12150        _window: &mut Window,
12151        cx: &mut Context<Self>,
12152    ) {
12153        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12154        let selections = self.selections.all::<Point>(cx);
12155        let ranges = selections
12156            .iter()
12157            .map(|s| {
12158                let mut range = s.display_range(&display_map).sorted();
12159                *range.start.column_mut() = 0;
12160                *range.end.column_mut() = display_map.line_len(range.end.row());
12161                let start = range.start.to_point(&display_map);
12162                let end = range.end.to_point(&display_map);
12163                start..end
12164            })
12165            .collect::<Vec<_>>();
12166
12167        self.unfold_ranges(&ranges, true, true, cx);
12168    }
12169
12170    pub fn unfold_at(
12171        &mut self,
12172        unfold_at: &UnfoldAt,
12173        _window: &mut Window,
12174        cx: &mut Context<Self>,
12175    ) {
12176        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12177
12178        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12179            ..Point::new(
12180                unfold_at.buffer_row.0,
12181                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12182            );
12183
12184        let autoscroll = self
12185            .selections
12186            .all::<Point>(cx)
12187            .iter()
12188            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12189
12190        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12191    }
12192
12193    pub fn unfold_all(
12194        &mut self,
12195        _: &actions::UnfoldAll,
12196        _window: &mut Window,
12197        cx: &mut Context<Self>,
12198    ) {
12199        if self.buffer.read(cx).is_singleton() {
12200            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12201            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12202        } else {
12203            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12204                editor
12205                    .update(&mut cx, |editor, cx| {
12206                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12207                            editor.unfold_buffer(buffer_id, cx);
12208                        }
12209                    })
12210                    .ok();
12211            });
12212        }
12213    }
12214
12215    pub fn fold_selected_ranges(
12216        &mut self,
12217        _: &FoldSelectedRanges,
12218        window: &mut Window,
12219        cx: &mut Context<Self>,
12220    ) {
12221        let selections = self.selections.all::<Point>(cx);
12222        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12223        let line_mode = self.selections.line_mode;
12224        let ranges = selections
12225            .into_iter()
12226            .map(|s| {
12227                if line_mode {
12228                    let start = Point::new(s.start.row, 0);
12229                    let end = Point::new(
12230                        s.end.row,
12231                        display_map
12232                            .buffer_snapshot
12233                            .line_len(MultiBufferRow(s.end.row)),
12234                    );
12235                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12236                } else {
12237                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12238                }
12239            })
12240            .collect::<Vec<_>>();
12241        self.fold_creases(ranges, true, window, cx);
12242    }
12243
12244    pub fn fold_ranges<T: ToOffset + Clone>(
12245        &mut self,
12246        ranges: Vec<Range<T>>,
12247        auto_scroll: bool,
12248        window: &mut Window,
12249        cx: &mut Context<Self>,
12250    ) {
12251        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12252        let ranges = ranges
12253            .into_iter()
12254            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12255            .collect::<Vec<_>>();
12256        self.fold_creases(ranges, auto_scroll, window, cx);
12257    }
12258
12259    pub fn fold_creases<T: ToOffset + Clone>(
12260        &mut self,
12261        creases: Vec<Crease<T>>,
12262        auto_scroll: bool,
12263        window: &mut Window,
12264        cx: &mut Context<Self>,
12265    ) {
12266        if creases.is_empty() {
12267            return;
12268        }
12269
12270        let mut buffers_affected = HashSet::default();
12271        let multi_buffer = self.buffer().read(cx);
12272        for crease in &creases {
12273            if let Some((_, buffer, _)) =
12274                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12275            {
12276                buffers_affected.insert(buffer.read(cx).remote_id());
12277            };
12278        }
12279
12280        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12281
12282        if auto_scroll {
12283            self.request_autoscroll(Autoscroll::fit(), cx);
12284        }
12285
12286        cx.notify();
12287
12288        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12289            // Clear diagnostics block when folding a range that contains it.
12290            let snapshot = self.snapshot(window, cx);
12291            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12292                drop(snapshot);
12293                self.active_diagnostics = Some(active_diagnostics);
12294                self.dismiss_diagnostics(cx);
12295            } else {
12296                self.active_diagnostics = Some(active_diagnostics);
12297            }
12298        }
12299
12300        self.scrollbar_marker_state.dirty = true;
12301    }
12302
12303    /// Removes any folds whose ranges intersect any of the given ranges.
12304    pub fn unfold_ranges<T: ToOffset + Clone>(
12305        &mut self,
12306        ranges: &[Range<T>],
12307        inclusive: bool,
12308        auto_scroll: bool,
12309        cx: &mut Context<Self>,
12310    ) {
12311        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12312            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12313        });
12314    }
12315
12316    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12317        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12318            return;
12319        }
12320        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12321        self.display_map
12322            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12323        cx.emit(EditorEvent::BufferFoldToggled {
12324            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12325            folded: true,
12326        });
12327        cx.notify();
12328    }
12329
12330    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12331        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12332            return;
12333        }
12334        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12335        self.display_map.update(cx, |display_map, cx| {
12336            display_map.unfold_buffer(buffer_id, cx);
12337        });
12338        cx.emit(EditorEvent::BufferFoldToggled {
12339            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12340            folded: false,
12341        });
12342        cx.notify();
12343    }
12344
12345    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12346        self.display_map.read(cx).is_buffer_folded(buffer)
12347    }
12348
12349    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12350        self.display_map.read(cx).folded_buffers()
12351    }
12352
12353    /// Removes any folds with the given ranges.
12354    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12355        &mut self,
12356        ranges: &[Range<T>],
12357        type_id: TypeId,
12358        auto_scroll: bool,
12359        cx: &mut Context<Self>,
12360    ) {
12361        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12362            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12363        });
12364    }
12365
12366    fn remove_folds_with<T: ToOffset + Clone>(
12367        &mut self,
12368        ranges: &[Range<T>],
12369        auto_scroll: bool,
12370        cx: &mut Context<Self>,
12371        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12372    ) {
12373        if ranges.is_empty() {
12374            return;
12375        }
12376
12377        let mut buffers_affected = HashSet::default();
12378        let multi_buffer = self.buffer().read(cx);
12379        for range in ranges {
12380            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12381                buffers_affected.insert(buffer.read(cx).remote_id());
12382            };
12383        }
12384
12385        self.display_map.update(cx, update);
12386
12387        if auto_scroll {
12388            self.request_autoscroll(Autoscroll::fit(), cx);
12389        }
12390
12391        cx.notify();
12392        self.scrollbar_marker_state.dirty = true;
12393        self.active_indent_guides_state.dirty = true;
12394    }
12395
12396    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12397        self.display_map.read(cx).fold_placeholder.clone()
12398    }
12399
12400    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12401        self.buffer.update(cx, |buffer, cx| {
12402            buffer.set_all_diff_hunks_expanded(cx);
12403        });
12404    }
12405
12406    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12407        self.distinguish_unstaged_diff_hunks = true;
12408    }
12409
12410    pub fn expand_all_diff_hunks(
12411        &mut self,
12412        _: &ExpandAllHunkDiffs,
12413        _window: &mut Window,
12414        cx: &mut Context<Self>,
12415    ) {
12416        self.buffer.update(cx, |buffer, cx| {
12417            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12418        });
12419    }
12420
12421    pub fn toggle_selected_diff_hunks(
12422        &mut self,
12423        _: &ToggleSelectedDiffHunks,
12424        _window: &mut Window,
12425        cx: &mut Context<Self>,
12426    ) {
12427        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12428        self.toggle_diff_hunks_in_ranges(ranges, cx);
12429    }
12430
12431    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12432        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12433        self.buffer
12434            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12435    }
12436
12437    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12438        self.buffer.update(cx, |buffer, cx| {
12439            let ranges = vec![Anchor::min()..Anchor::max()];
12440            if !buffer.all_diff_hunks_expanded()
12441                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12442            {
12443                buffer.collapse_diff_hunks(ranges, cx);
12444                true
12445            } else {
12446                false
12447            }
12448        })
12449    }
12450
12451    fn toggle_diff_hunks_in_ranges(
12452        &mut self,
12453        ranges: Vec<Range<Anchor>>,
12454        cx: &mut Context<'_, Editor>,
12455    ) {
12456        self.buffer.update(cx, |buffer, cx| {
12457            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12458            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12459        })
12460    }
12461
12462    fn toggle_diff_hunks_in_ranges_narrow(
12463        &mut self,
12464        ranges: Vec<Range<Anchor>>,
12465        cx: &mut Context<'_, Editor>,
12466    ) {
12467        self.buffer.update(cx, |buffer, cx| {
12468            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12469            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12470        })
12471    }
12472
12473    pub(crate) fn apply_all_diff_hunks(
12474        &mut self,
12475        _: &ApplyAllDiffHunks,
12476        window: &mut Window,
12477        cx: &mut Context<Self>,
12478    ) {
12479        let buffers = self.buffer.read(cx).all_buffers();
12480        for branch_buffer in buffers {
12481            branch_buffer.update(cx, |branch_buffer, cx| {
12482                branch_buffer.merge_into_base(Vec::new(), cx);
12483            });
12484        }
12485
12486        if let Some(project) = self.project.clone() {
12487            self.save(true, project, window, cx).detach_and_log_err(cx);
12488        }
12489    }
12490
12491    pub(crate) fn apply_selected_diff_hunks(
12492        &mut self,
12493        _: &ApplyDiffHunk,
12494        window: &mut Window,
12495        cx: &mut Context<Self>,
12496    ) {
12497        let snapshot = self.snapshot(window, cx);
12498        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12499        let mut ranges_by_buffer = HashMap::default();
12500        self.transact(window, cx, |editor, _window, cx| {
12501            for hunk in hunks {
12502                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12503                    ranges_by_buffer
12504                        .entry(buffer.clone())
12505                        .or_insert_with(Vec::new)
12506                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12507                }
12508            }
12509
12510            for (buffer, ranges) in ranges_by_buffer {
12511                buffer.update(cx, |buffer, cx| {
12512                    buffer.merge_into_base(ranges, cx);
12513                });
12514            }
12515        });
12516
12517        if let Some(project) = self.project.clone() {
12518            self.save(true, project, window, cx).detach_and_log_err(cx);
12519        }
12520    }
12521
12522    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12523        if hovered != self.gutter_hovered {
12524            self.gutter_hovered = hovered;
12525            cx.notify();
12526        }
12527    }
12528
12529    pub fn insert_blocks(
12530        &mut self,
12531        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12532        autoscroll: Option<Autoscroll>,
12533        cx: &mut Context<Self>,
12534    ) -> Vec<CustomBlockId> {
12535        let blocks = self
12536            .display_map
12537            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12538        if let Some(autoscroll) = autoscroll {
12539            self.request_autoscroll(autoscroll, cx);
12540        }
12541        cx.notify();
12542        blocks
12543    }
12544
12545    pub fn resize_blocks(
12546        &mut self,
12547        heights: HashMap<CustomBlockId, u32>,
12548        autoscroll: Option<Autoscroll>,
12549        cx: &mut Context<Self>,
12550    ) {
12551        self.display_map
12552            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12553        if let Some(autoscroll) = autoscroll {
12554            self.request_autoscroll(autoscroll, cx);
12555        }
12556        cx.notify();
12557    }
12558
12559    pub fn replace_blocks(
12560        &mut self,
12561        renderers: HashMap<CustomBlockId, RenderBlock>,
12562        autoscroll: Option<Autoscroll>,
12563        cx: &mut Context<Self>,
12564    ) {
12565        self.display_map
12566            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12567        if let Some(autoscroll) = autoscroll {
12568            self.request_autoscroll(autoscroll, cx);
12569        }
12570        cx.notify();
12571    }
12572
12573    pub fn remove_blocks(
12574        &mut self,
12575        block_ids: HashSet<CustomBlockId>,
12576        autoscroll: Option<Autoscroll>,
12577        cx: &mut Context<Self>,
12578    ) {
12579        self.display_map.update(cx, |display_map, cx| {
12580            display_map.remove_blocks(block_ids, cx)
12581        });
12582        if let Some(autoscroll) = autoscroll {
12583            self.request_autoscroll(autoscroll, cx);
12584        }
12585        cx.notify();
12586    }
12587
12588    pub fn row_for_block(
12589        &self,
12590        block_id: CustomBlockId,
12591        cx: &mut Context<Self>,
12592    ) -> Option<DisplayRow> {
12593        self.display_map
12594            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12595    }
12596
12597    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12598        self.focused_block = Some(focused_block);
12599    }
12600
12601    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12602        self.focused_block.take()
12603    }
12604
12605    pub fn insert_creases(
12606        &mut self,
12607        creases: impl IntoIterator<Item = Crease<Anchor>>,
12608        cx: &mut Context<Self>,
12609    ) -> Vec<CreaseId> {
12610        self.display_map
12611            .update(cx, |map, cx| map.insert_creases(creases, cx))
12612    }
12613
12614    pub fn remove_creases(
12615        &mut self,
12616        ids: impl IntoIterator<Item = CreaseId>,
12617        cx: &mut Context<Self>,
12618    ) {
12619        self.display_map
12620            .update(cx, |map, cx| map.remove_creases(ids, cx));
12621    }
12622
12623    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12624        self.display_map
12625            .update(cx, |map, cx| map.snapshot(cx))
12626            .longest_row()
12627    }
12628
12629    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12630        self.display_map
12631            .update(cx, |map, cx| map.snapshot(cx))
12632            .max_point()
12633    }
12634
12635    pub fn text(&self, cx: &App) -> String {
12636        self.buffer.read(cx).read(cx).text()
12637    }
12638
12639    pub fn is_empty(&self, cx: &App) -> bool {
12640        self.buffer.read(cx).read(cx).is_empty()
12641    }
12642
12643    pub fn text_option(&self, cx: &App) -> Option<String> {
12644        let text = self.text(cx);
12645        let text = text.trim();
12646
12647        if text.is_empty() {
12648            return None;
12649        }
12650
12651        Some(text.to_string())
12652    }
12653
12654    pub fn set_text(
12655        &mut self,
12656        text: impl Into<Arc<str>>,
12657        window: &mut Window,
12658        cx: &mut Context<Self>,
12659    ) {
12660        self.transact(window, cx, |this, _, cx| {
12661            this.buffer
12662                .read(cx)
12663                .as_singleton()
12664                .expect("you can only call set_text on editors for singleton buffers")
12665                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12666        });
12667    }
12668
12669    pub fn display_text(&self, cx: &mut App) -> String {
12670        self.display_map
12671            .update(cx, |map, cx| map.snapshot(cx))
12672            .text()
12673    }
12674
12675    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12676        let mut wrap_guides = smallvec::smallvec![];
12677
12678        if self.show_wrap_guides == Some(false) {
12679            return wrap_guides;
12680        }
12681
12682        let settings = self.buffer.read(cx).settings_at(0, cx);
12683        if settings.show_wrap_guides {
12684            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12685                wrap_guides.push((soft_wrap as usize, true));
12686            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12687                wrap_guides.push((soft_wrap as usize, true));
12688            }
12689            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12690        }
12691
12692        wrap_guides
12693    }
12694
12695    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12696        let settings = self.buffer.read(cx).settings_at(0, cx);
12697        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12698        match mode {
12699            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12700                SoftWrap::None
12701            }
12702            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12703            language_settings::SoftWrap::PreferredLineLength => {
12704                SoftWrap::Column(settings.preferred_line_length)
12705            }
12706            language_settings::SoftWrap::Bounded => {
12707                SoftWrap::Bounded(settings.preferred_line_length)
12708            }
12709        }
12710    }
12711
12712    pub fn set_soft_wrap_mode(
12713        &mut self,
12714        mode: language_settings::SoftWrap,
12715
12716        cx: &mut Context<Self>,
12717    ) {
12718        self.soft_wrap_mode_override = Some(mode);
12719        cx.notify();
12720    }
12721
12722    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12723        self.text_style_refinement = Some(style);
12724    }
12725
12726    /// called by the Element so we know what style we were most recently rendered with.
12727    pub(crate) fn set_style(
12728        &mut self,
12729        style: EditorStyle,
12730        window: &mut Window,
12731        cx: &mut Context<Self>,
12732    ) {
12733        let rem_size = window.rem_size();
12734        self.display_map.update(cx, |map, cx| {
12735            map.set_font(
12736                style.text.font(),
12737                style.text.font_size.to_pixels(rem_size),
12738                cx,
12739            )
12740        });
12741        self.style = Some(style);
12742    }
12743
12744    pub fn style(&self) -> Option<&EditorStyle> {
12745        self.style.as_ref()
12746    }
12747
12748    // Called by the element. This method is not designed to be called outside of the editor
12749    // element's layout code because it does not notify when rewrapping is computed synchronously.
12750    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12751        self.display_map
12752            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12753    }
12754
12755    pub fn set_soft_wrap(&mut self) {
12756        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12757    }
12758
12759    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12760        if self.soft_wrap_mode_override.is_some() {
12761            self.soft_wrap_mode_override.take();
12762        } else {
12763            let soft_wrap = match self.soft_wrap_mode(cx) {
12764                SoftWrap::GitDiff => return,
12765                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12766                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12767                    language_settings::SoftWrap::None
12768                }
12769            };
12770            self.soft_wrap_mode_override = Some(soft_wrap);
12771        }
12772        cx.notify();
12773    }
12774
12775    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12776        let Some(workspace) = self.workspace() else {
12777            return;
12778        };
12779        let fs = workspace.read(cx).app_state().fs.clone();
12780        let current_show = TabBarSettings::get_global(cx).show;
12781        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12782            setting.show = Some(!current_show);
12783        });
12784    }
12785
12786    pub fn toggle_indent_guides(
12787        &mut self,
12788        _: &ToggleIndentGuides,
12789        _: &mut Window,
12790        cx: &mut Context<Self>,
12791    ) {
12792        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12793            self.buffer
12794                .read(cx)
12795                .settings_at(0, cx)
12796                .indent_guides
12797                .enabled
12798        });
12799        self.show_indent_guides = Some(!currently_enabled);
12800        cx.notify();
12801    }
12802
12803    fn should_show_indent_guides(&self) -> Option<bool> {
12804        self.show_indent_guides
12805    }
12806
12807    pub fn toggle_line_numbers(
12808        &mut self,
12809        _: &ToggleLineNumbers,
12810        _: &mut Window,
12811        cx: &mut Context<Self>,
12812    ) {
12813        let mut editor_settings = EditorSettings::get_global(cx).clone();
12814        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12815        EditorSettings::override_global(editor_settings, cx);
12816    }
12817
12818    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12819        self.use_relative_line_numbers
12820            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12821    }
12822
12823    pub fn toggle_relative_line_numbers(
12824        &mut self,
12825        _: &ToggleRelativeLineNumbers,
12826        _: &mut Window,
12827        cx: &mut Context<Self>,
12828    ) {
12829        let is_relative = self.should_use_relative_line_numbers(cx);
12830        self.set_relative_line_number(Some(!is_relative), cx)
12831    }
12832
12833    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12834        self.use_relative_line_numbers = is_relative;
12835        cx.notify();
12836    }
12837
12838    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12839        self.show_gutter = show_gutter;
12840        cx.notify();
12841    }
12842
12843    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12844        self.show_scrollbars = show_scrollbars;
12845        cx.notify();
12846    }
12847
12848    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12849        self.show_line_numbers = Some(show_line_numbers);
12850        cx.notify();
12851    }
12852
12853    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12854        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12855        cx.notify();
12856    }
12857
12858    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12859        self.show_code_actions = Some(show_code_actions);
12860        cx.notify();
12861    }
12862
12863    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12864        self.show_runnables = Some(show_runnables);
12865        cx.notify();
12866    }
12867
12868    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12869        if self.display_map.read(cx).masked != masked {
12870            self.display_map.update(cx, |map, _| map.masked = masked);
12871        }
12872        cx.notify()
12873    }
12874
12875    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12876        self.show_wrap_guides = Some(show_wrap_guides);
12877        cx.notify();
12878    }
12879
12880    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12881        self.show_indent_guides = Some(show_indent_guides);
12882        cx.notify();
12883    }
12884
12885    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12886        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12887            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12888                if let Some(dir) = file.abs_path(cx).parent() {
12889                    return Some(dir.to_owned());
12890                }
12891            }
12892
12893            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12894                return Some(project_path.path.to_path_buf());
12895            }
12896        }
12897
12898        None
12899    }
12900
12901    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12902        self.active_excerpt(cx)?
12903            .1
12904            .read(cx)
12905            .file()
12906            .and_then(|f| f.as_local())
12907    }
12908
12909    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12910        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12911            let buffer = buffer.read(cx);
12912            if let Some(project_path) = buffer.project_path(cx) {
12913                let project = self.project.as_ref()?.read(cx);
12914                project.absolute_path(&project_path, cx)
12915            } else {
12916                buffer
12917                    .file()
12918                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
12919            }
12920        })
12921    }
12922
12923    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12924        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12925            let project_path = buffer.read(cx).project_path(cx)?;
12926            let project = self.project.as_ref()?.read(cx);
12927            let entry = project.entry_for_path(&project_path, cx)?;
12928            let path = entry.path.to_path_buf();
12929            Some(path)
12930        })
12931    }
12932
12933    pub fn reveal_in_finder(
12934        &mut self,
12935        _: &RevealInFileManager,
12936        _window: &mut Window,
12937        cx: &mut Context<Self>,
12938    ) {
12939        if let Some(target) = self.target_file(cx) {
12940            cx.reveal_path(&target.abs_path(cx));
12941        }
12942    }
12943
12944    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12945        if let Some(path) = self.target_file_abs_path(cx) {
12946            if let Some(path) = path.to_str() {
12947                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12948            }
12949        }
12950    }
12951
12952    pub fn copy_relative_path(
12953        &mut self,
12954        _: &CopyRelativePath,
12955        _window: &mut Window,
12956        cx: &mut Context<Self>,
12957    ) {
12958        if let Some(path) = self.target_file_path(cx) {
12959            if let Some(path) = path.to_str() {
12960                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12961            }
12962        }
12963    }
12964
12965    pub fn copy_file_name_without_extension(
12966        &mut self,
12967        _: &CopyFileNameWithoutExtension,
12968        _: &mut Window,
12969        cx: &mut Context<Self>,
12970    ) {
12971        if let Some(file) = self.target_file(cx) {
12972            if let Some(file_stem) = file.path().file_stem() {
12973                if let Some(name) = file_stem.to_str() {
12974                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12975                }
12976            }
12977        }
12978    }
12979
12980    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
12981        if let Some(file) = self.target_file(cx) {
12982            if let Some(file_name) = file.path().file_name() {
12983                if let Some(name) = file_name.to_str() {
12984                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12985                }
12986            }
12987        }
12988    }
12989
12990    pub fn toggle_git_blame(
12991        &mut self,
12992        _: &ToggleGitBlame,
12993        window: &mut Window,
12994        cx: &mut Context<Self>,
12995    ) {
12996        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12997
12998        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12999            self.start_git_blame(true, window, cx);
13000        }
13001
13002        cx.notify();
13003    }
13004
13005    pub fn toggle_git_blame_inline(
13006        &mut self,
13007        _: &ToggleGitBlameInline,
13008        window: &mut Window,
13009        cx: &mut Context<Self>,
13010    ) {
13011        self.toggle_git_blame_inline_internal(true, window, cx);
13012        cx.notify();
13013    }
13014
13015    pub fn git_blame_inline_enabled(&self) -> bool {
13016        self.git_blame_inline_enabled
13017    }
13018
13019    pub fn toggle_selection_menu(
13020        &mut self,
13021        _: &ToggleSelectionMenu,
13022        _: &mut Window,
13023        cx: &mut Context<Self>,
13024    ) {
13025        self.show_selection_menu = self
13026            .show_selection_menu
13027            .map(|show_selections_menu| !show_selections_menu)
13028            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13029
13030        cx.notify();
13031    }
13032
13033    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13034        self.show_selection_menu
13035            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13036    }
13037
13038    fn start_git_blame(
13039        &mut self,
13040        user_triggered: bool,
13041        window: &mut Window,
13042        cx: &mut Context<Self>,
13043    ) {
13044        if let Some(project) = self.project.as_ref() {
13045            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13046                return;
13047            };
13048
13049            if buffer.read(cx).file().is_none() {
13050                return;
13051            }
13052
13053            let focused = self.focus_handle(cx).contains_focused(window, cx);
13054
13055            let project = project.clone();
13056            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13057            self.blame_subscription =
13058                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13059            self.blame = Some(blame);
13060        }
13061    }
13062
13063    fn toggle_git_blame_inline_internal(
13064        &mut self,
13065        user_triggered: bool,
13066        window: &mut Window,
13067        cx: &mut Context<Self>,
13068    ) {
13069        if self.git_blame_inline_enabled {
13070            self.git_blame_inline_enabled = false;
13071            self.show_git_blame_inline = false;
13072            self.show_git_blame_inline_delay_task.take();
13073        } else {
13074            self.git_blame_inline_enabled = true;
13075            self.start_git_blame_inline(user_triggered, window, cx);
13076        }
13077
13078        cx.notify();
13079    }
13080
13081    fn start_git_blame_inline(
13082        &mut self,
13083        user_triggered: bool,
13084        window: &mut Window,
13085        cx: &mut Context<Self>,
13086    ) {
13087        self.start_git_blame(user_triggered, window, cx);
13088
13089        if ProjectSettings::get_global(cx)
13090            .git
13091            .inline_blame_delay()
13092            .is_some()
13093        {
13094            self.start_inline_blame_timer(window, cx);
13095        } else {
13096            self.show_git_blame_inline = true
13097        }
13098    }
13099
13100    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13101        self.blame.as_ref()
13102    }
13103
13104    pub fn show_git_blame_gutter(&self) -> bool {
13105        self.show_git_blame_gutter
13106    }
13107
13108    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13109        self.show_git_blame_gutter && self.has_blame_entries(cx)
13110    }
13111
13112    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13113        self.show_git_blame_inline
13114            && self.focus_handle.is_focused(window)
13115            && !self.newest_selection_head_on_empty_line(cx)
13116            && self.has_blame_entries(cx)
13117    }
13118
13119    fn has_blame_entries(&self, cx: &App) -> bool {
13120        self.blame()
13121            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13122    }
13123
13124    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13125        let cursor_anchor = self.selections.newest_anchor().head();
13126
13127        let snapshot = self.buffer.read(cx).snapshot(cx);
13128        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13129
13130        snapshot.line_len(buffer_row) == 0
13131    }
13132
13133    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13134        let buffer_and_selection = maybe!({
13135            let selection = self.selections.newest::<Point>(cx);
13136            let selection_range = selection.range();
13137
13138            let multi_buffer = self.buffer().read(cx);
13139            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13140            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13141
13142            let (buffer, range, _) = if selection.reversed {
13143                buffer_ranges.first()
13144            } else {
13145                buffer_ranges.last()
13146            }?;
13147
13148            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13149                ..text::ToPoint::to_point(&range.end, &buffer).row;
13150            Some((
13151                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13152                selection,
13153            ))
13154        });
13155
13156        let Some((buffer, selection)) = buffer_and_selection else {
13157            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13158        };
13159
13160        let Some(project) = self.project.as_ref() else {
13161            return Task::ready(Err(anyhow!("editor does not have project")));
13162        };
13163
13164        project.update(cx, |project, cx| {
13165            project.get_permalink_to_line(&buffer, selection, cx)
13166        })
13167    }
13168
13169    pub fn copy_permalink_to_line(
13170        &mut self,
13171        _: &CopyPermalinkToLine,
13172        window: &mut Window,
13173        cx: &mut Context<Self>,
13174    ) {
13175        let permalink_task = self.get_permalink_to_line(cx);
13176        let workspace = self.workspace();
13177
13178        cx.spawn_in(window, |_, mut cx| async move {
13179            match permalink_task.await {
13180                Ok(permalink) => {
13181                    cx.update(|_, cx| {
13182                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13183                    })
13184                    .ok();
13185                }
13186                Err(err) => {
13187                    let message = format!("Failed to copy permalink: {err}");
13188
13189                    Err::<(), anyhow::Error>(err).log_err();
13190
13191                    if let Some(workspace) = workspace {
13192                        workspace
13193                            .update_in(&mut cx, |workspace, _, cx| {
13194                                struct CopyPermalinkToLine;
13195
13196                                workspace.show_toast(
13197                                    Toast::new(
13198                                        NotificationId::unique::<CopyPermalinkToLine>(),
13199                                        message,
13200                                    ),
13201                                    cx,
13202                                )
13203                            })
13204                            .ok();
13205                    }
13206                }
13207            }
13208        })
13209        .detach();
13210    }
13211
13212    pub fn copy_file_location(
13213        &mut self,
13214        _: &CopyFileLocation,
13215        _: &mut Window,
13216        cx: &mut Context<Self>,
13217    ) {
13218        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13219        if let Some(file) = self.target_file(cx) {
13220            if let Some(path) = file.path().to_str() {
13221                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13222            }
13223        }
13224    }
13225
13226    pub fn open_permalink_to_line(
13227        &mut self,
13228        _: &OpenPermalinkToLine,
13229        window: &mut Window,
13230        cx: &mut Context<Self>,
13231    ) {
13232        let permalink_task = self.get_permalink_to_line(cx);
13233        let workspace = self.workspace();
13234
13235        cx.spawn_in(window, |_, mut cx| async move {
13236            match permalink_task.await {
13237                Ok(permalink) => {
13238                    cx.update(|_, cx| {
13239                        cx.open_url(permalink.as_ref());
13240                    })
13241                    .ok();
13242                }
13243                Err(err) => {
13244                    let message = format!("Failed to open permalink: {err}");
13245
13246                    Err::<(), anyhow::Error>(err).log_err();
13247
13248                    if let Some(workspace) = workspace {
13249                        workspace
13250                            .update(&mut cx, |workspace, cx| {
13251                                struct OpenPermalinkToLine;
13252
13253                                workspace.show_toast(
13254                                    Toast::new(
13255                                        NotificationId::unique::<OpenPermalinkToLine>(),
13256                                        message,
13257                                    ),
13258                                    cx,
13259                                )
13260                            })
13261                            .ok();
13262                    }
13263                }
13264            }
13265        })
13266        .detach();
13267    }
13268
13269    pub fn insert_uuid_v4(
13270        &mut self,
13271        _: &InsertUuidV4,
13272        window: &mut Window,
13273        cx: &mut Context<Self>,
13274    ) {
13275        self.insert_uuid(UuidVersion::V4, window, cx);
13276    }
13277
13278    pub fn insert_uuid_v7(
13279        &mut self,
13280        _: &InsertUuidV7,
13281        window: &mut Window,
13282        cx: &mut Context<Self>,
13283    ) {
13284        self.insert_uuid(UuidVersion::V7, window, cx);
13285    }
13286
13287    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13288        self.transact(window, cx, |this, window, cx| {
13289            let edits = this
13290                .selections
13291                .all::<Point>(cx)
13292                .into_iter()
13293                .map(|selection| {
13294                    let uuid = match version {
13295                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13296                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13297                    };
13298
13299                    (selection.range(), uuid.to_string())
13300                });
13301            this.edit(edits, cx);
13302            this.refresh_inline_completion(true, false, window, cx);
13303        });
13304    }
13305
13306    pub fn open_selections_in_multibuffer(
13307        &mut self,
13308        _: &OpenSelectionsInMultibuffer,
13309        window: &mut Window,
13310        cx: &mut Context<Self>,
13311    ) {
13312        let multibuffer = self.buffer.read(cx);
13313
13314        let Some(buffer) = multibuffer.as_singleton() else {
13315            return;
13316        };
13317
13318        let Some(workspace) = self.workspace() else {
13319            return;
13320        };
13321
13322        let locations = self
13323            .selections
13324            .disjoint_anchors()
13325            .iter()
13326            .map(|range| Location {
13327                buffer: buffer.clone(),
13328                range: range.start.text_anchor..range.end.text_anchor,
13329            })
13330            .collect::<Vec<_>>();
13331
13332        let title = multibuffer.title(cx).to_string();
13333
13334        cx.spawn_in(window, |_, mut cx| async move {
13335            workspace.update_in(&mut cx, |workspace, window, cx| {
13336                Self::open_locations_in_multibuffer(
13337                    workspace,
13338                    locations,
13339                    format!("Selections for '{title}'"),
13340                    false,
13341                    MultibufferSelectionMode::All,
13342                    window,
13343                    cx,
13344                );
13345            })
13346        })
13347        .detach();
13348    }
13349
13350    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13351    /// last highlight added will be used.
13352    ///
13353    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13354    pub fn highlight_rows<T: 'static>(
13355        &mut self,
13356        range: Range<Anchor>,
13357        color: Hsla,
13358        should_autoscroll: bool,
13359        cx: &mut Context<Self>,
13360    ) {
13361        let snapshot = self.buffer().read(cx).snapshot(cx);
13362        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13363        let ix = row_highlights.binary_search_by(|highlight| {
13364            Ordering::Equal
13365                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13366                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13367        });
13368
13369        if let Err(mut ix) = ix {
13370            let index = post_inc(&mut self.highlight_order);
13371
13372            // If this range intersects with the preceding highlight, then merge it with
13373            // the preceding highlight. Otherwise insert a new highlight.
13374            let mut merged = false;
13375            if ix > 0 {
13376                let prev_highlight = &mut row_highlights[ix - 1];
13377                if prev_highlight
13378                    .range
13379                    .end
13380                    .cmp(&range.start, &snapshot)
13381                    .is_ge()
13382                {
13383                    ix -= 1;
13384                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13385                        prev_highlight.range.end = range.end;
13386                    }
13387                    merged = true;
13388                    prev_highlight.index = index;
13389                    prev_highlight.color = color;
13390                    prev_highlight.should_autoscroll = should_autoscroll;
13391                }
13392            }
13393
13394            if !merged {
13395                row_highlights.insert(
13396                    ix,
13397                    RowHighlight {
13398                        range: range.clone(),
13399                        index,
13400                        color,
13401                        should_autoscroll,
13402                    },
13403                );
13404            }
13405
13406            // If any of the following highlights intersect with this one, merge them.
13407            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13408                let highlight = &row_highlights[ix];
13409                if next_highlight
13410                    .range
13411                    .start
13412                    .cmp(&highlight.range.end, &snapshot)
13413                    .is_le()
13414                {
13415                    if next_highlight
13416                        .range
13417                        .end
13418                        .cmp(&highlight.range.end, &snapshot)
13419                        .is_gt()
13420                    {
13421                        row_highlights[ix].range.end = next_highlight.range.end;
13422                    }
13423                    row_highlights.remove(ix + 1);
13424                } else {
13425                    break;
13426                }
13427            }
13428        }
13429    }
13430
13431    /// Remove any highlighted row ranges of the given type that intersect the
13432    /// given ranges.
13433    pub fn remove_highlighted_rows<T: 'static>(
13434        &mut self,
13435        ranges_to_remove: Vec<Range<Anchor>>,
13436        cx: &mut Context<Self>,
13437    ) {
13438        let snapshot = self.buffer().read(cx).snapshot(cx);
13439        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13440        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13441        row_highlights.retain(|highlight| {
13442            while let Some(range_to_remove) = ranges_to_remove.peek() {
13443                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13444                    Ordering::Less | Ordering::Equal => {
13445                        ranges_to_remove.next();
13446                    }
13447                    Ordering::Greater => {
13448                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13449                            Ordering::Less | Ordering::Equal => {
13450                                return false;
13451                            }
13452                            Ordering::Greater => break,
13453                        }
13454                    }
13455                }
13456            }
13457
13458            true
13459        })
13460    }
13461
13462    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13463    pub fn clear_row_highlights<T: 'static>(&mut self) {
13464        self.highlighted_rows.remove(&TypeId::of::<T>());
13465    }
13466
13467    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13468    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13469        self.highlighted_rows
13470            .get(&TypeId::of::<T>())
13471            .map_or(&[] as &[_], |vec| vec.as_slice())
13472            .iter()
13473            .map(|highlight| (highlight.range.clone(), highlight.color))
13474    }
13475
13476    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13477    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13478    /// Allows to ignore certain kinds of highlights.
13479    pub fn highlighted_display_rows(
13480        &self,
13481        window: &mut Window,
13482        cx: &mut App,
13483    ) -> BTreeMap<DisplayRow, Background> {
13484        let snapshot = self.snapshot(window, cx);
13485        let mut used_highlight_orders = HashMap::default();
13486        self.highlighted_rows
13487            .iter()
13488            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13489            .fold(
13490                BTreeMap::<DisplayRow, Background>::new(),
13491                |mut unique_rows, highlight| {
13492                    let start = highlight.range.start.to_display_point(&snapshot);
13493                    let end = highlight.range.end.to_display_point(&snapshot);
13494                    let start_row = start.row().0;
13495                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13496                        && end.column() == 0
13497                    {
13498                        end.row().0.saturating_sub(1)
13499                    } else {
13500                        end.row().0
13501                    };
13502                    for row in start_row..=end_row {
13503                        let used_index =
13504                            used_highlight_orders.entry(row).or_insert(highlight.index);
13505                        if highlight.index >= *used_index {
13506                            *used_index = highlight.index;
13507                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13508                        }
13509                    }
13510                    unique_rows
13511                },
13512            )
13513    }
13514
13515    pub fn highlighted_display_row_for_autoscroll(
13516        &self,
13517        snapshot: &DisplaySnapshot,
13518    ) -> Option<DisplayRow> {
13519        self.highlighted_rows
13520            .values()
13521            .flat_map(|highlighted_rows| highlighted_rows.iter())
13522            .filter_map(|highlight| {
13523                if highlight.should_autoscroll {
13524                    Some(highlight.range.start.to_display_point(snapshot).row())
13525                } else {
13526                    None
13527                }
13528            })
13529            .min()
13530    }
13531
13532    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13533        self.highlight_background::<SearchWithinRange>(
13534            ranges,
13535            |colors| colors.editor_document_highlight_read_background,
13536            cx,
13537        )
13538    }
13539
13540    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13541        self.breadcrumb_header = Some(new_header);
13542    }
13543
13544    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13545        self.clear_background_highlights::<SearchWithinRange>(cx);
13546    }
13547
13548    pub fn highlight_background<T: 'static>(
13549        &mut self,
13550        ranges: &[Range<Anchor>],
13551        color_fetcher: fn(&ThemeColors) -> Hsla,
13552        cx: &mut Context<Self>,
13553    ) {
13554        self.background_highlights
13555            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13556        self.scrollbar_marker_state.dirty = true;
13557        cx.notify();
13558    }
13559
13560    pub fn clear_background_highlights<T: 'static>(
13561        &mut self,
13562        cx: &mut Context<Self>,
13563    ) -> Option<BackgroundHighlight> {
13564        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13565        if !text_highlights.1.is_empty() {
13566            self.scrollbar_marker_state.dirty = true;
13567            cx.notify();
13568        }
13569        Some(text_highlights)
13570    }
13571
13572    pub fn highlight_gutter<T: 'static>(
13573        &mut self,
13574        ranges: &[Range<Anchor>],
13575        color_fetcher: fn(&App) -> Hsla,
13576        cx: &mut Context<Self>,
13577    ) {
13578        self.gutter_highlights
13579            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13580        cx.notify();
13581    }
13582
13583    pub fn clear_gutter_highlights<T: 'static>(
13584        &mut self,
13585        cx: &mut Context<Self>,
13586    ) -> Option<GutterHighlight> {
13587        cx.notify();
13588        self.gutter_highlights.remove(&TypeId::of::<T>())
13589    }
13590
13591    #[cfg(feature = "test-support")]
13592    pub fn all_text_background_highlights(
13593        &self,
13594        window: &mut Window,
13595        cx: &mut Context<Self>,
13596    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13597        let snapshot = self.snapshot(window, cx);
13598        let buffer = &snapshot.buffer_snapshot;
13599        let start = buffer.anchor_before(0);
13600        let end = buffer.anchor_after(buffer.len());
13601        let theme = cx.theme().colors();
13602        self.background_highlights_in_range(start..end, &snapshot, theme)
13603    }
13604
13605    #[cfg(feature = "test-support")]
13606    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13607        let snapshot = self.buffer().read(cx).snapshot(cx);
13608
13609        let highlights = self
13610            .background_highlights
13611            .get(&TypeId::of::<items::BufferSearchHighlights>());
13612
13613        if let Some((_color, ranges)) = highlights {
13614            ranges
13615                .iter()
13616                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13617                .collect_vec()
13618        } else {
13619            vec![]
13620        }
13621    }
13622
13623    fn document_highlights_for_position<'a>(
13624        &'a self,
13625        position: Anchor,
13626        buffer: &'a MultiBufferSnapshot,
13627    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13628        let read_highlights = self
13629            .background_highlights
13630            .get(&TypeId::of::<DocumentHighlightRead>())
13631            .map(|h| &h.1);
13632        let write_highlights = self
13633            .background_highlights
13634            .get(&TypeId::of::<DocumentHighlightWrite>())
13635            .map(|h| &h.1);
13636        let left_position = position.bias_left(buffer);
13637        let right_position = position.bias_right(buffer);
13638        read_highlights
13639            .into_iter()
13640            .chain(write_highlights)
13641            .flat_map(move |ranges| {
13642                let start_ix = match ranges.binary_search_by(|probe| {
13643                    let cmp = probe.end.cmp(&left_position, buffer);
13644                    if cmp.is_ge() {
13645                        Ordering::Greater
13646                    } else {
13647                        Ordering::Less
13648                    }
13649                }) {
13650                    Ok(i) | Err(i) => i,
13651                };
13652
13653                ranges[start_ix..]
13654                    .iter()
13655                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13656            })
13657    }
13658
13659    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13660        self.background_highlights
13661            .get(&TypeId::of::<T>())
13662            .map_or(false, |(_, highlights)| !highlights.is_empty())
13663    }
13664
13665    pub fn background_highlights_in_range(
13666        &self,
13667        search_range: Range<Anchor>,
13668        display_snapshot: &DisplaySnapshot,
13669        theme: &ThemeColors,
13670    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13671        let mut results = Vec::new();
13672        for (color_fetcher, ranges) in self.background_highlights.values() {
13673            let color = color_fetcher(theme);
13674            let start_ix = match ranges.binary_search_by(|probe| {
13675                let cmp = probe
13676                    .end
13677                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13678                if cmp.is_gt() {
13679                    Ordering::Greater
13680                } else {
13681                    Ordering::Less
13682                }
13683            }) {
13684                Ok(i) | Err(i) => i,
13685            };
13686            for range in &ranges[start_ix..] {
13687                if range
13688                    .start
13689                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13690                    .is_ge()
13691                {
13692                    break;
13693                }
13694
13695                let start = range.start.to_display_point(display_snapshot);
13696                let end = range.end.to_display_point(display_snapshot);
13697                results.push((start..end, color))
13698            }
13699        }
13700        results
13701    }
13702
13703    pub fn background_highlight_row_ranges<T: 'static>(
13704        &self,
13705        search_range: Range<Anchor>,
13706        display_snapshot: &DisplaySnapshot,
13707        count: usize,
13708    ) -> Vec<RangeInclusive<DisplayPoint>> {
13709        let mut results = Vec::new();
13710        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13711            return vec![];
13712        };
13713
13714        let start_ix = match ranges.binary_search_by(|probe| {
13715            let cmp = probe
13716                .end
13717                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13718            if cmp.is_gt() {
13719                Ordering::Greater
13720            } else {
13721                Ordering::Less
13722            }
13723        }) {
13724            Ok(i) | Err(i) => i,
13725        };
13726        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13727            if let (Some(start_display), Some(end_display)) = (start, end) {
13728                results.push(
13729                    start_display.to_display_point(display_snapshot)
13730                        ..=end_display.to_display_point(display_snapshot),
13731                );
13732            }
13733        };
13734        let mut start_row: Option<Point> = None;
13735        let mut end_row: Option<Point> = None;
13736        if ranges.len() > count {
13737            return Vec::new();
13738        }
13739        for range in &ranges[start_ix..] {
13740            if range
13741                .start
13742                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13743                .is_ge()
13744            {
13745                break;
13746            }
13747            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13748            if let Some(current_row) = &end_row {
13749                if end.row == current_row.row {
13750                    continue;
13751                }
13752            }
13753            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13754            if start_row.is_none() {
13755                assert_eq!(end_row, None);
13756                start_row = Some(start);
13757                end_row = Some(end);
13758                continue;
13759            }
13760            if let Some(current_end) = end_row.as_mut() {
13761                if start.row > current_end.row + 1 {
13762                    push_region(start_row, end_row);
13763                    start_row = Some(start);
13764                    end_row = Some(end);
13765                } else {
13766                    // Merge two hunks.
13767                    *current_end = end;
13768                }
13769            } else {
13770                unreachable!();
13771            }
13772        }
13773        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13774        push_region(start_row, end_row);
13775        results
13776    }
13777
13778    pub fn gutter_highlights_in_range(
13779        &self,
13780        search_range: Range<Anchor>,
13781        display_snapshot: &DisplaySnapshot,
13782        cx: &App,
13783    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13784        let mut results = Vec::new();
13785        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13786            let color = color_fetcher(cx);
13787            let start_ix = match ranges.binary_search_by(|probe| {
13788                let cmp = probe
13789                    .end
13790                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13791                if cmp.is_gt() {
13792                    Ordering::Greater
13793                } else {
13794                    Ordering::Less
13795                }
13796            }) {
13797                Ok(i) | Err(i) => i,
13798            };
13799            for range in &ranges[start_ix..] {
13800                if range
13801                    .start
13802                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13803                    .is_ge()
13804                {
13805                    break;
13806                }
13807
13808                let start = range.start.to_display_point(display_snapshot);
13809                let end = range.end.to_display_point(display_snapshot);
13810                results.push((start..end, color))
13811            }
13812        }
13813        results
13814    }
13815
13816    /// Get the text ranges corresponding to the redaction query
13817    pub fn redacted_ranges(
13818        &self,
13819        search_range: Range<Anchor>,
13820        display_snapshot: &DisplaySnapshot,
13821        cx: &App,
13822    ) -> Vec<Range<DisplayPoint>> {
13823        display_snapshot
13824            .buffer_snapshot
13825            .redacted_ranges(search_range, |file| {
13826                if let Some(file) = file {
13827                    file.is_private()
13828                        && EditorSettings::get(
13829                            Some(SettingsLocation {
13830                                worktree_id: file.worktree_id(cx),
13831                                path: file.path().as_ref(),
13832                            }),
13833                            cx,
13834                        )
13835                        .redact_private_values
13836                } else {
13837                    false
13838                }
13839            })
13840            .map(|range| {
13841                range.start.to_display_point(display_snapshot)
13842                    ..range.end.to_display_point(display_snapshot)
13843            })
13844            .collect()
13845    }
13846
13847    pub fn highlight_text<T: 'static>(
13848        &mut self,
13849        ranges: Vec<Range<Anchor>>,
13850        style: HighlightStyle,
13851        cx: &mut Context<Self>,
13852    ) {
13853        self.display_map.update(cx, |map, _| {
13854            map.highlight_text(TypeId::of::<T>(), ranges, style)
13855        });
13856        cx.notify();
13857    }
13858
13859    pub(crate) fn highlight_inlays<T: 'static>(
13860        &mut self,
13861        highlights: Vec<InlayHighlight>,
13862        style: HighlightStyle,
13863        cx: &mut Context<Self>,
13864    ) {
13865        self.display_map.update(cx, |map, _| {
13866            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13867        });
13868        cx.notify();
13869    }
13870
13871    pub fn text_highlights<'a, T: 'static>(
13872        &'a self,
13873        cx: &'a App,
13874    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13875        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13876    }
13877
13878    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13879        let cleared = self
13880            .display_map
13881            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13882        if cleared {
13883            cx.notify();
13884        }
13885    }
13886
13887    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13888        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13889            && self.focus_handle.is_focused(window)
13890    }
13891
13892    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13893        self.show_cursor_when_unfocused = is_enabled;
13894        cx.notify();
13895    }
13896
13897    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13898        self.project
13899            .as_ref()
13900            .map(|project| project.read(cx).lsp_store())
13901    }
13902
13903    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13904        cx.notify();
13905    }
13906
13907    fn on_buffer_event(
13908        &mut self,
13909        multibuffer: &Entity<MultiBuffer>,
13910        event: &multi_buffer::Event,
13911        window: &mut Window,
13912        cx: &mut Context<Self>,
13913    ) {
13914        match event {
13915            multi_buffer::Event::Edited {
13916                singleton_buffer_edited,
13917                edited_buffer: buffer_edited,
13918            } => {
13919                self.scrollbar_marker_state.dirty = true;
13920                self.active_indent_guides_state.dirty = true;
13921                self.refresh_active_diagnostics(cx);
13922                self.refresh_code_actions(window, cx);
13923                if self.has_active_inline_completion() {
13924                    self.update_visible_inline_completion(window, cx);
13925                }
13926                if let Some(buffer) = buffer_edited {
13927                    let buffer_id = buffer.read(cx).remote_id();
13928                    if !self.registered_buffers.contains_key(&buffer_id) {
13929                        if let Some(lsp_store) = self.lsp_store(cx) {
13930                            lsp_store.update(cx, |lsp_store, cx| {
13931                                self.registered_buffers.insert(
13932                                    buffer_id,
13933                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13934                                );
13935                            })
13936                        }
13937                    }
13938                }
13939                cx.emit(EditorEvent::BufferEdited);
13940                cx.emit(SearchEvent::MatchesInvalidated);
13941                if *singleton_buffer_edited {
13942                    if let Some(project) = &self.project {
13943                        let project = project.read(cx);
13944                        #[allow(clippy::mutable_key_type)]
13945                        let languages_affected = multibuffer
13946                            .read(cx)
13947                            .all_buffers()
13948                            .into_iter()
13949                            .filter_map(|buffer| {
13950                                let buffer = buffer.read(cx);
13951                                let language = buffer.language()?;
13952                                if project.is_local()
13953                                    && project
13954                                        .language_servers_for_local_buffer(buffer, cx)
13955                                        .count()
13956                                        == 0
13957                                {
13958                                    None
13959                                } else {
13960                                    Some(language)
13961                                }
13962                            })
13963                            .cloned()
13964                            .collect::<HashSet<_>>();
13965                        if !languages_affected.is_empty() {
13966                            self.refresh_inlay_hints(
13967                                InlayHintRefreshReason::BufferEdited(languages_affected),
13968                                cx,
13969                            );
13970                        }
13971                    }
13972                }
13973
13974                let Some(project) = &self.project else { return };
13975                let (telemetry, is_via_ssh) = {
13976                    let project = project.read(cx);
13977                    let telemetry = project.client().telemetry().clone();
13978                    let is_via_ssh = project.is_via_ssh();
13979                    (telemetry, is_via_ssh)
13980                };
13981                refresh_linked_ranges(self, window, cx);
13982                telemetry.log_edit_event("editor", is_via_ssh);
13983            }
13984            multi_buffer::Event::ExcerptsAdded {
13985                buffer,
13986                predecessor,
13987                excerpts,
13988            } => {
13989                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13990                let buffer_id = buffer.read(cx).remote_id();
13991                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13992                    if let Some(project) = &self.project {
13993                        get_uncommitted_diff_for_buffer(
13994                            project,
13995                            [buffer.clone()],
13996                            self.buffer.clone(),
13997                            cx,
13998                        );
13999                    }
14000                }
14001                cx.emit(EditorEvent::ExcerptsAdded {
14002                    buffer: buffer.clone(),
14003                    predecessor: *predecessor,
14004                    excerpts: excerpts.clone(),
14005                });
14006                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14007            }
14008            multi_buffer::Event::ExcerptsRemoved { ids } => {
14009                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14010                let buffer = self.buffer.read(cx);
14011                self.registered_buffers
14012                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14013                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14014            }
14015            multi_buffer::Event::ExcerptsEdited { ids } => {
14016                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14017            }
14018            multi_buffer::Event::ExcerptsExpanded { ids } => {
14019                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14020                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14021            }
14022            multi_buffer::Event::Reparsed(buffer_id) => {
14023                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14024
14025                cx.emit(EditorEvent::Reparsed(*buffer_id));
14026            }
14027            multi_buffer::Event::DiffHunksToggled => {
14028                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14029            }
14030            multi_buffer::Event::LanguageChanged(buffer_id) => {
14031                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14032                cx.emit(EditorEvent::Reparsed(*buffer_id));
14033                cx.notify();
14034            }
14035            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14036            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14037            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14038                cx.emit(EditorEvent::TitleChanged)
14039            }
14040            // multi_buffer::Event::DiffBaseChanged => {
14041            //     self.scrollbar_marker_state.dirty = true;
14042            //     cx.emit(EditorEvent::DiffBaseChanged);
14043            //     cx.notify();
14044            // }
14045            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14046            multi_buffer::Event::DiagnosticsUpdated => {
14047                self.refresh_active_diagnostics(cx);
14048                self.scrollbar_marker_state.dirty = true;
14049                cx.notify();
14050            }
14051            _ => {}
14052        };
14053    }
14054
14055    fn on_display_map_changed(
14056        &mut self,
14057        _: Entity<DisplayMap>,
14058        _: &mut Window,
14059        cx: &mut Context<Self>,
14060    ) {
14061        cx.notify();
14062    }
14063
14064    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14065        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14066        self.refresh_inline_completion(true, false, window, cx);
14067        self.refresh_inlay_hints(
14068            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14069                self.selections.newest_anchor().head(),
14070                &self.buffer.read(cx).snapshot(cx),
14071                cx,
14072            )),
14073            cx,
14074        );
14075
14076        let old_cursor_shape = self.cursor_shape;
14077
14078        {
14079            let editor_settings = EditorSettings::get_global(cx);
14080            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14081            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14082            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14083        }
14084
14085        if old_cursor_shape != self.cursor_shape {
14086            cx.emit(EditorEvent::CursorShapeChanged);
14087        }
14088
14089        let project_settings = ProjectSettings::get_global(cx);
14090        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14091
14092        if self.mode == EditorMode::Full {
14093            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14094            if self.git_blame_inline_enabled != inline_blame_enabled {
14095                self.toggle_git_blame_inline_internal(false, window, cx);
14096            }
14097        }
14098
14099        cx.notify();
14100    }
14101
14102    pub fn set_searchable(&mut self, searchable: bool) {
14103        self.searchable = searchable;
14104    }
14105
14106    pub fn searchable(&self) -> bool {
14107        self.searchable
14108    }
14109
14110    fn open_proposed_changes_editor(
14111        &mut self,
14112        _: &OpenProposedChangesEditor,
14113        window: &mut Window,
14114        cx: &mut Context<Self>,
14115    ) {
14116        let Some(workspace) = self.workspace() else {
14117            cx.propagate();
14118            return;
14119        };
14120
14121        let selections = self.selections.all::<usize>(cx);
14122        let multi_buffer = self.buffer.read(cx);
14123        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14124        let mut new_selections_by_buffer = HashMap::default();
14125        for selection in selections {
14126            for (buffer, range, _) in
14127                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14128            {
14129                let mut range = range.to_point(buffer);
14130                range.start.column = 0;
14131                range.end.column = buffer.line_len(range.end.row);
14132                new_selections_by_buffer
14133                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14134                    .or_insert(Vec::new())
14135                    .push(range)
14136            }
14137        }
14138
14139        let proposed_changes_buffers = new_selections_by_buffer
14140            .into_iter()
14141            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14142            .collect::<Vec<_>>();
14143        let proposed_changes_editor = cx.new(|cx| {
14144            ProposedChangesEditor::new(
14145                "Proposed changes",
14146                proposed_changes_buffers,
14147                self.project.clone(),
14148                window,
14149                cx,
14150            )
14151        });
14152
14153        window.defer(cx, move |window, cx| {
14154            workspace.update(cx, |workspace, cx| {
14155                workspace.active_pane().update(cx, |pane, cx| {
14156                    pane.add_item(
14157                        Box::new(proposed_changes_editor),
14158                        true,
14159                        true,
14160                        None,
14161                        window,
14162                        cx,
14163                    );
14164                });
14165            });
14166        });
14167    }
14168
14169    pub fn open_excerpts_in_split(
14170        &mut self,
14171        _: &OpenExcerptsSplit,
14172        window: &mut Window,
14173        cx: &mut Context<Self>,
14174    ) {
14175        self.open_excerpts_common(None, true, window, cx)
14176    }
14177
14178    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14179        self.open_excerpts_common(None, false, window, cx)
14180    }
14181
14182    fn open_excerpts_common(
14183        &mut self,
14184        jump_data: Option<JumpData>,
14185        split: bool,
14186        window: &mut Window,
14187        cx: &mut Context<Self>,
14188    ) {
14189        let Some(workspace) = self.workspace() else {
14190            cx.propagate();
14191            return;
14192        };
14193
14194        if self.buffer.read(cx).is_singleton() {
14195            cx.propagate();
14196            return;
14197        }
14198
14199        let mut new_selections_by_buffer = HashMap::default();
14200        match &jump_data {
14201            Some(JumpData::MultiBufferPoint {
14202                excerpt_id,
14203                position,
14204                anchor,
14205                line_offset_from_top,
14206            }) => {
14207                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14208                if let Some(buffer) = multi_buffer_snapshot
14209                    .buffer_id_for_excerpt(*excerpt_id)
14210                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14211                {
14212                    let buffer_snapshot = buffer.read(cx).snapshot();
14213                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14214                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14215                    } else {
14216                        buffer_snapshot.clip_point(*position, Bias::Left)
14217                    };
14218                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14219                    new_selections_by_buffer.insert(
14220                        buffer,
14221                        (
14222                            vec![jump_to_offset..jump_to_offset],
14223                            Some(*line_offset_from_top),
14224                        ),
14225                    );
14226                }
14227            }
14228            Some(JumpData::MultiBufferRow {
14229                row,
14230                line_offset_from_top,
14231            }) => {
14232                let point = MultiBufferPoint::new(row.0, 0);
14233                if let Some((buffer, buffer_point, _)) =
14234                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14235                {
14236                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14237                    new_selections_by_buffer
14238                        .entry(buffer)
14239                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14240                        .0
14241                        .push(buffer_offset..buffer_offset)
14242                }
14243            }
14244            None => {
14245                let selections = self.selections.all::<usize>(cx);
14246                let multi_buffer = self.buffer.read(cx);
14247                for selection in selections {
14248                    for (buffer, mut range, _) in multi_buffer
14249                        .snapshot(cx)
14250                        .range_to_buffer_ranges(selection.range())
14251                    {
14252                        // When editing branch buffers, jump to the corresponding location
14253                        // in their base buffer.
14254                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14255                        let buffer = buffer_handle.read(cx);
14256                        if let Some(base_buffer) = buffer.base_buffer() {
14257                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14258                            buffer_handle = base_buffer;
14259                        }
14260
14261                        if selection.reversed {
14262                            mem::swap(&mut range.start, &mut range.end);
14263                        }
14264                        new_selections_by_buffer
14265                            .entry(buffer_handle)
14266                            .or_insert((Vec::new(), None))
14267                            .0
14268                            .push(range)
14269                    }
14270                }
14271            }
14272        }
14273
14274        if new_selections_by_buffer.is_empty() {
14275            return;
14276        }
14277
14278        // We defer the pane interaction because we ourselves are a workspace item
14279        // and activating a new item causes the pane to call a method on us reentrantly,
14280        // which panics if we're on the stack.
14281        window.defer(cx, move |window, cx| {
14282            workspace.update(cx, |workspace, cx| {
14283                let pane = if split {
14284                    workspace.adjacent_pane(window, cx)
14285                } else {
14286                    workspace.active_pane().clone()
14287                };
14288
14289                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14290                    let editor = buffer
14291                        .read(cx)
14292                        .file()
14293                        .is_none()
14294                        .then(|| {
14295                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14296                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14297                            // Instead, we try to activate the existing editor in the pane first.
14298                            let (editor, pane_item_index) =
14299                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14300                                    let editor = item.downcast::<Editor>()?;
14301                                    let singleton_buffer =
14302                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14303                                    if singleton_buffer == buffer {
14304                                        Some((editor, i))
14305                                    } else {
14306                                        None
14307                                    }
14308                                })?;
14309                            pane.update(cx, |pane, cx| {
14310                                pane.activate_item(pane_item_index, true, true, window, cx)
14311                            });
14312                            Some(editor)
14313                        })
14314                        .flatten()
14315                        .unwrap_or_else(|| {
14316                            workspace.open_project_item::<Self>(
14317                                pane.clone(),
14318                                buffer,
14319                                true,
14320                                true,
14321                                window,
14322                                cx,
14323                            )
14324                        });
14325
14326                    editor.update(cx, |editor, cx| {
14327                        let autoscroll = match scroll_offset {
14328                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14329                            None => Autoscroll::newest(),
14330                        };
14331                        let nav_history = editor.nav_history.take();
14332                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14333                            s.select_ranges(ranges);
14334                        });
14335                        editor.nav_history = nav_history;
14336                    });
14337                }
14338            })
14339        });
14340    }
14341
14342    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14343        let snapshot = self.buffer.read(cx).read(cx);
14344        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14345        Some(
14346            ranges
14347                .iter()
14348                .map(move |range| {
14349                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14350                })
14351                .collect(),
14352        )
14353    }
14354
14355    fn selection_replacement_ranges(
14356        &self,
14357        range: Range<OffsetUtf16>,
14358        cx: &mut App,
14359    ) -> Vec<Range<OffsetUtf16>> {
14360        let selections = self.selections.all::<OffsetUtf16>(cx);
14361        let newest_selection = selections
14362            .iter()
14363            .max_by_key(|selection| selection.id)
14364            .unwrap();
14365        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14366        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14367        let snapshot = self.buffer.read(cx).read(cx);
14368        selections
14369            .into_iter()
14370            .map(|mut selection| {
14371                selection.start.0 =
14372                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14373                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14374                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14375                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14376            })
14377            .collect()
14378    }
14379
14380    fn report_editor_event(
14381        &self,
14382        event_type: &'static str,
14383        file_extension: Option<String>,
14384        cx: &App,
14385    ) {
14386        if cfg!(any(test, feature = "test-support")) {
14387            return;
14388        }
14389
14390        let Some(project) = &self.project else { return };
14391
14392        // If None, we are in a file without an extension
14393        let file = self
14394            .buffer
14395            .read(cx)
14396            .as_singleton()
14397            .and_then(|b| b.read(cx).file());
14398        let file_extension = file_extension.or(file
14399            .as_ref()
14400            .and_then(|file| Path::new(file.file_name(cx)).extension())
14401            .and_then(|e| e.to_str())
14402            .map(|a| a.to_string()));
14403
14404        let vim_mode = cx
14405            .global::<SettingsStore>()
14406            .raw_user_settings()
14407            .get("vim_mode")
14408            == Some(&serde_json::Value::Bool(true));
14409
14410        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14411        let copilot_enabled = edit_predictions_provider
14412            == language::language_settings::EditPredictionProvider::Copilot;
14413        let copilot_enabled_for_language = self
14414            .buffer
14415            .read(cx)
14416            .settings_at(0, cx)
14417            .show_edit_predictions;
14418
14419        let project = project.read(cx);
14420        telemetry::event!(
14421            event_type,
14422            file_extension,
14423            vim_mode,
14424            copilot_enabled,
14425            copilot_enabled_for_language,
14426            edit_predictions_provider,
14427            is_via_ssh = project.is_via_ssh(),
14428        );
14429    }
14430
14431    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14432    /// with each line being an array of {text, highlight} objects.
14433    fn copy_highlight_json(
14434        &mut self,
14435        _: &CopyHighlightJson,
14436        window: &mut Window,
14437        cx: &mut Context<Self>,
14438    ) {
14439        #[derive(Serialize)]
14440        struct Chunk<'a> {
14441            text: String,
14442            highlight: Option<&'a str>,
14443        }
14444
14445        let snapshot = self.buffer.read(cx).snapshot(cx);
14446        let range = self
14447            .selected_text_range(false, window, cx)
14448            .and_then(|selection| {
14449                if selection.range.is_empty() {
14450                    None
14451                } else {
14452                    Some(selection.range)
14453                }
14454            })
14455            .unwrap_or_else(|| 0..snapshot.len());
14456
14457        let chunks = snapshot.chunks(range, true);
14458        let mut lines = Vec::new();
14459        let mut line: VecDeque<Chunk> = VecDeque::new();
14460
14461        let Some(style) = self.style.as_ref() else {
14462            return;
14463        };
14464
14465        for chunk in chunks {
14466            let highlight = chunk
14467                .syntax_highlight_id
14468                .and_then(|id| id.name(&style.syntax));
14469            let mut chunk_lines = chunk.text.split('\n').peekable();
14470            while let Some(text) = chunk_lines.next() {
14471                let mut merged_with_last_token = false;
14472                if let Some(last_token) = line.back_mut() {
14473                    if last_token.highlight == highlight {
14474                        last_token.text.push_str(text);
14475                        merged_with_last_token = true;
14476                    }
14477                }
14478
14479                if !merged_with_last_token {
14480                    line.push_back(Chunk {
14481                        text: text.into(),
14482                        highlight,
14483                    });
14484                }
14485
14486                if chunk_lines.peek().is_some() {
14487                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14488                        line.pop_front();
14489                    }
14490                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14491                        line.pop_back();
14492                    }
14493
14494                    lines.push(mem::take(&mut line));
14495                }
14496            }
14497        }
14498
14499        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14500            return;
14501        };
14502        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14503    }
14504
14505    pub fn open_context_menu(
14506        &mut self,
14507        _: &OpenContextMenu,
14508        window: &mut Window,
14509        cx: &mut Context<Self>,
14510    ) {
14511        self.request_autoscroll(Autoscroll::newest(), cx);
14512        let position = self.selections.newest_display(cx).start;
14513        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14514    }
14515
14516    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14517        &self.inlay_hint_cache
14518    }
14519
14520    pub fn replay_insert_event(
14521        &mut self,
14522        text: &str,
14523        relative_utf16_range: Option<Range<isize>>,
14524        window: &mut Window,
14525        cx: &mut Context<Self>,
14526    ) {
14527        if !self.input_enabled {
14528            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14529            return;
14530        }
14531        if let Some(relative_utf16_range) = relative_utf16_range {
14532            let selections = self.selections.all::<OffsetUtf16>(cx);
14533            self.change_selections(None, window, cx, |s| {
14534                let new_ranges = selections.into_iter().map(|range| {
14535                    let start = OffsetUtf16(
14536                        range
14537                            .head()
14538                            .0
14539                            .saturating_add_signed(relative_utf16_range.start),
14540                    );
14541                    let end = OffsetUtf16(
14542                        range
14543                            .head()
14544                            .0
14545                            .saturating_add_signed(relative_utf16_range.end),
14546                    );
14547                    start..end
14548                });
14549                s.select_ranges(new_ranges);
14550            });
14551        }
14552
14553        self.handle_input(text, window, cx);
14554    }
14555
14556    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14557        let Some(provider) = self.semantics_provider.as_ref() else {
14558            return false;
14559        };
14560
14561        let mut supports = false;
14562        self.buffer().read(cx).for_each_buffer(|buffer| {
14563            supports |= provider.supports_inlay_hints(buffer, cx);
14564        });
14565        supports
14566    }
14567
14568    pub fn is_focused(&self, window: &Window) -> bool {
14569        self.focus_handle.is_focused(window)
14570    }
14571
14572    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14573        cx.emit(EditorEvent::Focused);
14574
14575        if let Some(descendant) = self
14576            .last_focused_descendant
14577            .take()
14578            .and_then(|descendant| descendant.upgrade())
14579        {
14580            window.focus(&descendant);
14581        } else {
14582            if let Some(blame) = self.blame.as_ref() {
14583                blame.update(cx, GitBlame::focus)
14584            }
14585
14586            self.blink_manager.update(cx, BlinkManager::enable);
14587            self.show_cursor_names(window, cx);
14588            self.buffer.update(cx, |buffer, cx| {
14589                buffer.finalize_last_transaction(cx);
14590                if self.leader_peer_id.is_none() {
14591                    buffer.set_active_selections(
14592                        &self.selections.disjoint_anchors(),
14593                        self.selections.line_mode,
14594                        self.cursor_shape,
14595                        cx,
14596                    );
14597                }
14598            });
14599        }
14600    }
14601
14602    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14603        cx.emit(EditorEvent::FocusedIn)
14604    }
14605
14606    fn handle_focus_out(
14607        &mut self,
14608        event: FocusOutEvent,
14609        _window: &mut Window,
14610        _cx: &mut Context<Self>,
14611    ) {
14612        if event.blurred != self.focus_handle {
14613            self.last_focused_descendant = Some(event.blurred);
14614        }
14615    }
14616
14617    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14618        self.blink_manager.update(cx, BlinkManager::disable);
14619        self.buffer
14620            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14621
14622        if let Some(blame) = self.blame.as_ref() {
14623            blame.update(cx, GitBlame::blur)
14624        }
14625        if !self.hover_state.focused(window, cx) {
14626            hide_hover(self, cx);
14627        }
14628
14629        self.hide_context_menu(window, cx);
14630        self.discard_inline_completion(false, cx);
14631        cx.emit(EditorEvent::Blurred);
14632        cx.notify();
14633    }
14634
14635    pub fn register_action<A: Action>(
14636        &mut self,
14637        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14638    ) -> Subscription {
14639        let id = self.next_editor_action_id.post_inc();
14640        let listener = Arc::new(listener);
14641        self.editor_actions.borrow_mut().insert(
14642            id,
14643            Box::new(move |window, _| {
14644                let listener = listener.clone();
14645                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14646                    let action = action.downcast_ref().unwrap();
14647                    if phase == DispatchPhase::Bubble {
14648                        listener(action, window, cx)
14649                    }
14650                })
14651            }),
14652        );
14653
14654        let editor_actions = self.editor_actions.clone();
14655        Subscription::new(move || {
14656            editor_actions.borrow_mut().remove(&id);
14657        })
14658    }
14659
14660    pub fn file_header_size(&self) -> u32 {
14661        FILE_HEADER_HEIGHT
14662    }
14663
14664    pub fn revert(
14665        &mut self,
14666        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14667        window: &mut Window,
14668        cx: &mut Context<Self>,
14669    ) {
14670        self.buffer().update(cx, |multi_buffer, cx| {
14671            for (buffer_id, changes) in revert_changes {
14672                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14673                    buffer.update(cx, |buffer, cx| {
14674                        buffer.edit(
14675                            changes.into_iter().map(|(range, text)| {
14676                                (range, text.to_string().map(Arc::<str>::from))
14677                            }),
14678                            None,
14679                            cx,
14680                        );
14681                    });
14682                }
14683            }
14684        });
14685        self.change_selections(None, window, cx, |selections| selections.refresh());
14686    }
14687
14688    pub fn to_pixel_point(
14689        &self,
14690        source: multi_buffer::Anchor,
14691        editor_snapshot: &EditorSnapshot,
14692        window: &mut Window,
14693    ) -> Option<gpui::Point<Pixels>> {
14694        let source_point = source.to_display_point(editor_snapshot);
14695        self.display_to_pixel_point(source_point, editor_snapshot, window)
14696    }
14697
14698    pub fn display_to_pixel_point(
14699        &self,
14700        source: DisplayPoint,
14701        editor_snapshot: &EditorSnapshot,
14702        window: &mut Window,
14703    ) -> Option<gpui::Point<Pixels>> {
14704        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14705        let text_layout_details = self.text_layout_details(window);
14706        let scroll_top = text_layout_details
14707            .scroll_anchor
14708            .scroll_position(editor_snapshot)
14709            .y;
14710
14711        if source.row().as_f32() < scroll_top.floor() {
14712            return None;
14713        }
14714        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14715        let source_y = line_height * (source.row().as_f32() - scroll_top);
14716        Some(gpui::Point::new(source_x, source_y))
14717    }
14718
14719    pub fn has_visible_completions_menu(&self) -> bool {
14720        !self.edit_prediction_preview_is_active()
14721            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14722                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14723            })
14724    }
14725
14726    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14727        self.addons
14728            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14729    }
14730
14731    pub fn unregister_addon<T: Addon>(&mut self) {
14732        self.addons.remove(&std::any::TypeId::of::<T>());
14733    }
14734
14735    pub fn addon<T: Addon>(&self) -> Option<&T> {
14736        let type_id = std::any::TypeId::of::<T>();
14737        self.addons
14738            .get(&type_id)
14739            .and_then(|item| item.to_any().downcast_ref::<T>())
14740    }
14741
14742    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14743        let text_layout_details = self.text_layout_details(window);
14744        let style = &text_layout_details.editor_style;
14745        let font_id = window.text_system().resolve_font(&style.text.font());
14746        let font_size = style.text.font_size.to_pixels(window.rem_size());
14747        let line_height = style.text.line_height_in_pixels(window.rem_size());
14748        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14749
14750        gpui::Size::new(em_width, line_height)
14751    }
14752}
14753
14754fn get_uncommitted_diff_for_buffer(
14755    project: &Entity<Project>,
14756    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14757    buffer: Entity<MultiBuffer>,
14758    cx: &mut App,
14759) {
14760    let mut tasks = Vec::new();
14761    project.update(cx, |project, cx| {
14762        for buffer in buffers {
14763            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14764        }
14765    });
14766    cx.spawn(|mut cx| async move {
14767        let diffs = futures::future::join_all(tasks).await;
14768        buffer
14769            .update(&mut cx, |buffer, cx| {
14770                for diff in diffs.into_iter().flatten() {
14771                    buffer.add_diff(diff, cx);
14772                }
14773            })
14774            .ok();
14775    })
14776    .detach();
14777}
14778
14779fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14780    let tab_size = tab_size.get() as usize;
14781    let mut width = offset;
14782
14783    for ch in text.chars() {
14784        width += if ch == '\t' {
14785            tab_size - (width % tab_size)
14786        } else {
14787            1
14788        };
14789    }
14790
14791    width - offset
14792}
14793
14794#[cfg(test)]
14795mod tests {
14796    use super::*;
14797
14798    #[test]
14799    fn test_string_size_with_expanded_tabs() {
14800        let nz = |val| NonZeroU32::new(val).unwrap();
14801        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14802        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14803        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14804        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14805        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14806        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14807        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14808        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14809    }
14810}
14811
14812/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14813struct WordBreakingTokenizer<'a> {
14814    input: &'a str,
14815}
14816
14817impl<'a> WordBreakingTokenizer<'a> {
14818    fn new(input: &'a str) -> Self {
14819        Self { input }
14820    }
14821}
14822
14823fn is_char_ideographic(ch: char) -> bool {
14824    use unicode_script::Script::*;
14825    use unicode_script::UnicodeScript;
14826    matches!(ch.script(), Han | Tangut | Yi)
14827}
14828
14829fn is_grapheme_ideographic(text: &str) -> bool {
14830    text.chars().any(is_char_ideographic)
14831}
14832
14833fn is_grapheme_whitespace(text: &str) -> bool {
14834    text.chars().any(|x| x.is_whitespace())
14835}
14836
14837fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14838    text.chars().next().map_or(false, |ch| {
14839        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14840    })
14841}
14842
14843#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14844struct WordBreakToken<'a> {
14845    token: &'a str,
14846    grapheme_len: usize,
14847    is_whitespace: bool,
14848}
14849
14850impl<'a> Iterator for WordBreakingTokenizer<'a> {
14851    /// Yields a span, the count of graphemes in the token, and whether it was
14852    /// whitespace. Note that it also breaks at word boundaries.
14853    type Item = WordBreakToken<'a>;
14854
14855    fn next(&mut self) -> Option<Self::Item> {
14856        use unicode_segmentation::UnicodeSegmentation;
14857        if self.input.is_empty() {
14858            return None;
14859        }
14860
14861        let mut iter = self.input.graphemes(true).peekable();
14862        let mut offset = 0;
14863        let mut graphemes = 0;
14864        if let Some(first_grapheme) = iter.next() {
14865            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14866            offset += first_grapheme.len();
14867            graphemes += 1;
14868            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14869                if let Some(grapheme) = iter.peek().copied() {
14870                    if should_stay_with_preceding_ideograph(grapheme) {
14871                        offset += grapheme.len();
14872                        graphemes += 1;
14873                    }
14874                }
14875            } else {
14876                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14877                let mut next_word_bound = words.peek().copied();
14878                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14879                    next_word_bound = words.next();
14880                }
14881                while let Some(grapheme) = iter.peek().copied() {
14882                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14883                        break;
14884                    };
14885                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14886                        break;
14887                    };
14888                    offset += grapheme.len();
14889                    graphemes += 1;
14890                    iter.next();
14891                }
14892            }
14893            let token = &self.input[..offset];
14894            self.input = &self.input[offset..];
14895            if is_whitespace {
14896                Some(WordBreakToken {
14897                    token: " ",
14898                    grapheme_len: 1,
14899                    is_whitespace: true,
14900                })
14901            } else {
14902                Some(WordBreakToken {
14903                    token,
14904                    grapheme_len: graphemes,
14905                    is_whitespace: false,
14906                })
14907            }
14908        } else {
14909            None
14910        }
14911    }
14912}
14913
14914#[test]
14915fn test_word_breaking_tokenizer() {
14916    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14917        ("", &[]),
14918        ("  ", &[(" ", 1, true)]),
14919        ("Ʒ", &[("Ʒ", 1, false)]),
14920        ("Ǽ", &[("Ǽ", 1, false)]),
14921        ("", &[("", 1, false)]),
14922        ("⋑⋑", &[("⋑⋑", 2, false)]),
14923        (
14924            "原理,进而",
14925            &[
14926                ("", 1, false),
14927                ("理,", 2, false),
14928                ("", 1, false),
14929                ("", 1, false),
14930            ],
14931        ),
14932        (
14933            "hello world",
14934            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14935        ),
14936        (
14937            "hello, world",
14938            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14939        ),
14940        (
14941            "  hello world",
14942            &[
14943                (" ", 1, true),
14944                ("hello", 5, false),
14945                (" ", 1, true),
14946                ("world", 5, false),
14947            ],
14948        ),
14949        (
14950            "这是什么 \n 钢笔",
14951            &[
14952                ("", 1, false),
14953                ("", 1, false),
14954                ("", 1, false),
14955                ("", 1, false),
14956                (" ", 1, true),
14957                ("", 1, false),
14958                ("", 1, false),
14959            ],
14960        ),
14961        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14962    ];
14963
14964    for (input, result) in tests {
14965        assert_eq!(
14966            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14967            result
14968                .iter()
14969                .copied()
14970                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14971                    token,
14972                    grapheme_len,
14973                    is_whitespace,
14974                })
14975                .collect::<Vec<_>>()
14976        );
14977    }
14978}
14979
14980fn wrap_with_prefix(
14981    line_prefix: String,
14982    unwrapped_text: String,
14983    wrap_column: usize,
14984    tab_size: NonZeroU32,
14985) -> String {
14986    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14987    let mut wrapped_text = String::new();
14988    let mut current_line = line_prefix.clone();
14989
14990    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14991    let mut current_line_len = line_prefix_len;
14992    for WordBreakToken {
14993        token,
14994        grapheme_len,
14995        is_whitespace,
14996    } in tokenizer
14997    {
14998        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14999            wrapped_text.push_str(current_line.trim_end());
15000            wrapped_text.push('\n');
15001            current_line.truncate(line_prefix.len());
15002            current_line_len = line_prefix_len;
15003            if !is_whitespace {
15004                current_line.push_str(token);
15005                current_line_len += grapheme_len;
15006            }
15007        } else if !is_whitespace {
15008            current_line.push_str(token);
15009            current_line_len += grapheme_len;
15010        } else if current_line_len != line_prefix_len {
15011            current_line.push(' ');
15012            current_line_len += 1;
15013        }
15014    }
15015
15016    if !current_line.is_empty() {
15017        wrapped_text.push_str(&current_line);
15018    }
15019    wrapped_text
15020}
15021
15022#[test]
15023fn test_wrap_with_prefix() {
15024    assert_eq!(
15025        wrap_with_prefix(
15026            "# ".to_string(),
15027            "abcdefg".to_string(),
15028            4,
15029            NonZeroU32::new(4).unwrap()
15030        ),
15031        "# abcdefg"
15032    );
15033    assert_eq!(
15034        wrap_with_prefix(
15035            "".to_string(),
15036            "\thello world".to_string(),
15037            8,
15038            NonZeroU32::new(4).unwrap()
15039        ),
15040        "hello\nworld"
15041    );
15042    assert_eq!(
15043        wrap_with_prefix(
15044            "// ".to_string(),
15045            "xx \nyy zz aa bb cc".to_string(),
15046            12,
15047            NonZeroU32::new(4).unwrap()
15048        ),
15049        "// xx yy zz\n// aa bb cc"
15050    );
15051    assert_eq!(
15052        wrap_with_prefix(
15053            String::new(),
15054            "这是什么 \n 钢笔".to_string(),
15055            3,
15056            NonZeroU32::new(4).unwrap()
15057        ),
15058        "这是什\n么 钢\n"
15059    );
15060}
15061
15062pub trait CollaborationHub {
15063    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15064    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15065    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15066}
15067
15068impl CollaborationHub for Entity<Project> {
15069    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15070        self.read(cx).collaborators()
15071    }
15072
15073    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15074        self.read(cx).user_store().read(cx).participant_indices()
15075    }
15076
15077    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15078        let this = self.read(cx);
15079        let user_ids = this.collaborators().values().map(|c| c.user_id);
15080        this.user_store().read_with(cx, |user_store, cx| {
15081            user_store.participant_names(user_ids, cx)
15082        })
15083    }
15084}
15085
15086pub trait SemanticsProvider {
15087    fn hover(
15088        &self,
15089        buffer: &Entity<Buffer>,
15090        position: text::Anchor,
15091        cx: &mut App,
15092    ) -> Option<Task<Vec<project::Hover>>>;
15093
15094    fn inlay_hints(
15095        &self,
15096        buffer_handle: Entity<Buffer>,
15097        range: Range<text::Anchor>,
15098        cx: &mut App,
15099    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15100
15101    fn resolve_inlay_hint(
15102        &self,
15103        hint: InlayHint,
15104        buffer_handle: Entity<Buffer>,
15105        server_id: LanguageServerId,
15106        cx: &mut App,
15107    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15108
15109    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15110
15111    fn document_highlights(
15112        &self,
15113        buffer: &Entity<Buffer>,
15114        position: text::Anchor,
15115        cx: &mut App,
15116    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15117
15118    fn definitions(
15119        &self,
15120        buffer: &Entity<Buffer>,
15121        position: text::Anchor,
15122        kind: GotoDefinitionKind,
15123        cx: &mut App,
15124    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15125
15126    fn range_for_rename(
15127        &self,
15128        buffer: &Entity<Buffer>,
15129        position: text::Anchor,
15130        cx: &mut App,
15131    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15132
15133    fn perform_rename(
15134        &self,
15135        buffer: &Entity<Buffer>,
15136        position: text::Anchor,
15137        new_name: String,
15138        cx: &mut App,
15139    ) -> Option<Task<Result<ProjectTransaction>>>;
15140}
15141
15142pub trait CompletionProvider {
15143    fn completions(
15144        &self,
15145        buffer: &Entity<Buffer>,
15146        buffer_position: text::Anchor,
15147        trigger: CompletionContext,
15148        window: &mut Window,
15149        cx: &mut Context<Editor>,
15150    ) -> Task<Result<Vec<Completion>>>;
15151
15152    fn resolve_completions(
15153        &self,
15154        buffer: Entity<Buffer>,
15155        completion_indices: Vec<usize>,
15156        completions: Rc<RefCell<Box<[Completion]>>>,
15157        cx: &mut Context<Editor>,
15158    ) -> Task<Result<bool>>;
15159
15160    fn apply_additional_edits_for_completion(
15161        &self,
15162        _buffer: Entity<Buffer>,
15163        _completions: Rc<RefCell<Box<[Completion]>>>,
15164        _completion_index: usize,
15165        _push_to_history: bool,
15166        _cx: &mut Context<Editor>,
15167    ) -> Task<Result<Option<language::Transaction>>> {
15168        Task::ready(Ok(None))
15169    }
15170
15171    fn is_completion_trigger(
15172        &self,
15173        buffer: &Entity<Buffer>,
15174        position: language::Anchor,
15175        text: &str,
15176        trigger_in_words: bool,
15177        cx: &mut Context<Editor>,
15178    ) -> bool;
15179
15180    fn sort_completions(&self) -> bool {
15181        true
15182    }
15183}
15184
15185pub trait CodeActionProvider {
15186    fn id(&self) -> Arc<str>;
15187
15188    fn code_actions(
15189        &self,
15190        buffer: &Entity<Buffer>,
15191        range: Range<text::Anchor>,
15192        window: &mut Window,
15193        cx: &mut App,
15194    ) -> Task<Result<Vec<CodeAction>>>;
15195
15196    fn apply_code_action(
15197        &self,
15198        buffer_handle: Entity<Buffer>,
15199        action: CodeAction,
15200        excerpt_id: ExcerptId,
15201        push_to_history: bool,
15202        window: &mut Window,
15203        cx: &mut App,
15204    ) -> Task<Result<ProjectTransaction>>;
15205}
15206
15207impl CodeActionProvider for Entity<Project> {
15208    fn id(&self) -> Arc<str> {
15209        "project".into()
15210    }
15211
15212    fn code_actions(
15213        &self,
15214        buffer: &Entity<Buffer>,
15215        range: Range<text::Anchor>,
15216        _window: &mut Window,
15217        cx: &mut App,
15218    ) -> Task<Result<Vec<CodeAction>>> {
15219        self.update(cx, |project, cx| {
15220            project.code_actions(buffer, range, None, cx)
15221        })
15222    }
15223
15224    fn apply_code_action(
15225        &self,
15226        buffer_handle: Entity<Buffer>,
15227        action: CodeAction,
15228        _excerpt_id: ExcerptId,
15229        push_to_history: bool,
15230        _window: &mut Window,
15231        cx: &mut App,
15232    ) -> Task<Result<ProjectTransaction>> {
15233        self.update(cx, |project, cx| {
15234            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15235        })
15236    }
15237}
15238
15239fn snippet_completions(
15240    project: &Project,
15241    buffer: &Entity<Buffer>,
15242    buffer_position: text::Anchor,
15243    cx: &mut App,
15244) -> Task<Result<Vec<Completion>>> {
15245    let language = buffer.read(cx).language_at(buffer_position);
15246    let language_name = language.as_ref().map(|language| language.lsp_id());
15247    let snippet_store = project.snippets().read(cx);
15248    let snippets = snippet_store.snippets_for(language_name, cx);
15249
15250    if snippets.is_empty() {
15251        return Task::ready(Ok(vec![]));
15252    }
15253    let snapshot = buffer.read(cx).text_snapshot();
15254    let chars: String = snapshot
15255        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15256        .collect();
15257
15258    let scope = language.map(|language| language.default_scope());
15259    let executor = cx.background_executor().clone();
15260
15261    cx.background_executor().spawn(async move {
15262        let classifier = CharClassifier::new(scope).for_completion(true);
15263        let mut last_word = chars
15264            .chars()
15265            .take_while(|c| classifier.is_word(*c))
15266            .collect::<String>();
15267        last_word = last_word.chars().rev().collect();
15268
15269        if last_word.is_empty() {
15270            return Ok(vec![]);
15271        }
15272
15273        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15274        let to_lsp = |point: &text::Anchor| {
15275            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15276            point_to_lsp(end)
15277        };
15278        let lsp_end = to_lsp(&buffer_position);
15279
15280        let candidates = snippets
15281            .iter()
15282            .enumerate()
15283            .flat_map(|(ix, snippet)| {
15284                snippet
15285                    .prefix
15286                    .iter()
15287                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15288            })
15289            .collect::<Vec<StringMatchCandidate>>();
15290
15291        let mut matches = fuzzy::match_strings(
15292            &candidates,
15293            &last_word,
15294            last_word.chars().any(|c| c.is_uppercase()),
15295            100,
15296            &Default::default(),
15297            executor,
15298        )
15299        .await;
15300
15301        // Remove all candidates where the query's start does not match the start of any word in the candidate
15302        if let Some(query_start) = last_word.chars().next() {
15303            matches.retain(|string_match| {
15304                split_words(&string_match.string).any(|word| {
15305                    // Check that the first codepoint of the word as lowercase matches the first
15306                    // codepoint of the query as lowercase
15307                    word.chars()
15308                        .flat_map(|codepoint| codepoint.to_lowercase())
15309                        .zip(query_start.to_lowercase())
15310                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15311                })
15312            });
15313        }
15314
15315        let matched_strings = matches
15316            .into_iter()
15317            .map(|m| m.string)
15318            .collect::<HashSet<_>>();
15319
15320        let result: Vec<Completion> = snippets
15321            .into_iter()
15322            .filter_map(|snippet| {
15323                let matching_prefix = snippet
15324                    .prefix
15325                    .iter()
15326                    .find(|prefix| matched_strings.contains(*prefix))?;
15327                let start = as_offset - last_word.len();
15328                let start = snapshot.anchor_before(start);
15329                let range = start..buffer_position;
15330                let lsp_start = to_lsp(&start);
15331                let lsp_range = lsp::Range {
15332                    start: lsp_start,
15333                    end: lsp_end,
15334                };
15335                Some(Completion {
15336                    old_range: range,
15337                    new_text: snippet.body.clone(),
15338                    resolved: false,
15339                    label: CodeLabel {
15340                        text: matching_prefix.clone(),
15341                        runs: vec![],
15342                        filter_range: 0..matching_prefix.len(),
15343                    },
15344                    server_id: LanguageServerId(usize::MAX),
15345                    documentation: snippet
15346                        .description
15347                        .clone()
15348                        .map(CompletionDocumentation::SingleLine),
15349                    lsp_completion: lsp::CompletionItem {
15350                        label: snippet.prefix.first().unwrap().clone(),
15351                        kind: Some(CompletionItemKind::SNIPPET),
15352                        label_details: snippet.description.as_ref().map(|description| {
15353                            lsp::CompletionItemLabelDetails {
15354                                detail: Some(description.clone()),
15355                                description: None,
15356                            }
15357                        }),
15358                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15359                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15360                            lsp::InsertReplaceEdit {
15361                                new_text: snippet.body.clone(),
15362                                insert: lsp_range,
15363                                replace: lsp_range,
15364                            },
15365                        )),
15366                        filter_text: Some(snippet.body.clone()),
15367                        sort_text: Some(char::MAX.to_string()),
15368                        ..Default::default()
15369                    },
15370                    confirm: None,
15371                })
15372            })
15373            .collect();
15374
15375        Ok(result)
15376    })
15377}
15378
15379impl CompletionProvider for Entity<Project> {
15380    fn completions(
15381        &self,
15382        buffer: &Entity<Buffer>,
15383        buffer_position: text::Anchor,
15384        options: CompletionContext,
15385        _window: &mut Window,
15386        cx: &mut Context<Editor>,
15387    ) -> Task<Result<Vec<Completion>>> {
15388        self.update(cx, |project, cx| {
15389            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15390            let project_completions = project.completions(buffer, buffer_position, options, cx);
15391            cx.background_executor().spawn(async move {
15392                let mut completions = project_completions.await?;
15393                let snippets_completions = snippets.await?;
15394                completions.extend(snippets_completions);
15395                Ok(completions)
15396            })
15397        })
15398    }
15399
15400    fn resolve_completions(
15401        &self,
15402        buffer: Entity<Buffer>,
15403        completion_indices: Vec<usize>,
15404        completions: Rc<RefCell<Box<[Completion]>>>,
15405        cx: &mut Context<Editor>,
15406    ) -> Task<Result<bool>> {
15407        self.update(cx, |project, cx| {
15408            project.lsp_store().update(cx, |lsp_store, cx| {
15409                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15410            })
15411        })
15412    }
15413
15414    fn apply_additional_edits_for_completion(
15415        &self,
15416        buffer: Entity<Buffer>,
15417        completions: Rc<RefCell<Box<[Completion]>>>,
15418        completion_index: usize,
15419        push_to_history: bool,
15420        cx: &mut Context<Editor>,
15421    ) -> Task<Result<Option<language::Transaction>>> {
15422        self.update(cx, |project, cx| {
15423            project.lsp_store().update(cx, |lsp_store, cx| {
15424                lsp_store.apply_additional_edits_for_completion(
15425                    buffer,
15426                    completions,
15427                    completion_index,
15428                    push_to_history,
15429                    cx,
15430                )
15431            })
15432        })
15433    }
15434
15435    fn is_completion_trigger(
15436        &self,
15437        buffer: &Entity<Buffer>,
15438        position: language::Anchor,
15439        text: &str,
15440        trigger_in_words: bool,
15441        cx: &mut Context<Editor>,
15442    ) -> bool {
15443        let mut chars = text.chars();
15444        let char = if let Some(char) = chars.next() {
15445            char
15446        } else {
15447            return false;
15448        };
15449        if chars.next().is_some() {
15450            return false;
15451        }
15452
15453        let buffer = buffer.read(cx);
15454        let snapshot = buffer.snapshot();
15455        if !snapshot.settings_at(position, cx).show_completions_on_input {
15456            return false;
15457        }
15458        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15459        if trigger_in_words && classifier.is_word(char) {
15460            return true;
15461        }
15462
15463        buffer.completion_triggers().contains(text)
15464    }
15465}
15466
15467impl SemanticsProvider for Entity<Project> {
15468    fn hover(
15469        &self,
15470        buffer: &Entity<Buffer>,
15471        position: text::Anchor,
15472        cx: &mut App,
15473    ) -> Option<Task<Vec<project::Hover>>> {
15474        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15475    }
15476
15477    fn document_highlights(
15478        &self,
15479        buffer: &Entity<Buffer>,
15480        position: text::Anchor,
15481        cx: &mut App,
15482    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15483        Some(self.update(cx, |project, cx| {
15484            project.document_highlights(buffer, position, cx)
15485        }))
15486    }
15487
15488    fn definitions(
15489        &self,
15490        buffer: &Entity<Buffer>,
15491        position: text::Anchor,
15492        kind: GotoDefinitionKind,
15493        cx: &mut App,
15494    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15495        Some(self.update(cx, |project, cx| match kind {
15496            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15497            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15498            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15499            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15500        }))
15501    }
15502
15503    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15504        // TODO: make this work for remote projects
15505        self.read(cx)
15506            .language_servers_for_local_buffer(buffer.read(cx), cx)
15507            .any(
15508                |(_, server)| match server.capabilities().inlay_hint_provider {
15509                    Some(lsp::OneOf::Left(enabled)) => enabled,
15510                    Some(lsp::OneOf::Right(_)) => true,
15511                    None => false,
15512                },
15513            )
15514    }
15515
15516    fn inlay_hints(
15517        &self,
15518        buffer_handle: Entity<Buffer>,
15519        range: Range<text::Anchor>,
15520        cx: &mut App,
15521    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15522        Some(self.update(cx, |project, cx| {
15523            project.inlay_hints(buffer_handle, range, cx)
15524        }))
15525    }
15526
15527    fn resolve_inlay_hint(
15528        &self,
15529        hint: InlayHint,
15530        buffer_handle: Entity<Buffer>,
15531        server_id: LanguageServerId,
15532        cx: &mut App,
15533    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15534        Some(self.update(cx, |project, cx| {
15535            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15536        }))
15537    }
15538
15539    fn range_for_rename(
15540        &self,
15541        buffer: &Entity<Buffer>,
15542        position: text::Anchor,
15543        cx: &mut App,
15544    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15545        Some(self.update(cx, |project, cx| {
15546            let buffer = buffer.clone();
15547            let task = project.prepare_rename(buffer.clone(), position, cx);
15548            cx.spawn(|_, mut cx| async move {
15549                Ok(match task.await? {
15550                    PrepareRenameResponse::Success(range) => Some(range),
15551                    PrepareRenameResponse::InvalidPosition => None,
15552                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15553                        // Fallback on using TreeSitter info to determine identifier range
15554                        buffer.update(&mut cx, |buffer, _| {
15555                            let snapshot = buffer.snapshot();
15556                            let (range, kind) = snapshot.surrounding_word(position);
15557                            if kind != Some(CharKind::Word) {
15558                                return None;
15559                            }
15560                            Some(
15561                                snapshot.anchor_before(range.start)
15562                                    ..snapshot.anchor_after(range.end),
15563                            )
15564                        })?
15565                    }
15566                })
15567            })
15568        }))
15569    }
15570
15571    fn perform_rename(
15572        &self,
15573        buffer: &Entity<Buffer>,
15574        position: text::Anchor,
15575        new_name: String,
15576        cx: &mut App,
15577    ) -> Option<Task<Result<ProjectTransaction>>> {
15578        Some(self.update(cx, |project, cx| {
15579            project.perform_rename(buffer.clone(), position, new_name, cx)
15580        }))
15581    }
15582}
15583
15584fn inlay_hint_settings(
15585    location: Anchor,
15586    snapshot: &MultiBufferSnapshot,
15587    cx: &mut Context<Editor>,
15588) -> InlayHintSettings {
15589    let file = snapshot.file_at(location);
15590    let language = snapshot.language_at(location).map(|l| l.name());
15591    language_settings(language, file, cx).inlay_hints
15592}
15593
15594fn consume_contiguous_rows(
15595    contiguous_row_selections: &mut Vec<Selection<Point>>,
15596    selection: &Selection<Point>,
15597    display_map: &DisplaySnapshot,
15598    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15599) -> (MultiBufferRow, MultiBufferRow) {
15600    contiguous_row_selections.push(selection.clone());
15601    let start_row = MultiBufferRow(selection.start.row);
15602    let mut end_row = ending_row(selection, display_map);
15603
15604    while let Some(next_selection) = selections.peek() {
15605        if next_selection.start.row <= end_row.0 {
15606            end_row = ending_row(next_selection, display_map);
15607            contiguous_row_selections.push(selections.next().unwrap().clone());
15608        } else {
15609            break;
15610        }
15611    }
15612    (start_row, end_row)
15613}
15614
15615fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15616    if next_selection.end.column > 0 || next_selection.is_empty() {
15617        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15618    } else {
15619        MultiBufferRow(next_selection.end.row)
15620    }
15621}
15622
15623impl EditorSnapshot {
15624    pub fn remote_selections_in_range<'a>(
15625        &'a self,
15626        range: &'a Range<Anchor>,
15627        collaboration_hub: &dyn CollaborationHub,
15628        cx: &'a App,
15629    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15630        let participant_names = collaboration_hub.user_names(cx);
15631        let participant_indices = collaboration_hub.user_participant_indices(cx);
15632        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15633        let collaborators_by_replica_id = collaborators_by_peer_id
15634            .iter()
15635            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15636            .collect::<HashMap<_, _>>();
15637        self.buffer_snapshot
15638            .selections_in_range(range, false)
15639            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15640                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15641                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15642                let user_name = participant_names.get(&collaborator.user_id).cloned();
15643                Some(RemoteSelection {
15644                    replica_id,
15645                    selection,
15646                    cursor_shape,
15647                    line_mode,
15648                    participant_index,
15649                    peer_id: collaborator.peer_id,
15650                    user_name,
15651                })
15652            })
15653    }
15654
15655    pub fn hunks_for_ranges(
15656        &self,
15657        ranges: impl Iterator<Item = Range<Point>>,
15658    ) -> Vec<MultiBufferDiffHunk> {
15659        let mut hunks = Vec::new();
15660        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15661            HashMap::default();
15662        for query_range in ranges {
15663            let query_rows =
15664                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15665            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15666                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15667            ) {
15668                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15669                // when the caret is just above or just below the deleted hunk.
15670                let allow_adjacent = hunk.status().is_removed();
15671                let related_to_selection = if allow_adjacent {
15672                    hunk.row_range.overlaps(&query_rows)
15673                        || hunk.row_range.start == query_rows.end
15674                        || hunk.row_range.end == query_rows.start
15675                } else {
15676                    hunk.row_range.overlaps(&query_rows)
15677                };
15678                if related_to_selection {
15679                    if !processed_buffer_rows
15680                        .entry(hunk.buffer_id)
15681                        .or_default()
15682                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15683                    {
15684                        continue;
15685                    }
15686                    hunks.push(hunk);
15687                }
15688            }
15689        }
15690
15691        hunks
15692    }
15693
15694    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15695        self.display_snapshot.buffer_snapshot.language_at(position)
15696    }
15697
15698    pub fn is_focused(&self) -> bool {
15699        self.is_focused
15700    }
15701
15702    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15703        self.placeholder_text.as_ref()
15704    }
15705
15706    pub fn scroll_position(&self) -> gpui::Point<f32> {
15707        self.scroll_anchor.scroll_position(&self.display_snapshot)
15708    }
15709
15710    fn gutter_dimensions(
15711        &self,
15712        font_id: FontId,
15713        font_size: Pixels,
15714        max_line_number_width: Pixels,
15715        cx: &App,
15716    ) -> Option<GutterDimensions> {
15717        if !self.show_gutter {
15718            return None;
15719        }
15720
15721        let descent = cx.text_system().descent(font_id, font_size);
15722        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15723        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15724
15725        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15726            matches!(
15727                ProjectSettings::get_global(cx).git.git_gutter,
15728                Some(GitGutterSetting::TrackedFiles)
15729            )
15730        });
15731        let gutter_settings = EditorSettings::get_global(cx).gutter;
15732        let show_line_numbers = self
15733            .show_line_numbers
15734            .unwrap_or(gutter_settings.line_numbers);
15735        let line_gutter_width = if show_line_numbers {
15736            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15737            let min_width_for_number_on_gutter = em_advance * 4.0;
15738            max_line_number_width.max(min_width_for_number_on_gutter)
15739        } else {
15740            0.0.into()
15741        };
15742
15743        let show_code_actions = self
15744            .show_code_actions
15745            .unwrap_or(gutter_settings.code_actions);
15746
15747        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15748
15749        let git_blame_entries_width =
15750            self.git_blame_gutter_max_author_length
15751                .map(|max_author_length| {
15752                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15753
15754                    /// The number of characters to dedicate to gaps and margins.
15755                    const SPACING_WIDTH: usize = 4;
15756
15757                    let max_char_count = max_author_length
15758                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15759                        + ::git::SHORT_SHA_LENGTH
15760                        + MAX_RELATIVE_TIMESTAMP.len()
15761                        + SPACING_WIDTH;
15762
15763                    em_advance * max_char_count
15764                });
15765
15766        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15767        left_padding += if show_code_actions || show_runnables {
15768            em_width * 3.0
15769        } else if show_git_gutter && show_line_numbers {
15770            em_width * 2.0
15771        } else if show_git_gutter || show_line_numbers {
15772            em_width
15773        } else {
15774            px(0.)
15775        };
15776
15777        let right_padding = if gutter_settings.folds && show_line_numbers {
15778            em_width * 4.0
15779        } else if gutter_settings.folds {
15780            em_width * 3.0
15781        } else if show_line_numbers {
15782            em_width
15783        } else {
15784            px(0.)
15785        };
15786
15787        Some(GutterDimensions {
15788            left_padding,
15789            right_padding,
15790            width: line_gutter_width + left_padding + right_padding,
15791            margin: -descent,
15792            git_blame_entries_width,
15793        })
15794    }
15795
15796    pub fn render_crease_toggle(
15797        &self,
15798        buffer_row: MultiBufferRow,
15799        row_contains_cursor: bool,
15800        editor: Entity<Editor>,
15801        window: &mut Window,
15802        cx: &mut App,
15803    ) -> Option<AnyElement> {
15804        let folded = self.is_line_folded(buffer_row);
15805        let mut is_foldable = false;
15806
15807        if let Some(crease) = self
15808            .crease_snapshot
15809            .query_row(buffer_row, &self.buffer_snapshot)
15810        {
15811            is_foldable = true;
15812            match crease {
15813                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15814                    if let Some(render_toggle) = render_toggle {
15815                        let toggle_callback =
15816                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15817                                if folded {
15818                                    editor.update(cx, |editor, cx| {
15819                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15820                                    });
15821                                } else {
15822                                    editor.update(cx, |editor, cx| {
15823                                        editor.unfold_at(
15824                                            &crate::UnfoldAt { buffer_row },
15825                                            window,
15826                                            cx,
15827                                        )
15828                                    });
15829                                }
15830                            });
15831                        return Some((render_toggle)(
15832                            buffer_row,
15833                            folded,
15834                            toggle_callback,
15835                            window,
15836                            cx,
15837                        ));
15838                    }
15839                }
15840            }
15841        }
15842
15843        is_foldable |= self.starts_indent(buffer_row);
15844
15845        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15846            Some(
15847                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15848                    .toggle_state(folded)
15849                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15850                        if folded {
15851                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15852                        } else {
15853                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15854                        }
15855                    }))
15856                    .into_any_element(),
15857            )
15858        } else {
15859            None
15860        }
15861    }
15862
15863    pub fn render_crease_trailer(
15864        &self,
15865        buffer_row: MultiBufferRow,
15866        window: &mut Window,
15867        cx: &mut App,
15868    ) -> Option<AnyElement> {
15869        let folded = self.is_line_folded(buffer_row);
15870        if let Crease::Inline { render_trailer, .. } = self
15871            .crease_snapshot
15872            .query_row(buffer_row, &self.buffer_snapshot)?
15873        {
15874            let render_trailer = render_trailer.as_ref()?;
15875            Some(render_trailer(buffer_row, folded, window, cx))
15876        } else {
15877            None
15878        }
15879    }
15880}
15881
15882impl Deref for EditorSnapshot {
15883    type Target = DisplaySnapshot;
15884
15885    fn deref(&self) -> &Self::Target {
15886        &self.display_snapshot
15887    }
15888}
15889
15890#[derive(Clone, Debug, PartialEq, Eq)]
15891pub enum EditorEvent {
15892    InputIgnored {
15893        text: Arc<str>,
15894    },
15895    InputHandled {
15896        utf16_range_to_replace: Option<Range<isize>>,
15897        text: Arc<str>,
15898    },
15899    ExcerptsAdded {
15900        buffer: Entity<Buffer>,
15901        predecessor: ExcerptId,
15902        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15903    },
15904    ExcerptsRemoved {
15905        ids: Vec<ExcerptId>,
15906    },
15907    BufferFoldToggled {
15908        ids: Vec<ExcerptId>,
15909        folded: bool,
15910    },
15911    ExcerptsEdited {
15912        ids: Vec<ExcerptId>,
15913    },
15914    ExcerptsExpanded {
15915        ids: Vec<ExcerptId>,
15916    },
15917    BufferEdited,
15918    Edited {
15919        transaction_id: clock::Lamport,
15920    },
15921    Reparsed(BufferId),
15922    Focused,
15923    FocusedIn,
15924    Blurred,
15925    DirtyChanged,
15926    Saved,
15927    TitleChanged,
15928    DiffBaseChanged,
15929    SelectionsChanged {
15930        local: bool,
15931    },
15932    ScrollPositionChanged {
15933        local: bool,
15934        autoscroll: bool,
15935    },
15936    Closed,
15937    TransactionUndone {
15938        transaction_id: clock::Lamport,
15939    },
15940    TransactionBegun {
15941        transaction_id: clock::Lamport,
15942    },
15943    Reloaded,
15944    CursorShapeChanged,
15945}
15946
15947impl EventEmitter<EditorEvent> for Editor {}
15948
15949impl Focusable for Editor {
15950    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15951        self.focus_handle.clone()
15952    }
15953}
15954
15955impl Render for Editor {
15956    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15957        let settings = ThemeSettings::get_global(cx);
15958
15959        let mut text_style = match self.mode {
15960            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15961                color: cx.theme().colors().editor_foreground,
15962                font_family: settings.ui_font.family.clone(),
15963                font_features: settings.ui_font.features.clone(),
15964                font_fallbacks: settings.ui_font.fallbacks.clone(),
15965                font_size: rems(0.875).into(),
15966                font_weight: settings.ui_font.weight,
15967                line_height: relative(settings.buffer_line_height.value()),
15968                ..Default::default()
15969            },
15970            EditorMode::Full => TextStyle {
15971                color: cx.theme().colors().editor_foreground,
15972                font_family: settings.buffer_font.family.clone(),
15973                font_features: settings.buffer_font.features.clone(),
15974                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15975                font_size: settings.buffer_font_size().into(),
15976                font_weight: settings.buffer_font.weight,
15977                line_height: relative(settings.buffer_line_height.value()),
15978                ..Default::default()
15979            },
15980        };
15981        if let Some(text_style_refinement) = &self.text_style_refinement {
15982            text_style.refine(text_style_refinement)
15983        }
15984
15985        let background = match self.mode {
15986            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15987            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15988            EditorMode::Full => cx.theme().colors().editor_background,
15989        };
15990
15991        EditorElement::new(
15992            &cx.entity(),
15993            EditorStyle {
15994                background,
15995                local_player: cx.theme().players().local(),
15996                text: text_style,
15997                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15998                syntax: cx.theme().syntax().clone(),
15999                status: cx.theme().status().clone(),
16000                inlay_hints_style: make_inlay_hints_style(cx),
16001                inline_completion_styles: make_suggestion_styles(cx),
16002                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16003            },
16004        )
16005    }
16006}
16007
16008impl EntityInputHandler for Editor {
16009    fn text_for_range(
16010        &mut self,
16011        range_utf16: Range<usize>,
16012        adjusted_range: &mut Option<Range<usize>>,
16013        _: &mut Window,
16014        cx: &mut Context<Self>,
16015    ) -> Option<String> {
16016        let snapshot = self.buffer.read(cx).read(cx);
16017        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16018        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16019        if (start.0..end.0) != range_utf16 {
16020            adjusted_range.replace(start.0..end.0);
16021        }
16022        Some(snapshot.text_for_range(start..end).collect())
16023    }
16024
16025    fn selected_text_range(
16026        &mut self,
16027        ignore_disabled_input: bool,
16028        _: &mut Window,
16029        cx: &mut Context<Self>,
16030    ) -> Option<UTF16Selection> {
16031        // Prevent the IME menu from appearing when holding down an alphabetic key
16032        // while input is disabled.
16033        if !ignore_disabled_input && !self.input_enabled {
16034            return None;
16035        }
16036
16037        let selection = self.selections.newest::<OffsetUtf16>(cx);
16038        let range = selection.range();
16039
16040        Some(UTF16Selection {
16041            range: range.start.0..range.end.0,
16042            reversed: selection.reversed,
16043        })
16044    }
16045
16046    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16047        let snapshot = self.buffer.read(cx).read(cx);
16048        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16049        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16050    }
16051
16052    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16053        self.clear_highlights::<InputComposition>(cx);
16054        self.ime_transaction.take();
16055    }
16056
16057    fn replace_text_in_range(
16058        &mut self,
16059        range_utf16: Option<Range<usize>>,
16060        text: &str,
16061        window: &mut Window,
16062        cx: &mut Context<Self>,
16063    ) {
16064        if !self.input_enabled {
16065            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16066            return;
16067        }
16068
16069        self.transact(window, cx, |this, window, cx| {
16070            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16071                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16072                Some(this.selection_replacement_ranges(range_utf16, cx))
16073            } else {
16074                this.marked_text_ranges(cx)
16075            };
16076
16077            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16078                let newest_selection_id = this.selections.newest_anchor().id;
16079                this.selections
16080                    .all::<OffsetUtf16>(cx)
16081                    .iter()
16082                    .zip(ranges_to_replace.iter())
16083                    .find_map(|(selection, range)| {
16084                        if selection.id == newest_selection_id {
16085                            Some(
16086                                (range.start.0 as isize - selection.head().0 as isize)
16087                                    ..(range.end.0 as isize - selection.head().0 as isize),
16088                            )
16089                        } else {
16090                            None
16091                        }
16092                    })
16093            });
16094
16095            cx.emit(EditorEvent::InputHandled {
16096                utf16_range_to_replace: range_to_replace,
16097                text: text.into(),
16098            });
16099
16100            if let Some(new_selected_ranges) = new_selected_ranges {
16101                this.change_selections(None, window, cx, |selections| {
16102                    selections.select_ranges(new_selected_ranges)
16103                });
16104                this.backspace(&Default::default(), window, cx);
16105            }
16106
16107            this.handle_input(text, window, cx);
16108        });
16109
16110        if let Some(transaction) = self.ime_transaction {
16111            self.buffer.update(cx, |buffer, cx| {
16112                buffer.group_until_transaction(transaction, cx);
16113            });
16114        }
16115
16116        self.unmark_text(window, cx);
16117    }
16118
16119    fn replace_and_mark_text_in_range(
16120        &mut self,
16121        range_utf16: Option<Range<usize>>,
16122        text: &str,
16123        new_selected_range_utf16: Option<Range<usize>>,
16124        window: &mut Window,
16125        cx: &mut Context<Self>,
16126    ) {
16127        if !self.input_enabled {
16128            return;
16129        }
16130
16131        let transaction = self.transact(window, cx, |this, window, cx| {
16132            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16133                let snapshot = this.buffer.read(cx).read(cx);
16134                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16135                    for marked_range in &mut marked_ranges {
16136                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16137                        marked_range.start.0 += relative_range_utf16.start;
16138                        marked_range.start =
16139                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16140                        marked_range.end =
16141                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16142                    }
16143                }
16144                Some(marked_ranges)
16145            } else if let Some(range_utf16) = range_utf16 {
16146                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16147                Some(this.selection_replacement_ranges(range_utf16, cx))
16148            } else {
16149                None
16150            };
16151
16152            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16153                let newest_selection_id = this.selections.newest_anchor().id;
16154                this.selections
16155                    .all::<OffsetUtf16>(cx)
16156                    .iter()
16157                    .zip(ranges_to_replace.iter())
16158                    .find_map(|(selection, range)| {
16159                        if selection.id == newest_selection_id {
16160                            Some(
16161                                (range.start.0 as isize - selection.head().0 as isize)
16162                                    ..(range.end.0 as isize - selection.head().0 as isize),
16163                            )
16164                        } else {
16165                            None
16166                        }
16167                    })
16168            });
16169
16170            cx.emit(EditorEvent::InputHandled {
16171                utf16_range_to_replace: range_to_replace,
16172                text: text.into(),
16173            });
16174
16175            if let Some(ranges) = ranges_to_replace {
16176                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16177            }
16178
16179            let marked_ranges = {
16180                let snapshot = this.buffer.read(cx).read(cx);
16181                this.selections
16182                    .disjoint_anchors()
16183                    .iter()
16184                    .map(|selection| {
16185                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16186                    })
16187                    .collect::<Vec<_>>()
16188            };
16189
16190            if text.is_empty() {
16191                this.unmark_text(window, cx);
16192            } else {
16193                this.highlight_text::<InputComposition>(
16194                    marked_ranges.clone(),
16195                    HighlightStyle {
16196                        underline: Some(UnderlineStyle {
16197                            thickness: px(1.),
16198                            color: None,
16199                            wavy: false,
16200                        }),
16201                        ..Default::default()
16202                    },
16203                    cx,
16204                );
16205            }
16206
16207            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16208            let use_autoclose = this.use_autoclose;
16209            let use_auto_surround = this.use_auto_surround;
16210            this.set_use_autoclose(false);
16211            this.set_use_auto_surround(false);
16212            this.handle_input(text, window, cx);
16213            this.set_use_autoclose(use_autoclose);
16214            this.set_use_auto_surround(use_auto_surround);
16215
16216            if let Some(new_selected_range) = new_selected_range_utf16 {
16217                let snapshot = this.buffer.read(cx).read(cx);
16218                let new_selected_ranges = marked_ranges
16219                    .into_iter()
16220                    .map(|marked_range| {
16221                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16222                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16223                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16224                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16225                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16226                    })
16227                    .collect::<Vec<_>>();
16228
16229                drop(snapshot);
16230                this.change_selections(None, window, cx, |selections| {
16231                    selections.select_ranges(new_selected_ranges)
16232                });
16233            }
16234        });
16235
16236        self.ime_transaction = self.ime_transaction.or(transaction);
16237        if let Some(transaction) = self.ime_transaction {
16238            self.buffer.update(cx, |buffer, cx| {
16239                buffer.group_until_transaction(transaction, cx);
16240            });
16241        }
16242
16243        if self.text_highlights::<InputComposition>(cx).is_none() {
16244            self.ime_transaction.take();
16245        }
16246    }
16247
16248    fn bounds_for_range(
16249        &mut self,
16250        range_utf16: Range<usize>,
16251        element_bounds: gpui::Bounds<Pixels>,
16252        window: &mut Window,
16253        cx: &mut Context<Self>,
16254    ) -> Option<gpui::Bounds<Pixels>> {
16255        let text_layout_details = self.text_layout_details(window);
16256        let gpui::Size {
16257            width: em_width,
16258            height: line_height,
16259        } = self.character_size(window);
16260
16261        let snapshot = self.snapshot(window, cx);
16262        let scroll_position = snapshot.scroll_position();
16263        let scroll_left = scroll_position.x * em_width;
16264
16265        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16266        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16267            + self.gutter_dimensions.width
16268            + self.gutter_dimensions.margin;
16269        let y = line_height * (start.row().as_f32() - scroll_position.y);
16270
16271        Some(Bounds {
16272            origin: element_bounds.origin + point(x, y),
16273            size: size(em_width, line_height),
16274        })
16275    }
16276
16277    fn character_index_for_point(
16278        &mut self,
16279        point: gpui::Point<Pixels>,
16280        _window: &mut Window,
16281        _cx: &mut Context<Self>,
16282    ) -> Option<usize> {
16283        let position_map = self.last_position_map.as_ref()?;
16284        if !position_map.text_hitbox.contains(&point) {
16285            return None;
16286        }
16287        let display_point = position_map.point_for_position(point).previous_valid;
16288        let anchor = position_map
16289            .snapshot
16290            .display_point_to_anchor(display_point, Bias::Left);
16291        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16292        Some(utf16_offset.0)
16293    }
16294}
16295
16296trait SelectionExt {
16297    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16298    fn spanned_rows(
16299        &self,
16300        include_end_if_at_line_start: bool,
16301        map: &DisplaySnapshot,
16302    ) -> Range<MultiBufferRow>;
16303}
16304
16305impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16306    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16307        let start = self
16308            .start
16309            .to_point(&map.buffer_snapshot)
16310            .to_display_point(map);
16311        let end = self
16312            .end
16313            .to_point(&map.buffer_snapshot)
16314            .to_display_point(map);
16315        if self.reversed {
16316            end..start
16317        } else {
16318            start..end
16319        }
16320    }
16321
16322    fn spanned_rows(
16323        &self,
16324        include_end_if_at_line_start: bool,
16325        map: &DisplaySnapshot,
16326    ) -> Range<MultiBufferRow> {
16327        let start = self.start.to_point(&map.buffer_snapshot);
16328        let mut end = self.end.to_point(&map.buffer_snapshot);
16329        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16330            end.row -= 1;
16331        }
16332
16333        let buffer_start = map.prev_line_boundary(start).0;
16334        let buffer_end = map.next_line_boundary(end).0;
16335        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16336    }
16337}
16338
16339impl<T: InvalidationRegion> InvalidationStack<T> {
16340    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16341    where
16342        S: Clone + ToOffset,
16343    {
16344        while let Some(region) = self.last() {
16345            let all_selections_inside_invalidation_ranges =
16346                if selections.len() == region.ranges().len() {
16347                    selections
16348                        .iter()
16349                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16350                        .all(|(selection, invalidation_range)| {
16351                            let head = selection.head().to_offset(buffer);
16352                            invalidation_range.start <= head && invalidation_range.end >= head
16353                        })
16354                } else {
16355                    false
16356                };
16357
16358            if all_selections_inside_invalidation_ranges {
16359                break;
16360            } else {
16361                self.pop();
16362            }
16363        }
16364    }
16365}
16366
16367impl<T> Default for InvalidationStack<T> {
16368    fn default() -> Self {
16369        Self(Default::default())
16370    }
16371}
16372
16373impl<T> Deref for InvalidationStack<T> {
16374    type Target = Vec<T>;
16375
16376    fn deref(&self) -> &Self::Target {
16377        &self.0
16378    }
16379}
16380
16381impl<T> DerefMut for InvalidationStack<T> {
16382    fn deref_mut(&mut self) -> &mut Self::Target {
16383        &mut self.0
16384    }
16385}
16386
16387impl InvalidationRegion for SnippetState {
16388    fn ranges(&self) -> &[Range<Anchor>] {
16389        &self.ranges[self.active_index]
16390    }
16391}
16392
16393pub fn diagnostic_block_renderer(
16394    diagnostic: Diagnostic,
16395    max_message_rows: Option<u8>,
16396    allow_closing: bool,
16397    _is_valid: bool,
16398) -> RenderBlock {
16399    let (text_without_backticks, code_ranges) =
16400        highlight_diagnostic_message(&diagnostic, max_message_rows);
16401
16402    Arc::new(move |cx: &mut BlockContext| {
16403        let group_id: SharedString = cx.block_id.to_string().into();
16404
16405        let mut text_style = cx.window.text_style().clone();
16406        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16407        let theme_settings = ThemeSettings::get_global(cx);
16408        text_style.font_family = theme_settings.buffer_font.family.clone();
16409        text_style.font_style = theme_settings.buffer_font.style;
16410        text_style.font_features = theme_settings.buffer_font.features.clone();
16411        text_style.font_weight = theme_settings.buffer_font.weight;
16412
16413        let multi_line_diagnostic = diagnostic.message.contains('\n');
16414
16415        let buttons = |diagnostic: &Diagnostic| {
16416            if multi_line_diagnostic {
16417                v_flex()
16418            } else {
16419                h_flex()
16420            }
16421            .when(allow_closing, |div| {
16422                div.children(diagnostic.is_primary.then(|| {
16423                    IconButton::new("close-block", IconName::XCircle)
16424                        .icon_color(Color::Muted)
16425                        .size(ButtonSize::Compact)
16426                        .style(ButtonStyle::Transparent)
16427                        .visible_on_hover(group_id.clone())
16428                        .on_click(move |_click, window, cx| {
16429                            window.dispatch_action(Box::new(Cancel), cx)
16430                        })
16431                        .tooltip(|window, cx| {
16432                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16433                        })
16434                }))
16435            })
16436            .child(
16437                IconButton::new("copy-block", IconName::Copy)
16438                    .icon_color(Color::Muted)
16439                    .size(ButtonSize::Compact)
16440                    .style(ButtonStyle::Transparent)
16441                    .visible_on_hover(group_id.clone())
16442                    .on_click({
16443                        let message = diagnostic.message.clone();
16444                        move |_click, _, cx| {
16445                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16446                        }
16447                    })
16448                    .tooltip(Tooltip::text("Copy diagnostic message")),
16449            )
16450        };
16451
16452        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16453            AvailableSpace::min_size(),
16454            cx.window,
16455            cx.app,
16456        );
16457
16458        h_flex()
16459            .id(cx.block_id)
16460            .group(group_id.clone())
16461            .relative()
16462            .size_full()
16463            .block_mouse_down()
16464            .pl(cx.gutter_dimensions.width)
16465            .w(cx.max_width - cx.gutter_dimensions.full_width())
16466            .child(
16467                div()
16468                    .flex()
16469                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16470                    .flex_shrink(),
16471            )
16472            .child(buttons(&diagnostic))
16473            .child(div().flex().flex_shrink_0().child(
16474                StyledText::new(text_without_backticks.clone()).with_highlights(
16475                    &text_style,
16476                    code_ranges.iter().map(|range| {
16477                        (
16478                            range.clone(),
16479                            HighlightStyle {
16480                                font_weight: Some(FontWeight::BOLD),
16481                                ..Default::default()
16482                            },
16483                        )
16484                    }),
16485                ),
16486            ))
16487            .into_any_element()
16488    })
16489}
16490
16491fn inline_completion_edit_text(
16492    current_snapshot: &BufferSnapshot,
16493    edits: &[(Range<Anchor>, String)],
16494    edit_preview: &EditPreview,
16495    include_deletions: bool,
16496    cx: &App,
16497) -> HighlightedText {
16498    let edits = edits
16499        .iter()
16500        .map(|(anchor, text)| {
16501            (
16502                anchor.start.text_anchor..anchor.end.text_anchor,
16503                text.clone(),
16504            )
16505        })
16506        .collect::<Vec<_>>();
16507
16508    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16509}
16510
16511pub fn highlight_diagnostic_message(
16512    diagnostic: &Diagnostic,
16513    mut max_message_rows: Option<u8>,
16514) -> (SharedString, Vec<Range<usize>>) {
16515    let mut text_without_backticks = String::new();
16516    let mut code_ranges = Vec::new();
16517
16518    if let Some(source) = &diagnostic.source {
16519        text_without_backticks.push_str(source);
16520        code_ranges.push(0..source.len());
16521        text_without_backticks.push_str(": ");
16522    }
16523
16524    let mut prev_offset = 0;
16525    let mut in_code_block = false;
16526    let has_row_limit = max_message_rows.is_some();
16527    let mut newline_indices = diagnostic
16528        .message
16529        .match_indices('\n')
16530        .filter(|_| has_row_limit)
16531        .map(|(ix, _)| ix)
16532        .fuse()
16533        .peekable();
16534
16535    for (quote_ix, _) in diagnostic
16536        .message
16537        .match_indices('`')
16538        .chain([(diagnostic.message.len(), "")])
16539    {
16540        let mut first_newline_ix = None;
16541        let mut last_newline_ix = None;
16542        while let Some(newline_ix) = newline_indices.peek() {
16543            if *newline_ix < quote_ix {
16544                if first_newline_ix.is_none() {
16545                    first_newline_ix = Some(*newline_ix);
16546                }
16547                last_newline_ix = Some(*newline_ix);
16548
16549                if let Some(rows_left) = &mut max_message_rows {
16550                    if *rows_left == 0 {
16551                        break;
16552                    } else {
16553                        *rows_left -= 1;
16554                    }
16555                }
16556                let _ = newline_indices.next();
16557            } else {
16558                break;
16559            }
16560        }
16561        let prev_len = text_without_backticks.len();
16562        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16563        text_without_backticks.push_str(new_text);
16564        if in_code_block {
16565            code_ranges.push(prev_len..text_without_backticks.len());
16566        }
16567        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16568        in_code_block = !in_code_block;
16569        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16570            text_without_backticks.push_str("...");
16571            break;
16572        }
16573    }
16574
16575    (text_without_backticks.into(), code_ranges)
16576}
16577
16578fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16579    match severity {
16580        DiagnosticSeverity::ERROR => colors.error,
16581        DiagnosticSeverity::WARNING => colors.warning,
16582        DiagnosticSeverity::INFORMATION => colors.info,
16583        DiagnosticSeverity::HINT => colors.info,
16584        _ => colors.ignored,
16585    }
16586}
16587
16588pub fn styled_runs_for_code_label<'a>(
16589    label: &'a CodeLabel,
16590    syntax_theme: &'a theme::SyntaxTheme,
16591) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16592    let fade_out = HighlightStyle {
16593        fade_out: Some(0.35),
16594        ..Default::default()
16595    };
16596
16597    let mut prev_end = label.filter_range.end;
16598    label
16599        .runs
16600        .iter()
16601        .enumerate()
16602        .flat_map(move |(ix, (range, highlight_id))| {
16603            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16604                style
16605            } else {
16606                return Default::default();
16607            };
16608            let mut muted_style = style;
16609            muted_style.highlight(fade_out);
16610
16611            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16612            if range.start >= label.filter_range.end {
16613                if range.start > prev_end {
16614                    runs.push((prev_end..range.start, fade_out));
16615                }
16616                runs.push((range.clone(), muted_style));
16617            } else if range.end <= label.filter_range.end {
16618                runs.push((range.clone(), style));
16619            } else {
16620                runs.push((range.start..label.filter_range.end, style));
16621                runs.push((label.filter_range.end..range.end, muted_style));
16622            }
16623            prev_end = cmp::max(prev_end, range.end);
16624
16625            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16626                runs.push((prev_end..label.text.len(), fade_out));
16627            }
16628
16629            runs
16630        })
16631}
16632
16633pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16634    let mut prev_index = 0;
16635    let mut prev_codepoint: Option<char> = None;
16636    text.char_indices()
16637        .chain([(text.len(), '\0')])
16638        .filter_map(move |(index, codepoint)| {
16639            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16640            let is_boundary = index == text.len()
16641                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16642                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16643            if is_boundary {
16644                let chunk = &text[prev_index..index];
16645                prev_index = index;
16646                Some(chunk)
16647            } else {
16648                None
16649            }
16650        })
16651}
16652
16653pub trait RangeToAnchorExt: Sized {
16654    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16655
16656    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16657        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16658        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16659    }
16660}
16661
16662impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16663    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16664        let start_offset = self.start.to_offset(snapshot);
16665        let end_offset = self.end.to_offset(snapshot);
16666        if start_offset == end_offset {
16667            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16668        } else {
16669            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16670        }
16671    }
16672}
16673
16674pub trait RowExt {
16675    fn as_f32(&self) -> f32;
16676
16677    fn next_row(&self) -> Self;
16678
16679    fn previous_row(&self) -> Self;
16680
16681    fn minus(&self, other: Self) -> u32;
16682}
16683
16684impl RowExt for DisplayRow {
16685    fn as_f32(&self) -> f32 {
16686        self.0 as f32
16687    }
16688
16689    fn next_row(&self) -> Self {
16690        Self(self.0 + 1)
16691    }
16692
16693    fn previous_row(&self) -> Self {
16694        Self(self.0.saturating_sub(1))
16695    }
16696
16697    fn minus(&self, other: Self) -> u32 {
16698        self.0 - other.0
16699    }
16700}
16701
16702impl RowExt for MultiBufferRow {
16703    fn as_f32(&self) -> f32 {
16704        self.0 as f32
16705    }
16706
16707    fn next_row(&self) -> Self {
16708        Self(self.0 + 1)
16709    }
16710
16711    fn previous_row(&self) -> Self {
16712        Self(self.0.saturating_sub(1))
16713    }
16714
16715    fn minus(&self, other: Self) -> u32 {
16716        self.0 - other.0
16717    }
16718}
16719
16720trait RowRangeExt {
16721    type Row;
16722
16723    fn len(&self) -> usize;
16724
16725    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16726}
16727
16728impl RowRangeExt for Range<MultiBufferRow> {
16729    type Row = MultiBufferRow;
16730
16731    fn len(&self) -> usize {
16732        (self.end.0 - self.start.0) as usize
16733    }
16734
16735    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16736        (self.start.0..self.end.0).map(MultiBufferRow)
16737    }
16738}
16739
16740impl RowRangeExt for Range<DisplayRow> {
16741    type Row = DisplayRow;
16742
16743    fn len(&self) -> usize {
16744        (self.end.0 - self.start.0) as usize
16745    }
16746
16747    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16748        (self.start.0..self.end.0).map(DisplayRow)
16749    }
16750}
16751
16752/// If select range has more than one line, we
16753/// just point the cursor to range.start.
16754fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16755    if range.start.row == range.end.row {
16756        range
16757    } else {
16758        range.start..range.start
16759    }
16760}
16761pub struct KillRing(ClipboardItem);
16762impl Global for KillRing {}
16763
16764const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16765
16766fn all_edits_insertions_or_deletions(
16767    edits: &Vec<(Range<Anchor>, String)>,
16768    snapshot: &MultiBufferSnapshot,
16769) -> bool {
16770    let mut all_insertions = true;
16771    let mut all_deletions = true;
16772
16773    for (range, new_text) in edits.iter() {
16774        let range_is_empty = range.to_offset(&snapshot).is_empty();
16775        let text_is_empty = new_text.is_empty();
16776
16777        if range_is_empty != text_is_empty {
16778            if range_is_empty {
16779                all_deletions = false;
16780            } else {
16781                all_insertions = false;
16782            }
16783        } else {
16784            return false;
16785        }
16786
16787        if !all_insertions && !all_deletions {
16788            return false;
16789        }
16790    }
16791    all_insertions || all_deletions
16792}