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 {
 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    #[allow(clippy::too_many_arguments)]
 5652    fn render_edit_prediction_cursor_popover(
 5653        &self,
 5654        min_width: Pixels,
 5655        max_width: Pixels,
 5656        cursor_point: Point,
 5657        style: &EditorStyle,
 5658        accept_keystroke: &gpui::Keystroke,
 5659        _window: &Window,
 5660        cx: &mut Context<Editor>,
 5661    ) -> Option<AnyElement> {
 5662        let provider = self.edit_prediction_provider.as_ref()?;
 5663
 5664        if provider.provider.needs_terms_acceptance(cx) {
 5665            return Some(
 5666                h_flex()
 5667                    .min_w(min_width)
 5668                    .flex_1()
 5669                    .px_2()
 5670                    .py_1()
 5671                    .gap_3()
 5672                    .elevation_2(cx)
 5673                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5674                    .id("accept-terms")
 5675                    .cursor_pointer()
 5676                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5677                    .on_click(cx.listener(|this, _event, window, cx| {
 5678                        cx.stop_propagation();
 5679                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5680                        window.dispatch_action(
 5681                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5682                            cx,
 5683                        );
 5684                    }))
 5685                    .child(
 5686                        h_flex()
 5687                            .flex_1()
 5688                            .gap_2()
 5689                            .child(Icon::new(IconName::ZedPredict))
 5690                            .child(Label::new("Accept Terms of Service"))
 5691                            .child(div().w_full())
 5692                            .child(
 5693                                Icon::new(IconName::ArrowUpRight)
 5694                                    .color(Color::Muted)
 5695                                    .size(IconSize::Small),
 5696                            )
 5697                            .into_any_element(),
 5698                    )
 5699                    .into_any(),
 5700            );
 5701        }
 5702
 5703        let is_refreshing = provider.provider.is_refreshing(cx);
 5704
 5705        fn pending_completion_container() -> Div {
 5706            h_flex()
 5707                .h_full()
 5708                .flex_1()
 5709                .gap_2()
 5710                .child(Icon::new(IconName::ZedPredict))
 5711        }
 5712
 5713        let completion = match &self.active_inline_completion {
 5714            Some(completion) => match &completion.completion {
 5715                InlineCompletion::Move {
 5716                    target, snapshot, ..
 5717                } if !self.has_visible_completions_menu() => {
 5718                    use text::ToPoint as _;
 5719
 5720                    return Some(
 5721                        h_flex()
 5722                            .px_2()
 5723                            .py_1()
 5724                            .elevation_2(cx)
 5725                            .border_color(cx.theme().colors().border)
 5726                            .rounded_tl(px(0.))
 5727                            .gap_2()
 5728                            .child(
 5729                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5730                                    Icon::new(IconName::ZedPredictDown)
 5731                                } else {
 5732                                    Icon::new(IconName::ZedPredictUp)
 5733                                },
 5734                            )
 5735                            .child(Label::new("Hold").size(LabelSize::Small))
 5736                            .children(ui::render_modifiers(
 5737                                &accept_keystroke.modifiers,
 5738                                PlatformStyle::platform(),
 5739                                Some(Color::Default),
 5740                                Some(IconSize::Small.rems().into()),
 5741                                true,
 5742                            ))
 5743                            .into_any(),
 5744                    );
 5745                }
 5746                _ => self.render_edit_prediction_cursor_popover_preview(
 5747                    completion,
 5748                    cursor_point,
 5749                    style,
 5750                    cx,
 5751                )?,
 5752            },
 5753
 5754            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5755                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5756                    stale_completion,
 5757                    cursor_point,
 5758                    style,
 5759                    cx,
 5760                )?,
 5761
 5762                None => {
 5763                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5764                }
 5765            },
 5766
 5767            None => pending_completion_container().child(Label::new("No Prediction")),
 5768        };
 5769
 5770        let completion = if is_refreshing {
 5771            completion
 5772                .with_animation(
 5773                    "loading-completion",
 5774                    Animation::new(Duration::from_secs(2))
 5775                        .repeat()
 5776                        .with_easing(pulsating_between(0.4, 0.8)),
 5777                    |label, delta| label.opacity(delta),
 5778                )
 5779                .into_any_element()
 5780        } else {
 5781            completion.into_any_element()
 5782        };
 5783
 5784        let has_completion = self.active_inline_completion.is_some();
 5785
 5786        Some(
 5787            h_flex()
 5788                .min_w(min_width)
 5789                .max_w(max_width)
 5790                .flex_1()
 5791                .px_2()
 5792                .elevation_2(cx)
 5793                .border_color(cx.theme().colors().border)
 5794                .child(div().py_1().overflow_hidden().child(completion))
 5795                .child(
 5796                    h_flex()
 5797                        .h_full()
 5798                        .border_l_1()
 5799                        .border_color(cx.theme().colors().border)
 5800                        .gap_1()
 5801                        .py_1()
 5802                        .pl_2()
 5803                        .child(
 5804                            h_flex()
 5805                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5806                                .gap_1()
 5807                                .children(ui::render_modifiers(
 5808                                    &accept_keystroke.modifiers,
 5809                                    PlatformStyle::platform(),
 5810                                    Some(if !has_completion {
 5811                                        Color::Muted
 5812                                    } else {
 5813                                        Color::Default
 5814                                    }),
 5815                                    None,
 5816                                    true,
 5817                                )),
 5818                        )
 5819                        .child(Label::new("Preview").into_any_element())
 5820                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5821                )
 5822                .into_any(),
 5823        )
 5824    }
 5825
 5826    fn render_edit_prediction_cursor_popover_preview(
 5827        &self,
 5828        completion: &InlineCompletionState,
 5829        cursor_point: Point,
 5830        style: &EditorStyle,
 5831        cx: &mut Context<Editor>,
 5832    ) -> Option<Div> {
 5833        use text::ToPoint as _;
 5834
 5835        fn render_relative_row_jump(
 5836            prefix: impl Into<String>,
 5837            current_row: u32,
 5838            target_row: u32,
 5839        ) -> Div {
 5840            let (row_diff, arrow) = if target_row < current_row {
 5841                (current_row - target_row, IconName::ArrowUp)
 5842            } else {
 5843                (target_row - current_row, IconName::ArrowDown)
 5844            };
 5845
 5846            h_flex()
 5847                .child(
 5848                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5849                        .color(Color::Muted)
 5850                        .size(LabelSize::Small),
 5851                )
 5852                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5853        }
 5854
 5855        match &completion.completion {
 5856            InlineCompletion::Move {
 5857                target, snapshot, ..
 5858            } => Some(
 5859                h_flex()
 5860                    .px_2()
 5861                    .gap_2()
 5862                    .flex_1()
 5863                    .child(
 5864                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5865                            Icon::new(IconName::ZedPredictDown)
 5866                        } else {
 5867                            Icon::new(IconName::ZedPredictUp)
 5868                        },
 5869                    )
 5870                    .child(Label::new("Jump to Edit")),
 5871            ),
 5872
 5873            InlineCompletion::Edit {
 5874                edits,
 5875                edit_preview,
 5876                snapshot,
 5877                display_mode: _,
 5878            } => {
 5879                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5880
 5881                let highlighted_edits = crate::inline_completion_edit_text(
 5882                    &snapshot,
 5883                    &edits,
 5884                    edit_preview.as_ref()?,
 5885                    true,
 5886                    cx,
 5887                );
 5888
 5889                let len_total = highlighted_edits.text.len();
 5890                let first_line = &highlighted_edits.text
 5891                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5892                let first_line_len = first_line.len();
 5893
 5894                let first_highlight_start = highlighted_edits
 5895                    .highlights
 5896                    .first()
 5897                    .map_or(0, |(range, _)| range.start);
 5898                let drop_prefix_len = first_line
 5899                    .char_indices()
 5900                    .find(|(_, c)| !c.is_whitespace())
 5901                    .map_or(first_highlight_start, |(ix, _)| {
 5902                        ix.min(first_highlight_start)
 5903                    });
 5904
 5905                let preview_text = &first_line[drop_prefix_len..];
 5906                let preview_len = preview_text.len();
 5907                let highlights = highlighted_edits
 5908                    .highlights
 5909                    .into_iter()
 5910                    .take_until(|(range, _)| range.start > first_line_len)
 5911                    .map(|(range, style)| {
 5912                        (
 5913                            range.start - drop_prefix_len
 5914                                ..(range.end - drop_prefix_len).min(preview_len),
 5915                            style,
 5916                        )
 5917                    });
 5918
 5919                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5920                    .with_highlights(&style.text, highlights);
 5921
 5922                let preview = h_flex()
 5923                    .gap_1()
 5924                    .min_w_16()
 5925                    .child(styled_text)
 5926                    .when(len_total > first_line_len, |parent| parent.child(""));
 5927
 5928                let left = if first_edit_row != cursor_point.row {
 5929                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5930                        .into_any_element()
 5931                } else {
 5932                    Icon::new(IconName::ZedPredict).into_any_element()
 5933                };
 5934
 5935                Some(
 5936                    h_flex()
 5937                        .h_full()
 5938                        .flex_1()
 5939                        .gap_2()
 5940                        .pr_1()
 5941                        .overflow_x_hidden()
 5942                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5943                        .child(left)
 5944                        .child(preview),
 5945                )
 5946            }
 5947        }
 5948    }
 5949
 5950    fn render_context_menu(
 5951        &self,
 5952        style: &EditorStyle,
 5953        max_height_in_lines: u32,
 5954        y_flipped: bool,
 5955        window: &mut Window,
 5956        cx: &mut Context<Editor>,
 5957    ) -> Option<AnyElement> {
 5958        let menu = self.context_menu.borrow();
 5959        let menu = menu.as_ref()?;
 5960        if !menu.visible() {
 5961            return None;
 5962        };
 5963        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5964    }
 5965
 5966    fn render_context_menu_aside(
 5967        &self,
 5968        style: &EditorStyle,
 5969        max_size: Size<Pixels>,
 5970        cx: &mut Context<Editor>,
 5971    ) -> Option<AnyElement> {
 5972        self.context_menu.borrow().as_ref().and_then(|menu| {
 5973            if menu.visible() {
 5974                menu.render_aside(
 5975                    style,
 5976                    max_size,
 5977                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5978                    cx,
 5979                )
 5980            } else {
 5981                None
 5982            }
 5983        })
 5984    }
 5985
 5986    fn hide_context_menu(
 5987        &mut self,
 5988        window: &mut Window,
 5989        cx: &mut Context<Self>,
 5990    ) -> Option<CodeContextMenu> {
 5991        cx.notify();
 5992        self.completion_tasks.clear();
 5993        let context_menu = self.context_menu.borrow_mut().take();
 5994        self.stale_inline_completion_in_menu.take();
 5995        self.update_visible_inline_completion(window, cx);
 5996        context_menu
 5997    }
 5998
 5999    fn show_snippet_choices(
 6000        &mut self,
 6001        choices: &Vec<String>,
 6002        selection: Range<Anchor>,
 6003        cx: &mut Context<Self>,
 6004    ) {
 6005        if selection.start.buffer_id.is_none() {
 6006            return;
 6007        }
 6008        let buffer_id = selection.start.buffer_id.unwrap();
 6009        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6010        let id = post_inc(&mut self.next_completion_id);
 6011
 6012        if let Some(buffer) = buffer {
 6013            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6014                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6015            ));
 6016        }
 6017    }
 6018
 6019    pub fn insert_snippet(
 6020        &mut self,
 6021        insertion_ranges: &[Range<usize>],
 6022        snippet: Snippet,
 6023        window: &mut Window,
 6024        cx: &mut Context<Self>,
 6025    ) -> Result<()> {
 6026        struct Tabstop<T> {
 6027            is_end_tabstop: bool,
 6028            ranges: Vec<Range<T>>,
 6029            choices: Option<Vec<String>>,
 6030        }
 6031
 6032        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6033            let snippet_text: Arc<str> = snippet.text.clone().into();
 6034            buffer.edit(
 6035                insertion_ranges
 6036                    .iter()
 6037                    .cloned()
 6038                    .map(|range| (range, snippet_text.clone())),
 6039                Some(AutoindentMode::EachLine),
 6040                cx,
 6041            );
 6042
 6043            let snapshot = &*buffer.read(cx);
 6044            let snippet = &snippet;
 6045            snippet
 6046                .tabstops
 6047                .iter()
 6048                .map(|tabstop| {
 6049                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6050                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6051                    });
 6052                    let mut tabstop_ranges = tabstop
 6053                        .ranges
 6054                        .iter()
 6055                        .flat_map(|tabstop_range| {
 6056                            let mut delta = 0_isize;
 6057                            insertion_ranges.iter().map(move |insertion_range| {
 6058                                let insertion_start = insertion_range.start as isize + delta;
 6059                                delta +=
 6060                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6061
 6062                                let start = ((insertion_start + tabstop_range.start) as usize)
 6063                                    .min(snapshot.len());
 6064                                let end = ((insertion_start + tabstop_range.end) as usize)
 6065                                    .min(snapshot.len());
 6066                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6067                            })
 6068                        })
 6069                        .collect::<Vec<_>>();
 6070                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6071
 6072                    Tabstop {
 6073                        is_end_tabstop,
 6074                        ranges: tabstop_ranges,
 6075                        choices: tabstop.choices.clone(),
 6076                    }
 6077                })
 6078                .collect::<Vec<_>>()
 6079        });
 6080        if let Some(tabstop) = tabstops.first() {
 6081            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6082                s.select_ranges(tabstop.ranges.iter().cloned());
 6083            });
 6084
 6085            if let Some(choices) = &tabstop.choices {
 6086                if let Some(selection) = tabstop.ranges.first() {
 6087                    self.show_snippet_choices(choices, selection.clone(), cx)
 6088                }
 6089            }
 6090
 6091            // If we're already at the last tabstop and it's at the end of the snippet,
 6092            // we're done, we don't need to keep the state around.
 6093            if !tabstop.is_end_tabstop {
 6094                let choices = tabstops
 6095                    .iter()
 6096                    .map(|tabstop| tabstop.choices.clone())
 6097                    .collect();
 6098
 6099                let ranges = tabstops
 6100                    .into_iter()
 6101                    .map(|tabstop| tabstop.ranges)
 6102                    .collect::<Vec<_>>();
 6103
 6104                self.snippet_stack.push(SnippetState {
 6105                    active_index: 0,
 6106                    ranges,
 6107                    choices,
 6108                });
 6109            }
 6110
 6111            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6112            if self.autoclose_regions.is_empty() {
 6113                let snapshot = self.buffer.read(cx).snapshot(cx);
 6114                for selection in &mut self.selections.all::<Point>(cx) {
 6115                    let selection_head = selection.head();
 6116                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6117                        continue;
 6118                    };
 6119
 6120                    let mut bracket_pair = None;
 6121                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6122                    let prev_chars = snapshot
 6123                        .reversed_chars_at(selection_head)
 6124                        .collect::<String>();
 6125                    for (pair, enabled) in scope.brackets() {
 6126                        if enabled
 6127                            && pair.close
 6128                            && prev_chars.starts_with(pair.start.as_str())
 6129                            && next_chars.starts_with(pair.end.as_str())
 6130                        {
 6131                            bracket_pair = Some(pair.clone());
 6132                            break;
 6133                        }
 6134                    }
 6135                    if let Some(pair) = bracket_pair {
 6136                        let start = snapshot.anchor_after(selection_head);
 6137                        let end = snapshot.anchor_after(selection_head);
 6138                        self.autoclose_regions.push(AutocloseRegion {
 6139                            selection_id: selection.id,
 6140                            range: start..end,
 6141                            pair,
 6142                        });
 6143                    }
 6144                }
 6145            }
 6146        }
 6147        Ok(())
 6148    }
 6149
 6150    pub fn move_to_next_snippet_tabstop(
 6151        &mut self,
 6152        window: &mut Window,
 6153        cx: &mut Context<Self>,
 6154    ) -> bool {
 6155        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6156    }
 6157
 6158    pub fn move_to_prev_snippet_tabstop(
 6159        &mut self,
 6160        window: &mut Window,
 6161        cx: &mut Context<Self>,
 6162    ) -> bool {
 6163        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6164    }
 6165
 6166    pub fn move_to_snippet_tabstop(
 6167        &mut self,
 6168        bias: Bias,
 6169        window: &mut Window,
 6170        cx: &mut Context<Self>,
 6171    ) -> bool {
 6172        if let Some(mut snippet) = self.snippet_stack.pop() {
 6173            match bias {
 6174                Bias::Left => {
 6175                    if snippet.active_index > 0 {
 6176                        snippet.active_index -= 1;
 6177                    } else {
 6178                        self.snippet_stack.push(snippet);
 6179                        return false;
 6180                    }
 6181                }
 6182                Bias::Right => {
 6183                    if snippet.active_index + 1 < snippet.ranges.len() {
 6184                        snippet.active_index += 1;
 6185                    } else {
 6186                        self.snippet_stack.push(snippet);
 6187                        return false;
 6188                    }
 6189                }
 6190            }
 6191            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6192                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6193                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6194                });
 6195
 6196                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6197                    if let Some(selection) = current_ranges.first() {
 6198                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6199                    }
 6200                }
 6201
 6202                // If snippet state is not at the last tabstop, push it back on the stack
 6203                if snippet.active_index + 1 < snippet.ranges.len() {
 6204                    self.snippet_stack.push(snippet);
 6205                }
 6206                return true;
 6207            }
 6208        }
 6209
 6210        false
 6211    }
 6212
 6213    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6214        self.transact(window, cx, |this, window, cx| {
 6215            this.select_all(&SelectAll, window, cx);
 6216            this.insert("", window, cx);
 6217        });
 6218    }
 6219
 6220    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6221        self.transact(window, cx, |this, window, cx| {
 6222            this.select_autoclose_pair(window, cx);
 6223            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6224            if !this.linked_edit_ranges.is_empty() {
 6225                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6226                let snapshot = this.buffer.read(cx).snapshot(cx);
 6227
 6228                for selection in selections.iter() {
 6229                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6230                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6231                    if selection_start.buffer_id != selection_end.buffer_id {
 6232                        continue;
 6233                    }
 6234                    if let Some(ranges) =
 6235                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6236                    {
 6237                        for (buffer, entries) in ranges {
 6238                            linked_ranges.entry(buffer).or_default().extend(entries);
 6239                        }
 6240                    }
 6241                }
 6242            }
 6243
 6244            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6245            if !this.selections.line_mode {
 6246                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6247                for selection in &mut selections {
 6248                    if selection.is_empty() {
 6249                        let old_head = selection.head();
 6250                        let mut new_head =
 6251                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6252                                .to_point(&display_map);
 6253                        if let Some((buffer, line_buffer_range)) = display_map
 6254                            .buffer_snapshot
 6255                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6256                        {
 6257                            let indent_size =
 6258                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6259                            let indent_len = match indent_size.kind {
 6260                                IndentKind::Space => {
 6261                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6262                                }
 6263                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6264                            };
 6265                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6266                                let indent_len = indent_len.get();
 6267                                new_head = cmp::min(
 6268                                    new_head,
 6269                                    MultiBufferPoint::new(
 6270                                        old_head.row,
 6271                                        ((old_head.column - 1) / indent_len) * indent_len,
 6272                                    ),
 6273                                );
 6274                            }
 6275                        }
 6276
 6277                        selection.set_head(new_head, SelectionGoal::None);
 6278                    }
 6279                }
 6280            }
 6281
 6282            this.signature_help_state.set_backspace_pressed(true);
 6283            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6284                s.select(selections)
 6285            });
 6286            this.insert("", window, cx);
 6287            let empty_str: Arc<str> = Arc::from("");
 6288            for (buffer, edits) in linked_ranges {
 6289                let snapshot = buffer.read(cx).snapshot();
 6290                use text::ToPoint as TP;
 6291
 6292                let edits = edits
 6293                    .into_iter()
 6294                    .map(|range| {
 6295                        let end_point = TP::to_point(&range.end, &snapshot);
 6296                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6297
 6298                        if end_point == start_point {
 6299                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6300                                .saturating_sub(1);
 6301                            start_point =
 6302                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6303                        };
 6304
 6305                        (start_point..end_point, empty_str.clone())
 6306                    })
 6307                    .sorted_by_key(|(range, _)| range.start)
 6308                    .collect::<Vec<_>>();
 6309                buffer.update(cx, |this, cx| {
 6310                    this.edit(edits, None, cx);
 6311                })
 6312            }
 6313            this.refresh_inline_completion(true, false, window, cx);
 6314            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6315        });
 6316    }
 6317
 6318    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6319        self.transact(window, cx, |this, window, cx| {
 6320            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6321                let line_mode = s.line_mode;
 6322                s.move_with(|map, selection| {
 6323                    if selection.is_empty() && !line_mode {
 6324                        let cursor = movement::right(map, selection.head());
 6325                        selection.end = cursor;
 6326                        selection.reversed = true;
 6327                        selection.goal = SelectionGoal::None;
 6328                    }
 6329                })
 6330            });
 6331            this.insert("", window, cx);
 6332            this.refresh_inline_completion(true, false, window, cx);
 6333        });
 6334    }
 6335
 6336    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6337        if self.move_to_prev_snippet_tabstop(window, cx) {
 6338            return;
 6339        }
 6340
 6341        self.outdent(&Outdent, window, cx);
 6342    }
 6343
 6344    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6345        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6346            return;
 6347        }
 6348
 6349        let mut selections = self.selections.all_adjusted(cx);
 6350        let buffer = self.buffer.read(cx);
 6351        let snapshot = buffer.snapshot(cx);
 6352        let rows_iter = selections.iter().map(|s| s.head().row);
 6353        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6354
 6355        let mut edits = Vec::new();
 6356        let mut prev_edited_row = 0;
 6357        let mut row_delta = 0;
 6358        for selection in &mut selections {
 6359            if selection.start.row != prev_edited_row {
 6360                row_delta = 0;
 6361            }
 6362            prev_edited_row = selection.end.row;
 6363
 6364            // If the selection is non-empty, then increase the indentation of the selected lines.
 6365            if !selection.is_empty() {
 6366                row_delta =
 6367                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6368                continue;
 6369            }
 6370
 6371            // If the selection is empty and the cursor is in the leading whitespace before the
 6372            // suggested indentation, then auto-indent the line.
 6373            let cursor = selection.head();
 6374            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6375            if let Some(suggested_indent) =
 6376                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6377            {
 6378                if cursor.column < suggested_indent.len
 6379                    && cursor.column <= current_indent.len
 6380                    && current_indent.len <= suggested_indent.len
 6381                {
 6382                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6383                    selection.end = selection.start;
 6384                    if row_delta == 0 {
 6385                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6386                            cursor.row,
 6387                            current_indent,
 6388                            suggested_indent,
 6389                        ));
 6390                        row_delta = suggested_indent.len - current_indent.len;
 6391                    }
 6392                    continue;
 6393                }
 6394            }
 6395
 6396            // Otherwise, insert a hard or soft tab.
 6397            let settings = buffer.settings_at(cursor, cx);
 6398            let tab_size = if settings.hard_tabs {
 6399                IndentSize::tab()
 6400            } else {
 6401                let tab_size = settings.tab_size.get();
 6402                let char_column = snapshot
 6403                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6404                    .flat_map(str::chars)
 6405                    .count()
 6406                    + row_delta as usize;
 6407                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6408                IndentSize::spaces(chars_to_next_tab_stop)
 6409            };
 6410            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6411            selection.end = selection.start;
 6412            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6413            row_delta += tab_size.len;
 6414        }
 6415
 6416        self.transact(window, cx, |this, window, cx| {
 6417            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6418            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6419                s.select(selections)
 6420            });
 6421            this.refresh_inline_completion(true, false, window, cx);
 6422        });
 6423    }
 6424
 6425    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6426        if self.read_only(cx) {
 6427            return;
 6428        }
 6429        let mut selections = self.selections.all::<Point>(cx);
 6430        let mut prev_edited_row = 0;
 6431        let mut row_delta = 0;
 6432        let mut edits = Vec::new();
 6433        let buffer = self.buffer.read(cx);
 6434        let snapshot = buffer.snapshot(cx);
 6435        for selection in &mut selections {
 6436            if selection.start.row != prev_edited_row {
 6437                row_delta = 0;
 6438            }
 6439            prev_edited_row = selection.end.row;
 6440
 6441            row_delta =
 6442                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6443        }
 6444
 6445        self.transact(window, cx, |this, window, cx| {
 6446            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6447            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6448                s.select(selections)
 6449            });
 6450        });
 6451    }
 6452
 6453    fn indent_selection(
 6454        buffer: &MultiBuffer,
 6455        snapshot: &MultiBufferSnapshot,
 6456        selection: &mut Selection<Point>,
 6457        edits: &mut Vec<(Range<Point>, String)>,
 6458        delta_for_start_row: u32,
 6459        cx: &App,
 6460    ) -> u32 {
 6461        let settings = buffer.settings_at(selection.start, cx);
 6462        let tab_size = settings.tab_size.get();
 6463        let indent_kind = if settings.hard_tabs {
 6464            IndentKind::Tab
 6465        } else {
 6466            IndentKind::Space
 6467        };
 6468        let mut start_row = selection.start.row;
 6469        let mut end_row = selection.end.row + 1;
 6470
 6471        // If a selection ends at the beginning of a line, don't indent
 6472        // that last line.
 6473        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6474            end_row -= 1;
 6475        }
 6476
 6477        // Avoid re-indenting a row that has already been indented by a
 6478        // previous selection, but still update this selection's column
 6479        // to reflect that indentation.
 6480        if delta_for_start_row > 0 {
 6481            start_row += 1;
 6482            selection.start.column += delta_for_start_row;
 6483            if selection.end.row == selection.start.row {
 6484                selection.end.column += delta_for_start_row;
 6485            }
 6486        }
 6487
 6488        let mut delta_for_end_row = 0;
 6489        let has_multiple_rows = start_row + 1 != end_row;
 6490        for row in start_row..end_row {
 6491            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6492            let indent_delta = match (current_indent.kind, indent_kind) {
 6493                (IndentKind::Space, IndentKind::Space) => {
 6494                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6495                    IndentSize::spaces(columns_to_next_tab_stop)
 6496                }
 6497                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6498                (_, IndentKind::Tab) => IndentSize::tab(),
 6499            };
 6500
 6501            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6502                0
 6503            } else {
 6504                selection.start.column
 6505            };
 6506            let row_start = Point::new(row, start);
 6507            edits.push((
 6508                row_start..row_start,
 6509                indent_delta.chars().collect::<String>(),
 6510            ));
 6511
 6512            // Update this selection's endpoints to reflect the indentation.
 6513            if row == selection.start.row {
 6514                selection.start.column += indent_delta.len;
 6515            }
 6516            if row == selection.end.row {
 6517                selection.end.column += indent_delta.len;
 6518                delta_for_end_row = indent_delta.len;
 6519            }
 6520        }
 6521
 6522        if selection.start.row == selection.end.row {
 6523            delta_for_start_row + delta_for_end_row
 6524        } else {
 6525            delta_for_end_row
 6526        }
 6527    }
 6528
 6529    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6530        if self.read_only(cx) {
 6531            return;
 6532        }
 6533        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6534        let selections = self.selections.all::<Point>(cx);
 6535        let mut deletion_ranges = Vec::new();
 6536        let mut last_outdent = None;
 6537        {
 6538            let buffer = self.buffer.read(cx);
 6539            let snapshot = buffer.snapshot(cx);
 6540            for selection in &selections {
 6541                let settings = buffer.settings_at(selection.start, cx);
 6542                let tab_size = settings.tab_size.get();
 6543                let mut rows = selection.spanned_rows(false, &display_map);
 6544
 6545                // Avoid re-outdenting a row that has already been outdented by a
 6546                // previous selection.
 6547                if let Some(last_row) = last_outdent {
 6548                    if last_row == rows.start {
 6549                        rows.start = rows.start.next_row();
 6550                    }
 6551                }
 6552                let has_multiple_rows = rows.len() > 1;
 6553                for row in rows.iter_rows() {
 6554                    let indent_size = snapshot.indent_size_for_line(row);
 6555                    if indent_size.len > 0 {
 6556                        let deletion_len = match indent_size.kind {
 6557                            IndentKind::Space => {
 6558                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6559                                if columns_to_prev_tab_stop == 0 {
 6560                                    tab_size
 6561                                } else {
 6562                                    columns_to_prev_tab_stop
 6563                                }
 6564                            }
 6565                            IndentKind::Tab => 1,
 6566                        };
 6567                        let start = if has_multiple_rows
 6568                            || deletion_len > selection.start.column
 6569                            || indent_size.len < selection.start.column
 6570                        {
 6571                            0
 6572                        } else {
 6573                            selection.start.column - deletion_len
 6574                        };
 6575                        deletion_ranges.push(
 6576                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6577                        );
 6578                        last_outdent = Some(row);
 6579                    }
 6580                }
 6581            }
 6582        }
 6583
 6584        self.transact(window, cx, |this, window, cx| {
 6585            this.buffer.update(cx, |buffer, cx| {
 6586                let empty_str: Arc<str> = Arc::default();
 6587                buffer.edit(
 6588                    deletion_ranges
 6589                        .into_iter()
 6590                        .map(|range| (range, empty_str.clone())),
 6591                    None,
 6592                    cx,
 6593                );
 6594            });
 6595            let selections = this.selections.all::<usize>(cx);
 6596            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6597                s.select(selections)
 6598            });
 6599        });
 6600    }
 6601
 6602    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6603        if self.read_only(cx) {
 6604            return;
 6605        }
 6606        let selections = self
 6607            .selections
 6608            .all::<usize>(cx)
 6609            .into_iter()
 6610            .map(|s| s.range());
 6611
 6612        self.transact(window, cx, |this, window, cx| {
 6613            this.buffer.update(cx, |buffer, cx| {
 6614                buffer.autoindent_ranges(selections, cx);
 6615            });
 6616            let selections = this.selections.all::<usize>(cx);
 6617            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6618                s.select(selections)
 6619            });
 6620        });
 6621    }
 6622
 6623    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6624        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6625        let selections = self.selections.all::<Point>(cx);
 6626
 6627        let mut new_cursors = Vec::new();
 6628        let mut edit_ranges = Vec::new();
 6629        let mut selections = selections.iter().peekable();
 6630        while let Some(selection) = selections.next() {
 6631            let mut rows = selection.spanned_rows(false, &display_map);
 6632            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6633
 6634            // Accumulate contiguous regions of rows that we want to delete.
 6635            while let Some(next_selection) = selections.peek() {
 6636                let next_rows = next_selection.spanned_rows(false, &display_map);
 6637                if next_rows.start <= rows.end {
 6638                    rows.end = next_rows.end;
 6639                    selections.next().unwrap();
 6640                } else {
 6641                    break;
 6642                }
 6643            }
 6644
 6645            let buffer = &display_map.buffer_snapshot;
 6646            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6647            let edit_end;
 6648            let cursor_buffer_row;
 6649            if buffer.max_point().row >= rows.end.0 {
 6650                // If there's a line after the range, delete the \n from the end of the row range
 6651                // and position the cursor on the next line.
 6652                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6653                cursor_buffer_row = rows.end;
 6654            } else {
 6655                // If there isn't a line after the range, delete the \n from the line before the
 6656                // start of the row range and position the cursor there.
 6657                edit_start = edit_start.saturating_sub(1);
 6658                edit_end = buffer.len();
 6659                cursor_buffer_row = rows.start.previous_row();
 6660            }
 6661
 6662            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6663            *cursor.column_mut() =
 6664                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6665
 6666            new_cursors.push((
 6667                selection.id,
 6668                buffer.anchor_after(cursor.to_point(&display_map)),
 6669            ));
 6670            edit_ranges.push(edit_start..edit_end);
 6671        }
 6672
 6673        self.transact(window, cx, |this, window, cx| {
 6674            let buffer = this.buffer.update(cx, |buffer, cx| {
 6675                let empty_str: Arc<str> = Arc::default();
 6676                buffer.edit(
 6677                    edit_ranges
 6678                        .into_iter()
 6679                        .map(|range| (range, empty_str.clone())),
 6680                    None,
 6681                    cx,
 6682                );
 6683                buffer.snapshot(cx)
 6684            });
 6685            let new_selections = new_cursors
 6686                .into_iter()
 6687                .map(|(id, cursor)| {
 6688                    let cursor = cursor.to_point(&buffer);
 6689                    Selection {
 6690                        id,
 6691                        start: cursor,
 6692                        end: cursor,
 6693                        reversed: false,
 6694                        goal: SelectionGoal::None,
 6695                    }
 6696                })
 6697                .collect();
 6698
 6699            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6700                s.select(new_selections);
 6701            });
 6702        });
 6703    }
 6704
 6705    pub fn join_lines_impl(
 6706        &mut self,
 6707        insert_whitespace: bool,
 6708        window: &mut Window,
 6709        cx: &mut Context<Self>,
 6710    ) {
 6711        if self.read_only(cx) {
 6712            return;
 6713        }
 6714        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6715        for selection in self.selections.all::<Point>(cx) {
 6716            let start = MultiBufferRow(selection.start.row);
 6717            // Treat single line selections as if they include the next line. Otherwise this action
 6718            // would do nothing for single line selections individual cursors.
 6719            let end = if selection.start.row == selection.end.row {
 6720                MultiBufferRow(selection.start.row + 1)
 6721            } else {
 6722                MultiBufferRow(selection.end.row)
 6723            };
 6724
 6725            if let Some(last_row_range) = row_ranges.last_mut() {
 6726                if start <= last_row_range.end {
 6727                    last_row_range.end = end;
 6728                    continue;
 6729                }
 6730            }
 6731            row_ranges.push(start..end);
 6732        }
 6733
 6734        let snapshot = self.buffer.read(cx).snapshot(cx);
 6735        let mut cursor_positions = Vec::new();
 6736        for row_range in &row_ranges {
 6737            let anchor = snapshot.anchor_before(Point::new(
 6738                row_range.end.previous_row().0,
 6739                snapshot.line_len(row_range.end.previous_row()),
 6740            ));
 6741            cursor_positions.push(anchor..anchor);
 6742        }
 6743
 6744        self.transact(window, cx, |this, window, cx| {
 6745            for row_range in row_ranges.into_iter().rev() {
 6746                for row in row_range.iter_rows().rev() {
 6747                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6748                    let next_line_row = row.next_row();
 6749                    let indent = snapshot.indent_size_for_line(next_line_row);
 6750                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6751
 6752                    let replace =
 6753                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6754                            " "
 6755                        } else {
 6756                            ""
 6757                        };
 6758
 6759                    this.buffer.update(cx, |buffer, cx| {
 6760                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6761                    });
 6762                }
 6763            }
 6764
 6765            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6766                s.select_anchor_ranges(cursor_positions)
 6767            });
 6768        });
 6769    }
 6770
 6771    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6772        self.join_lines_impl(true, window, cx);
 6773    }
 6774
 6775    pub fn sort_lines_case_sensitive(
 6776        &mut self,
 6777        _: &SortLinesCaseSensitive,
 6778        window: &mut Window,
 6779        cx: &mut Context<Self>,
 6780    ) {
 6781        self.manipulate_lines(window, cx, |lines| lines.sort())
 6782    }
 6783
 6784    pub fn sort_lines_case_insensitive(
 6785        &mut self,
 6786        _: &SortLinesCaseInsensitive,
 6787        window: &mut Window,
 6788        cx: &mut Context<Self>,
 6789    ) {
 6790        self.manipulate_lines(window, cx, |lines| {
 6791            lines.sort_by_key(|line| line.to_lowercase())
 6792        })
 6793    }
 6794
 6795    pub fn unique_lines_case_insensitive(
 6796        &mut self,
 6797        _: &UniqueLinesCaseInsensitive,
 6798        window: &mut Window,
 6799        cx: &mut Context<Self>,
 6800    ) {
 6801        self.manipulate_lines(window, cx, |lines| {
 6802            let mut seen = HashSet::default();
 6803            lines.retain(|line| seen.insert(line.to_lowercase()));
 6804        })
 6805    }
 6806
 6807    pub fn unique_lines_case_sensitive(
 6808        &mut self,
 6809        _: &UniqueLinesCaseSensitive,
 6810        window: &mut Window,
 6811        cx: &mut Context<Self>,
 6812    ) {
 6813        self.manipulate_lines(window, cx, |lines| {
 6814            let mut seen = HashSet::default();
 6815            lines.retain(|line| seen.insert(*line));
 6816        })
 6817    }
 6818
 6819    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6820        let mut revert_changes = HashMap::default();
 6821        let snapshot = self.snapshot(window, cx);
 6822        for hunk in snapshot
 6823            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6824        {
 6825            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6826        }
 6827        if !revert_changes.is_empty() {
 6828            self.transact(window, cx, |editor, window, cx| {
 6829                editor.revert(revert_changes, window, cx);
 6830            });
 6831        }
 6832    }
 6833
 6834    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6835        let Some(project) = self.project.clone() else {
 6836            return;
 6837        };
 6838        self.reload(project, window, cx)
 6839            .detach_and_notify_err(window, cx);
 6840    }
 6841
 6842    pub fn revert_selected_hunks(
 6843        &mut self,
 6844        _: &RevertSelectedHunks,
 6845        window: &mut Window,
 6846        cx: &mut Context<Self>,
 6847    ) {
 6848        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6849        self.revert_hunks_in_ranges(selections, window, cx);
 6850    }
 6851
 6852    fn revert_hunks_in_ranges(
 6853        &mut self,
 6854        ranges: impl Iterator<Item = Range<Point>>,
 6855        window: &mut Window,
 6856        cx: &mut Context<Editor>,
 6857    ) {
 6858        let mut revert_changes = HashMap::default();
 6859        let snapshot = self.snapshot(window, cx);
 6860        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6861            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6862        }
 6863        if !revert_changes.is_empty() {
 6864            self.transact(window, cx, |editor, window, cx| {
 6865                editor.revert(revert_changes, window, cx);
 6866            });
 6867        }
 6868    }
 6869
 6870    pub fn open_active_item_in_terminal(
 6871        &mut self,
 6872        _: &OpenInTerminal,
 6873        window: &mut Window,
 6874        cx: &mut Context<Self>,
 6875    ) {
 6876        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6877            let project_path = buffer.read(cx).project_path(cx)?;
 6878            let project = self.project.as_ref()?.read(cx);
 6879            let entry = project.entry_for_path(&project_path, cx)?;
 6880            let parent = match &entry.canonical_path {
 6881                Some(canonical_path) => canonical_path.to_path_buf(),
 6882                None => project.absolute_path(&project_path, cx)?,
 6883            }
 6884            .parent()?
 6885            .to_path_buf();
 6886            Some(parent)
 6887        }) {
 6888            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6889        }
 6890    }
 6891
 6892    pub fn prepare_revert_change(
 6893        &self,
 6894        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6895        hunk: &MultiBufferDiffHunk,
 6896        cx: &mut App,
 6897    ) -> Option<()> {
 6898        let buffer = self.buffer.read(cx);
 6899        let diff = buffer.diff_for(hunk.buffer_id)?;
 6900        let buffer = buffer.buffer(hunk.buffer_id)?;
 6901        let buffer = buffer.read(cx);
 6902        let original_text = diff
 6903            .read(cx)
 6904            .base_text()
 6905            .as_ref()?
 6906            .as_rope()
 6907            .slice(hunk.diff_base_byte_range.clone());
 6908        let buffer_snapshot = buffer.snapshot();
 6909        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6910        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6911            probe
 6912                .0
 6913                .start
 6914                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6915                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6916        }) {
 6917            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6918            Some(())
 6919        } else {
 6920            None
 6921        }
 6922    }
 6923
 6924    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6925        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6926    }
 6927
 6928    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6929        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6930    }
 6931
 6932    fn manipulate_lines<Fn>(
 6933        &mut self,
 6934        window: &mut Window,
 6935        cx: &mut Context<Self>,
 6936        mut callback: Fn,
 6937    ) where
 6938        Fn: FnMut(&mut Vec<&str>),
 6939    {
 6940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6941        let buffer = self.buffer.read(cx).snapshot(cx);
 6942
 6943        let mut edits = Vec::new();
 6944
 6945        let selections = self.selections.all::<Point>(cx);
 6946        let mut selections = selections.iter().peekable();
 6947        let mut contiguous_row_selections = Vec::new();
 6948        let mut new_selections = Vec::new();
 6949        let mut added_lines = 0;
 6950        let mut removed_lines = 0;
 6951
 6952        while let Some(selection) = selections.next() {
 6953            let (start_row, end_row) = consume_contiguous_rows(
 6954                &mut contiguous_row_selections,
 6955                selection,
 6956                &display_map,
 6957                &mut selections,
 6958            );
 6959
 6960            let start_point = Point::new(start_row.0, 0);
 6961            let end_point = Point::new(
 6962                end_row.previous_row().0,
 6963                buffer.line_len(end_row.previous_row()),
 6964            );
 6965            let text = buffer
 6966                .text_for_range(start_point..end_point)
 6967                .collect::<String>();
 6968
 6969            let mut lines = text.split('\n').collect_vec();
 6970
 6971            let lines_before = lines.len();
 6972            callback(&mut lines);
 6973            let lines_after = lines.len();
 6974
 6975            edits.push((start_point..end_point, lines.join("\n")));
 6976
 6977            // Selections must change based on added and removed line count
 6978            let start_row =
 6979                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6980            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6981            new_selections.push(Selection {
 6982                id: selection.id,
 6983                start: start_row,
 6984                end: end_row,
 6985                goal: SelectionGoal::None,
 6986                reversed: selection.reversed,
 6987            });
 6988
 6989            if lines_after > lines_before {
 6990                added_lines += lines_after - lines_before;
 6991            } else if lines_before > lines_after {
 6992                removed_lines += lines_before - lines_after;
 6993            }
 6994        }
 6995
 6996        self.transact(window, cx, |this, window, cx| {
 6997            let buffer = this.buffer.update(cx, |buffer, cx| {
 6998                buffer.edit(edits, None, cx);
 6999                buffer.snapshot(cx)
 7000            });
 7001
 7002            // Recalculate offsets on newly edited buffer
 7003            let new_selections = new_selections
 7004                .iter()
 7005                .map(|s| {
 7006                    let start_point = Point::new(s.start.0, 0);
 7007                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7008                    Selection {
 7009                        id: s.id,
 7010                        start: buffer.point_to_offset(start_point),
 7011                        end: buffer.point_to_offset(end_point),
 7012                        goal: s.goal,
 7013                        reversed: s.reversed,
 7014                    }
 7015                })
 7016                .collect();
 7017
 7018            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7019                s.select(new_selections);
 7020            });
 7021
 7022            this.request_autoscroll(Autoscroll::fit(), cx);
 7023        });
 7024    }
 7025
 7026    pub fn convert_to_upper_case(
 7027        &mut self,
 7028        _: &ConvertToUpperCase,
 7029        window: &mut Window,
 7030        cx: &mut Context<Self>,
 7031    ) {
 7032        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7033    }
 7034
 7035    pub fn convert_to_lower_case(
 7036        &mut self,
 7037        _: &ConvertToLowerCase,
 7038        window: &mut Window,
 7039        cx: &mut Context<Self>,
 7040    ) {
 7041        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7042    }
 7043
 7044    pub fn convert_to_title_case(
 7045        &mut self,
 7046        _: &ConvertToTitleCase,
 7047        window: &mut Window,
 7048        cx: &mut Context<Self>,
 7049    ) {
 7050        self.manipulate_text(window, cx, |text| {
 7051            text.split('\n')
 7052                .map(|line| line.to_case(Case::Title))
 7053                .join("\n")
 7054        })
 7055    }
 7056
 7057    pub fn convert_to_snake_case(
 7058        &mut self,
 7059        _: &ConvertToSnakeCase,
 7060        window: &mut Window,
 7061        cx: &mut Context<Self>,
 7062    ) {
 7063        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7064    }
 7065
 7066    pub fn convert_to_kebab_case(
 7067        &mut self,
 7068        _: &ConvertToKebabCase,
 7069        window: &mut Window,
 7070        cx: &mut Context<Self>,
 7071    ) {
 7072        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7073    }
 7074
 7075    pub fn convert_to_upper_camel_case(
 7076        &mut self,
 7077        _: &ConvertToUpperCamelCase,
 7078        window: &mut Window,
 7079        cx: &mut Context<Self>,
 7080    ) {
 7081        self.manipulate_text(window, cx, |text| {
 7082            text.split('\n')
 7083                .map(|line| line.to_case(Case::UpperCamel))
 7084                .join("\n")
 7085        })
 7086    }
 7087
 7088    pub fn convert_to_lower_camel_case(
 7089        &mut self,
 7090        _: &ConvertToLowerCamelCase,
 7091        window: &mut Window,
 7092        cx: &mut Context<Self>,
 7093    ) {
 7094        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7095    }
 7096
 7097    pub fn convert_to_opposite_case(
 7098        &mut self,
 7099        _: &ConvertToOppositeCase,
 7100        window: &mut Window,
 7101        cx: &mut Context<Self>,
 7102    ) {
 7103        self.manipulate_text(window, cx, |text| {
 7104            text.chars()
 7105                .fold(String::with_capacity(text.len()), |mut t, c| {
 7106                    if c.is_uppercase() {
 7107                        t.extend(c.to_lowercase());
 7108                    } else {
 7109                        t.extend(c.to_uppercase());
 7110                    }
 7111                    t
 7112                })
 7113        })
 7114    }
 7115
 7116    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7117    where
 7118        Fn: FnMut(&str) -> String,
 7119    {
 7120        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7121        let buffer = self.buffer.read(cx).snapshot(cx);
 7122
 7123        let mut new_selections = Vec::new();
 7124        let mut edits = Vec::new();
 7125        let mut selection_adjustment = 0i32;
 7126
 7127        for selection in self.selections.all::<usize>(cx) {
 7128            let selection_is_empty = selection.is_empty();
 7129
 7130            let (start, end) = if selection_is_empty {
 7131                let word_range = movement::surrounding_word(
 7132                    &display_map,
 7133                    selection.start.to_display_point(&display_map),
 7134                );
 7135                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7136                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7137                (start, end)
 7138            } else {
 7139                (selection.start, selection.end)
 7140            };
 7141
 7142            let text = buffer.text_for_range(start..end).collect::<String>();
 7143            let old_length = text.len() as i32;
 7144            let text = callback(&text);
 7145
 7146            new_selections.push(Selection {
 7147                start: (start as i32 - selection_adjustment) as usize,
 7148                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7149                goal: SelectionGoal::None,
 7150                ..selection
 7151            });
 7152
 7153            selection_adjustment += old_length - text.len() as i32;
 7154
 7155            edits.push((start..end, text));
 7156        }
 7157
 7158        self.transact(window, cx, |this, window, cx| {
 7159            this.buffer.update(cx, |buffer, cx| {
 7160                buffer.edit(edits, None, cx);
 7161            });
 7162
 7163            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7164                s.select(new_selections);
 7165            });
 7166
 7167            this.request_autoscroll(Autoscroll::fit(), cx);
 7168        });
 7169    }
 7170
 7171    pub fn duplicate(
 7172        &mut self,
 7173        upwards: bool,
 7174        whole_lines: bool,
 7175        window: &mut Window,
 7176        cx: &mut Context<Self>,
 7177    ) {
 7178        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7179        let buffer = &display_map.buffer_snapshot;
 7180        let selections = self.selections.all::<Point>(cx);
 7181
 7182        let mut edits = Vec::new();
 7183        let mut selections_iter = selections.iter().peekable();
 7184        while let Some(selection) = selections_iter.next() {
 7185            let mut rows = selection.spanned_rows(false, &display_map);
 7186            // duplicate line-wise
 7187            if whole_lines || selection.start == selection.end {
 7188                // Avoid duplicating the same lines twice.
 7189                while let Some(next_selection) = selections_iter.peek() {
 7190                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7191                    if next_rows.start < rows.end {
 7192                        rows.end = next_rows.end;
 7193                        selections_iter.next().unwrap();
 7194                    } else {
 7195                        break;
 7196                    }
 7197                }
 7198
 7199                // Copy the text from the selected row region and splice it either at the start
 7200                // or end of the region.
 7201                let start = Point::new(rows.start.0, 0);
 7202                let end = Point::new(
 7203                    rows.end.previous_row().0,
 7204                    buffer.line_len(rows.end.previous_row()),
 7205                );
 7206                let text = buffer
 7207                    .text_for_range(start..end)
 7208                    .chain(Some("\n"))
 7209                    .collect::<String>();
 7210                let insert_location = if upwards {
 7211                    Point::new(rows.end.0, 0)
 7212                } else {
 7213                    start
 7214                };
 7215                edits.push((insert_location..insert_location, text));
 7216            } else {
 7217                // duplicate character-wise
 7218                let start = selection.start;
 7219                let end = selection.end;
 7220                let text = buffer.text_for_range(start..end).collect::<String>();
 7221                edits.push((selection.end..selection.end, text));
 7222            }
 7223        }
 7224
 7225        self.transact(window, cx, |this, _, cx| {
 7226            this.buffer.update(cx, |buffer, cx| {
 7227                buffer.edit(edits, None, cx);
 7228            });
 7229
 7230            this.request_autoscroll(Autoscroll::fit(), cx);
 7231        });
 7232    }
 7233
 7234    pub fn duplicate_line_up(
 7235        &mut self,
 7236        _: &DuplicateLineUp,
 7237        window: &mut Window,
 7238        cx: &mut Context<Self>,
 7239    ) {
 7240        self.duplicate(true, true, window, cx);
 7241    }
 7242
 7243    pub fn duplicate_line_down(
 7244        &mut self,
 7245        _: &DuplicateLineDown,
 7246        window: &mut Window,
 7247        cx: &mut Context<Self>,
 7248    ) {
 7249        self.duplicate(false, true, window, cx);
 7250    }
 7251
 7252    pub fn duplicate_selection(
 7253        &mut self,
 7254        _: &DuplicateSelection,
 7255        window: &mut Window,
 7256        cx: &mut Context<Self>,
 7257    ) {
 7258        self.duplicate(false, false, window, cx);
 7259    }
 7260
 7261    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7262        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7263        let buffer = self.buffer.read(cx).snapshot(cx);
 7264
 7265        let mut edits = Vec::new();
 7266        let mut unfold_ranges = Vec::new();
 7267        let mut refold_creases = Vec::new();
 7268
 7269        let selections = self.selections.all::<Point>(cx);
 7270        let mut selections = selections.iter().peekable();
 7271        let mut contiguous_row_selections = Vec::new();
 7272        let mut new_selections = Vec::new();
 7273
 7274        while let Some(selection) = selections.next() {
 7275            // Find all the selections that span a contiguous row range
 7276            let (start_row, end_row) = consume_contiguous_rows(
 7277                &mut contiguous_row_selections,
 7278                selection,
 7279                &display_map,
 7280                &mut selections,
 7281            );
 7282
 7283            // Move the text spanned by the row range to be before the line preceding the row range
 7284            if start_row.0 > 0 {
 7285                let range_to_move = Point::new(
 7286                    start_row.previous_row().0,
 7287                    buffer.line_len(start_row.previous_row()),
 7288                )
 7289                    ..Point::new(
 7290                        end_row.previous_row().0,
 7291                        buffer.line_len(end_row.previous_row()),
 7292                    );
 7293                let insertion_point = display_map
 7294                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7295                    .0;
 7296
 7297                // Don't move lines across excerpts
 7298                if buffer
 7299                    .excerpt_containing(insertion_point..range_to_move.end)
 7300                    .is_some()
 7301                {
 7302                    let text = buffer
 7303                        .text_for_range(range_to_move.clone())
 7304                        .flat_map(|s| s.chars())
 7305                        .skip(1)
 7306                        .chain(['\n'])
 7307                        .collect::<String>();
 7308
 7309                    edits.push((
 7310                        buffer.anchor_after(range_to_move.start)
 7311                            ..buffer.anchor_before(range_to_move.end),
 7312                        String::new(),
 7313                    ));
 7314                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7315                    edits.push((insertion_anchor..insertion_anchor, text));
 7316
 7317                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7318
 7319                    // Move selections up
 7320                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7321                        |mut selection| {
 7322                            selection.start.row -= row_delta;
 7323                            selection.end.row -= row_delta;
 7324                            selection
 7325                        },
 7326                    ));
 7327
 7328                    // Move folds up
 7329                    unfold_ranges.push(range_to_move.clone());
 7330                    for fold in display_map.folds_in_range(
 7331                        buffer.anchor_before(range_to_move.start)
 7332                            ..buffer.anchor_after(range_to_move.end),
 7333                    ) {
 7334                        let mut start = fold.range.start.to_point(&buffer);
 7335                        let mut end = fold.range.end.to_point(&buffer);
 7336                        start.row -= row_delta;
 7337                        end.row -= row_delta;
 7338                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7339                    }
 7340                }
 7341            }
 7342
 7343            // If we didn't move line(s), preserve the existing selections
 7344            new_selections.append(&mut contiguous_row_selections);
 7345        }
 7346
 7347        self.transact(window, cx, |this, window, cx| {
 7348            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7349            this.buffer.update(cx, |buffer, cx| {
 7350                for (range, text) in edits {
 7351                    buffer.edit([(range, text)], None, cx);
 7352                }
 7353            });
 7354            this.fold_creases(refold_creases, true, window, cx);
 7355            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7356                s.select(new_selections);
 7357            })
 7358        });
 7359    }
 7360
 7361    pub fn move_line_down(
 7362        &mut self,
 7363        _: &MoveLineDown,
 7364        window: &mut Window,
 7365        cx: &mut Context<Self>,
 7366    ) {
 7367        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7368        let buffer = self.buffer.read(cx).snapshot(cx);
 7369
 7370        let mut edits = Vec::new();
 7371        let mut unfold_ranges = Vec::new();
 7372        let mut refold_creases = Vec::new();
 7373
 7374        let selections = self.selections.all::<Point>(cx);
 7375        let mut selections = selections.iter().peekable();
 7376        let mut contiguous_row_selections = Vec::new();
 7377        let mut new_selections = Vec::new();
 7378
 7379        while let Some(selection) = selections.next() {
 7380            // Find all the selections that span a contiguous row range
 7381            let (start_row, end_row) = consume_contiguous_rows(
 7382                &mut contiguous_row_selections,
 7383                selection,
 7384                &display_map,
 7385                &mut selections,
 7386            );
 7387
 7388            // Move the text spanned by the row range to be after the last line of the row range
 7389            if end_row.0 <= buffer.max_point().row {
 7390                let range_to_move =
 7391                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7392                let insertion_point = display_map
 7393                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7394                    .0;
 7395
 7396                // Don't move lines across excerpt boundaries
 7397                if buffer
 7398                    .excerpt_containing(range_to_move.start..insertion_point)
 7399                    .is_some()
 7400                {
 7401                    let mut text = String::from("\n");
 7402                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7403                    text.pop(); // Drop trailing newline
 7404                    edits.push((
 7405                        buffer.anchor_after(range_to_move.start)
 7406                            ..buffer.anchor_before(range_to_move.end),
 7407                        String::new(),
 7408                    ));
 7409                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7410                    edits.push((insertion_anchor..insertion_anchor, text));
 7411
 7412                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7413
 7414                    // Move selections down
 7415                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7416                        |mut selection| {
 7417                            selection.start.row += row_delta;
 7418                            selection.end.row += row_delta;
 7419                            selection
 7420                        },
 7421                    ));
 7422
 7423                    // Move folds down
 7424                    unfold_ranges.push(range_to_move.clone());
 7425                    for fold in display_map.folds_in_range(
 7426                        buffer.anchor_before(range_to_move.start)
 7427                            ..buffer.anchor_after(range_to_move.end),
 7428                    ) {
 7429                        let mut start = fold.range.start.to_point(&buffer);
 7430                        let mut end = fold.range.end.to_point(&buffer);
 7431                        start.row += row_delta;
 7432                        end.row += row_delta;
 7433                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7434                    }
 7435                }
 7436            }
 7437
 7438            // If we didn't move line(s), preserve the existing selections
 7439            new_selections.append(&mut contiguous_row_selections);
 7440        }
 7441
 7442        self.transact(window, cx, |this, window, cx| {
 7443            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7444            this.buffer.update(cx, |buffer, cx| {
 7445                for (range, text) in edits {
 7446                    buffer.edit([(range, text)], None, cx);
 7447                }
 7448            });
 7449            this.fold_creases(refold_creases, true, window, cx);
 7450            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7451                s.select(new_selections)
 7452            });
 7453        });
 7454    }
 7455
 7456    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7457        let text_layout_details = &self.text_layout_details(window);
 7458        self.transact(window, cx, |this, window, cx| {
 7459            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7460                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7461                let line_mode = s.line_mode;
 7462                s.move_with(|display_map, selection| {
 7463                    if !selection.is_empty() || line_mode {
 7464                        return;
 7465                    }
 7466
 7467                    let mut head = selection.head();
 7468                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7469                    if head.column() == display_map.line_len(head.row()) {
 7470                        transpose_offset = display_map
 7471                            .buffer_snapshot
 7472                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7473                    }
 7474
 7475                    if transpose_offset == 0 {
 7476                        return;
 7477                    }
 7478
 7479                    *head.column_mut() += 1;
 7480                    head = display_map.clip_point(head, Bias::Right);
 7481                    let goal = SelectionGoal::HorizontalPosition(
 7482                        display_map
 7483                            .x_for_display_point(head, text_layout_details)
 7484                            .into(),
 7485                    );
 7486                    selection.collapse_to(head, goal);
 7487
 7488                    let transpose_start = display_map
 7489                        .buffer_snapshot
 7490                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7491                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7492                        let transpose_end = display_map
 7493                            .buffer_snapshot
 7494                            .clip_offset(transpose_offset + 1, Bias::Right);
 7495                        if let Some(ch) =
 7496                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7497                        {
 7498                            edits.push((transpose_start..transpose_offset, String::new()));
 7499                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7500                        }
 7501                    }
 7502                });
 7503                edits
 7504            });
 7505            this.buffer
 7506                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7507            let selections = this.selections.all::<usize>(cx);
 7508            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7509                s.select(selections);
 7510            });
 7511        });
 7512    }
 7513
 7514    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7515        self.rewrap_impl(IsVimMode::No, cx)
 7516    }
 7517
 7518    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7519        let buffer = self.buffer.read(cx).snapshot(cx);
 7520        let selections = self.selections.all::<Point>(cx);
 7521        let mut selections = selections.iter().peekable();
 7522
 7523        let mut edits = Vec::new();
 7524        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7525
 7526        while let Some(selection) = selections.next() {
 7527            let mut start_row = selection.start.row;
 7528            let mut end_row = selection.end.row;
 7529
 7530            // Skip selections that overlap with a range that has already been rewrapped.
 7531            let selection_range = start_row..end_row;
 7532            if rewrapped_row_ranges
 7533                .iter()
 7534                .any(|range| range.overlaps(&selection_range))
 7535            {
 7536                continue;
 7537            }
 7538
 7539            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7540
 7541            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7542                match language_scope.language_name().as_ref() {
 7543                    "Markdown" | "Plain Text" => {
 7544                        should_rewrap = true;
 7545                    }
 7546                    _ => {}
 7547                }
 7548            }
 7549
 7550            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7551
 7552            // Since not all lines in the selection may be at the same indent
 7553            // level, choose the indent size that is the most common between all
 7554            // of the lines.
 7555            //
 7556            // If there is a tie, we use the deepest indent.
 7557            let (indent_size, indent_end) = {
 7558                let mut indent_size_occurrences = HashMap::default();
 7559                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7560
 7561                for row in start_row..=end_row {
 7562                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7563                    rows_by_indent_size.entry(indent).or_default().push(row);
 7564                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7565                }
 7566
 7567                let indent_size = indent_size_occurrences
 7568                    .into_iter()
 7569                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7570                    .map(|(indent, _)| indent)
 7571                    .unwrap_or_default();
 7572                let row = rows_by_indent_size[&indent_size][0];
 7573                let indent_end = Point::new(row, indent_size.len);
 7574
 7575                (indent_size, indent_end)
 7576            };
 7577
 7578            let mut line_prefix = indent_size.chars().collect::<String>();
 7579
 7580            if let Some(comment_prefix) =
 7581                buffer
 7582                    .language_scope_at(selection.head())
 7583                    .and_then(|language| {
 7584                        language
 7585                            .line_comment_prefixes()
 7586                            .iter()
 7587                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7588                            .cloned()
 7589                    })
 7590            {
 7591                line_prefix.push_str(&comment_prefix);
 7592                should_rewrap = true;
 7593            }
 7594
 7595            if !should_rewrap {
 7596                continue;
 7597            }
 7598
 7599            if selection.is_empty() {
 7600                'expand_upwards: while start_row > 0 {
 7601                    let prev_row = start_row - 1;
 7602                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7603                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7604                    {
 7605                        start_row = prev_row;
 7606                    } else {
 7607                        break 'expand_upwards;
 7608                    }
 7609                }
 7610
 7611                'expand_downwards: while end_row < buffer.max_point().row {
 7612                    let next_row = end_row + 1;
 7613                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7614                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7615                    {
 7616                        end_row = next_row;
 7617                    } else {
 7618                        break 'expand_downwards;
 7619                    }
 7620                }
 7621            }
 7622
 7623            let start = Point::new(start_row, 0);
 7624            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7625            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7626            let Some(lines_without_prefixes) = selection_text
 7627                .lines()
 7628                .map(|line| {
 7629                    line.strip_prefix(&line_prefix)
 7630                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7631                        .ok_or_else(|| {
 7632                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7633                        })
 7634                })
 7635                .collect::<Result<Vec<_>, _>>()
 7636                .log_err()
 7637            else {
 7638                continue;
 7639            };
 7640
 7641            let wrap_column = buffer
 7642                .settings_at(Point::new(start_row, 0), cx)
 7643                .preferred_line_length as usize;
 7644            let wrapped_text = wrap_with_prefix(
 7645                line_prefix,
 7646                lines_without_prefixes.join(" "),
 7647                wrap_column,
 7648                tab_size,
 7649            );
 7650
 7651            // TODO: should always use char-based diff while still supporting cursor behavior that
 7652            // matches vim.
 7653            let diff = match is_vim_mode {
 7654                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7655                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7656            };
 7657            let mut offset = start.to_offset(&buffer);
 7658            let mut moved_since_edit = true;
 7659
 7660            for change in diff.iter_all_changes() {
 7661                let value = change.value();
 7662                match change.tag() {
 7663                    ChangeTag::Equal => {
 7664                        offset += value.len();
 7665                        moved_since_edit = true;
 7666                    }
 7667                    ChangeTag::Delete => {
 7668                        let start = buffer.anchor_after(offset);
 7669                        let end = buffer.anchor_before(offset + value.len());
 7670
 7671                        if moved_since_edit {
 7672                            edits.push((start..end, String::new()));
 7673                        } else {
 7674                            edits.last_mut().unwrap().0.end = end;
 7675                        }
 7676
 7677                        offset += value.len();
 7678                        moved_since_edit = false;
 7679                    }
 7680                    ChangeTag::Insert => {
 7681                        if moved_since_edit {
 7682                            let anchor = buffer.anchor_after(offset);
 7683                            edits.push((anchor..anchor, value.to_string()));
 7684                        } else {
 7685                            edits.last_mut().unwrap().1.push_str(value);
 7686                        }
 7687
 7688                        moved_since_edit = false;
 7689                    }
 7690                }
 7691            }
 7692
 7693            rewrapped_row_ranges.push(start_row..=end_row);
 7694        }
 7695
 7696        self.buffer
 7697            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7698    }
 7699
 7700    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7701        let mut text = String::new();
 7702        let buffer = self.buffer.read(cx).snapshot(cx);
 7703        let mut selections = self.selections.all::<Point>(cx);
 7704        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7705        {
 7706            let max_point = buffer.max_point();
 7707            let mut is_first = true;
 7708            for selection in &mut selections {
 7709                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7710                if is_entire_line {
 7711                    selection.start = Point::new(selection.start.row, 0);
 7712                    if !selection.is_empty() && selection.end.column == 0 {
 7713                        selection.end = cmp::min(max_point, selection.end);
 7714                    } else {
 7715                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7716                    }
 7717                    selection.goal = SelectionGoal::None;
 7718                }
 7719                if is_first {
 7720                    is_first = false;
 7721                } else {
 7722                    text += "\n";
 7723                }
 7724                let mut len = 0;
 7725                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7726                    text.push_str(chunk);
 7727                    len += chunk.len();
 7728                }
 7729                clipboard_selections.push(ClipboardSelection {
 7730                    len,
 7731                    is_entire_line,
 7732                    first_line_indent: buffer
 7733                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7734                        .len,
 7735                });
 7736            }
 7737        }
 7738
 7739        self.transact(window, cx, |this, window, cx| {
 7740            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7741                s.select(selections);
 7742            });
 7743            this.insert("", window, cx);
 7744        });
 7745        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7746    }
 7747
 7748    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7749        let item = self.cut_common(window, cx);
 7750        cx.write_to_clipboard(item);
 7751    }
 7752
 7753    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7754        self.change_selections(None, window, cx, |s| {
 7755            s.move_with(|snapshot, sel| {
 7756                if sel.is_empty() {
 7757                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7758                }
 7759            });
 7760        });
 7761        let item = self.cut_common(window, cx);
 7762        cx.set_global(KillRing(item))
 7763    }
 7764
 7765    pub fn kill_ring_yank(
 7766        &mut self,
 7767        _: &KillRingYank,
 7768        window: &mut Window,
 7769        cx: &mut Context<Self>,
 7770    ) {
 7771        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7772            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7773                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7774            } else {
 7775                return;
 7776            }
 7777        } else {
 7778            return;
 7779        };
 7780        self.do_paste(&text, metadata, false, window, cx);
 7781    }
 7782
 7783    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7784        let selections = self.selections.all::<Point>(cx);
 7785        let buffer = self.buffer.read(cx).read(cx);
 7786        let mut text = String::new();
 7787
 7788        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7789        {
 7790            let max_point = buffer.max_point();
 7791            let mut is_first = true;
 7792            for selection in selections.iter() {
 7793                let mut start = selection.start;
 7794                let mut end = selection.end;
 7795                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7796                if is_entire_line {
 7797                    start = Point::new(start.row, 0);
 7798                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7799                }
 7800                if is_first {
 7801                    is_first = false;
 7802                } else {
 7803                    text += "\n";
 7804                }
 7805                let mut len = 0;
 7806                for chunk in buffer.text_for_range(start..end) {
 7807                    text.push_str(chunk);
 7808                    len += chunk.len();
 7809                }
 7810                clipboard_selections.push(ClipboardSelection {
 7811                    len,
 7812                    is_entire_line,
 7813                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7814                });
 7815            }
 7816        }
 7817
 7818        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7819            text,
 7820            clipboard_selections,
 7821        ));
 7822    }
 7823
 7824    pub fn do_paste(
 7825        &mut self,
 7826        text: &String,
 7827        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7828        handle_entire_lines: bool,
 7829        window: &mut Window,
 7830        cx: &mut Context<Self>,
 7831    ) {
 7832        if self.read_only(cx) {
 7833            return;
 7834        }
 7835
 7836        let clipboard_text = Cow::Borrowed(text);
 7837
 7838        self.transact(window, cx, |this, window, cx| {
 7839            if let Some(mut clipboard_selections) = clipboard_selections {
 7840                let old_selections = this.selections.all::<usize>(cx);
 7841                let all_selections_were_entire_line =
 7842                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7843                let first_selection_indent_column =
 7844                    clipboard_selections.first().map(|s| s.first_line_indent);
 7845                if clipboard_selections.len() != old_selections.len() {
 7846                    clipboard_selections.drain(..);
 7847                }
 7848                let cursor_offset = this.selections.last::<usize>(cx).head();
 7849                let mut auto_indent_on_paste = true;
 7850
 7851                this.buffer.update(cx, |buffer, cx| {
 7852                    let snapshot = buffer.read(cx);
 7853                    auto_indent_on_paste =
 7854                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7855
 7856                    let mut start_offset = 0;
 7857                    let mut edits = Vec::new();
 7858                    let mut original_indent_columns = Vec::new();
 7859                    for (ix, selection) in old_selections.iter().enumerate() {
 7860                        let to_insert;
 7861                        let entire_line;
 7862                        let original_indent_column;
 7863                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7864                            let end_offset = start_offset + clipboard_selection.len;
 7865                            to_insert = &clipboard_text[start_offset..end_offset];
 7866                            entire_line = clipboard_selection.is_entire_line;
 7867                            start_offset = end_offset + 1;
 7868                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7869                        } else {
 7870                            to_insert = clipboard_text.as_str();
 7871                            entire_line = all_selections_were_entire_line;
 7872                            original_indent_column = first_selection_indent_column
 7873                        }
 7874
 7875                        // If the corresponding selection was empty when this slice of the
 7876                        // clipboard text was written, then the entire line containing the
 7877                        // selection was copied. If this selection is also currently empty,
 7878                        // then paste the line before the current line of the buffer.
 7879                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7880                            let column = selection.start.to_point(&snapshot).column as usize;
 7881                            let line_start = selection.start - column;
 7882                            line_start..line_start
 7883                        } else {
 7884                            selection.range()
 7885                        };
 7886
 7887                        edits.push((range, to_insert));
 7888                        original_indent_columns.extend(original_indent_column);
 7889                    }
 7890                    drop(snapshot);
 7891
 7892                    buffer.edit(
 7893                        edits,
 7894                        if auto_indent_on_paste {
 7895                            Some(AutoindentMode::Block {
 7896                                original_indent_columns,
 7897                            })
 7898                        } else {
 7899                            None
 7900                        },
 7901                        cx,
 7902                    );
 7903                });
 7904
 7905                let selections = this.selections.all::<usize>(cx);
 7906                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7907                    s.select(selections)
 7908                });
 7909            } else {
 7910                this.insert(&clipboard_text, window, cx);
 7911            }
 7912        });
 7913    }
 7914
 7915    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7916        if let Some(item) = cx.read_from_clipboard() {
 7917            let entries = item.entries();
 7918
 7919            match entries.first() {
 7920                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7921                // of all the pasted entries.
 7922                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7923                    .do_paste(
 7924                        clipboard_string.text(),
 7925                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7926                        true,
 7927                        window,
 7928                        cx,
 7929                    ),
 7930                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7931            }
 7932        }
 7933    }
 7934
 7935    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7936        if self.read_only(cx) {
 7937            return;
 7938        }
 7939
 7940        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7941            if let Some((selections, _)) =
 7942                self.selection_history.transaction(transaction_id).cloned()
 7943            {
 7944                self.change_selections(None, window, cx, |s| {
 7945                    s.select_anchors(selections.to_vec());
 7946                });
 7947            }
 7948            self.request_autoscroll(Autoscroll::fit(), cx);
 7949            self.unmark_text(window, cx);
 7950            self.refresh_inline_completion(true, false, window, cx);
 7951            cx.emit(EditorEvent::Edited { transaction_id });
 7952            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7953        }
 7954    }
 7955
 7956    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7957        if self.read_only(cx) {
 7958            return;
 7959        }
 7960
 7961        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7962            if let Some((_, Some(selections))) =
 7963                self.selection_history.transaction(transaction_id).cloned()
 7964            {
 7965                self.change_selections(None, window, cx, |s| {
 7966                    s.select_anchors(selections.to_vec());
 7967                });
 7968            }
 7969            self.request_autoscroll(Autoscroll::fit(), cx);
 7970            self.unmark_text(window, cx);
 7971            self.refresh_inline_completion(true, false, window, cx);
 7972            cx.emit(EditorEvent::Edited { transaction_id });
 7973        }
 7974    }
 7975
 7976    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7977        self.buffer
 7978            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7979    }
 7980
 7981    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7982        self.buffer
 7983            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7984    }
 7985
 7986    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7987        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7988            let line_mode = s.line_mode;
 7989            s.move_with(|map, selection| {
 7990                let cursor = if selection.is_empty() && !line_mode {
 7991                    movement::left(map, selection.start)
 7992                } else {
 7993                    selection.start
 7994                };
 7995                selection.collapse_to(cursor, SelectionGoal::None);
 7996            });
 7997        })
 7998    }
 7999
 8000    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8001        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8002            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8003        })
 8004    }
 8005
 8006    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8007        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8008            let line_mode = s.line_mode;
 8009            s.move_with(|map, selection| {
 8010                let cursor = if selection.is_empty() && !line_mode {
 8011                    movement::right(map, selection.end)
 8012                } else {
 8013                    selection.end
 8014                };
 8015                selection.collapse_to(cursor, SelectionGoal::None)
 8016            });
 8017        })
 8018    }
 8019
 8020    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8021        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8022            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8023        })
 8024    }
 8025
 8026    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8027        if self.take_rename(true, window, cx).is_some() {
 8028            return;
 8029        }
 8030
 8031        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8032            cx.propagate();
 8033            return;
 8034        }
 8035
 8036        let text_layout_details = &self.text_layout_details(window);
 8037        let selection_count = self.selections.count();
 8038        let first_selection = self.selections.first_anchor();
 8039
 8040        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8041            let line_mode = s.line_mode;
 8042            s.move_with(|map, selection| {
 8043                if !selection.is_empty() && !line_mode {
 8044                    selection.goal = SelectionGoal::None;
 8045                }
 8046                let (cursor, goal) = movement::up(
 8047                    map,
 8048                    selection.start,
 8049                    selection.goal,
 8050                    false,
 8051                    text_layout_details,
 8052                );
 8053                selection.collapse_to(cursor, goal);
 8054            });
 8055        });
 8056
 8057        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8058        {
 8059            cx.propagate();
 8060        }
 8061    }
 8062
 8063    pub fn move_up_by_lines(
 8064        &mut self,
 8065        action: &MoveUpByLines,
 8066        window: &mut Window,
 8067        cx: &mut Context<Self>,
 8068    ) {
 8069        if self.take_rename(true, window, cx).is_some() {
 8070            return;
 8071        }
 8072
 8073        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8074            cx.propagate();
 8075            return;
 8076        }
 8077
 8078        let text_layout_details = &self.text_layout_details(window);
 8079
 8080        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8081            let line_mode = s.line_mode;
 8082            s.move_with(|map, selection| {
 8083                if !selection.is_empty() && !line_mode {
 8084                    selection.goal = SelectionGoal::None;
 8085                }
 8086                let (cursor, goal) = movement::up_by_rows(
 8087                    map,
 8088                    selection.start,
 8089                    action.lines,
 8090                    selection.goal,
 8091                    false,
 8092                    text_layout_details,
 8093                );
 8094                selection.collapse_to(cursor, goal);
 8095            });
 8096        })
 8097    }
 8098
 8099    pub fn move_down_by_lines(
 8100        &mut self,
 8101        action: &MoveDownByLines,
 8102        window: &mut Window,
 8103        cx: &mut Context<Self>,
 8104    ) {
 8105        if self.take_rename(true, window, cx).is_some() {
 8106            return;
 8107        }
 8108
 8109        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8110            cx.propagate();
 8111            return;
 8112        }
 8113
 8114        let text_layout_details = &self.text_layout_details(window);
 8115
 8116        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8117            let line_mode = s.line_mode;
 8118            s.move_with(|map, selection| {
 8119                if !selection.is_empty() && !line_mode {
 8120                    selection.goal = SelectionGoal::None;
 8121                }
 8122                let (cursor, goal) = movement::down_by_rows(
 8123                    map,
 8124                    selection.start,
 8125                    action.lines,
 8126                    selection.goal,
 8127                    false,
 8128                    text_layout_details,
 8129                );
 8130                selection.collapse_to(cursor, goal);
 8131            });
 8132        })
 8133    }
 8134
 8135    pub fn select_down_by_lines(
 8136        &mut self,
 8137        action: &SelectDownByLines,
 8138        window: &mut Window,
 8139        cx: &mut Context<Self>,
 8140    ) {
 8141        let text_layout_details = &self.text_layout_details(window);
 8142        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8143            s.move_heads_with(|map, head, goal| {
 8144                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8145            })
 8146        })
 8147    }
 8148
 8149    pub fn select_up_by_lines(
 8150        &mut self,
 8151        action: &SelectUpByLines,
 8152        window: &mut Window,
 8153        cx: &mut Context<Self>,
 8154    ) {
 8155        let text_layout_details = &self.text_layout_details(window);
 8156        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8157            s.move_heads_with(|map, head, goal| {
 8158                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8159            })
 8160        })
 8161    }
 8162
 8163    pub fn select_page_up(
 8164        &mut self,
 8165        _: &SelectPageUp,
 8166        window: &mut Window,
 8167        cx: &mut Context<Self>,
 8168    ) {
 8169        let Some(row_count) = self.visible_row_count() else {
 8170            return;
 8171        };
 8172
 8173        let text_layout_details = &self.text_layout_details(window);
 8174
 8175        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8176            s.move_heads_with(|map, head, goal| {
 8177                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8178            })
 8179        })
 8180    }
 8181
 8182    pub fn move_page_up(
 8183        &mut self,
 8184        action: &MovePageUp,
 8185        window: &mut Window,
 8186        cx: &mut Context<Self>,
 8187    ) {
 8188        if self.take_rename(true, window, cx).is_some() {
 8189            return;
 8190        }
 8191
 8192        if self
 8193            .context_menu
 8194            .borrow_mut()
 8195            .as_mut()
 8196            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8197            .unwrap_or(false)
 8198        {
 8199            return;
 8200        }
 8201
 8202        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8203            cx.propagate();
 8204            return;
 8205        }
 8206
 8207        let Some(row_count) = self.visible_row_count() else {
 8208            return;
 8209        };
 8210
 8211        let autoscroll = if action.center_cursor {
 8212            Autoscroll::center()
 8213        } else {
 8214            Autoscroll::fit()
 8215        };
 8216
 8217        let text_layout_details = &self.text_layout_details(window);
 8218
 8219        self.change_selections(Some(autoscroll), window, cx, |s| {
 8220            let line_mode = s.line_mode;
 8221            s.move_with(|map, selection| {
 8222                if !selection.is_empty() && !line_mode {
 8223                    selection.goal = SelectionGoal::None;
 8224                }
 8225                let (cursor, goal) = movement::up_by_rows(
 8226                    map,
 8227                    selection.end,
 8228                    row_count,
 8229                    selection.goal,
 8230                    false,
 8231                    text_layout_details,
 8232                );
 8233                selection.collapse_to(cursor, goal);
 8234            });
 8235        });
 8236    }
 8237
 8238    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8239        let text_layout_details = &self.text_layout_details(window);
 8240        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8241            s.move_heads_with(|map, head, goal| {
 8242                movement::up(map, head, goal, false, text_layout_details)
 8243            })
 8244        })
 8245    }
 8246
 8247    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8248        self.take_rename(true, window, cx);
 8249
 8250        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8251            cx.propagate();
 8252            return;
 8253        }
 8254
 8255        let text_layout_details = &self.text_layout_details(window);
 8256        let selection_count = self.selections.count();
 8257        let first_selection = self.selections.first_anchor();
 8258
 8259        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8260            let line_mode = s.line_mode;
 8261            s.move_with(|map, selection| {
 8262                if !selection.is_empty() && !line_mode {
 8263                    selection.goal = SelectionGoal::None;
 8264                }
 8265                let (cursor, goal) = movement::down(
 8266                    map,
 8267                    selection.end,
 8268                    selection.goal,
 8269                    false,
 8270                    text_layout_details,
 8271                );
 8272                selection.collapse_to(cursor, goal);
 8273            });
 8274        });
 8275
 8276        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8277        {
 8278            cx.propagate();
 8279        }
 8280    }
 8281
 8282    pub fn select_page_down(
 8283        &mut self,
 8284        _: &SelectPageDown,
 8285        window: &mut Window,
 8286        cx: &mut Context<Self>,
 8287    ) {
 8288        let Some(row_count) = self.visible_row_count() else {
 8289            return;
 8290        };
 8291
 8292        let text_layout_details = &self.text_layout_details(window);
 8293
 8294        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8295            s.move_heads_with(|map, head, goal| {
 8296                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8297            })
 8298        })
 8299    }
 8300
 8301    pub fn move_page_down(
 8302        &mut self,
 8303        action: &MovePageDown,
 8304        window: &mut Window,
 8305        cx: &mut Context<Self>,
 8306    ) {
 8307        if self.take_rename(true, window, cx).is_some() {
 8308            return;
 8309        }
 8310
 8311        if self
 8312            .context_menu
 8313            .borrow_mut()
 8314            .as_mut()
 8315            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8316            .unwrap_or(false)
 8317        {
 8318            return;
 8319        }
 8320
 8321        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8322            cx.propagate();
 8323            return;
 8324        }
 8325
 8326        let Some(row_count) = self.visible_row_count() else {
 8327            return;
 8328        };
 8329
 8330        let autoscroll = if action.center_cursor {
 8331            Autoscroll::center()
 8332        } else {
 8333            Autoscroll::fit()
 8334        };
 8335
 8336        let text_layout_details = &self.text_layout_details(window);
 8337        self.change_selections(Some(autoscroll), window, cx, |s| {
 8338            let line_mode = s.line_mode;
 8339            s.move_with(|map, selection| {
 8340                if !selection.is_empty() && !line_mode {
 8341                    selection.goal = SelectionGoal::None;
 8342                }
 8343                let (cursor, goal) = movement::down_by_rows(
 8344                    map,
 8345                    selection.end,
 8346                    row_count,
 8347                    selection.goal,
 8348                    false,
 8349                    text_layout_details,
 8350                );
 8351                selection.collapse_to(cursor, goal);
 8352            });
 8353        });
 8354    }
 8355
 8356    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8357        let text_layout_details = &self.text_layout_details(window);
 8358        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8359            s.move_heads_with(|map, head, goal| {
 8360                movement::down(map, head, goal, false, text_layout_details)
 8361            })
 8362        });
 8363    }
 8364
 8365    pub fn context_menu_first(
 8366        &mut self,
 8367        _: &ContextMenuFirst,
 8368        _window: &mut Window,
 8369        cx: &mut Context<Self>,
 8370    ) {
 8371        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8372            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8373        }
 8374    }
 8375
 8376    pub fn context_menu_prev(
 8377        &mut self,
 8378        _: &ContextMenuPrev,
 8379        _window: &mut Window,
 8380        cx: &mut Context<Self>,
 8381    ) {
 8382        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8383            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8384        }
 8385    }
 8386
 8387    pub fn context_menu_next(
 8388        &mut self,
 8389        _: &ContextMenuNext,
 8390        _window: &mut Window,
 8391        cx: &mut Context<Self>,
 8392    ) {
 8393        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8394            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8395        }
 8396    }
 8397
 8398    pub fn context_menu_last(
 8399        &mut self,
 8400        _: &ContextMenuLast,
 8401        _window: &mut Window,
 8402        cx: &mut Context<Self>,
 8403    ) {
 8404        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8405            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8406        }
 8407    }
 8408
 8409    pub fn move_to_previous_word_start(
 8410        &mut self,
 8411        _: &MoveToPreviousWordStart,
 8412        window: &mut Window,
 8413        cx: &mut Context<Self>,
 8414    ) {
 8415        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8416            s.move_cursors_with(|map, head, _| {
 8417                (
 8418                    movement::previous_word_start(map, head),
 8419                    SelectionGoal::None,
 8420                )
 8421            });
 8422        })
 8423    }
 8424
 8425    pub fn move_to_previous_subword_start(
 8426        &mut self,
 8427        _: &MoveToPreviousSubwordStart,
 8428        window: &mut Window,
 8429        cx: &mut Context<Self>,
 8430    ) {
 8431        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8432            s.move_cursors_with(|map, head, _| {
 8433                (
 8434                    movement::previous_subword_start(map, head),
 8435                    SelectionGoal::None,
 8436                )
 8437            });
 8438        })
 8439    }
 8440
 8441    pub fn select_to_previous_word_start(
 8442        &mut self,
 8443        _: &SelectToPreviousWordStart,
 8444        window: &mut Window,
 8445        cx: &mut Context<Self>,
 8446    ) {
 8447        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8448            s.move_heads_with(|map, head, _| {
 8449                (
 8450                    movement::previous_word_start(map, head),
 8451                    SelectionGoal::None,
 8452                )
 8453            });
 8454        })
 8455    }
 8456
 8457    pub fn select_to_previous_subword_start(
 8458        &mut self,
 8459        _: &SelectToPreviousSubwordStart,
 8460        window: &mut Window,
 8461        cx: &mut Context<Self>,
 8462    ) {
 8463        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8464            s.move_heads_with(|map, head, _| {
 8465                (
 8466                    movement::previous_subword_start(map, head),
 8467                    SelectionGoal::None,
 8468                )
 8469            });
 8470        })
 8471    }
 8472
 8473    pub fn delete_to_previous_word_start(
 8474        &mut self,
 8475        action: &DeleteToPreviousWordStart,
 8476        window: &mut Window,
 8477        cx: &mut Context<Self>,
 8478    ) {
 8479        self.transact(window, cx, |this, window, cx| {
 8480            this.select_autoclose_pair(window, cx);
 8481            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8482                let line_mode = s.line_mode;
 8483                s.move_with(|map, selection| {
 8484                    if selection.is_empty() && !line_mode {
 8485                        let cursor = if action.ignore_newlines {
 8486                            movement::previous_word_start(map, selection.head())
 8487                        } else {
 8488                            movement::previous_word_start_or_newline(map, selection.head())
 8489                        };
 8490                        selection.set_head(cursor, SelectionGoal::None);
 8491                    }
 8492                });
 8493            });
 8494            this.insert("", window, cx);
 8495        });
 8496    }
 8497
 8498    pub fn delete_to_previous_subword_start(
 8499        &mut self,
 8500        _: &DeleteToPreviousSubwordStart,
 8501        window: &mut Window,
 8502        cx: &mut Context<Self>,
 8503    ) {
 8504        self.transact(window, cx, |this, window, cx| {
 8505            this.select_autoclose_pair(window, cx);
 8506            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8507                let line_mode = s.line_mode;
 8508                s.move_with(|map, selection| {
 8509                    if selection.is_empty() && !line_mode {
 8510                        let cursor = movement::previous_subword_start(map, selection.head());
 8511                        selection.set_head(cursor, SelectionGoal::None);
 8512                    }
 8513                });
 8514            });
 8515            this.insert("", window, cx);
 8516        });
 8517    }
 8518
 8519    pub fn move_to_next_word_end(
 8520        &mut self,
 8521        _: &MoveToNextWordEnd,
 8522        window: &mut Window,
 8523        cx: &mut Context<Self>,
 8524    ) {
 8525        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8526            s.move_cursors_with(|map, head, _| {
 8527                (movement::next_word_end(map, head), SelectionGoal::None)
 8528            });
 8529        })
 8530    }
 8531
 8532    pub fn move_to_next_subword_end(
 8533        &mut self,
 8534        _: &MoveToNextSubwordEnd,
 8535        window: &mut Window,
 8536        cx: &mut Context<Self>,
 8537    ) {
 8538        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8539            s.move_cursors_with(|map, head, _| {
 8540                (movement::next_subword_end(map, head), SelectionGoal::None)
 8541            });
 8542        })
 8543    }
 8544
 8545    pub fn select_to_next_word_end(
 8546        &mut self,
 8547        _: &SelectToNextWordEnd,
 8548        window: &mut Window,
 8549        cx: &mut Context<Self>,
 8550    ) {
 8551        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8552            s.move_heads_with(|map, head, _| {
 8553                (movement::next_word_end(map, head), SelectionGoal::None)
 8554            });
 8555        })
 8556    }
 8557
 8558    pub fn select_to_next_subword_end(
 8559        &mut self,
 8560        _: &SelectToNextSubwordEnd,
 8561        window: &mut Window,
 8562        cx: &mut Context<Self>,
 8563    ) {
 8564        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8565            s.move_heads_with(|map, head, _| {
 8566                (movement::next_subword_end(map, head), SelectionGoal::None)
 8567            });
 8568        })
 8569    }
 8570
 8571    pub fn delete_to_next_word_end(
 8572        &mut self,
 8573        action: &DeleteToNextWordEnd,
 8574        window: &mut Window,
 8575        cx: &mut Context<Self>,
 8576    ) {
 8577        self.transact(window, cx, |this, window, cx| {
 8578            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8579                let line_mode = s.line_mode;
 8580                s.move_with(|map, selection| {
 8581                    if selection.is_empty() && !line_mode {
 8582                        let cursor = if action.ignore_newlines {
 8583                            movement::next_word_end(map, selection.head())
 8584                        } else {
 8585                            movement::next_word_end_or_newline(map, selection.head())
 8586                        };
 8587                        selection.set_head(cursor, SelectionGoal::None);
 8588                    }
 8589                });
 8590            });
 8591            this.insert("", window, cx);
 8592        });
 8593    }
 8594
 8595    pub fn delete_to_next_subword_end(
 8596        &mut self,
 8597        _: &DeleteToNextSubwordEnd,
 8598        window: &mut Window,
 8599        cx: &mut Context<Self>,
 8600    ) {
 8601        self.transact(window, cx, |this, window, cx| {
 8602            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8603                s.move_with(|map, selection| {
 8604                    if selection.is_empty() {
 8605                        let cursor = movement::next_subword_end(map, selection.head());
 8606                        selection.set_head(cursor, SelectionGoal::None);
 8607                    }
 8608                });
 8609            });
 8610            this.insert("", window, cx);
 8611        });
 8612    }
 8613
 8614    pub fn move_to_beginning_of_line(
 8615        &mut self,
 8616        action: &MoveToBeginningOfLine,
 8617        window: &mut Window,
 8618        cx: &mut Context<Self>,
 8619    ) {
 8620        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8621            s.move_cursors_with(|map, head, _| {
 8622                (
 8623                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8624                    SelectionGoal::None,
 8625                )
 8626            });
 8627        })
 8628    }
 8629
 8630    pub fn select_to_beginning_of_line(
 8631        &mut self,
 8632        action: &SelectToBeginningOfLine,
 8633        window: &mut Window,
 8634        cx: &mut Context<Self>,
 8635    ) {
 8636        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8637            s.move_heads_with(|map, head, _| {
 8638                (
 8639                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8640                    SelectionGoal::None,
 8641                )
 8642            });
 8643        });
 8644    }
 8645
 8646    pub fn delete_to_beginning_of_line(
 8647        &mut self,
 8648        _: &DeleteToBeginningOfLine,
 8649        window: &mut Window,
 8650        cx: &mut Context<Self>,
 8651    ) {
 8652        self.transact(window, cx, |this, window, cx| {
 8653            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8654                s.move_with(|_, selection| {
 8655                    selection.reversed = true;
 8656                });
 8657            });
 8658
 8659            this.select_to_beginning_of_line(
 8660                &SelectToBeginningOfLine {
 8661                    stop_at_soft_wraps: false,
 8662                },
 8663                window,
 8664                cx,
 8665            );
 8666            this.backspace(&Backspace, window, cx);
 8667        });
 8668    }
 8669
 8670    pub fn move_to_end_of_line(
 8671        &mut self,
 8672        action: &MoveToEndOfLine,
 8673        window: &mut Window,
 8674        cx: &mut Context<Self>,
 8675    ) {
 8676        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8677            s.move_cursors_with(|map, head, _| {
 8678                (
 8679                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8680                    SelectionGoal::None,
 8681                )
 8682            });
 8683        })
 8684    }
 8685
 8686    pub fn select_to_end_of_line(
 8687        &mut self,
 8688        action: &SelectToEndOfLine,
 8689        window: &mut Window,
 8690        cx: &mut Context<Self>,
 8691    ) {
 8692        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8693            s.move_heads_with(|map, head, _| {
 8694                (
 8695                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8696                    SelectionGoal::None,
 8697                )
 8698            });
 8699        })
 8700    }
 8701
 8702    pub fn delete_to_end_of_line(
 8703        &mut self,
 8704        _: &DeleteToEndOfLine,
 8705        window: &mut Window,
 8706        cx: &mut Context<Self>,
 8707    ) {
 8708        self.transact(window, cx, |this, window, cx| {
 8709            this.select_to_end_of_line(
 8710                &SelectToEndOfLine {
 8711                    stop_at_soft_wraps: false,
 8712                },
 8713                window,
 8714                cx,
 8715            );
 8716            this.delete(&Delete, window, cx);
 8717        });
 8718    }
 8719
 8720    pub fn cut_to_end_of_line(
 8721        &mut self,
 8722        _: &CutToEndOfLine,
 8723        window: &mut Window,
 8724        cx: &mut Context<Self>,
 8725    ) {
 8726        self.transact(window, cx, |this, window, cx| {
 8727            this.select_to_end_of_line(
 8728                &SelectToEndOfLine {
 8729                    stop_at_soft_wraps: false,
 8730                },
 8731                window,
 8732                cx,
 8733            );
 8734            this.cut(&Cut, window, cx);
 8735        });
 8736    }
 8737
 8738    pub fn move_to_start_of_paragraph(
 8739        &mut self,
 8740        _: &MoveToStartOfParagraph,
 8741        window: &mut Window,
 8742        cx: &mut Context<Self>,
 8743    ) {
 8744        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8745            cx.propagate();
 8746            return;
 8747        }
 8748
 8749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8750            s.move_with(|map, selection| {
 8751                selection.collapse_to(
 8752                    movement::start_of_paragraph(map, selection.head(), 1),
 8753                    SelectionGoal::None,
 8754                )
 8755            });
 8756        })
 8757    }
 8758
 8759    pub fn move_to_end_of_paragraph(
 8760        &mut self,
 8761        _: &MoveToEndOfParagraph,
 8762        window: &mut Window,
 8763        cx: &mut Context<Self>,
 8764    ) {
 8765        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8766            cx.propagate();
 8767            return;
 8768        }
 8769
 8770        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8771            s.move_with(|map, selection| {
 8772                selection.collapse_to(
 8773                    movement::end_of_paragraph(map, selection.head(), 1),
 8774                    SelectionGoal::None,
 8775                )
 8776            });
 8777        })
 8778    }
 8779
 8780    pub fn select_to_start_of_paragraph(
 8781        &mut self,
 8782        _: &SelectToStartOfParagraph,
 8783        window: &mut Window,
 8784        cx: &mut Context<Self>,
 8785    ) {
 8786        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8787            cx.propagate();
 8788            return;
 8789        }
 8790
 8791        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8792            s.move_heads_with(|map, head, _| {
 8793                (
 8794                    movement::start_of_paragraph(map, head, 1),
 8795                    SelectionGoal::None,
 8796                )
 8797            });
 8798        })
 8799    }
 8800
 8801    pub fn select_to_end_of_paragraph(
 8802        &mut self,
 8803        _: &SelectToEndOfParagraph,
 8804        window: &mut Window,
 8805        cx: &mut Context<Self>,
 8806    ) {
 8807        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8808            cx.propagate();
 8809            return;
 8810        }
 8811
 8812        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8813            s.move_heads_with(|map, head, _| {
 8814                (
 8815                    movement::end_of_paragraph(map, head, 1),
 8816                    SelectionGoal::None,
 8817                )
 8818            });
 8819        })
 8820    }
 8821
 8822    pub fn move_to_beginning(
 8823        &mut self,
 8824        _: &MoveToBeginning,
 8825        window: &mut Window,
 8826        cx: &mut Context<Self>,
 8827    ) {
 8828        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8829            cx.propagate();
 8830            return;
 8831        }
 8832
 8833        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8834            s.select_ranges(vec![0..0]);
 8835        });
 8836    }
 8837
 8838    pub fn select_to_beginning(
 8839        &mut self,
 8840        _: &SelectToBeginning,
 8841        window: &mut Window,
 8842        cx: &mut Context<Self>,
 8843    ) {
 8844        let mut selection = self.selections.last::<Point>(cx);
 8845        selection.set_head(Point::zero(), SelectionGoal::None);
 8846
 8847        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8848            s.select(vec![selection]);
 8849        });
 8850    }
 8851
 8852    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8853        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8854            cx.propagate();
 8855            return;
 8856        }
 8857
 8858        let cursor = self.buffer.read(cx).read(cx).len();
 8859        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8860            s.select_ranges(vec![cursor..cursor])
 8861        });
 8862    }
 8863
 8864    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8865        self.nav_history = nav_history;
 8866    }
 8867
 8868    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8869        self.nav_history.as_ref()
 8870    }
 8871
 8872    fn push_to_nav_history(
 8873        &mut self,
 8874        cursor_anchor: Anchor,
 8875        new_position: Option<Point>,
 8876        cx: &mut Context<Self>,
 8877    ) {
 8878        if let Some(nav_history) = self.nav_history.as_mut() {
 8879            let buffer = self.buffer.read(cx).read(cx);
 8880            let cursor_position = cursor_anchor.to_point(&buffer);
 8881            let scroll_state = self.scroll_manager.anchor();
 8882            let scroll_top_row = scroll_state.top_row(&buffer);
 8883            drop(buffer);
 8884
 8885            if let Some(new_position) = new_position {
 8886                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8887                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8888                    return;
 8889                }
 8890            }
 8891
 8892            nav_history.push(
 8893                Some(NavigationData {
 8894                    cursor_anchor,
 8895                    cursor_position,
 8896                    scroll_anchor: scroll_state,
 8897                    scroll_top_row,
 8898                }),
 8899                cx,
 8900            );
 8901        }
 8902    }
 8903
 8904    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8905        let buffer = self.buffer.read(cx).snapshot(cx);
 8906        let mut selection = self.selections.first::<usize>(cx);
 8907        selection.set_head(buffer.len(), SelectionGoal::None);
 8908        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8909            s.select(vec![selection]);
 8910        });
 8911    }
 8912
 8913    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8914        let end = self.buffer.read(cx).read(cx).len();
 8915        self.change_selections(None, window, cx, |s| {
 8916            s.select_ranges(vec![0..end]);
 8917        });
 8918    }
 8919
 8920    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8921        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8922        let mut selections = self.selections.all::<Point>(cx);
 8923        let max_point = display_map.buffer_snapshot.max_point();
 8924        for selection in &mut selections {
 8925            let rows = selection.spanned_rows(true, &display_map);
 8926            selection.start = Point::new(rows.start.0, 0);
 8927            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8928            selection.reversed = false;
 8929        }
 8930        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8931            s.select(selections);
 8932        });
 8933    }
 8934
 8935    pub fn split_selection_into_lines(
 8936        &mut self,
 8937        _: &SplitSelectionIntoLines,
 8938        window: &mut Window,
 8939        cx: &mut Context<Self>,
 8940    ) {
 8941        let mut to_unfold = Vec::new();
 8942        let mut new_selection_ranges = Vec::new();
 8943        {
 8944            let selections = self.selections.all::<Point>(cx);
 8945            let buffer = self.buffer.read(cx).read(cx);
 8946            for selection in selections {
 8947                for row in selection.start.row..selection.end.row {
 8948                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8949                    new_selection_ranges.push(cursor..cursor);
 8950                }
 8951                new_selection_ranges.push(selection.end..selection.end);
 8952                to_unfold.push(selection.start..selection.end);
 8953            }
 8954        }
 8955        self.unfold_ranges(&to_unfold, true, true, cx);
 8956        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8957            s.select_ranges(new_selection_ranges);
 8958        });
 8959    }
 8960
 8961    pub fn add_selection_above(
 8962        &mut self,
 8963        _: &AddSelectionAbove,
 8964        window: &mut Window,
 8965        cx: &mut Context<Self>,
 8966    ) {
 8967        self.add_selection(true, window, cx);
 8968    }
 8969
 8970    pub fn add_selection_below(
 8971        &mut self,
 8972        _: &AddSelectionBelow,
 8973        window: &mut Window,
 8974        cx: &mut Context<Self>,
 8975    ) {
 8976        self.add_selection(false, window, cx);
 8977    }
 8978
 8979    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8980        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8981        let mut selections = self.selections.all::<Point>(cx);
 8982        let text_layout_details = self.text_layout_details(window);
 8983        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8984            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8985            let range = oldest_selection.display_range(&display_map).sorted();
 8986
 8987            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8988            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8989            let positions = start_x.min(end_x)..start_x.max(end_x);
 8990
 8991            selections.clear();
 8992            let mut stack = Vec::new();
 8993            for row in range.start.row().0..=range.end.row().0 {
 8994                if let Some(selection) = self.selections.build_columnar_selection(
 8995                    &display_map,
 8996                    DisplayRow(row),
 8997                    &positions,
 8998                    oldest_selection.reversed,
 8999                    &text_layout_details,
 9000                ) {
 9001                    stack.push(selection.id);
 9002                    selections.push(selection);
 9003                }
 9004            }
 9005
 9006            if above {
 9007                stack.reverse();
 9008            }
 9009
 9010            AddSelectionsState { above, stack }
 9011        });
 9012
 9013        let last_added_selection = *state.stack.last().unwrap();
 9014        let mut new_selections = Vec::new();
 9015        if above == state.above {
 9016            let end_row = if above {
 9017                DisplayRow(0)
 9018            } else {
 9019                display_map.max_point().row()
 9020            };
 9021
 9022            'outer: for selection in selections {
 9023                if selection.id == last_added_selection {
 9024                    let range = selection.display_range(&display_map).sorted();
 9025                    debug_assert_eq!(range.start.row(), range.end.row());
 9026                    let mut row = range.start.row();
 9027                    let positions =
 9028                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9029                            px(start)..px(end)
 9030                        } else {
 9031                            let start_x =
 9032                                display_map.x_for_display_point(range.start, &text_layout_details);
 9033                            let end_x =
 9034                                display_map.x_for_display_point(range.end, &text_layout_details);
 9035                            start_x.min(end_x)..start_x.max(end_x)
 9036                        };
 9037
 9038                    while row != end_row {
 9039                        if above {
 9040                            row.0 -= 1;
 9041                        } else {
 9042                            row.0 += 1;
 9043                        }
 9044
 9045                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9046                            &display_map,
 9047                            row,
 9048                            &positions,
 9049                            selection.reversed,
 9050                            &text_layout_details,
 9051                        ) {
 9052                            state.stack.push(new_selection.id);
 9053                            if above {
 9054                                new_selections.push(new_selection);
 9055                                new_selections.push(selection);
 9056                            } else {
 9057                                new_selections.push(selection);
 9058                                new_selections.push(new_selection);
 9059                            }
 9060
 9061                            continue 'outer;
 9062                        }
 9063                    }
 9064                }
 9065
 9066                new_selections.push(selection);
 9067            }
 9068        } else {
 9069            new_selections = selections;
 9070            new_selections.retain(|s| s.id != last_added_selection);
 9071            state.stack.pop();
 9072        }
 9073
 9074        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9075            s.select(new_selections);
 9076        });
 9077        if state.stack.len() > 1 {
 9078            self.add_selections_state = Some(state);
 9079        }
 9080    }
 9081
 9082    pub fn select_next_match_internal(
 9083        &mut self,
 9084        display_map: &DisplaySnapshot,
 9085        replace_newest: bool,
 9086        autoscroll: Option<Autoscroll>,
 9087        window: &mut Window,
 9088        cx: &mut Context<Self>,
 9089    ) -> Result<()> {
 9090        fn select_next_match_ranges(
 9091            this: &mut Editor,
 9092            range: Range<usize>,
 9093            replace_newest: bool,
 9094            auto_scroll: Option<Autoscroll>,
 9095            window: &mut Window,
 9096            cx: &mut Context<Editor>,
 9097        ) {
 9098            this.unfold_ranges(&[range.clone()], false, true, cx);
 9099            this.change_selections(auto_scroll, window, cx, |s| {
 9100                if replace_newest {
 9101                    s.delete(s.newest_anchor().id);
 9102                }
 9103                s.insert_range(range.clone());
 9104            });
 9105        }
 9106
 9107        let buffer = &display_map.buffer_snapshot;
 9108        let mut selections = self.selections.all::<usize>(cx);
 9109        if let Some(mut select_next_state) = self.select_next_state.take() {
 9110            let query = &select_next_state.query;
 9111            if !select_next_state.done {
 9112                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9113                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9114                let mut next_selected_range = None;
 9115
 9116                let bytes_after_last_selection =
 9117                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9118                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9119                let query_matches = query
 9120                    .stream_find_iter(bytes_after_last_selection)
 9121                    .map(|result| (last_selection.end, result))
 9122                    .chain(
 9123                        query
 9124                            .stream_find_iter(bytes_before_first_selection)
 9125                            .map(|result| (0, result)),
 9126                    );
 9127
 9128                for (start_offset, query_match) in query_matches {
 9129                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9130                    let offset_range =
 9131                        start_offset + query_match.start()..start_offset + query_match.end();
 9132                    let display_range = offset_range.start.to_display_point(display_map)
 9133                        ..offset_range.end.to_display_point(display_map);
 9134
 9135                    if !select_next_state.wordwise
 9136                        || (!movement::is_inside_word(display_map, display_range.start)
 9137                            && !movement::is_inside_word(display_map, display_range.end))
 9138                    {
 9139                        // TODO: This is n^2, because we might check all the selections
 9140                        if !selections
 9141                            .iter()
 9142                            .any(|selection| selection.range().overlaps(&offset_range))
 9143                        {
 9144                            next_selected_range = Some(offset_range);
 9145                            break;
 9146                        }
 9147                    }
 9148                }
 9149
 9150                if let Some(next_selected_range) = next_selected_range {
 9151                    select_next_match_ranges(
 9152                        self,
 9153                        next_selected_range,
 9154                        replace_newest,
 9155                        autoscroll,
 9156                        window,
 9157                        cx,
 9158                    );
 9159                } else {
 9160                    select_next_state.done = true;
 9161                }
 9162            }
 9163
 9164            self.select_next_state = Some(select_next_state);
 9165        } else {
 9166            let mut only_carets = true;
 9167            let mut same_text_selected = true;
 9168            let mut selected_text = None;
 9169
 9170            let mut selections_iter = selections.iter().peekable();
 9171            while let Some(selection) = selections_iter.next() {
 9172                if selection.start != selection.end {
 9173                    only_carets = false;
 9174                }
 9175
 9176                if same_text_selected {
 9177                    if selected_text.is_none() {
 9178                        selected_text =
 9179                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9180                    }
 9181
 9182                    if let Some(next_selection) = selections_iter.peek() {
 9183                        if next_selection.range().len() == selection.range().len() {
 9184                            let next_selected_text = buffer
 9185                                .text_for_range(next_selection.range())
 9186                                .collect::<String>();
 9187                            if Some(next_selected_text) != selected_text {
 9188                                same_text_selected = false;
 9189                                selected_text = None;
 9190                            }
 9191                        } else {
 9192                            same_text_selected = false;
 9193                            selected_text = None;
 9194                        }
 9195                    }
 9196                }
 9197            }
 9198
 9199            if only_carets {
 9200                for selection in &mut selections {
 9201                    let word_range = movement::surrounding_word(
 9202                        display_map,
 9203                        selection.start.to_display_point(display_map),
 9204                    );
 9205                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9206                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9207                    selection.goal = SelectionGoal::None;
 9208                    selection.reversed = false;
 9209                    select_next_match_ranges(
 9210                        self,
 9211                        selection.start..selection.end,
 9212                        replace_newest,
 9213                        autoscroll,
 9214                        window,
 9215                        cx,
 9216                    );
 9217                }
 9218
 9219                if selections.len() == 1 {
 9220                    let selection = selections
 9221                        .last()
 9222                        .expect("ensured that there's only one selection");
 9223                    let query = buffer
 9224                        .text_for_range(selection.start..selection.end)
 9225                        .collect::<String>();
 9226                    let is_empty = query.is_empty();
 9227                    let select_state = SelectNextState {
 9228                        query: AhoCorasick::new(&[query])?,
 9229                        wordwise: true,
 9230                        done: is_empty,
 9231                    };
 9232                    self.select_next_state = Some(select_state);
 9233                } else {
 9234                    self.select_next_state = None;
 9235                }
 9236            } else if let Some(selected_text) = selected_text {
 9237                self.select_next_state = Some(SelectNextState {
 9238                    query: AhoCorasick::new(&[selected_text])?,
 9239                    wordwise: false,
 9240                    done: false,
 9241                });
 9242                self.select_next_match_internal(
 9243                    display_map,
 9244                    replace_newest,
 9245                    autoscroll,
 9246                    window,
 9247                    cx,
 9248                )?;
 9249            }
 9250        }
 9251        Ok(())
 9252    }
 9253
 9254    pub fn select_all_matches(
 9255        &mut self,
 9256        _action: &SelectAllMatches,
 9257        window: &mut Window,
 9258        cx: &mut Context<Self>,
 9259    ) -> Result<()> {
 9260        self.push_to_selection_history();
 9261        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9262
 9263        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9264        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9265            return Ok(());
 9266        };
 9267        if select_next_state.done {
 9268            return Ok(());
 9269        }
 9270
 9271        let mut new_selections = self.selections.all::<usize>(cx);
 9272
 9273        let buffer = &display_map.buffer_snapshot;
 9274        let query_matches = select_next_state
 9275            .query
 9276            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9277
 9278        for query_match in query_matches {
 9279            let query_match = query_match.unwrap(); // can only fail due to I/O
 9280            let offset_range = query_match.start()..query_match.end();
 9281            let display_range = offset_range.start.to_display_point(&display_map)
 9282                ..offset_range.end.to_display_point(&display_map);
 9283
 9284            if !select_next_state.wordwise
 9285                || (!movement::is_inside_word(&display_map, display_range.start)
 9286                    && !movement::is_inside_word(&display_map, display_range.end))
 9287            {
 9288                self.selections.change_with(cx, |selections| {
 9289                    new_selections.push(Selection {
 9290                        id: selections.new_selection_id(),
 9291                        start: offset_range.start,
 9292                        end: offset_range.end,
 9293                        reversed: false,
 9294                        goal: SelectionGoal::None,
 9295                    });
 9296                });
 9297            }
 9298        }
 9299
 9300        new_selections.sort_by_key(|selection| selection.start);
 9301        let mut ix = 0;
 9302        while ix + 1 < new_selections.len() {
 9303            let current_selection = &new_selections[ix];
 9304            let next_selection = &new_selections[ix + 1];
 9305            if current_selection.range().overlaps(&next_selection.range()) {
 9306                if current_selection.id < next_selection.id {
 9307                    new_selections.remove(ix + 1);
 9308                } else {
 9309                    new_selections.remove(ix);
 9310                }
 9311            } else {
 9312                ix += 1;
 9313            }
 9314        }
 9315
 9316        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9317
 9318        for selection in new_selections.iter_mut() {
 9319            selection.reversed = reversed;
 9320        }
 9321
 9322        select_next_state.done = true;
 9323        self.unfold_ranges(
 9324            &new_selections
 9325                .iter()
 9326                .map(|selection| selection.range())
 9327                .collect::<Vec<_>>(),
 9328            false,
 9329            false,
 9330            cx,
 9331        );
 9332        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9333            selections.select(new_selections)
 9334        });
 9335
 9336        Ok(())
 9337    }
 9338
 9339    pub fn select_next(
 9340        &mut self,
 9341        action: &SelectNext,
 9342        window: &mut Window,
 9343        cx: &mut Context<Self>,
 9344    ) -> Result<()> {
 9345        self.push_to_selection_history();
 9346        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9347        self.select_next_match_internal(
 9348            &display_map,
 9349            action.replace_newest,
 9350            Some(Autoscroll::newest()),
 9351            window,
 9352            cx,
 9353        )?;
 9354        Ok(())
 9355    }
 9356
 9357    pub fn select_previous(
 9358        &mut self,
 9359        action: &SelectPrevious,
 9360        window: &mut Window,
 9361        cx: &mut Context<Self>,
 9362    ) -> Result<()> {
 9363        self.push_to_selection_history();
 9364        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9365        let buffer = &display_map.buffer_snapshot;
 9366        let mut selections = self.selections.all::<usize>(cx);
 9367        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9368            let query = &select_prev_state.query;
 9369            if !select_prev_state.done {
 9370                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9371                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9372                let mut next_selected_range = None;
 9373                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9374                let bytes_before_last_selection =
 9375                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9376                let bytes_after_first_selection =
 9377                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9378                let query_matches = query
 9379                    .stream_find_iter(bytes_before_last_selection)
 9380                    .map(|result| (last_selection.start, result))
 9381                    .chain(
 9382                        query
 9383                            .stream_find_iter(bytes_after_first_selection)
 9384                            .map(|result| (buffer.len(), result)),
 9385                    );
 9386                for (end_offset, query_match) in query_matches {
 9387                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9388                    let offset_range =
 9389                        end_offset - query_match.end()..end_offset - query_match.start();
 9390                    let display_range = offset_range.start.to_display_point(&display_map)
 9391                        ..offset_range.end.to_display_point(&display_map);
 9392
 9393                    if !select_prev_state.wordwise
 9394                        || (!movement::is_inside_word(&display_map, display_range.start)
 9395                            && !movement::is_inside_word(&display_map, display_range.end))
 9396                    {
 9397                        next_selected_range = Some(offset_range);
 9398                        break;
 9399                    }
 9400                }
 9401
 9402                if let Some(next_selected_range) = next_selected_range {
 9403                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9404                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9405                        if action.replace_newest {
 9406                            s.delete(s.newest_anchor().id);
 9407                        }
 9408                        s.insert_range(next_selected_range);
 9409                    });
 9410                } else {
 9411                    select_prev_state.done = true;
 9412                }
 9413            }
 9414
 9415            self.select_prev_state = Some(select_prev_state);
 9416        } else {
 9417            let mut only_carets = true;
 9418            let mut same_text_selected = true;
 9419            let mut selected_text = None;
 9420
 9421            let mut selections_iter = selections.iter().peekable();
 9422            while let Some(selection) = selections_iter.next() {
 9423                if selection.start != selection.end {
 9424                    only_carets = false;
 9425                }
 9426
 9427                if same_text_selected {
 9428                    if selected_text.is_none() {
 9429                        selected_text =
 9430                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9431                    }
 9432
 9433                    if let Some(next_selection) = selections_iter.peek() {
 9434                        if next_selection.range().len() == selection.range().len() {
 9435                            let next_selected_text = buffer
 9436                                .text_for_range(next_selection.range())
 9437                                .collect::<String>();
 9438                            if Some(next_selected_text) != selected_text {
 9439                                same_text_selected = false;
 9440                                selected_text = None;
 9441                            }
 9442                        } else {
 9443                            same_text_selected = false;
 9444                            selected_text = None;
 9445                        }
 9446                    }
 9447                }
 9448            }
 9449
 9450            if only_carets {
 9451                for selection in &mut selections {
 9452                    let word_range = movement::surrounding_word(
 9453                        &display_map,
 9454                        selection.start.to_display_point(&display_map),
 9455                    );
 9456                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9457                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9458                    selection.goal = SelectionGoal::None;
 9459                    selection.reversed = false;
 9460                }
 9461                if selections.len() == 1 {
 9462                    let selection = selections
 9463                        .last()
 9464                        .expect("ensured that there's only one selection");
 9465                    let query = buffer
 9466                        .text_for_range(selection.start..selection.end)
 9467                        .collect::<String>();
 9468                    let is_empty = query.is_empty();
 9469                    let select_state = SelectNextState {
 9470                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9471                        wordwise: true,
 9472                        done: is_empty,
 9473                    };
 9474                    self.select_prev_state = Some(select_state);
 9475                } else {
 9476                    self.select_prev_state = None;
 9477                }
 9478
 9479                self.unfold_ranges(
 9480                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9481                    false,
 9482                    true,
 9483                    cx,
 9484                );
 9485                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9486                    s.select(selections);
 9487                });
 9488            } else if let Some(selected_text) = selected_text {
 9489                self.select_prev_state = Some(SelectNextState {
 9490                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9491                    wordwise: false,
 9492                    done: false,
 9493                });
 9494                self.select_previous(action, window, cx)?;
 9495            }
 9496        }
 9497        Ok(())
 9498    }
 9499
 9500    pub fn toggle_comments(
 9501        &mut self,
 9502        action: &ToggleComments,
 9503        window: &mut Window,
 9504        cx: &mut Context<Self>,
 9505    ) {
 9506        if self.read_only(cx) {
 9507            return;
 9508        }
 9509        let text_layout_details = &self.text_layout_details(window);
 9510        self.transact(window, cx, |this, window, cx| {
 9511            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9512            let mut edits = Vec::new();
 9513            let mut selection_edit_ranges = Vec::new();
 9514            let mut last_toggled_row = None;
 9515            let snapshot = this.buffer.read(cx).read(cx);
 9516            let empty_str: Arc<str> = Arc::default();
 9517            let mut suffixes_inserted = Vec::new();
 9518            let ignore_indent = action.ignore_indent;
 9519
 9520            fn comment_prefix_range(
 9521                snapshot: &MultiBufferSnapshot,
 9522                row: MultiBufferRow,
 9523                comment_prefix: &str,
 9524                comment_prefix_whitespace: &str,
 9525                ignore_indent: bool,
 9526            ) -> Range<Point> {
 9527                let indent_size = if ignore_indent {
 9528                    0
 9529                } else {
 9530                    snapshot.indent_size_for_line(row).len
 9531                };
 9532
 9533                let start = Point::new(row.0, indent_size);
 9534
 9535                let mut line_bytes = snapshot
 9536                    .bytes_in_range(start..snapshot.max_point())
 9537                    .flatten()
 9538                    .copied();
 9539
 9540                // If this line currently begins with the line comment prefix, then record
 9541                // the range containing the prefix.
 9542                if line_bytes
 9543                    .by_ref()
 9544                    .take(comment_prefix.len())
 9545                    .eq(comment_prefix.bytes())
 9546                {
 9547                    // Include any whitespace that matches the comment prefix.
 9548                    let matching_whitespace_len = line_bytes
 9549                        .zip(comment_prefix_whitespace.bytes())
 9550                        .take_while(|(a, b)| a == b)
 9551                        .count() as u32;
 9552                    let end = Point::new(
 9553                        start.row,
 9554                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9555                    );
 9556                    start..end
 9557                } else {
 9558                    start..start
 9559                }
 9560            }
 9561
 9562            fn comment_suffix_range(
 9563                snapshot: &MultiBufferSnapshot,
 9564                row: MultiBufferRow,
 9565                comment_suffix: &str,
 9566                comment_suffix_has_leading_space: bool,
 9567            ) -> Range<Point> {
 9568                let end = Point::new(row.0, snapshot.line_len(row));
 9569                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9570
 9571                let mut line_end_bytes = snapshot
 9572                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9573                    .flatten()
 9574                    .copied();
 9575
 9576                let leading_space_len = if suffix_start_column > 0
 9577                    && line_end_bytes.next() == Some(b' ')
 9578                    && comment_suffix_has_leading_space
 9579                {
 9580                    1
 9581                } else {
 9582                    0
 9583                };
 9584
 9585                // If this line currently begins with the line comment prefix, then record
 9586                // the range containing the prefix.
 9587                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9588                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9589                    start..end
 9590                } else {
 9591                    end..end
 9592                }
 9593            }
 9594
 9595            // TODO: Handle selections that cross excerpts
 9596            for selection in &mut selections {
 9597                let start_column = snapshot
 9598                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9599                    .len;
 9600                let language = if let Some(language) =
 9601                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9602                {
 9603                    language
 9604                } else {
 9605                    continue;
 9606                };
 9607
 9608                selection_edit_ranges.clear();
 9609
 9610                // If multiple selections contain a given row, avoid processing that
 9611                // row more than once.
 9612                let mut start_row = MultiBufferRow(selection.start.row);
 9613                if last_toggled_row == Some(start_row) {
 9614                    start_row = start_row.next_row();
 9615                }
 9616                let end_row =
 9617                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9618                        MultiBufferRow(selection.end.row - 1)
 9619                    } else {
 9620                        MultiBufferRow(selection.end.row)
 9621                    };
 9622                last_toggled_row = Some(end_row);
 9623
 9624                if start_row > end_row {
 9625                    continue;
 9626                }
 9627
 9628                // If the language has line comments, toggle those.
 9629                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9630
 9631                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9632                if ignore_indent {
 9633                    full_comment_prefixes = full_comment_prefixes
 9634                        .into_iter()
 9635                        .map(|s| Arc::from(s.trim_end()))
 9636                        .collect();
 9637                }
 9638
 9639                if !full_comment_prefixes.is_empty() {
 9640                    let first_prefix = full_comment_prefixes
 9641                        .first()
 9642                        .expect("prefixes is non-empty");
 9643                    let prefix_trimmed_lengths = full_comment_prefixes
 9644                        .iter()
 9645                        .map(|p| p.trim_end_matches(' ').len())
 9646                        .collect::<SmallVec<[usize; 4]>>();
 9647
 9648                    let mut all_selection_lines_are_comments = true;
 9649
 9650                    for row in start_row.0..=end_row.0 {
 9651                        let row = MultiBufferRow(row);
 9652                        if start_row < end_row && snapshot.is_line_blank(row) {
 9653                            continue;
 9654                        }
 9655
 9656                        let prefix_range = full_comment_prefixes
 9657                            .iter()
 9658                            .zip(prefix_trimmed_lengths.iter().copied())
 9659                            .map(|(prefix, trimmed_prefix_len)| {
 9660                                comment_prefix_range(
 9661                                    snapshot.deref(),
 9662                                    row,
 9663                                    &prefix[..trimmed_prefix_len],
 9664                                    &prefix[trimmed_prefix_len..],
 9665                                    ignore_indent,
 9666                                )
 9667                            })
 9668                            .max_by_key(|range| range.end.column - range.start.column)
 9669                            .expect("prefixes is non-empty");
 9670
 9671                        if prefix_range.is_empty() {
 9672                            all_selection_lines_are_comments = false;
 9673                        }
 9674
 9675                        selection_edit_ranges.push(prefix_range);
 9676                    }
 9677
 9678                    if all_selection_lines_are_comments {
 9679                        edits.extend(
 9680                            selection_edit_ranges
 9681                                .iter()
 9682                                .cloned()
 9683                                .map(|range| (range, empty_str.clone())),
 9684                        );
 9685                    } else {
 9686                        let min_column = selection_edit_ranges
 9687                            .iter()
 9688                            .map(|range| range.start.column)
 9689                            .min()
 9690                            .unwrap_or(0);
 9691                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9692                            let position = Point::new(range.start.row, min_column);
 9693                            (position..position, first_prefix.clone())
 9694                        }));
 9695                    }
 9696                } else if let Some((full_comment_prefix, comment_suffix)) =
 9697                    language.block_comment_delimiters()
 9698                {
 9699                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9700                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9701                    let prefix_range = comment_prefix_range(
 9702                        snapshot.deref(),
 9703                        start_row,
 9704                        comment_prefix,
 9705                        comment_prefix_whitespace,
 9706                        ignore_indent,
 9707                    );
 9708                    let suffix_range = comment_suffix_range(
 9709                        snapshot.deref(),
 9710                        end_row,
 9711                        comment_suffix.trim_start_matches(' '),
 9712                        comment_suffix.starts_with(' '),
 9713                    );
 9714
 9715                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9716                        edits.push((
 9717                            prefix_range.start..prefix_range.start,
 9718                            full_comment_prefix.clone(),
 9719                        ));
 9720                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9721                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9722                    } else {
 9723                        edits.push((prefix_range, empty_str.clone()));
 9724                        edits.push((suffix_range, empty_str.clone()));
 9725                    }
 9726                } else {
 9727                    continue;
 9728                }
 9729            }
 9730
 9731            drop(snapshot);
 9732            this.buffer.update(cx, |buffer, cx| {
 9733                buffer.edit(edits, None, cx);
 9734            });
 9735
 9736            // Adjust selections so that they end before any comment suffixes that
 9737            // were inserted.
 9738            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9739            let mut selections = this.selections.all::<Point>(cx);
 9740            let snapshot = this.buffer.read(cx).read(cx);
 9741            for selection in &mut selections {
 9742                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9743                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9744                        Ordering::Less => {
 9745                            suffixes_inserted.next();
 9746                            continue;
 9747                        }
 9748                        Ordering::Greater => break,
 9749                        Ordering::Equal => {
 9750                            if selection.end.column == snapshot.line_len(row) {
 9751                                if selection.is_empty() {
 9752                                    selection.start.column -= suffix_len as u32;
 9753                                }
 9754                                selection.end.column -= suffix_len as u32;
 9755                            }
 9756                            break;
 9757                        }
 9758                    }
 9759                }
 9760            }
 9761
 9762            drop(snapshot);
 9763            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9764                s.select(selections)
 9765            });
 9766
 9767            let selections = this.selections.all::<Point>(cx);
 9768            let selections_on_single_row = selections.windows(2).all(|selections| {
 9769                selections[0].start.row == selections[1].start.row
 9770                    && selections[0].end.row == selections[1].end.row
 9771                    && selections[0].start.row == selections[0].end.row
 9772            });
 9773            let selections_selecting = selections
 9774                .iter()
 9775                .any(|selection| selection.start != selection.end);
 9776            let advance_downwards = action.advance_downwards
 9777                && selections_on_single_row
 9778                && !selections_selecting
 9779                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9780
 9781            if advance_downwards {
 9782                let snapshot = this.buffer.read(cx).snapshot(cx);
 9783
 9784                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9785                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9786                        let mut point = display_point.to_point(display_snapshot);
 9787                        point.row += 1;
 9788                        point = snapshot.clip_point(point, Bias::Left);
 9789                        let display_point = point.to_display_point(display_snapshot);
 9790                        let goal = SelectionGoal::HorizontalPosition(
 9791                            display_snapshot
 9792                                .x_for_display_point(display_point, text_layout_details)
 9793                                .into(),
 9794                        );
 9795                        (display_point, goal)
 9796                    })
 9797                });
 9798            }
 9799        });
 9800    }
 9801
 9802    pub fn select_enclosing_symbol(
 9803        &mut self,
 9804        _: &SelectEnclosingSymbol,
 9805        window: &mut Window,
 9806        cx: &mut Context<Self>,
 9807    ) {
 9808        let buffer = self.buffer.read(cx).snapshot(cx);
 9809        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9810
 9811        fn update_selection(
 9812            selection: &Selection<usize>,
 9813            buffer_snap: &MultiBufferSnapshot,
 9814        ) -> Option<Selection<usize>> {
 9815            let cursor = selection.head();
 9816            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9817            for symbol in symbols.iter().rev() {
 9818                let start = symbol.range.start.to_offset(buffer_snap);
 9819                let end = symbol.range.end.to_offset(buffer_snap);
 9820                let new_range = start..end;
 9821                if start < selection.start || end > selection.end {
 9822                    return Some(Selection {
 9823                        id: selection.id,
 9824                        start: new_range.start,
 9825                        end: new_range.end,
 9826                        goal: SelectionGoal::None,
 9827                        reversed: selection.reversed,
 9828                    });
 9829                }
 9830            }
 9831            None
 9832        }
 9833
 9834        let mut selected_larger_symbol = false;
 9835        let new_selections = old_selections
 9836            .iter()
 9837            .map(|selection| match update_selection(selection, &buffer) {
 9838                Some(new_selection) => {
 9839                    if new_selection.range() != selection.range() {
 9840                        selected_larger_symbol = true;
 9841                    }
 9842                    new_selection
 9843                }
 9844                None => selection.clone(),
 9845            })
 9846            .collect::<Vec<_>>();
 9847
 9848        if selected_larger_symbol {
 9849            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9850                s.select(new_selections);
 9851            });
 9852        }
 9853    }
 9854
 9855    pub fn select_larger_syntax_node(
 9856        &mut self,
 9857        _: &SelectLargerSyntaxNode,
 9858        window: &mut Window,
 9859        cx: &mut Context<Self>,
 9860    ) {
 9861        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9862        let buffer = self.buffer.read(cx).snapshot(cx);
 9863        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9864
 9865        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9866        let mut selected_larger_node = false;
 9867        let new_selections = old_selections
 9868            .iter()
 9869            .map(|selection| {
 9870                let old_range = selection.start..selection.end;
 9871                let mut new_range = old_range.clone();
 9872                let mut new_node = None;
 9873                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9874                {
 9875                    new_node = Some(node);
 9876                    new_range = containing_range;
 9877                    if !display_map.intersects_fold(new_range.start)
 9878                        && !display_map.intersects_fold(new_range.end)
 9879                    {
 9880                        break;
 9881                    }
 9882                }
 9883
 9884                if let Some(node) = new_node {
 9885                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9886                    // nodes. Parent and grandparent are also logged because this operation will not
 9887                    // visit nodes that have the same range as their parent.
 9888                    log::info!("Node: {node:?}");
 9889                    let parent = node.parent();
 9890                    log::info!("Parent: {parent:?}");
 9891                    let grandparent = parent.and_then(|x| x.parent());
 9892                    log::info!("Grandparent: {grandparent:?}");
 9893                }
 9894
 9895                selected_larger_node |= new_range != old_range;
 9896                Selection {
 9897                    id: selection.id,
 9898                    start: new_range.start,
 9899                    end: new_range.end,
 9900                    goal: SelectionGoal::None,
 9901                    reversed: selection.reversed,
 9902                }
 9903            })
 9904            .collect::<Vec<_>>();
 9905
 9906        if selected_larger_node {
 9907            stack.push(old_selections);
 9908            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9909                s.select(new_selections);
 9910            });
 9911        }
 9912        self.select_larger_syntax_node_stack = stack;
 9913    }
 9914
 9915    pub fn select_smaller_syntax_node(
 9916        &mut self,
 9917        _: &SelectSmallerSyntaxNode,
 9918        window: &mut Window,
 9919        cx: &mut Context<Self>,
 9920    ) {
 9921        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9922        if let Some(selections) = stack.pop() {
 9923            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9924                s.select(selections.to_vec());
 9925            });
 9926        }
 9927        self.select_larger_syntax_node_stack = stack;
 9928    }
 9929
 9930    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9931        if !EditorSettings::get_global(cx).gutter.runnables {
 9932            self.clear_tasks();
 9933            return Task::ready(());
 9934        }
 9935        let project = self.project.as_ref().map(Entity::downgrade);
 9936        cx.spawn_in(window, |this, mut cx| async move {
 9937            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9938            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9939                return;
 9940            };
 9941            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9942                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9943            }) else {
 9944                return;
 9945            };
 9946
 9947            let hide_runnables = project
 9948                .update(&mut cx, |project, cx| {
 9949                    // Do not display any test indicators in non-dev server remote projects.
 9950                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9951                })
 9952                .unwrap_or(true);
 9953            if hide_runnables {
 9954                return;
 9955            }
 9956            let new_rows =
 9957                cx.background_executor()
 9958                    .spawn({
 9959                        let snapshot = display_snapshot.clone();
 9960                        async move {
 9961                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9962                        }
 9963                    })
 9964                    .await;
 9965
 9966            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9967            this.update(&mut cx, |this, _| {
 9968                this.clear_tasks();
 9969                for (key, value) in rows {
 9970                    this.insert_tasks(key, value);
 9971                }
 9972            })
 9973            .ok();
 9974        })
 9975    }
 9976    fn fetch_runnable_ranges(
 9977        snapshot: &DisplaySnapshot,
 9978        range: Range<Anchor>,
 9979    ) -> Vec<language::RunnableRange> {
 9980        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9981    }
 9982
 9983    fn runnable_rows(
 9984        project: Entity<Project>,
 9985        snapshot: DisplaySnapshot,
 9986        runnable_ranges: Vec<RunnableRange>,
 9987        mut cx: AsyncWindowContext,
 9988    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9989        runnable_ranges
 9990            .into_iter()
 9991            .filter_map(|mut runnable| {
 9992                let tasks = cx
 9993                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9994                    .ok()?;
 9995                if tasks.is_empty() {
 9996                    return None;
 9997                }
 9998
 9999                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10000
10001                let row = snapshot
10002                    .buffer_snapshot
10003                    .buffer_line_for_row(MultiBufferRow(point.row))?
10004                    .1
10005                    .start
10006                    .row;
10007
10008                let context_range =
10009                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10010                Some((
10011                    (runnable.buffer_id, row),
10012                    RunnableTasks {
10013                        templates: tasks,
10014                        offset: MultiBufferOffset(runnable.run_range.start),
10015                        context_range,
10016                        column: point.column,
10017                        extra_variables: runnable.extra_captures,
10018                    },
10019                ))
10020            })
10021            .collect()
10022    }
10023
10024    fn templates_with_tags(
10025        project: &Entity<Project>,
10026        runnable: &mut Runnable,
10027        cx: &mut App,
10028    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10029        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10030            let (worktree_id, file) = project
10031                .buffer_for_id(runnable.buffer, cx)
10032                .and_then(|buffer| buffer.read(cx).file())
10033                .map(|file| (file.worktree_id(cx), file.clone()))
10034                .unzip();
10035
10036            (
10037                project.task_store().read(cx).task_inventory().cloned(),
10038                worktree_id,
10039                file,
10040            )
10041        });
10042
10043        let tags = mem::take(&mut runnable.tags);
10044        let mut tags: Vec<_> = tags
10045            .into_iter()
10046            .flat_map(|tag| {
10047                let tag = tag.0.clone();
10048                inventory
10049                    .as_ref()
10050                    .into_iter()
10051                    .flat_map(|inventory| {
10052                        inventory.read(cx).list_tasks(
10053                            file.clone(),
10054                            Some(runnable.language.clone()),
10055                            worktree_id,
10056                            cx,
10057                        )
10058                    })
10059                    .filter(move |(_, template)| {
10060                        template.tags.iter().any(|source_tag| source_tag == &tag)
10061                    })
10062            })
10063            .sorted_by_key(|(kind, _)| kind.to_owned())
10064            .collect();
10065        if let Some((leading_tag_source, _)) = tags.first() {
10066            // Strongest source wins; if we have worktree tag binding, prefer that to
10067            // global and language bindings;
10068            // if we have a global binding, prefer that to language binding.
10069            let first_mismatch = tags
10070                .iter()
10071                .position(|(tag_source, _)| tag_source != leading_tag_source);
10072            if let Some(index) = first_mismatch {
10073                tags.truncate(index);
10074            }
10075        }
10076
10077        tags
10078    }
10079
10080    pub fn move_to_enclosing_bracket(
10081        &mut self,
10082        _: &MoveToEnclosingBracket,
10083        window: &mut Window,
10084        cx: &mut Context<Self>,
10085    ) {
10086        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10087            s.move_offsets_with(|snapshot, selection| {
10088                let Some(enclosing_bracket_ranges) =
10089                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10090                else {
10091                    return;
10092                };
10093
10094                let mut best_length = usize::MAX;
10095                let mut best_inside = false;
10096                let mut best_in_bracket_range = false;
10097                let mut best_destination = None;
10098                for (open, close) in enclosing_bracket_ranges {
10099                    let close = close.to_inclusive();
10100                    let length = close.end() - open.start;
10101                    let inside = selection.start >= open.end && selection.end <= *close.start();
10102                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10103                        || close.contains(&selection.head());
10104
10105                    // If best is next to a bracket and current isn't, skip
10106                    if !in_bracket_range && best_in_bracket_range {
10107                        continue;
10108                    }
10109
10110                    // Prefer smaller lengths unless best is inside and current isn't
10111                    if length > best_length && (best_inside || !inside) {
10112                        continue;
10113                    }
10114
10115                    best_length = length;
10116                    best_inside = inside;
10117                    best_in_bracket_range = in_bracket_range;
10118                    best_destination = Some(
10119                        if close.contains(&selection.start) && close.contains(&selection.end) {
10120                            if inside {
10121                                open.end
10122                            } else {
10123                                open.start
10124                            }
10125                        } else if inside {
10126                            *close.start()
10127                        } else {
10128                            *close.end()
10129                        },
10130                    );
10131                }
10132
10133                if let Some(destination) = best_destination {
10134                    selection.collapse_to(destination, SelectionGoal::None);
10135                }
10136            })
10137        });
10138    }
10139
10140    pub fn undo_selection(
10141        &mut self,
10142        _: &UndoSelection,
10143        window: &mut Window,
10144        cx: &mut Context<Self>,
10145    ) {
10146        self.end_selection(window, cx);
10147        self.selection_history.mode = SelectionHistoryMode::Undoing;
10148        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10149            self.change_selections(None, window, cx, |s| {
10150                s.select_anchors(entry.selections.to_vec())
10151            });
10152            self.select_next_state = entry.select_next_state;
10153            self.select_prev_state = entry.select_prev_state;
10154            self.add_selections_state = entry.add_selections_state;
10155            self.request_autoscroll(Autoscroll::newest(), cx);
10156        }
10157        self.selection_history.mode = SelectionHistoryMode::Normal;
10158    }
10159
10160    pub fn redo_selection(
10161        &mut self,
10162        _: &RedoSelection,
10163        window: &mut Window,
10164        cx: &mut Context<Self>,
10165    ) {
10166        self.end_selection(window, cx);
10167        self.selection_history.mode = SelectionHistoryMode::Redoing;
10168        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10169            self.change_selections(None, window, cx, |s| {
10170                s.select_anchors(entry.selections.to_vec())
10171            });
10172            self.select_next_state = entry.select_next_state;
10173            self.select_prev_state = entry.select_prev_state;
10174            self.add_selections_state = entry.add_selections_state;
10175            self.request_autoscroll(Autoscroll::newest(), cx);
10176        }
10177        self.selection_history.mode = SelectionHistoryMode::Normal;
10178    }
10179
10180    pub fn expand_excerpts(
10181        &mut self,
10182        action: &ExpandExcerpts,
10183        _: &mut Window,
10184        cx: &mut Context<Self>,
10185    ) {
10186        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10187    }
10188
10189    pub fn expand_excerpts_down(
10190        &mut self,
10191        action: &ExpandExcerptsDown,
10192        _: &mut Window,
10193        cx: &mut Context<Self>,
10194    ) {
10195        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10196    }
10197
10198    pub fn expand_excerpts_up(
10199        &mut self,
10200        action: &ExpandExcerptsUp,
10201        _: &mut Window,
10202        cx: &mut Context<Self>,
10203    ) {
10204        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10205    }
10206
10207    pub fn expand_excerpts_for_direction(
10208        &mut self,
10209        lines: u32,
10210        direction: ExpandExcerptDirection,
10211
10212        cx: &mut Context<Self>,
10213    ) {
10214        let selections = self.selections.disjoint_anchors();
10215
10216        let lines = if lines == 0 {
10217            EditorSettings::get_global(cx).expand_excerpt_lines
10218        } else {
10219            lines
10220        };
10221
10222        self.buffer.update(cx, |buffer, cx| {
10223            let snapshot = buffer.snapshot(cx);
10224            let mut excerpt_ids = selections
10225                .iter()
10226                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10227                .collect::<Vec<_>>();
10228            excerpt_ids.sort();
10229            excerpt_ids.dedup();
10230            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10231        })
10232    }
10233
10234    pub fn expand_excerpt(
10235        &mut self,
10236        excerpt: ExcerptId,
10237        direction: ExpandExcerptDirection,
10238        cx: &mut Context<Self>,
10239    ) {
10240        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10241        self.buffer.update(cx, |buffer, cx| {
10242            buffer.expand_excerpts([excerpt], lines, direction, cx)
10243        })
10244    }
10245
10246    pub fn go_to_singleton_buffer_point(
10247        &mut self,
10248        point: Point,
10249        window: &mut Window,
10250        cx: &mut Context<Self>,
10251    ) {
10252        self.go_to_singleton_buffer_range(point..point, window, cx);
10253    }
10254
10255    pub fn go_to_singleton_buffer_range(
10256        &mut self,
10257        range: Range<Point>,
10258        window: &mut Window,
10259        cx: &mut Context<Self>,
10260    ) {
10261        let multibuffer = self.buffer().read(cx);
10262        let Some(buffer) = multibuffer.as_singleton() else {
10263            return;
10264        };
10265        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10266            return;
10267        };
10268        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10269            return;
10270        };
10271        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10272            s.select_anchor_ranges([start..end])
10273        });
10274    }
10275
10276    fn go_to_diagnostic(
10277        &mut self,
10278        _: &GoToDiagnostic,
10279        window: &mut Window,
10280        cx: &mut Context<Self>,
10281    ) {
10282        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10283    }
10284
10285    fn go_to_prev_diagnostic(
10286        &mut self,
10287        _: &GoToPrevDiagnostic,
10288        window: &mut Window,
10289        cx: &mut Context<Self>,
10290    ) {
10291        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10292    }
10293
10294    pub fn go_to_diagnostic_impl(
10295        &mut self,
10296        direction: Direction,
10297        window: &mut Window,
10298        cx: &mut Context<Self>,
10299    ) {
10300        let buffer = self.buffer.read(cx).snapshot(cx);
10301        let selection = self.selections.newest::<usize>(cx);
10302
10303        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10304        if direction == Direction::Next {
10305            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10306                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10307                    return;
10308                };
10309                self.activate_diagnostics(
10310                    buffer_id,
10311                    popover.local_diagnostic.diagnostic.group_id,
10312                    window,
10313                    cx,
10314                );
10315                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10316                    let primary_range_start = active_diagnostics.primary_range.start;
10317                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10318                        let mut new_selection = s.newest_anchor().clone();
10319                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10320                        s.select_anchors(vec![new_selection.clone()]);
10321                    });
10322                    self.refresh_inline_completion(false, true, window, cx);
10323                }
10324                return;
10325            }
10326        }
10327
10328        let active_group_id = self
10329            .active_diagnostics
10330            .as_ref()
10331            .map(|active_group| active_group.group_id);
10332        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10333            active_diagnostics
10334                .primary_range
10335                .to_offset(&buffer)
10336                .to_inclusive()
10337        });
10338        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10339            if active_primary_range.contains(&selection.head()) {
10340                *active_primary_range.start()
10341            } else {
10342                selection.head()
10343            }
10344        } else {
10345            selection.head()
10346        };
10347
10348        let snapshot = self.snapshot(window, cx);
10349        let primary_diagnostics_before = buffer
10350            .diagnostics_in_range::<usize>(0..search_start)
10351            .filter(|entry| entry.diagnostic.is_primary)
10352            .filter(|entry| entry.range.start != entry.range.end)
10353            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10354            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10355            .collect::<Vec<_>>();
10356        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10357            primary_diagnostics_before
10358                .iter()
10359                .position(|entry| entry.diagnostic.group_id == active_group_id)
10360        });
10361
10362        let primary_diagnostics_after = buffer
10363            .diagnostics_in_range::<usize>(search_start..buffer.len())
10364            .filter(|entry| entry.diagnostic.is_primary)
10365            .filter(|entry| entry.range.start != entry.range.end)
10366            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10367            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10368            .collect::<Vec<_>>();
10369        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10370            primary_diagnostics_after
10371                .iter()
10372                .enumerate()
10373                .rev()
10374                .find_map(|(i, entry)| {
10375                    if entry.diagnostic.group_id == active_group_id {
10376                        Some(i)
10377                    } else {
10378                        None
10379                    }
10380                })
10381        });
10382
10383        let next_primary_diagnostic = match direction {
10384            Direction::Prev => primary_diagnostics_before
10385                .iter()
10386                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10387                .rev()
10388                .next(),
10389            Direction::Next => primary_diagnostics_after
10390                .iter()
10391                .skip(
10392                    last_same_group_diagnostic_after
10393                        .map(|index| index + 1)
10394                        .unwrap_or(0),
10395                )
10396                .next(),
10397        };
10398
10399        // Cycle around to the start of the buffer, potentially moving back to the start of
10400        // the currently active diagnostic.
10401        let cycle_around = || match direction {
10402            Direction::Prev => primary_diagnostics_after
10403                .iter()
10404                .rev()
10405                .chain(primary_diagnostics_before.iter().rev())
10406                .next(),
10407            Direction::Next => primary_diagnostics_before
10408                .iter()
10409                .chain(primary_diagnostics_after.iter())
10410                .next(),
10411        };
10412
10413        if let Some((primary_range, group_id)) = next_primary_diagnostic
10414            .or_else(cycle_around)
10415            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10416        {
10417            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10418                return;
10419            };
10420            self.activate_diagnostics(buffer_id, group_id, window, cx);
10421            if self.active_diagnostics.is_some() {
10422                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10423                    s.select(vec![Selection {
10424                        id: selection.id,
10425                        start: primary_range.start,
10426                        end: primary_range.start,
10427                        reversed: false,
10428                        goal: SelectionGoal::None,
10429                    }]);
10430                });
10431                self.refresh_inline_completion(false, true, window, cx);
10432            }
10433        }
10434    }
10435
10436    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10437        let snapshot = self.snapshot(window, cx);
10438        let selection = self.selections.newest::<Point>(cx);
10439        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10440    }
10441
10442    fn go_to_hunk_after_position(
10443        &mut self,
10444        snapshot: &EditorSnapshot,
10445        position: Point,
10446        window: &mut Window,
10447        cx: &mut Context<Editor>,
10448    ) -> Option<MultiBufferDiffHunk> {
10449        let mut hunk = snapshot
10450            .buffer_snapshot
10451            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10452            .find(|hunk| hunk.row_range.start.0 > position.row);
10453        if hunk.is_none() {
10454            hunk = snapshot
10455                .buffer_snapshot
10456                .diff_hunks_in_range(Point::zero()..position)
10457                .find(|hunk| hunk.row_range.end.0 < position.row)
10458        }
10459        if let Some(hunk) = &hunk {
10460            let destination = Point::new(hunk.row_range.start.0, 0);
10461            self.unfold_ranges(&[destination..destination], false, false, cx);
10462            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10463                s.select_ranges(vec![destination..destination]);
10464            });
10465        }
10466
10467        hunk
10468    }
10469
10470    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10471        let snapshot = self.snapshot(window, cx);
10472        let selection = self.selections.newest::<Point>(cx);
10473        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10474    }
10475
10476    fn go_to_hunk_before_position(
10477        &mut self,
10478        snapshot: &EditorSnapshot,
10479        position: Point,
10480        window: &mut Window,
10481        cx: &mut Context<Editor>,
10482    ) -> Option<MultiBufferDiffHunk> {
10483        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10484        if hunk.is_none() {
10485            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10486        }
10487        if let Some(hunk) = &hunk {
10488            let destination = Point::new(hunk.row_range.start.0, 0);
10489            self.unfold_ranges(&[destination..destination], false, false, cx);
10490            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10491                s.select_ranges(vec![destination..destination]);
10492            });
10493        }
10494
10495        hunk
10496    }
10497
10498    pub fn go_to_definition(
10499        &mut self,
10500        _: &GoToDefinition,
10501        window: &mut Window,
10502        cx: &mut Context<Self>,
10503    ) -> Task<Result<Navigated>> {
10504        let definition =
10505            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10506        cx.spawn_in(window, |editor, mut cx| async move {
10507            if definition.await? == Navigated::Yes {
10508                return Ok(Navigated::Yes);
10509            }
10510            match editor.update_in(&mut cx, |editor, window, cx| {
10511                editor.find_all_references(&FindAllReferences, window, cx)
10512            })? {
10513                Some(references) => references.await,
10514                None => Ok(Navigated::No),
10515            }
10516        })
10517    }
10518
10519    pub fn go_to_declaration(
10520        &mut self,
10521        _: &GoToDeclaration,
10522        window: &mut Window,
10523        cx: &mut Context<Self>,
10524    ) -> Task<Result<Navigated>> {
10525        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10526    }
10527
10528    pub fn go_to_declaration_split(
10529        &mut self,
10530        _: &GoToDeclaration,
10531        window: &mut Window,
10532        cx: &mut Context<Self>,
10533    ) -> Task<Result<Navigated>> {
10534        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10535    }
10536
10537    pub fn go_to_implementation(
10538        &mut self,
10539        _: &GoToImplementation,
10540        window: &mut Window,
10541        cx: &mut Context<Self>,
10542    ) -> Task<Result<Navigated>> {
10543        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10544    }
10545
10546    pub fn go_to_implementation_split(
10547        &mut self,
10548        _: &GoToImplementationSplit,
10549        window: &mut Window,
10550        cx: &mut Context<Self>,
10551    ) -> Task<Result<Navigated>> {
10552        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10553    }
10554
10555    pub fn go_to_type_definition(
10556        &mut self,
10557        _: &GoToTypeDefinition,
10558        window: &mut Window,
10559        cx: &mut Context<Self>,
10560    ) -> Task<Result<Navigated>> {
10561        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10562    }
10563
10564    pub fn go_to_definition_split(
10565        &mut self,
10566        _: &GoToDefinitionSplit,
10567        window: &mut Window,
10568        cx: &mut Context<Self>,
10569    ) -> Task<Result<Navigated>> {
10570        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10571    }
10572
10573    pub fn go_to_type_definition_split(
10574        &mut self,
10575        _: &GoToTypeDefinitionSplit,
10576        window: &mut Window,
10577        cx: &mut Context<Self>,
10578    ) -> Task<Result<Navigated>> {
10579        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10580    }
10581
10582    fn go_to_definition_of_kind(
10583        &mut self,
10584        kind: GotoDefinitionKind,
10585        split: bool,
10586        window: &mut Window,
10587        cx: &mut Context<Self>,
10588    ) -> Task<Result<Navigated>> {
10589        let Some(provider) = self.semantics_provider.clone() else {
10590            return Task::ready(Ok(Navigated::No));
10591        };
10592        let head = self.selections.newest::<usize>(cx).head();
10593        let buffer = self.buffer.read(cx);
10594        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10595            text_anchor
10596        } else {
10597            return Task::ready(Ok(Navigated::No));
10598        };
10599
10600        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10601            return Task::ready(Ok(Navigated::No));
10602        };
10603
10604        cx.spawn_in(window, |editor, mut cx| async move {
10605            let definitions = definitions.await?;
10606            let navigated = editor
10607                .update_in(&mut cx, |editor, window, cx| {
10608                    editor.navigate_to_hover_links(
10609                        Some(kind),
10610                        definitions
10611                            .into_iter()
10612                            .filter(|location| {
10613                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10614                            })
10615                            .map(HoverLink::Text)
10616                            .collect::<Vec<_>>(),
10617                        split,
10618                        window,
10619                        cx,
10620                    )
10621                })?
10622                .await?;
10623            anyhow::Ok(navigated)
10624        })
10625    }
10626
10627    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10628        let selection = self.selections.newest_anchor();
10629        let head = selection.head();
10630        let tail = selection.tail();
10631
10632        let Some((buffer, start_position)) =
10633            self.buffer.read(cx).text_anchor_for_position(head, cx)
10634        else {
10635            return;
10636        };
10637
10638        let end_position = if head != tail {
10639            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10640                return;
10641            };
10642            Some(pos)
10643        } else {
10644            None
10645        };
10646
10647        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10648            let url = if let Some(end_pos) = end_position {
10649                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10650            } else {
10651                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10652            };
10653
10654            if let Some(url) = url {
10655                editor.update(&mut cx, |_, cx| {
10656                    cx.open_url(&url);
10657                })
10658            } else {
10659                Ok(())
10660            }
10661        });
10662
10663        url_finder.detach();
10664    }
10665
10666    pub fn open_selected_filename(
10667        &mut self,
10668        _: &OpenSelectedFilename,
10669        window: &mut Window,
10670        cx: &mut Context<Self>,
10671    ) {
10672        let Some(workspace) = self.workspace() else {
10673            return;
10674        };
10675
10676        let position = self.selections.newest_anchor().head();
10677
10678        let Some((buffer, buffer_position)) =
10679            self.buffer.read(cx).text_anchor_for_position(position, cx)
10680        else {
10681            return;
10682        };
10683
10684        let project = self.project.clone();
10685
10686        cx.spawn_in(window, |_, mut cx| async move {
10687            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10688
10689            if let Some((_, path)) = result {
10690                workspace
10691                    .update_in(&mut cx, |workspace, window, cx| {
10692                        workspace.open_resolved_path(path, window, cx)
10693                    })?
10694                    .await?;
10695            }
10696            anyhow::Ok(())
10697        })
10698        .detach();
10699    }
10700
10701    pub(crate) fn navigate_to_hover_links(
10702        &mut self,
10703        kind: Option<GotoDefinitionKind>,
10704        mut definitions: Vec<HoverLink>,
10705        split: bool,
10706        window: &mut Window,
10707        cx: &mut Context<Editor>,
10708    ) -> Task<Result<Navigated>> {
10709        // If there is one definition, just open it directly
10710        if definitions.len() == 1 {
10711            let definition = definitions.pop().unwrap();
10712
10713            enum TargetTaskResult {
10714                Location(Option<Location>),
10715                AlreadyNavigated,
10716            }
10717
10718            let target_task = match definition {
10719                HoverLink::Text(link) => {
10720                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10721                }
10722                HoverLink::InlayHint(lsp_location, server_id) => {
10723                    let computation =
10724                        self.compute_target_location(lsp_location, server_id, window, cx);
10725                    cx.background_executor().spawn(async move {
10726                        let location = computation.await?;
10727                        Ok(TargetTaskResult::Location(location))
10728                    })
10729                }
10730                HoverLink::Url(url) => {
10731                    cx.open_url(&url);
10732                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10733                }
10734                HoverLink::File(path) => {
10735                    if let Some(workspace) = self.workspace() {
10736                        cx.spawn_in(window, |_, mut cx| async move {
10737                            workspace
10738                                .update_in(&mut cx, |workspace, window, cx| {
10739                                    workspace.open_resolved_path(path, window, cx)
10740                                })?
10741                                .await
10742                                .map(|_| TargetTaskResult::AlreadyNavigated)
10743                        })
10744                    } else {
10745                        Task::ready(Ok(TargetTaskResult::Location(None)))
10746                    }
10747                }
10748            };
10749            cx.spawn_in(window, |editor, mut cx| async move {
10750                let target = match target_task.await.context("target resolution task")? {
10751                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10752                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10753                    TargetTaskResult::Location(Some(target)) => target,
10754                };
10755
10756                editor.update_in(&mut cx, |editor, window, cx| {
10757                    let Some(workspace) = editor.workspace() else {
10758                        return Navigated::No;
10759                    };
10760                    let pane = workspace.read(cx).active_pane().clone();
10761
10762                    let range = target.range.to_point(target.buffer.read(cx));
10763                    let range = editor.range_for_match(&range);
10764                    let range = collapse_multiline_range(range);
10765
10766                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10767                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10768                    } else {
10769                        window.defer(cx, move |window, cx| {
10770                            let target_editor: Entity<Self> =
10771                                workspace.update(cx, |workspace, cx| {
10772                                    let pane = if split {
10773                                        workspace.adjacent_pane(window, cx)
10774                                    } else {
10775                                        workspace.active_pane().clone()
10776                                    };
10777
10778                                    workspace.open_project_item(
10779                                        pane,
10780                                        target.buffer.clone(),
10781                                        true,
10782                                        true,
10783                                        window,
10784                                        cx,
10785                                    )
10786                                });
10787                            target_editor.update(cx, |target_editor, cx| {
10788                                // When selecting a definition in a different buffer, disable the nav history
10789                                // to avoid creating a history entry at the previous cursor location.
10790                                pane.update(cx, |pane, _| pane.disable_history());
10791                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10792                                pane.update(cx, |pane, _| pane.enable_history());
10793                            });
10794                        });
10795                    }
10796                    Navigated::Yes
10797                })
10798            })
10799        } else if !definitions.is_empty() {
10800            cx.spawn_in(window, |editor, mut cx| async move {
10801                let (title, location_tasks, workspace) = editor
10802                    .update_in(&mut cx, |editor, window, cx| {
10803                        let tab_kind = match kind {
10804                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10805                            _ => "Definitions",
10806                        };
10807                        let title = definitions
10808                            .iter()
10809                            .find_map(|definition| match definition {
10810                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10811                                    let buffer = origin.buffer.read(cx);
10812                                    format!(
10813                                        "{} for {}",
10814                                        tab_kind,
10815                                        buffer
10816                                            .text_for_range(origin.range.clone())
10817                                            .collect::<String>()
10818                                    )
10819                                }),
10820                                HoverLink::InlayHint(_, _) => None,
10821                                HoverLink::Url(_) => None,
10822                                HoverLink::File(_) => None,
10823                            })
10824                            .unwrap_or(tab_kind.to_string());
10825                        let location_tasks = definitions
10826                            .into_iter()
10827                            .map(|definition| match definition {
10828                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10829                                HoverLink::InlayHint(lsp_location, server_id) => editor
10830                                    .compute_target_location(lsp_location, server_id, window, cx),
10831                                HoverLink::Url(_) => Task::ready(Ok(None)),
10832                                HoverLink::File(_) => Task::ready(Ok(None)),
10833                            })
10834                            .collect::<Vec<_>>();
10835                        (title, location_tasks, editor.workspace().clone())
10836                    })
10837                    .context("location tasks preparation")?;
10838
10839                let locations = future::join_all(location_tasks)
10840                    .await
10841                    .into_iter()
10842                    .filter_map(|location| location.transpose())
10843                    .collect::<Result<_>>()
10844                    .context("location tasks")?;
10845
10846                let Some(workspace) = workspace else {
10847                    return Ok(Navigated::No);
10848                };
10849                let opened = workspace
10850                    .update_in(&mut cx, |workspace, window, cx| {
10851                        Self::open_locations_in_multibuffer(
10852                            workspace,
10853                            locations,
10854                            title,
10855                            split,
10856                            MultibufferSelectionMode::First,
10857                            window,
10858                            cx,
10859                        )
10860                    })
10861                    .ok();
10862
10863                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10864            })
10865        } else {
10866            Task::ready(Ok(Navigated::No))
10867        }
10868    }
10869
10870    fn compute_target_location(
10871        &self,
10872        lsp_location: lsp::Location,
10873        server_id: LanguageServerId,
10874        window: &mut Window,
10875        cx: &mut Context<Self>,
10876    ) -> Task<anyhow::Result<Option<Location>>> {
10877        let Some(project) = self.project.clone() else {
10878            return Task::ready(Ok(None));
10879        };
10880
10881        cx.spawn_in(window, move |editor, mut cx| async move {
10882            let location_task = editor.update(&mut cx, |_, cx| {
10883                project.update(cx, |project, cx| {
10884                    let language_server_name = project
10885                        .language_server_statuses(cx)
10886                        .find(|(id, _)| server_id == *id)
10887                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10888                    language_server_name.map(|language_server_name| {
10889                        project.open_local_buffer_via_lsp(
10890                            lsp_location.uri.clone(),
10891                            server_id,
10892                            language_server_name,
10893                            cx,
10894                        )
10895                    })
10896                })
10897            })?;
10898            let location = match location_task {
10899                Some(task) => Some({
10900                    let target_buffer_handle = task.await.context("open local buffer")?;
10901                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10902                        let target_start = target_buffer
10903                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10904                        let target_end = target_buffer
10905                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10906                        target_buffer.anchor_after(target_start)
10907                            ..target_buffer.anchor_before(target_end)
10908                    })?;
10909                    Location {
10910                        buffer: target_buffer_handle,
10911                        range,
10912                    }
10913                }),
10914                None => None,
10915            };
10916            Ok(location)
10917        })
10918    }
10919
10920    pub fn find_all_references(
10921        &mut self,
10922        _: &FindAllReferences,
10923        window: &mut Window,
10924        cx: &mut Context<Self>,
10925    ) -> Option<Task<Result<Navigated>>> {
10926        let selection = self.selections.newest::<usize>(cx);
10927        let multi_buffer = self.buffer.read(cx);
10928        let head = selection.head();
10929
10930        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10931        let head_anchor = multi_buffer_snapshot.anchor_at(
10932            head,
10933            if head < selection.tail() {
10934                Bias::Right
10935            } else {
10936                Bias::Left
10937            },
10938        );
10939
10940        match self
10941            .find_all_references_task_sources
10942            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10943        {
10944            Ok(_) => {
10945                log::info!(
10946                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10947                );
10948                return None;
10949            }
10950            Err(i) => {
10951                self.find_all_references_task_sources.insert(i, head_anchor);
10952            }
10953        }
10954
10955        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10956        let workspace = self.workspace()?;
10957        let project = workspace.read(cx).project().clone();
10958        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10959        Some(cx.spawn_in(window, |editor, mut cx| async move {
10960            let _cleanup = defer({
10961                let mut cx = cx.clone();
10962                move || {
10963                    let _ = editor.update(&mut cx, |editor, _| {
10964                        if let Ok(i) =
10965                            editor
10966                                .find_all_references_task_sources
10967                                .binary_search_by(|anchor| {
10968                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10969                                })
10970                        {
10971                            editor.find_all_references_task_sources.remove(i);
10972                        }
10973                    });
10974                }
10975            });
10976
10977            let locations = references.await?;
10978            if locations.is_empty() {
10979                return anyhow::Ok(Navigated::No);
10980            }
10981
10982            workspace.update_in(&mut cx, |workspace, window, cx| {
10983                let title = locations
10984                    .first()
10985                    .as_ref()
10986                    .map(|location| {
10987                        let buffer = location.buffer.read(cx);
10988                        format!(
10989                            "References to `{}`",
10990                            buffer
10991                                .text_for_range(location.range.clone())
10992                                .collect::<String>()
10993                        )
10994                    })
10995                    .unwrap();
10996                Self::open_locations_in_multibuffer(
10997                    workspace,
10998                    locations,
10999                    title,
11000                    false,
11001                    MultibufferSelectionMode::First,
11002                    window,
11003                    cx,
11004                );
11005                Navigated::Yes
11006            })
11007        }))
11008    }
11009
11010    /// Opens a multibuffer with the given project locations in it
11011    pub fn open_locations_in_multibuffer(
11012        workspace: &mut Workspace,
11013        mut locations: Vec<Location>,
11014        title: String,
11015        split: bool,
11016        multibuffer_selection_mode: MultibufferSelectionMode,
11017        window: &mut Window,
11018        cx: &mut Context<Workspace>,
11019    ) {
11020        // If there are multiple definitions, open them in a multibuffer
11021        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11022        let mut locations = locations.into_iter().peekable();
11023        let mut ranges = Vec::new();
11024        let capability = workspace.project().read(cx).capability();
11025
11026        let excerpt_buffer = cx.new(|cx| {
11027            let mut multibuffer = MultiBuffer::new(capability);
11028            while let Some(location) = locations.next() {
11029                let buffer = location.buffer.read(cx);
11030                let mut ranges_for_buffer = Vec::new();
11031                let range = location.range.to_offset(buffer);
11032                ranges_for_buffer.push(range.clone());
11033
11034                while let Some(next_location) = locations.peek() {
11035                    if next_location.buffer == location.buffer {
11036                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11037                        locations.next();
11038                    } else {
11039                        break;
11040                    }
11041                }
11042
11043                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11044                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11045                    location.buffer.clone(),
11046                    ranges_for_buffer,
11047                    DEFAULT_MULTIBUFFER_CONTEXT,
11048                    cx,
11049                ))
11050            }
11051
11052            multibuffer.with_title(title)
11053        });
11054
11055        let editor = cx.new(|cx| {
11056            Editor::for_multibuffer(
11057                excerpt_buffer,
11058                Some(workspace.project().clone()),
11059                true,
11060                window,
11061                cx,
11062            )
11063        });
11064        editor.update(cx, |editor, cx| {
11065            match multibuffer_selection_mode {
11066                MultibufferSelectionMode::First => {
11067                    if let Some(first_range) = ranges.first() {
11068                        editor.change_selections(None, window, cx, |selections| {
11069                            selections.clear_disjoint();
11070                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11071                        });
11072                    }
11073                    editor.highlight_background::<Self>(
11074                        &ranges,
11075                        |theme| theme.editor_highlighted_line_background,
11076                        cx,
11077                    );
11078                }
11079                MultibufferSelectionMode::All => {
11080                    editor.change_selections(None, window, cx, |selections| {
11081                        selections.clear_disjoint();
11082                        selections.select_anchor_ranges(ranges);
11083                    });
11084                }
11085            }
11086            editor.register_buffers_with_language_servers(cx);
11087        });
11088
11089        let item = Box::new(editor);
11090        let item_id = item.item_id();
11091
11092        if split {
11093            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11094        } else {
11095            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11096                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11097                    pane.close_current_preview_item(window, cx)
11098                } else {
11099                    None
11100                }
11101            });
11102            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11103        }
11104        workspace.active_pane().update(cx, |pane, cx| {
11105            pane.set_preview_item_id(Some(item_id), cx);
11106        });
11107    }
11108
11109    pub fn rename(
11110        &mut self,
11111        _: &Rename,
11112        window: &mut Window,
11113        cx: &mut Context<Self>,
11114    ) -> Option<Task<Result<()>>> {
11115        use language::ToOffset as _;
11116
11117        let provider = self.semantics_provider.clone()?;
11118        let selection = self.selections.newest_anchor().clone();
11119        let (cursor_buffer, cursor_buffer_position) = self
11120            .buffer
11121            .read(cx)
11122            .text_anchor_for_position(selection.head(), cx)?;
11123        let (tail_buffer, cursor_buffer_position_end) = self
11124            .buffer
11125            .read(cx)
11126            .text_anchor_for_position(selection.tail(), cx)?;
11127        if tail_buffer != cursor_buffer {
11128            return None;
11129        }
11130
11131        let snapshot = cursor_buffer.read(cx).snapshot();
11132        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11133        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11134        let prepare_rename = provider
11135            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11136            .unwrap_or_else(|| Task::ready(Ok(None)));
11137        drop(snapshot);
11138
11139        Some(cx.spawn_in(window, |this, mut cx| async move {
11140            let rename_range = if let Some(range) = prepare_rename.await? {
11141                Some(range)
11142            } else {
11143                this.update(&mut cx, |this, cx| {
11144                    let buffer = this.buffer.read(cx).snapshot(cx);
11145                    let mut buffer_highlights = this
11146                        .document_highlights_for_position(selection.head(), &buffer)
11147                        .filter(|highlight| {
11148                            highlight.start.excerpt_id == selection.head().excerpt_id
11149                                && highlight.end.excerpt_id == selection.head().excerpt_id
11150                        });
11151                    buffer_highlights
11152                        .next()
11153                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11154                })?
11155            };
11156            if let Some(rename_range) = rename_range {
11157                this.update_in(&mut cx, |this, window, cx| {
11158                    let snapshot = cursor_buffer.read(cx).snapshot();
11159                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11160                    let cursor_offset_in_rename_range =
11161                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11162                    let cursor_offset_in_rename_range_end =
11163                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11164
11165                    this.take_rename(false, window, cx);
11166                    let buffer = this.buffer.read(cx).read(cx);
11167                    let cursor_offset = selection.head().to_offset(&buffer);
11168                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11169                    let rename_end = rename_start + rename_buffer_range.len();
11170                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11171                    let mut old_highlight_id = None;
11172                    let old_name: Arc<str> = buffer
11173                        .chunks(rename_start..rename_end, true)
11174                        .map(|chunk| {
11175                            if old_highlight_id.is_none() {
11176                                old_highlight_id = chunk.syntax_highlight_id;
11177                            }
11178                            chunk.text
11179                        })
11180                        .collect::<String>()
11181                        .into();
11182
11183                    drop(buffer);
11184
11185                    // Position the selection in the rename editor so that it matches the current selection.
11186                    this.show_local_selections = false;
11187                    let rename_editor = cx.new(|cx| {
11188                        let mut editor = Editor::single_line(window, cx);
11189                        editor.buffer.update(cx, |buffer, cx| {
11190                            buffer.edit([(0..0, old_name.clone())], None, cx)
11191                        });
11192                        let rename_selection_range = match cursor_offset_in_rename_range
11193                            .cmp(&cursor_offset_in_rename_range_end)
11194                        {
11195                            Ordering::Equal => {
11196                                editor.select_all(&SelectAll, window, cx);
11197                                return editor;
11198                            }
11199                            Ordering::Less => {
11200                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11201                            }
11202                            Ordering::Greater => {
11203                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11204                            }
11205                        };
11206                        if rename_selection_range.end > old_name.len() {
11207                            editor.select_all(&SelectAll, window, cx);
11208                        } else {
11209                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11210                                s.select_ranges([rename_selection_range]);
11211                            });
11212                        }
11213                        editor
11214                    });
11215                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11216                        if e == &EditorEvent::Focused {
11217                            cx.emit(EditorEvent::FocusedIn)
11218                        }
11219                    })
11220                    .detach();
11221
11222                    let write_highlights =
11223                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11224                    let read_highlights =
11225                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11226                    let ranges = write_highlights
11227                        .iter()
11228                        .flat_map(|(_, ranges)| ranges.iter())
11229                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11230                        .cloned()
11231                        .collect();
11232
11233                    this.highlight_text::<Rename>(
11234                        ranges,
11235                        HighlightStyle {
11236                            fade_out: Some(0.6),
11237                            ..Default::default()
11238                        },
11239                        cx,
11240                    );
11241                    let rename_focus_handle = rename_editor.focus_handle(cx);
11242                    window.focus(&rename_focus_handle);
11243                    let block_id = this.insert_blocks(
11244                        [BlockProperties {
11245                            style: BlockStyle::Flex,
11246                            placement: BlockPlacement::Below(range.start),
11247                            height: 1,
11248                            render: Arc::new({
11249                                let rename_editor = rename_editor.clone();
11250                                move |cx: &mut BlockContext| {
11251                                    let mut text_style = cx.editor_style.text.clone();
11252                                    if let Some(highlight_style) = old_highlight_id
11253                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11254                                    {
11255                                        text_style = text_style.highlight(highlight_style);
11256                                    }
11257                                    div()
11258                                        .block_mouse_down()
11259                                        .pl(cx.anchor_x)
11260                                        .child(EditorElement::new(
11261                                            &rename_editor,
11262                                            EditorStyle {
11263                                                background: cx.theme().system().transparent,
11264                                                local_player: cx.editor_style.local_player,
11265                                                text: text_style,
11266                                                scrollbar_width: cx.editor_style.scrollbar_width,
11267                                                syntax: cx.editor_style.syntax.clone(),
11268                                                status: cx.editor_style.status.clone(),
11269                                                inlay_hints_style: HighlightStyle {
11270                                                    font_weight: Some(FontWeight::BOLD),
11271                                                    ..make_inlay_hints_style(cx.app)
11272                                                },
11273                                                inline_completion_styles: make_suggestion_styles(
11274                                                    cx.app,
11275                                                ),
11276                                                ..EditorStyle::default()
11277                                            },
11278                                        ))
11279                                        .into_any_element()
11280                                }
11281                            }),
11282                            priority: 0,
11283                        }],
11284                        Some(Autoscroll::fit()),
11285                        cx,
11286                    )[0];
11287                    this.pending_rename = Some(RenameState {
11288                        range,
11289                        old_name,
11290                        editor: rename_editor,
11291                        block_id,
11292                    });
11293                })?;
11294            }
11295
11296            Ok(())
11297        }))
11298    }
11299
11300    pub fn confirm_rename(
11301        &mut self,
11302        _: &ConfirmRename,
11303        window: &mut Window,
11304        cx: &mut Context<Self>,
11305    ) -> Option<Task<Result<()>>> {
11306        let rename = self.take_rename(false, window, cx)?;
11307        let workspace = self.workspace()?.downgrade();
11308        let (buffer, start) = self
11309            .buffer
11310            .read(cx)
11311            .text_anchor_for_position(rename.range.start, cx)?;
11312        let (end_buffer, _) = self
11313            .buffer
11314            .read(cx)
11315            .text_anchor_for_position(rename.range.end, cx)?;
11316        if buffer != end_buffer {
11317            return None;
11318        }
11319
11320        let old_name = rename.old_name;
11321        let new_name = rename.editor.read(cx).text(cx);
11322
11323        let rename = self.semantics_provider.as_ref()?.perform_rename(
11324            &buffer,
11325            start,
11326            new_name.clone(),
11327            cx,
11328        )?;
11329
11330        Some(cx.spawn_in(window, |editor, mut cx| async move {
11331            let project_transaction = rename.await?;
11332            Self::open_project_transaction(
11333                &editor,
11334                workspace,
11335                project_transaction,
11336                format!("Rename: {}{}", old_name, new_name),
11337                cx.clone(),
11338            )
11339            .await?;
11340
11341            editor.update(&mut cx, |editor, cx| {
11342                editor.refresh_document_highlights(cx);
11343            })?;
11344            Ok(())
11345        }))
11346    }
11347
11348    fn take_rename(
11349        &mut self,
11350        moving_cursor: bool,
11351        window: &mut Window,
11352        cx: &mut Context<Self>,
11353    ) -> Option<RenameState> {
11354        let rename = self.pending_rename.take()?;
11355        if rename.editor.focus_handle(cx).is_focused(window) {
11356            window.focus(&self.focus_handle);
11357        }
11358
11359        self.remove_blocks(
11360            [rename.block_id].into_iter().collect(),
11361            Some(Autoscroll::fit()),
11362            cx,
11363        );
11364        self.clear_highlights::<Rename>(cx);
11365        self.show_local_selections = true;
11366
11367        if moving_cursor {
11368            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11369                editor.selections.newest::<usize>(cx).head()
11370            });
11371
11372            // Update the selection to match the position of the selection inside
11373            // the rename editor.
11374            let snapshot = self.buffer.read(cx).read(cx);
11375            let rename_range = rename.range.to_offset(&snapshot);
11376            let cursor_in_editor = snapshot
11377                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11378                .min(rename_range.end);
11379            drop(snapshot);
11380
11381            self.change_selections(None, window, cx, |s| {
11382                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11383            });
11384        } else {
11385            self.refresh_document_highlights(cx);
11386        }
11387
11388        Some(rename)
11389    }
11390
11391    pub fn pending_rename(&self) -> Option<&RenameState> {
11392        self.pending_rename.as_ref()
11393    }
11394
11395    fn format(
11396        &mut self,
11397        _: &Format,
11398        window: &mut Window,
11399        cx: &mut Context<Self>,
11400    ) -> Option<Task<Result<()>>> {
11401        let project = match &self.project {
11402            Some(project) => project.clone(),
11403            None => return None,
11404        };
11405
11406        Some(self.perform_format(
11407            project,
11408            FormatTrigger::Manual,
11409            FormatTarget::Buffers,
11410            window,
11411            cx,
11412        ))
11413    }
11414
11415    fn format_selections(
11416        &mut self,
11417        _: &FormatSelections,
11418        window: &mut Window,
11419        cx: &mut Context<Self>,
11420    ) -> Option<Task<Result<()>>> {
11421        let project = match &self.project {
11422            Some(project) => project.clone(),
11423            None => return None,
11424        };
11425
11426        let ranges = self
11427            .selections
11428            .all_adjusted(cx)
11429            .into_iter()
11430            .map(|selection| selection.range())
11431            .collect_vec();
11432
11433        Some(self.perform_format(
11434            project,
11435            FormatTrigger::Manual,
11436            FormatTarget::Ranges(ranges),
11437            window,
11438            cx,
11439        ))
11440    }
11441
11442    fn perform_format(
11443        &mut self,
11444        project: Entity<Project>,
11445        trigger: FormatTrigger,
11446        target: FormatTarget,
11447        window: &mut Window,
11448        cx: &mut Context<Self>,
11449    ) -> Task<Result<()>> {
11450        let buffer = self.buffer.clone();
11451        let (buffers, target) = match target {
11452            FormatTarget::Buffers => {
11453                let mut buffers = buffer.read(cx).all_buffers();
11454                if trigger == FormatTrigger::Save {
11455                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11456                }
11457                (buffers, LspFormatTarget::Buffers)
11458            }
11459            FormatTarget::Ranges(selection_ranges) => {
11460                let multi_buffer = buffer.read(cx);
11461                let snapshot = multi_buffer.read(cx);
11462                let mut buffers = HashSet::default();
11463                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11464                    BTreeMap::new();
11465                for selection_range in selection_ranges {
11466                    for (buffer, buffer_range, _) in
11467                        snapshot.range_to_buffer_ranges(selection_range)
11468                    {
11469                        let buffer_id = buffer.remote_id();
11470                        let start = buffer.anchor_before(buffer_range.start);
11471                        let end = buffer.anchor_after(buffer_range.end);
11472                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11473                        buffer_id_to_ranges
11474                            .entry(buffer_id)
11475                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11476                            .or_insert_with(|| vec![start..end]);
11477                    }
11478                }
11479                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11480            }
11481        };
11482
11483        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11484        let format = project.update(cx, |project, cx| {
11485            project.format(buffers, target, true, trigger, cx)
11486        });
11487
11488        cx.spawn_in(window, |_, mut cx| async move {
11489            let transaction = futures::select_biased! {
11490                () = timeout => {
11491                    log::warn!("timed out waiting for formatting");
11492                    None
11493                }
11494                transaction = format.log_err().fuse() => transaction,
11495            };
11496
11497            buffer
11498                .update(&mut cx, |buffer, cx| {
11499                    if let Some(transaction) = transaction {
11500                        if !buffer.is_singleton() {
11501                            buffer.push_transaction(&transaction.0, cx);
11502                        }
11503                    }
11504
11505                    cx.notify();
11506                })
11507                .ok();
11508
11509            Ok(())
11510        })
11511    }
11512
11513    fn restart_language_server(
11514        &mut self,
11515        _: &RestartLanguageServer,
11516        _: &mut Window,
11517        cx: &mut Context<Self>,
11518    ) {
11519        if let Some(project) = self.project.clone() {
11520            self.buffer.update(cx, |multi_buffer, cx| {
11521                project.update(cx, |project, cx| {
11522                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11523                });
11524            })
11525        }
11526    }
11527
11528    fn cancel_language_server_work(
11529        workspace: &mut Workspace,
11530        _: &actions::CancelLanguageServerWork,
11531        _: &mut Window,
11532        cx: &mut Context<Workspace>,
11533    ) {
11534        let project = workspace.project();
11535        let buffers = workspace
11536            .active_item(cx)
11537            .and_then(|item| item.act_as::<Editor>(cx))
11538            .map_or(HashSet::default(), |editor| {
11539                editor.read(cx).buffer.read(cx).all_buffers()
11540            });
11541        project.update(cx, |project, cx| {
11542            project.cancel_language_server_work_for_buffers(buffers, cx);
11543        });
11544    }
11545
11546    fn show_character_palette(
11547        &mut self,
11548        _: &ShowCharacterPalette,
11549        window: &mut Window,
11550        _: &mut Context<Self>,
11551    ) {
11552        window.show_character_palette();
11553    }
11554
11555    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11556        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11557            let buffer = self.buffer.read(cx).snapshot(cx);
11558            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11559            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11560            let is_valid = buffer
11561                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11562                .any(|entry| {
11563                    entry.diagnostic.is_primary
11564                        && !entry.range.is_empty()
11565                        && entry.range.start == primary_range_start
11566                        && entry.diagnostic.message == active_diagnostics.primary_message
11567                });
11568
11569            if is_valid != active_diagnostics.is_valid {
11570                active_diagnostics.is_valid = is_valid;
11571                let mut new_styles = HashMap::default();
11572                for (block_id, diagnostic) in &active_diagnostics.blocks {
11573                    new_styles.insert(
11574                        *block_id,
11575                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11576                    );
11577                }
11578                self.display_map.update(cx, |display_map, _cx| {
11579                    display_map.replace_blocks(new_styles)
11580                });
11581            }
11582        }
11583    }
11584
11585    fn activate_diagnostics(
11586        &mut self,
11587        buffer_id: BufferId,
11588        group_id: usize,
11589        window: &mut Window,
11590        cx: &mut Context<Self>,
11591    ) {
11592        self.dismiss_diagnostics(cx);
11593        let snapshot = self.snapshot(window, cx);
11594        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11595            let buffer = self.buffer.read(cx).snapshot(cx);
11596
11597            let mut primary_range = None;
11598            let mut primary_message = None;
11599            let diagnostic_group = buffer
11600                .diagnostic_group(buffer_id, group_id)
11601                .filter_map(|entry| {
11602                    let start = entry.range.start;
11603                    let end = entry.range.end;
11604                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11605                        && (start.row == end.row
11606                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11607                    {
11608                        return None;
11609                    }
11610                    if entry.diagnostic.is_primary {
11611                        primary_range = Some(entry.range.clone());
11612                        primary_message = Some(entry.diagnostic.message.clone());
11613                    }
11614                    Some(entry)
11615                })
11616                .collect::<Vec<_>>();
11617            let primary_range = primary_range?;
11618            let primary_message = primary_message?;
11619
11620            let blocks = display_map
11621                .insert_blocks(
11622                    diagnostic_group.iter().map(|entry| {
11623                        let diagnostic = entry.diagnostic.clone();
11624                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11625                        BlockProperties {
11626                            style: BlockStyle::Fixed,
11627                            placement: BlockPlacement::Below(
11628                                buffer.anchor_after(entry.range.start),
11629                            ),
11630                            height: message_height,
11631                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11632                            priority: 0,
11633                        }
11634                    }),
11635                    cx,
11636                )
11637                .into_iter()
11638                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11639                .collect();
11640
11641            Some(ActiveDiagnosticGroup {
11642                primary_range: buffer.anchor_before(primary_range.start)
11643                    ..buffer.anchor_after(primary_range.end),
11644                primary_message,
11645                group_id,
11646                blocks,
11647                is_valid: true,
11648            })
11649        });
11650    }
11651
11652    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11653        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11654            self.display_map.update(cx, |display_map, cx| {
11655                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11656            });
11657            cx.notify();
11658        }
11659    }
11660
11661    pub fn set_selections_from_remote(
11662        &mut self,
11663        selections: Vec<Selection<Anchor>>,
11664        pending_selection: Option<Selection<Anchor>>,
11665        window: &mut Window,
11666        cx: &mut Context<Self>,
11667    ) {
11668        let old_cursor_position = self.selections.newest_anchor().head();
11669        self.selections.change_with(cx, |s| {
11670            s.select_anchors(selections);
11671            if let Some(pending_selection) = pending_selection {
11672                s.set_pending(pending_selection, SelectMode::Character);
11673            } else {
11674                s.clear_pending();
11675            }
11676        });
11677        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11678    }
11679
11680    fn push_to_selection_history(&mut self) {
11681        self.selection_history.push(SelectionHistoryEntry {
11682            selections: self.selections.disjoint_anchors(),
11683            select_next_state: self.select_next_state.clone(),
11684            select_prev_state: self.select_prev_state.clone(),
11685            add_selections_state: self.add_selections_state.clone(),
11686        });
11687    }
11688
11689    pub fn transact(
11690        &mut self,
11691        window: &mut Window,
11692        cx: &mut Context<Self>,
11693        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11694    ) -> Option<TransactionId> {
11695        self.start_transaction_at(Instant::now(), window, cx);
11696        update(self, window, cx);
11697        self.end_transaction_at(Instant::now(), cx)
11698    }
11699
11700    pub fn start_transaction_at(
11701        &mut self,
11702        now: Instant,
11703        window: &mut Window,
11704        cx: &mut Context<Self>,
11705    ) {
11706        self.end_selection(window, cx);
11707        if let Some(tx_id) = self
11708            .buffer
11709            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11710        {
11711            self.selection_history
11712                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11713            cx.emit(EditorEvent::TransactionBegun {
11714                transaction_id: tx_id,
11715            })
11716        }
11717    }
11718
11719    pub fn end_transaction_at(
11720        &mut self,
11721        now: Instant,
11722        cx: &mut Context<Self>,
11723    ) -> Option<TransactionId> {
11724        if let Some(transaction_id) = self
11725            .buffer
11726            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11727        {
11728            if let Some((_, end_selections)) =
11729                self.selection_history.transaction_mut(transaction_id)
11730            {
11731                *end_selections = Some(self.selections.disjoint_anchors());
11732            } else {
11733                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11734            }
11735
11736            cx.emit(EditorEvent::Edited { transaction_id });
11737            Some(transaction_id)
11738        } else {
11739            None
11740        }
11741    }
11742
11743    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11744        if self.selection_mark_mode {
11745            self.change_selections(None, window, cx, |s| {
11746                s.move_with(|_, sel| {
11747                    sel.collapse_to(sel.head(), SelectionGoal::None);
11748                });
11749            })
11750        }
11751        self.selection_mark_mode = true;
11752        cx.notify();
11753    }
11754
11755    pub fn swap_selection_ends(
11756        &mut self,
11757        _: &actions::SwapSelectionEnds,
11758        window: &mut Window,
11759        cx: &mut Context<Self>,
11760    ) {
11761        self.change_selections(None, window, cx, |s| {
11762            s.move_with(|_, sel| {
11763                if sel.start != sel.end {
11764                    sel.reversed = !sel.reversed
11765                }
11766            });
11767        });
11768        self.request_autoscroll(Autoscroll::newest(), cx);
11769        cx.notify();
11770    }
11771
11772    pub fn toggle_fold(
11773        &mut self,
11774        _: &actions::ToggleFold,
11775        window: &mut Window,
11776        cx: &mut Context<Self>,
11777    ) {
11778        if self.is_singleton(cx) {
11779            let selection = self.selections.newest::<Point>(cx);
11780
11781            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11782            let range = if selection.is_empty() {
11783                let point = selection.head().to_display_point(&display_map);
11784                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11785                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11786                    .to_point(&display_map);
11787                start..end
11788            } else {
11789                selection.range()
11790            };
11791            if display_map.folds_in_range(range).next().is_some() {
11792                self.unfold_lines(&Default::default(), window, cx)
11793            } else {
11794                self.fold(&Default::default(), window, cx)
11795            }
11796        } else {
11797            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11798            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11799                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11800                .map(|(snapshot, _, _)| snapshot.remote_id())
11801                .collect();
11802
11803            for buffer_id in buffer_ids {
11804                if self.is_buffer_folded(buffer_id, cx) {
11805                    self.unfold_buffer(buffer_id, cx);
11806                } else {
11807                    self.fold_buffer(buffer_id, cx);
11808                }
11809            }
11810        }
11811    }
11812
11813    pub fn toggle_fold_recursive(
11814        &mut self,
11815        _: &actions::ToggleFoldRecursive,
11816        window: &mut Window,
11817        cx: &mut Context<Self>,
11818    ) {
11819        let selection = self.selections.newest::<Point>(cx);
11820
11821        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11822        let range = if selection.is_empty() {
11823            let point = selection.head().to_display_point(&display_map);
11824            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11825            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11826                .to_point(&display_map);
11827            start..end
11828        } else {
11829            selection.range()
11830        };
11831        if display_map.folds_in_range(range).next().is_some() {
11832            self.unfold_recursive(&Default::default(), window, cx)
11833        } else {
11834            self.fold_recursive(&Default::default(), window, cx)
11835        }
11836    }
11837
11838    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11839        if self.is_singleton(cx) {
11840            let mut to_fold = Vec::new();
11841            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11842            let selections = self.selections.all_adjusted(cx);
11843
11844            for selection in selections {
11845                let range = selection.range().sorted();
11846                let buffer_start_row = range.start.row;
11847
11848                if range.start.row != range.end.row {
11849                    let mut found = false;
11850                    let mut row = range.start.row;
11851                    while row <= range.end.row {
11852                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11853                        {
11854                            found = true;
11855                            row = crease.range().end.row + 1;
11856                            to_fold.push(crease);
11857                        } else {
11858                            row += 1
11859                        }
11860                    }
11861                    if found {
11862                        continue;
11863                    }
11864                }
11865
11866                for row in (0..=range.start.row).rev() {
11867                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11868                        if crease.range().end.row >= buffer_start_row {
11869                            to_fold.push(crease);
11870                            if row <= range.start.row {
11871                                break;
11872                            }
11873                        }
11874                    }
11875                }
11876            }
11877
11878            self.fold_creases(to_fold, true, window, cx);
11879        } else {
11880            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11881
11882            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11883                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11884                .map(|(snapshot, _, _)| snapshot.remote_id())
11885                .collect();
11886            for buffer_id in buffer_ids {
11887                self.fold_buffer(buffer_id, cx);
11888            }
11889        }
11890    }
11891
11892    fn fold_at_level(
11893        &mut self,
11894        fold_at: &FoldAtLevel,
11895        window: &mut Window,
11896        cx: &mut Context<Self>,
11897    ) {
11898        if !self.buffer.read(cx).is_singleton() {
11899            return;
11900        }
11901
11902        let fold_at_level = fold_at.0;
11903        let snapshot = self.buffer.read(cx).snapshot(cx);
11904        let mut to_fold = Vec::new();
11905        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11906
11907        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11908            while start_row < end_row {
11909                match self
11910                    .snapshot(window, cx)
11911                    .crease_for_buffer_row(MultiBufferRow(start_row))
11912                {
11913                    Some(crease) => {
11914                        let nested_start_row = crease.range().start.row + 1;
11915                        let nested_end_row = crease.range().end.row;
11916
11917                        if current_level < fold_at_level {
11918                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11919                        } else if current_level == fold_at_level {
11920                            to_fold.push(crease);
11921                        }
11922
11923                        start_row = nested_end_row + 1;
11924                    }
11925                    None => start_row += 1,
11926                }
11927            }
11928        }
11929
11930        self.fold_creases(to_fold, true, window, cx);
11931    }
11932
11933    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11934        if self.buffer.read(cx).is_singleton() {
11935            let mut fold_ranges = Vec::new();
11936            let snapshot = self.buffer.read(cx).snapshot(cx);
11937
11938            for row in 0..snapshot.max_row().0 {
11939                if let Some(foldable_range) = self
11940                    .snapshot(window, cx)
11941                    .crease_for_buffer_row(MultiBufferRow(row))
11942                {
11943                    fold_ranges.push(foldable_range);
11944                }
11945            }
11946
11947            self.fold_creases(fold_ranges, true, window, cx);
11948        } else {
11949            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11950                editor
11951                    .update_in(&mut cx, |editor, _, cx| {
11952                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11953                            editor.fold_buffer(buffer_id, cx);
11954                        }
11955                    })
11956                    .ok();
11957            });
11958        }
11959    }
11960
11961    pub fn fold_function_bodies(
11962        &mut self,
11963        _: &actions::FoldFunctionBodies,
11964        window: &mut Window,
11965        cx: &mut Context<Self>,
11966    ) {
11967        let snapshot = self.buffer.read(cx).snapshot(cx);
11968
11969        let ranges = snapshot
11970            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11971            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11972            .collect::<Vec<_>>();
11973
11974        let creases = ranges
11975            .into_iter()
11976            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11977            .collect();
11978
11979        self.fold_creases(creases, true, window, cx);
11980    }
11981
11982    pub fn fold_recursive(
11983        &mut self,
11984        _: &actions::FoldRecursive,
11985        window: &mut Window,
11986        cx: &mut Context<Self>,
11987    ) {
11988        let mut to_fold = Vec::new();
11989        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11990        let selections = self.selections.all_adjusted(cx);
11991
11992        for selection in selections {
11993            let range = selection.range().sorted();
11994            let buffer_start_row = range.start.row;
11995
11996            if range.start.row != range.end.row {
11997                let mut found = false;
11998                for row in range.start.row..=range.end.row {
11999                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12000                        found = true;
12001                        to_fold.push(crease);
12002                    }
12003                }
12004                if found {
12005                    continue;
12006                }
12007            }
12008
12009            for row in (0..=range.start.row).rev() {
12010                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12011                    if crease.range().end.row >= buffer_start_row {
12012                        to_fold.push(crease);
12013                    } else {
12014                        break;
12015                    }
12016                }
12017            }
12018        }
12019
12020        self.fold_creases(to_fold, true, window, cx);
12021    }
12022
12023    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12024        let buffer_row = fold_at.buffer_row;
12025        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12026
12027        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12028            let autoscroll = self
12029                .selections
12030                .all::<Point>(cx)
12031                .iter()
12032                .any(|selection| crease.range().overlaps(&selection.range()));
12033
12034            self.fold_creases(vec![crease], autoscroll, window, cx);
12035        }
12036    }
12037
12038    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12039        if self.is_singleton(cx) {
12040            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12041            let buffer = &display_map.buffer_snapshot;
12042            let selections = self.selections.all::<Point>(cx);
12043            let ranges = selections
12044                .iter()
12045                .map(|s| {
12046                    let range = s.display_range(&display_map).sorted();
12047                    let mut start = range.start.to_point(&display_map);
12048                    let mut end = range.end.to_point(&display_map);
12049                    start.column = 0;
12050                    end.column = buffer.line_len(MultiBufferRow(end.row));
12051                    start..end
12052                })
12053                .collect::<Vec<_>>();
12054
12055            self.unfold_ranges(&ranges, true, true, cx);
12056        } else {
12057            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12058            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12059                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12060                .map(|(snapshot, _, _)| snapshot.remote_id())
12061                .collect();
12062            for buffer_id in buffer_ids {
12063                self.unfold_buffer(buffer_id, cx);
12064            }
12065        }
12066    }
12067
12068    pub fn unfold_recursive(
12069        &mut self,
12070        _: &UnfoldRecursive,
12071        _window: &mut Window,
12072        cx: &mut Context<Self>,
12073    ) {
12074        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12075        let selections = self.selections.all::<Point>(cx);
12076        let ranges = selections
12077            .iter()
12078            .map(|s| {
12079                let mut range = s.display_range(&display_map).sorted();
12080                *range.start.column_mut() = 0;
12081                *range.end.column_mut() = display_map.line_len(range.end.row());
12082                let start = range.start.to_point(&display_map);
12083                let end = range.end.to_point(&display_map);
12084                start..end
12085            })
12086            .collect::<Vec<_>>();
12087
12088        self.unfold_ranges(&ranges, true, true, cx);
12089    }
12090
12091    pub fn unfold_at(
12092        &mut self,
12093        unfold_at: &UnfoldAt,
12094        _window: &mut Window,
12095        cx: &mut Context<Self>,
12096    ) {
12097        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12098
12099        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12100            ..Point::new(
12101                unfold_at.buffer_row.0,
12102                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12103            );
12104
12105        let autoscroll = self
12106            .selections
12107            .all::<Point>(cx)
12108            .iter()
12109            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12110
12111        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12112    }
12113
12114    pub fn unfold_all(
12115        &mut self,
12116        _: &actions::UnfoldAll,
12117        _window: &mut Window,
12118        cx: &mut Context<Self>,
12119    ) {
12120        if self.buffer.read(cx).is_singleton() {
12121            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12122            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12123        } else {
12124            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12125                editor
12126                    .update(&mut cx, |editor, cx| {
12127                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12128                            editor.unfold_buffer(buffer_id, cx);
12129                        }
12130                    })
12131                    .ok();
12132            });
12133        }
12134    }
12135
12136    pub fn fold_selected_ranges(
12137        &mut self,
12138        _: &FoldSelectedRanges,
12139        window: &mut Window,
12140        cx: &mut Context<Self>,
12141    ) {
12142        let selections = self.selections.all::<Point>(cx);
12143        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12144        let line_mode = self.selections.line_mode;
12145        let ranges = selections
12146            .into_iter()
12147            .map(|s| {
12148                if line_mode {
12149                    let start = Point::new(s.start.row, 0);
12150                    let end = Point::new(
12151                        s.end.row,
12152                        display_map
12153                            .buffer_snapshot
12154                            .line_len(MultiBufferRow(s.end.row)),
12155                    );
12156                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12157                } else {
12158                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12159                }
12160            })
12161            .collect::<Vec<_>>();
12162        self.fold_creases(ranges, true, window, cx);
12163    }
12164
12165    pub fn fold_ranges<T: ToOffset + Clone>(
12166        &mut self,
12167        ranges: Vec<Range<T>>,
12168        auto_scroll: bool,
12169        window: &mut Window,
12170        cx: &mut Context<Self>,
12171    ) {
12172        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12173        let ranges = ranges
12174            .into_iter()
12175            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12176            .collect::<Vec<_>>();
12177        self.fold_creases(ranges, auto_scroll, window, cx);
12178    }
12179
12180    pub fn fold_creases<T: ToOffset + Clone>(
12181        &mut self,
12182        creases: Vec<Crease<T>>,
12183        auto_scroll: bool,
12184        window: &mut Window,
12185        cx: &mut Context<Self>,
12186    ) {
12187        if creases.is_empty() {
12188            return;
12189        }
12190
12191        let mut buffers_affected = HashSet::default();
12192        let multi_buffer = self.buffer().read(cx);
12193        for crease in &creases {
12194            if let Some((_, buffer, _)) =
12195                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12196            {
12197                buffers_affected.insert(buffer.read(cx).remote_id());
12198            };
12199        }
12200
12201        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12202
12203        if auto_scroll {
12204            self.request_autoscroll(Autoscroll::fit(), cx);
12205        }
12206
12207        cx.notify();
12208
12209        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12210            // Clear diagnostics block when folding a range that contains it.
12211            let snapshot = self.snapshot(window, cx);
12212            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12213                drop(snapshot);
12214                self.active_diagnostics = Some(active_diagnostics);
12215                self.dismiss_diagnostics(cx);
12216            } else {
12217                self.active_diagnostics = Some(active_diagnostics);
12218            }
12219        }
12220
12221        self.scrollbar_marker_state.dirty = true;
12222    }
12223
12224    /// Removes any folds whose ranges intersect any of the given ranges.
12225    pub fn unfold_ranges<T: ToOffset + Clone>(
12226        &mut self,
12227        ranges: &[Range<T>],
12228        inclusive: bool,
12229        auto_scroll: bool,
12230        cx: &mut Context<Self>,
12231    ) {
12232        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12233            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12234        });
12235    }
12236
12237    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12238        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12239            return;
12240        }
12241        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12242        self.display_map
12243            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12244        cx.emit(EditorEvent::BufferFoldToggled {
12245            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12246            folded: true,
12247        });
12248        cx.notify();
12249    }
12250
12251    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12252        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12253            return;
12254        }
12255        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12256        self.display_map.update(cx, |display_map, cx| {
12257            display_map.unfold_buffer(buffer_id, cx);
12258        });
12259        cx.emit(EditorEvent::BufferFoldToggled {
12260            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12261            folded: false,
12262        });
12263        cx.notify();
12264    }
12265
12266    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12267        self.display_map.read(cx).is_buffer_folded(buffer)
12268    }
12269
12270    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12271        self.display_map.read(cx).folded_buffers()
12272    }
12273
12274    /// Removes any folds with the given ranges.
12275    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12276        &mut self,
12277        ranges: &[Range<T>],
12278        type_id: TypeId,
12279        auto_scroll: bool,
12280        cx: &mut Context<Self>,
12281    ) {
12282        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12283            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12284        });
12285    }
12286
12287    fn remove_folds_with<T: ToOffset + Clone>(
12288        &mut self,
12289        ranges: &[Range<T>],
12290        auto_scroll: bool,
12291        cx: &mut Context<Self>,
12292        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12293    ) {
12294        if ranges.is_empty() {
12295            return;
12296        }
12297
12298        let mut buffers_affected = HashSet::default();
12299        let multi_buffer = self.buffer().read(cx);
12300        for range in ranges {
12301            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12302                buffers_affected.insert(buffer.read(cx).remote_id());
12303            };
12304        }
12305
12306        self.display_map.update(cx, update);
12307
12308        if auto_scroll {
12309            self.request_autoscroll(Autoscroll::fit(), cx);
12310        }
12311
12312        cx.notify();
12313        self.scrollbar_marker_state.dirty = true;
12314        self.active_indent_guides_state.dirty = true;
12315    }
12316
12317    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12318        self.display_map.read(cx).fold_placeholder.clone()
12319    }
12320
12321    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12322        self.buffer.update(cx, |buffer, cx| {
12323            buffer.set_all_diff_hunks_expanded(cx);
12324        });
12325    }
12326
12327    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12328        self.distinguish_unstaged_diff_hunks = true;
12329    }
12330
12331    pub fn expand_all_diff_hunks(
12332        &mut self,
12333        _: &ExpandAllHunkDiffs,
12334        _window: &mut Window,
12335        cx: &mut Context<Self>,
12336    ) {
12337        self.buffer.update(cx, |buffer, cx| {
12338            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12339        });
12340    }
12341
12342    pub fn toggle_selected_diff_hunks(
12343        &mut self,
12344        _: &ToggleSelectedDiffHunks,
12345        _window: &mut Window,
12346        cx: &mut Context<Self>,
12347    ) {
12348        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12349        self.toggle_diff_hunks_in_ranges(ranges, cx);
12350    }
12351
12352    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12353        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12354        self.buffer
12355            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12356    }
12357
12358    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12359        self.buffer.update(cx, |buffer, cx| {
12360            let ranges = vec![Anchor::min()..Anchor::max()];
12361            if !buffer.all_diff_hunks_expanded()
12362                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12363            {
12364                buffer.collapse_diff_hunks(ranges, cx);
12365                true
12366            } else {
12367                false
12368            }
12369        })
12370    }
12371
12372    fn toggle_diff_hunks_in_ranges(
12373        &mut self,
12374        ranges: Vec<Range<Anchor>>,
12375        cx: &mut Context<'_, Editor>,
12376    ) {
12377        self.buffer.update(cx, |buffer, cx| {
12378            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12379            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12380        })
12381    }
12382
12383    fn toggle_diff_hunks_in_ranges_narrow(
12384        &mut self,
12385        ranges: Vec<Range<Anchor>>,
12386        cx: &mut Context<'_, Editor>,
12387    ) {
12388        self.buffer.update(cx, |buffer, cx| {
12389            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12390            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12391        })
12392    }
12393
12394    pub(crate) fn apply_all_diff_hunks(
12395        &mut self,
12396        _: &ApplyAllDiffHunks,
12397        window: &mut Window,
12398        cx: &mut Context<Self>,
12399    ) {
12400        let buffers = self.buffer.read(cx).all_buffers();
12401        for branch_buffer in buffers {
12402            branch_buffer.update(cx, |branch_buffer, cx| {
12403                branch_buffer.merge_into_base(Vec::new(), cx);
12404            });
12405        }
12406
12407        if let Some(project) = self.project.clone() {
12408            self.save(true, project, window, cx).detach_and_log_err(cx);
12409        }
12410    }
12411
12412    pub(crate) fn apply_selected_diff_hunks(
12413        &mut self,
12414        _: &ApplyDiffHunk,
12415        window: &mut Window,
12416        cx: &mut Context<Self>,
12417    ) {
12418        let snapshot = self.snapshot(window, cx);
12419        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12420        let mut ranges_by_buffer = HashMap::default();
12421        self.transact(window, cx, |editor, _window, cx| {
12422            for hunk in hunks {
12423                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12424                    ranges_by_buffer
12425                        .entry(buffer.clone())
12426                        .or_insert_with(Vec::new)
12427                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12428                }
12429            }
12430
12431            for (buffer, ranges) in ranges_by_buffer {
12432                buffer.update(cx, |buffer, cx| {
12433                    buffer.merge_into_base(ranges, cx);
12434                });
12435            }
12436        });
12437
12438        if let Some(project) = self.project.clone() {
12439            self.save(true, project, window, cx).detach_and_log_err(cx);
12440        }
12441    }
12442
12443    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12444        if hovered != self.gutter_hovered {
12445            self.gutter_hovered = hovered;
12446            cx.notify();
12447        }
12448    }
12449
12450    pub fn insert_blocks(
12451        &mut self,
12452        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12453        autoscroll: Option<Autoscroll>,
12454        cx: &mut Context<Self>,
12455    ) -> Vec<CustomBlockId> {
12456        let blocks = self
12457            .display_map
12458            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12459        if let Some(autoscroll) = autoscroll {
12460            self.request_autoscroll(autoscroll, cx);
12461        }
12462        cx.notify();
12463        blocks
12464    }
12465
12466    pub fn resize_blocks(
12467        &mut self,
12468        heights: HashMap<CustomBlockId, u32>,
12469        autoscroll: Option<Autoscroll>,
12470        cx: &mut Context<Self>,
12471    ) {
12472        self.display_map
12473            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12474        if let Some(autoscroll) = autoscroll {
12475            self.request_autoscroll(autoscroll, cx);
12476        }
12477        cx.notify();
12478    }
12479
12480    pub fn replace_blocks(
12481        &mut self,
12482        renderers: HashMap<CustomBlockId, RenderBlock>,
12483        autoscroll: Option<Autoscroll>,
12484        cx: &mut Context<Self>,
12485    ) {
12486        self.display_map
12487            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12488        if let Some(autoscroll) = autoscroll {
12489            self.request_autoscroll(autoscroll, cx);
12490        }
12491        cx.notify();
12492    }
12493
12494    pub fn remove_blocks(
12495        &mut self,
12496        block_ids: HashSet<CustomBlockId>,
12497        autoscroll: Option<Autoscroll>,
12498        cx: &mut Context<Self>,
12499    ) {
12500        self.display_map.update(cx, |display_map, cx| {
12501            display_map.remove_blocks(block_ids, cx)
12502        });
12503        if let Some(autoscroll) = autoscroll {
12504            self.request_autoscroll(autoscroll, cx);
12505        }
12506        cx.notify();
12507    }
12508
12509    pub fn row_for_block(
12510        &self,
12511        block_id: CustomBlockId,
12512        cx: &mut Context<Self>,
12513    ) -> Option<DisplayRow> {
12514        self.display_map
12515            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12516    }
12517
12518    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12519        self.focused_block = Some(focused_block);
12520    }
12521
12522    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12523        self.focused_block.take()
12524    }
12525
12526    pub fn insert_creases(
12527        &mut self,
12528        creases: impl IntoIterator<Item = Crease<Anchor>>,
12529        cx: &mut Context<Self>,
12530    ) -> Vec<CreaseId> {
12531        self.display_map
12532            .update(cx, |map, cx| map.insert_creases(creases, cx))
12533    }
12534
12535    pub fn remove_creases(
12536        &mut self,
12537        ids: impl IntoIterator<Item = CreaseId>,
12538        cx: &mut Context<Self>,
12539    ) {
12540        self.display_map
12541            .update(cx, |map, cx| map.remove_creases(ids, cx));
12542    }
12543
12544    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12545        self.display_map
12546            .update(cx, |map, cx| map.snapshot(cx))
12547            .longest_row()
12548    }
12549
12550    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12551        self.display_map
12552            .update(cx, |map, cx| map.snapshot(cx))
12553            .max_point()
12554    }
12555
12556    pub fn text(&self, cx: &App) -> String {
12557        self.buffer.read(cx).read(cx).text()
12558    }
12559
12560    pub fn is_empty(&self, cx: &App) -> bool {
12561        self.buffer.read(cx).read(cx).is_empty()
12562    }
12563
12564    pub fn text_option(&self, cx: &App) -> Option<String> {
12565        let text = self.text(cx);
12566        let text = text.trim();
12567
12568        if text.is_empty() {
12569            return None;
12570        }
12571
12572        Some(text.to_string())
12573    }
12574
12575    pub fn set_text(
12576        &mut self,
12577        text: impl Into<Arc<str>>,
12578        window: &mut Window,
12579        cx: &mut Context<Self>,
12580    ) {
12581        self.transact(window, cx, |this, _, cx| {
12582            this.buffer
12583                .read(cx)
12584                .as_singleton()
12585                .expect("you can only call set_text on editors for singleton buffers")
12586                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12587        });
12588    }
12589
12590    pub fn display_text(&self, cx: &mut App) -> String {
12591        self.display_map
12592            .update(cx, |map, cx| map.snapshot(cx))
12593            .text()
12594    }
12595
12596    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12597        let mut wrap_guides = smallvec::smallvec![];
12598
12599        if self.show_wrap_guides == Some(false) {
12600            return wrap_guides;
12601        }
12602
12603        let settings = self.buffer.read(cx).settings_at(0, cx);
12604        if settings.show_wrap_guides {
12605            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12606                wrap_guides.push((soft_wrap as usize, true));
12607            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12608                wrap_guides.push((soft_wrap as usize, true));
12609            }
12610            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12611        }
12612
12613        wrap_guides
12614    }
12615
12616    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12617        let settings = self.buffer.read(cx).settings_at(0, cx);
12618        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12619        match mode {
12620            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12621                SoftWrap::None
12622            }
12623            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12624            language_settings::SoftWrap::PreferredLineLength => {
12625                SoftWrap::Column(settings.preferred_line_length)
12626            }
12627            language_settings::SoftWrap::Bounded => {
12628                SoftWrap::Bounded(settings.preferred_line_length)
12629            }
12630        }
12631    }
12632
12633    pub fn set_soft_wrap_mode(
12634        &mut self,
12635        mode: language_settings::SoftWrap,
12636
12637        cx: &mut Context<Self>,
12638    ) {
12639        self.soft_wrap_mode_override = Some(mode);
12640        cx.notify();
12641    }
12642
12643    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12644        self.text_style_refinement = Some(style);
12645    }
12646
12647    /// called by the Element so we know what style we were most recently rendered with.
12648    pub(crate) fn set_style(
12649        &mut self,
12650        style: EditorStyle,
12651        window: &mut Window,
12652        cx: &mut Context<Self>,
12653    ) {
12654        let rem_size = window.rem_size();
12655        self.display_map.update(cx, |map, cx| {
12656            map.set_font(
12657                style.text.font(),
12658                style.text.font_size.to_pixels(rem_size),
12659                cx,
12660            )
12661        });
12662        self.style = Some(style);
12663    }
12664
12665    pub fn style(&self) -> Option<&EditorStyle> {
12666        self.style.as_ref()
12667    }
12668
12669    // Called by the element. This method is not designed to be called outside of the editor
12670    // element's layout code because it does not notify when rewrapping is computed synchronously.
12671    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12672        self.display_map
12673            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12674    }
12675
12676    pub fn set_soft_wrap(&mut self) {
12677        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12678    }
12679
12680    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12681        if self.soft_wrap_mode_override.is_some() {
12682            self.soft_wrap_mode_override.take();
12683        } else {
12684            let soft_wrap = match self.soft_wrap_mode(cx) {
12685                SoftWrap::GitDiff => return,
12686                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12687                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12688                    language_settings::SoftWrap::None
12689                }
12690            };
12691            self.soft_wrap_mode_override = Some(soft_wrap);
12692        }
12693        cx.notify();
12694    }
12695
12696    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12697        let Some(workspace) = self.workspace() else {
12698            return;
12699        };
12700        let fs = workspace.read(cx).app_state().fs.clone();
12701        let current_show = TabBarSettings::get_global(cx).show;
12702        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12703            setting.show = Some(!current_show);
12704        });
12705    }
12706
12707    pub fn toggle_indent_guides(
12708        &mut self,
12709        _: &ToggleIndentGuides,
12710        _: &mut Window,
12711        cx: &mut Context<Self>,
12712    ) {
12713        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12714            self.buffer
12715                .read(cx)
12716                .settings_at(0, cx)
12717                .indent_guides
12718                .enabled
12719        });
12720        self.show_indent_guides = Some(!currently_enabled);
12721        cx.notify();
12722    }
12723
12724    fn should_show_indent_guides(&self) -> Option<bool> {
12725        self.show_indent_guides
12726    }
12727
12728    pub fn toggle_line_numbers(
12729        &mut self,
12730        _: &ToggleLineNumbers,
12731        _: &mut Window,
12732        cx: &mut Context<Self>,
12733    ) {
12734        let mut editor_settings = EditorSettings::get_global(cx).clone();
12735        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12736        EditorSettings::override_global(editor_settings, cx);
12737    }
12738
12739    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12740        self.use_relative_line_numbers
12741            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12742    }
12743
12744    pub fn toggle_relative_line_numbers(
12745        &mut self,
12746        _: &ToggleRelativeLineNumbers,
12747        _: &mut Window,
12748        cx: &mut Context<Self>,
12749    ) {
12750        let is_relative = self.should_use_relative_line_numbers(cx);
12751        self.set_relative_line_number(Some(!is_relative), cx)
12752    }
12753
12754    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12755        self.use_relative_line_numbers = is_relative;
12756        cx.notify();
12757    }
12758
12759    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12760        self.show_gutter = show_gutter;
12761        cx.notify();
12762    }
12763
12764    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12765        self.show_scrollbars = show_scrollbars;
12766        cx.notify();
12767    }
12768
12769    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12770        self.show_line_numbers = Some(show_line_numbers);
12771        cx.notify();
12772    }
12773
12774    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12775        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12776        cx.notify();
12777    }
12778
12779    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12780        self.show_code_actions = Some(show_code_actions);
12781        cx.notify();
12782    }
12783
12784    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12785        self.show_runnables = Some(show_runnables);
12786        cx.notify();
12787    }
12788
12789    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12790        if self.display_map.read(cx).masked != masked {
12791            self.display_map.update(cx, |map, _| map.masked = masked);
12792        }
12793        cx.notify()
12794    }
12795
12796    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12797        self.show_wrap_guides = Some(show_wrap_guides);
12798        cx.notify();
12799    }
12800
12801    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12802        self.show_indent_guides = Some(show_indent_guides);
12803        cx.notify();
12804    }
12805
12806    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12807        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12808            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12809                if let Some(dir) = file.abs_path(cx).parent() {
12810                    return Some(dir.to_owned());
12811                }
12812            }
12813
12814            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12815                return Some(project_path.path.to_path_buf());
12816            }
12817        }
12818
12819        None
12820    }
12821
12822    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12823        self.active_excerpt(cx)?
12824            .1
12825            .read(cx)
12826            .file()
12827            .and_then(|f| f.as_local())
12828    }
12829
12830    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12831        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12832            let project_path = buffer.read(cx).project_path(cx)?;
12833            let project = self.project.as_ref()?.read(cx);
12834            project.absolute_path(&project_path, cx)
12835        })
12836    }
12837
12838    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12839        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12840            let project_path = buffer.read(cx).project_path(cx)?;
12841            let project = self.project.as_ref()?.read(cx);
12842            let entry = project.entry_for_path(&project_path, cx)?;
12843            let path = entry.path.to_path_buf();
12844            Some(path)
12845        })
12846    }
12847
12848    pub fn reveal_in_finder(
12849        &mut self,
12850        _: &RevealInFileManager,
12851        _window: &mut Window,
12852        cx: &mut Context<Self>,
12853    ) {
12854        if let Some(target) = self.target_file(cx) {
12855            cx.reveal_path(&target.abs_path(cx));
12856        }
12857    }
12858
12859    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12860        if let Some(path) = self.target_file_abs_path(cx) {
12861            if let Some(path) = path.to_str() {
12862                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12863            }
12864        }
12865    }
12866
12867    pub fn copy_relative_path(
12868        &mut self,
12869        _: &CopyRelativePath,
12870        _window: &mut Window,
12871        cx: &mut Context<Self>,
12872    ) {
12873        if let Some(path) = self.target_file_path(cx) {
12874            if let Some(path) = path.to_str() {
12875                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12876            }
12877        }
12878    }
12879
12880    pub fn copy_file_name_without_extension(
12881        &mut self,
12882        _: &CopyFileNameWithoutExtension,
12883        _: &mut Window,
12884        cx: &mut Context<Self>,
12885    ) {
12886        if let Some(file) = self.target_file(cx) {
12887            if let Some(file_stem) = file.path().file_stem() {
12888                if let Some(name) = file_stem.to_str() {
12889                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12890                }
12891            }
12892        }
12893    }
12894
12895    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
12896        if let Some(file) = self.target_file(cx) {
12897            if let Some(file_name) = file.path().file_name() {
12898                if let Some(name) = file_name.to_str() {
12899                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12900                }
12901            }
12902        }
12903    }
12904
12905    pub fn toggle_git_blame(
12906        &mut self,
12907        _: &ToggleGitBlame,
12908        window: &mut Window,
12909        cx: &mut Context<Self>,
12910    ) {
12911        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12912
12913        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12914            self.start_git_blame(true, window, cx);
12915        }
12916
12917        cx.notify();
12918    }
12919
12920    pub fn toggle_git_blame_inline(
12921        &mut self,
12922        _: &ToggleGitBlameInline,
12923        window: &mut Window,
12924        cx: &mut Context<Self>,
12925    ) {
12926        self.toggle_git_blame_inline_internal(true, window, cx);
12927        cx.notify();
12928    }
12929
12930    pub fn git_blame_inline_enabled(&self) -> bool {
12931        self.git_blame_inline_enabled
12932    }
12933
12934    pub fn toggle_selection_menu(
12935        &mut self,
12936        _: &ToggleSelectionMenu,
12937        _: &mut Window,
12938        cx: &mut Context<Self>,
12939    ) {
12940        self.show_selection_menu = self
12941            .show_selection_menu
12942            .map(|show_selections_menu| !show_selections_menu)
12943            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12944
12945        cx.notify();
12946    }
12947
12948    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12949        self.show_selection_menu
12950            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12951    }
12952
12953    fn start_git_blame(
12954        &mut self,
12955        user_triggered: bool,
12956        window: &mut Window,
12957        cx: &mut Context<Self>,
12958    ) {
12959        if let Some(project) = self.project.as_ref() {
12960            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12961                return;
12962            };
12963
12964            if buffer.read(cx).file().is_none() {
12965                return;
12966            }
12967
12968            let focused = self.focus_handle(cx).contains_focused(window, cx);
12969
12970            let project = project.clone();
12971            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12972            self.blame_subscription =
12973                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12974            self.blame = Some(blame);
12975        }
12976    }
12977
12978    fn toggle_git_blame_inline_internal(
12979        &mut self,
12980        user_triggered: bool,
12981        window: &mut Window,
12982        cx: &mut Context<Self>,
12983    ) {
12984        if self.git_blame_inline_enabled {
12985            self.git_blame_inline_enabled = false;
12986            self.show_git_blame_inline = false;
12987            self.show_git_blame_inline_delay_task.take();
12988        } else {
12989            self.git_blame_inline_enabled = true;
12990            self.start_git_blame_inline(user_triggered, window, cx);
12991        }
12992
12993        cx.notify();
12994    }
12995
12996    fn start_git_blame_inline(
12997        &mut self,
12998        user_triggered: bool,
12999        window: &mut Window,
13000        cx: &mut Context<Self>,
13001    ) {
13002        self.start_git_blame(user_triggered, window, cx);
13003
13004        if ProjectSettings::get_global(cx)
13005            .git
13006            .inline_blame_delay()
13007            .is_some()
13008        {
13009            self.start_inline_blame_timer(window, cx);
13010        } else {
13011            self.show_git_blame_inline = true
13012        }
13013    }
13014
13015    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13016        self.blame.as_ref()
13017    }
13018
13019    pub fn show_git_blame_gutter(&self) -> bool {
13020        self.show_git_blame_gutter
13021    }
13022
13023    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13024        self.show_git_blame_gutter && self.has_blame_entries(cx)
13025    }
13026
13027    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13028        self.show_git_blame_inline
13029            && self.focus_handle.is_focused(window)
13030            && !self.newest_selection_head_on_empty_line(cx)
13031            && self.has_blame_entries(cx)
13032    }
13033
13034    fn has_blame_entries(&self, cx: &App) -> bool {
13035        self.blame()
13036            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13037    }
13038
13039    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13040        let cursor_anchor = self.selections.newest_anchor().head();
13041
13042        let snapshot = self.buffer.read(cx).snapshot(cx);
13043        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13044
13045        snapshot.line_len(buffer_row) == 0
13046    }
13047
13048    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13049        let buffer_and_selection = maybe!({
13050            let selection = self.selections.newest::<Point>(cx);
13051            let selection_range = selection.range();
13052
13053            let multi_buffer = self.buffer().read(cx);
13054            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13055            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13056
13057            let (buffer, range, _) = if selection.reversed {
13058                buffer_ranges.first()
13059            } else {
13060                buffer_ranges.last()
13061            }?;
13062
13063            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13064                ..text::ToPoint::to_point(&range.end, &buffer).row;
13065            Some((
13066                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13067                selection,
13068            ))
13069        });
13070
13071        let Some((buffer, selection)) = buffer_and_selection else {
13072            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13073        };
13074
13075        let Some(project) = self.project.as_ref() else {
13076            return Task::ready(Err(anyhow!("editor does not have project")));
13077        };
13078
13079        project.update(cx, |project, cx| {
13080            project.get_permalink_to_line(&buffer, selection, cx)
13081        })
13082    }
13083
13084    pub fn copy_permalink_to_line(
13085        &mut self,
13086        _: &CopyPermalinkToLine,
13087        window: &mut Window,
13088        cx: &mut Context<Self>,
13089    ) {
13090        let permalink_task = self.get_permalink_to_line(cx);
13091        let workspace = self.workspace();
13092
13093        cx.spawn_in(window, |_, mut cx| async move {
13094            match permalink_task.await {
13095                Ok(permalink) => {
13096                    cx.update(|_, cx| {
13097                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13098                    })
13099                    .ok();
13100                }
13101                Err(err) => {
13102                    let message = format!("Failed to copy permalink: {err}");
13103
13104                    Err::<(), anyhow::Error>(err).log_err();
13105
13106                    if let Some(workspace) = workspace {
13107                        workspace
13108                            .update_in(&mut cx, |workspace, _, cx| {
13109                                struct CopyPermalinkToLine;
13110
13111                                workspace.show_toast(
13112                                    Toast::new(
13113                                        NotificationId::unique::<CopyPermalinkToLine>(),
13114                                        message,
13115                                    ),
13116                                    cx,
13117                                )
13118                            })
13119                            .ok();
13120                    }
13121                }
13122            }
13123        })
13124        .detach();
13125    }
13126
13127    pub fn copy_file_location(
13128        &mut self,
13129        _: &CopyFileLocation,
13130        _: &mut Window,
13131        cx: &mut Context<Self>,
13132    ) {
13133        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13134        if let Some(file) = self.target_file(cx) {
13135            if let Some(path) = file.path().to_str() {
13136                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13137            }
13138        }
13139    }
13140
13141    pub fn open_permalink_to_line(
13142        &mut self,
13143        _: &OpenPermalinkToLine,
13144        window: &mut Window,
13145        cx: &mut Context<Self>,
13146    ) {
13147        let permalink_task = self.get_permalink_to_line(cx);
13148        let workspace = self.workspace();
13149
13150        cx.spawn_in(window, |_, mut cx| async move {
13151            match permalink_task.await {
13152                Ok(permalink) => {
13153                    cx.update(|_, cx| {
13154                        cx.open_url(permalink.as_ref());
13155                    })
13156                    .ok();
13157                }
13158                Err(err) => {
13159                    let message = format!("Failed to open permalink: {err}");
13160
13161                    Err::<(), anyhow::Error>(err).log_err();
13162
13163                    if let Some(workspace) = workspace {
13164                        workspace
13165                            .update(&mut cx, |workspace, cx| {
13166                                struct OpenPermalinkToLine;
13167
13168                                workspace.show_toast(
13169                                    Toast::new(
13170                                        NotificationId::unique::<OpenPermalinkToLine>(),
13171                                        message,
13172                                    ),
13173                                    cx,
13174                                )
13175                            })
13176                            .ok();
13177                    }
13178                }
13179            }
13180        })
13181        .detach();
13182    }
13183
13184    pub fn insert_uuid_v4(
13185        &mut self,
13186        _: &InsertUuidV4,
13187        window: &mut Window,
13188        cx: &mut Context<Self>,
13189    ) {
13190        self.insert_uuid(UuidVersion::V4, window, cx);
13191    }
13192
13193    pub fn insert_uuid_v7(
13194        &mut self,
13195        _: &InsertUuidV7,
13196        window: &mut Window,
13197        cx: &mut Context<Self>,
13198    ) {
13199        self.insert_uuid(UuidVersion::V7, window, cx);
13200    }
13201
13202    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13203        self.transact(window, cx, |this, window, cx| {
13204            let edits = this
13205                .selections
13206                .all::<Point>(cx)
13207                .into_iter()
13208                .map(|selection| {
13209                    let uuid = match version {
13210                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13211                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13212                    };
13213
13214                    (selection.range(), uuid.to_string())
13215                });
13216            this.edit(edits, cx);
13217            this.refresh_inline_completion(true, false, window, cx);
13218        });
13219    }
13220
13221    pub fn open_selections_in_multibuffer(
13222        &mut self,
13223        _: &OpenSelectionsInMultibuffer,
13224        window: &mut Window,
13225        cx: &mut Context<Self>,
13226    ) {
13227        let multibuffer = self.buffer.read(cx);
13228
13229        let Some(buffer) = multibuffer.as_singleton() else {
13230            return;
13231        };
13232
13233        let Some(workspace) = self.workspace() else {
13234            return;
13235        };
13236
13237        let locations = self
13238            .selections
13239            .disjoint_anchors()
13240            .iter()
13241            .map(|range| Location {
13242                buffer: buffer.clone(),
13243                range: range.start.text_anchor..range.end.text_anchor,
13244            })
13245            .collect::<Vec<_>>();
13246
13247        let title = multibuffer.title(cx).to_string();
13248
13249        cx.spawn_in(window, |_, mut cx| async move {
13250            workspace.update_in(&mut cx, |workspace, window, cx| {
13251                Self::open_locations_in_multibuffer(
13252                    workspace,
13253                    locations,
13254                    format!("Selections for '{title}'"),
13255                    false,
13256                    MultibufferSelectionMode::All,
13257                    window,
13258                    cx,
13259                );
13260            })
13261        })
13262        .detach();
13263    }
13264
13265    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13266    /// last highlight added will be used.
13267    ///
13268    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13269    pub fn highlight_rows<T: 'static>(
13270        &mut self,
13271        range: Range<Anchor>,
13272        color: Hsla,
13273        should_autoscroll: bool,
13274        cx: &mut Context<Self>,
13275    ) {
13276        let snapshot = self.buffer().read(cx).snapshot(cx);
13277        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13278        let ix = row_highlights.binary_search_by(|highlight| {
13279            Ordering::Equal
13280                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13281                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13282        });
13283
13284        if let Err(mut ix) = ix {
13285            let index = post_inc(&mut self.highlight_order);
13286
13287            // If this range intersects with the preceding highlight, then merge it with
13288            // the preceding highlight. Otherwise insert a new highlight.
13289            let mut merged = false;
13290            if ix > 0 {
13291                let prev_highlight = &mut row_highlights[ix - 1];
13292                if prev_highlight
13293                    .range
13294                    .end
13295                    .cmp(&range.start, &snapshot)
13296                    .is_ge()
13297                {
13298                    ix -= 1;
13299                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13300                        prev_highlight.range.end = range.end;
13301                    }
13302                    merged = true;
13303                    prev_highlight.index = index;
13304                    prev_highlight.color = color;
13305                    prev_highlight.should_autoscroll = should_autoscroll;
13306                }
13307            }
13308
13309            if !merged {
13310                row_highlights.insert(
13311                    ix,
13312                    RowHighlight {
13313                        range: range.clone(),
13314                        index,
13315                        color,
13316                        should_autoscroll,
13317                    },
13318                );
13319            }
13320
13321            // If any of the following highlights intersect with this one, merge them.
13322            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13323                let highlight = &row_highlights[ix];
13324                if next_highlight
13325                    .range
13326                    .start
13327                    .cmp(&highlight.range.end, &snapshot)
13328                    .is_le()
13329                {
13330                    if next_highlight
13331                        .range
13332                        .end
13333                        .cmp(&highlight.range.end, &snapshot)
13334                        .is_gt()
13335                    {
13336                        row_highlights[ix].range.end = next_highlight.range.end;
13337                    }
13338                    row_highlights.remove(ix + 1);
13339                } else {
13340                    break;
13341                }
13342            }
13343        }
13344    }
13345
13346    /// Remove any highlighted row ranges of the given type that intersect the
13347    /// given ranges.
13348    pub fn remove_highlighted_rows<T: 'static>(
13349        &mut self,
13350        ranges_to_remove: Vec<Range<Anchor>>,
13351        cx: &mut Context<Self>,
13352    ) {
13353        let snapshot = self.buffer().read(cx).snapshot(cx);
13354        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13355        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13356        row_highlights.retain(|highlight| {
13357            while let Some(range_to_remove) = ranges_to_remove.peek() {
13358                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13359                    Ordering::Less | Ordering::Equal => {
13360                        ranges_to_remove.next();
13361                    }
13362                    Ordering::Greater => {
13363                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13364                            Ordering::Less | Ordering::Equal => {
13365                                return false;
13366                            }
13367                            Ordering::Greater => break,
13368                        }
13369                    }
13370                }
13371            }
13372
13373            true
13374        })
13375    }
13376
13377    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13378    pub fn clear_row_highlights<T: 'static>(&mut self) {
13379        self.highlighted_rows.remove(&TypeId::of::<T>());
13380    }
13381
13382    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13383    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13384        self.highlighted_rows
13385            .get(&TypeId::of::<T>())
13386            .map_or(&[] as &[_], |vec| vec.as_slice())
13387            .iter()
13388            .map(|highlight| (highlight.range.clone(), highlight.color))
13389    }
13390
13391    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13392    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13393    /// Allows to ignore certain kinds of highlights.
13394    pub fn highlighted_display_rows(
13395        &self,
13396        window: &mut Window,
13397        cx: &mut App,
13398    ) -> BTreeMap<DisplayRow, Background> {
13399        let snapshot = self.snapshot(window, cx);
13400        let mut used_highlight_orders = HashMap::default();
13401        self.highlighted_rows
13402            .iter()
13403            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13404            .fold(
13405                BTreeMap::<DisplayRow, Background>::new(),
13406                |mut unique_rows, highlight| {
13407                    let start = highlight.range.start.to_display_point(&snapshot);
13408                    let end = highlight.range.end.to_display_point(&snapshot);
13409                    let start_row = start.row().0;
13410                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13411                        && end.column() == 0
13412                    {
13413                        end.row().0.saturating_sub(1)
13414                    } else {
13415                        end.row().0
13416                    };
13417                    for row in start_row..=end_row {
13418                        let used_index =
13419                            used_highlight_orders.entry(row).or_insert(highlight.index);
13420                        if highlight.index >= *used_index {
13421                            *used_index = highlight.index;
13422                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13423                        }
13424                    }
13425                    unique_rows
13426                },
13427            )
13428    }
13429
13430    pub fn highlighted_display_row_for_autoscroll(
13431        &self,
13432        snapshot: &DisplaySnapshot,
13433    ) -> Option<DisplayRow> {
13434        self.highlighted_rows
13435            .values()
13436            .flat_map(|highlighted_rows| highlighted_rows.iter())
13437            .filter_map(|highlight| {
13438                if highlight.should_autoscroll {
13439                    Some(highlight.range.start.to_display_point(snapshot).row())
13440                } else {
13441                    None
13442                }
13443            })
13444            .min()
13445    }
13446
13447    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13448        self.highlight_background::<SearchWithinRange>(
13449            ranges,
13450            |colors| colors.editor_document_highlight_read_background,
13451            cx,
13452        )
13453    }
13454
13455    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13456        self.breadcrumb_header = Some(new_header);
13457    }
13458
13459    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13460        self.clear_background_highlights::<SearchWithinRange>(cx);
13461    }
13462
13463    pub fn highlight_background<T: 'static>(
13464        &mut self,
13465        ranges: &[Range<Anchor>],
13466        color_fetcher: fn(&ThemeColors) -> Hsla,
13467        cx: &mut Context<Self>,
13468    ) {
13469        self.background_highlights
13470            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13471        self.scrollbar_marker_state.dirty = true;
13472        cx.notify();
13473    }
13474
13475    pub fn clear_background_highlights<T: 'static>(
13476        &mut self,
13477        cx: &mut Context<Self>,
13478    ) -> Option<BackgroundHighlight> {
13479        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13480        if !text_highlights.1.is_empty() {
13481            self.scrollbar_marker_state.dirty = true;
13482            cx.notify();
13483        }
13484        Some(text_highlights)
13485    }
13486
13487    pub fn highlight_gutter<T: 'static>(
13488        &mut self,
13489        ranges: &[Range<Anchor>],
13490        color_fetcher: fn(&App) -> Hsla,
13491        cx: &mut Context<Self>,
13492    ) {
13493        self.gutter_highlights
13494            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13495        cx.notify();
13496    }
13497
13498    pub fn clear_gutter_highlights<T: 'static>(
13499        &mut self,
13500        cx: &mut Context<Self>,
13501    ) -> Option<GutterHighlight> {
13502        cx.notify();
13503        self.gutter_highlights.remove(&TypeId::of::<T>())
13504    }
13505
13506    #[cfg(feature = "test-support")]
13507    pub fn all_text_background_highlights(
13508        &self,
13509        window: &mut Window,
13510        cx: &mut Context<Self>,
13511    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13512        let snapshot = self.snapshot(window, cx);
13513        let buffer = &snapshot.buffer_snapshot;
13514        let start = buffer.anchor_before(0);
13515        let end = buffer.anchor_after(buffer.len());
13516        let theme = cx.theme().colors();
13517        self.background_highlights_in_range(start..end, &snapshot, theme)
13518    }
13519
13520    #[cfg(feature = "test-support")]
13521    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13522        let snapshot = self.buffer().read(cx).snapshot(cx);
13523
13524        let highlights = self
13525            .background_highlights
13526            .get(&TypeId::of::<items::BufferSearchHighlights>());
13527
13528        if let Some((_color, ranges)) = highlights {
13529            ranges
13530                .iter()
13531                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13532                .collect_vec()
13533        } else {
13534            vec![]
13535        }
13536    }
13537
13538    fn document_highlights_for_position<'a>(
13539        &'a self,
13540        position: Anchor,
13541        buffer: &'a MultiBufferSnapshot,
13542    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13543        let read_highlights = self
13544            .background_highlights
13545            .get(&TypeId::of::<DocumentHighlightRead>())
13546            .map(|h| &h.1);
13547        let write_highlights = self
13548            .background_highlights
13549            .get(&TypeId::of::<DocumentHighlightWrite>())
13550            .map(|h| &h.1);
13551        let left_position = position.bias_left(buffer);
13552        let right_position = position.bias_right(buffer);
13553        read_highlights
13554            .into_iter()
13555            .chain(write_highlights)
13556            .flat_map(move |ranges| {
13557                let start_ix = match ranges.binary_search_by(|probe| {
13558                    let cmp = probe.end.cmp(&left_position, buffer);
13559                    if cmp.is_ge() {
13560                        Ordering::Greater
13561                    } else {
13562                        Ordering::Less
13563                    }
13564                }) {
13565                    Ok(i) | Err(i) => i,
13566                };
13567
13568                ranges[start_ix..]
13569                    .iter()
13570                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13571            })
13572    }
13573
13574    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13575        self.background_highlights
13576            .get(&TypeId::of::<T>())
13577            .map_or(false, |(_, highlights)| !highlights.is_empty())
13578    }
13579
13580    pub fn background_highlights_in_range(
13581        &self,
13582        search_range: Range<Anchor>,
13583        display_snapshot: &DisplaySnapshot,
13584        theme: &ThemeColors,
13585    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13586        let mut results = Vec::new();
13587        for (color_fetcher, ranges) in self.background_highlights.values() {
13588            let color = color_fetcher(theme);
13589            let start_ix = match ranges.binary_search_by(|probe| {
13590                let cmp = probe
13591                    .end
13592                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13593                if cmp.is_gt() {
13594                    Ordering::Greater
13595                } else {
13596                    Ordering::Less
13597                }
13598            }) {
13599                Ok(i) | Err(i) => i,
13600            };
13601            for range in &ranges[start_ix..] {
13602                if range
13603                    .start
13604                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13605                    .is_ge()
13606                {
13607                    break;
13608                }
13609
13610                let start = range.start.to_display_point(display_snapshot);
13611                let end = range.end.to_display_point(display_snapshot);
13612                results.push((start..end, color))
13613            }
13614        }
13615        results
13616    }
13617
13618    pub fn background_highlight_row_ranges<T: 'static>(
13619        &self,
13620        search_range: Range<Anchor>,
13621        display_snapshot: &DisplaySnapshot,
13622        count: usize,
13623    ) -> Vec<RangeInclusive<DisplayPoint>> {
13624        let mut results = Vec::new();
13625        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13626            return vec![];
13627        };
13628
13629        let start_ix = match ranges.binary_search_by(|probe| {
13630            let cmp = probe
13631                .end
13632                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13633            if cmp.is_gt() {
13634                Ordering::Greater
13635            } else {
13636                Ordering::Less
13637            }
13638        }) {
13639            Ok(i) | Err(i) => i,
13640        };
13641        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13642            if let (Some(start_display), Some(end_display)) = (start, end) {
13643                results.push(
13644                    start_display.to_display_point(display_snapshot)
13645                        ..=end_display.to_display_point(display_snapshot),
13646                );
13647            }
13648        };
13649        let mut start_row: Option<Point> = None;
13650        let mut end_row: Option<Point> = None;
13651        if ranges.len() > count {
13652            return Vec::new();
13653        }
13654        for range in &ranges[start_ix..] {
13655            if range
13656                .start
13657                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13658                .is_ge()
13659            {
13660                break;
13661            }
13662            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13663            if let Some(current_row) = &end_row {
13664                if end.row == current_row.row {
13665                    continue;
13666                }
13667            }
13668            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13669            if start_row.is_none() {
13670                assert_eq!(end_row, None);
13671                start_row = Some(start);
13672                end_row = Some(end);
13673                continue;
13674            }
13675            if let Some(current_end) = end_row.as_mut() {
13676                if start.row > current_end.row + 1 {
13677                    push_region(start_row, end_row);
13678                    start_row = Some(start);
13679                    end_row = Some(end);
13680                } else {
13681                    // Merge two hunks.
13682                    *current_end = end;
13683                }
13684            } else {
13685                unreachable!();
13686            }
13687        }
13688        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13689        push_region(start_row, end_row);
13690        results
13691    }
13692
13693    pub fn gutter_highlights_in_range(
13694        &self,
13695        search_range: Range<Anchor>,
13696        display_snapshot: &DisplaySnapshot,
13697        cx: &App,
13698    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13699        let mut results = Vec::new();
13700        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13701            let color = color_fetcher(cx);
13702            let start_ix = match ranges.binary_search_by(|probe| {
13703                let cmp = probe
13704                    .end
13705                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13706                if cmp.is_gt() {
13707                    Ordering::Greater
13708                } else {
13709                    Ordering::Less
13710                }
13711            }) {
13712                Ok(i) | Err(i) => i,
13713            };
13714            for range in &ranges[start_ix..] {
13715                if range
13716                    .start
13717                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13718                    .is_ge()
13719                {
13720                    break;
13721                }
13722
13723                let start = range.start.to_display_point(display_snapshot);
13724                let end = range.end.to_display_point(display_snapshot);
13725                results.push((start..end, color))
13726            }
13727        }
13728        results
13729    }
13730
13731    /// Get the text ranges corresponding to the redaction query
13732    pub fn redacted_ranges(
13733        &self,
13734        search_range: Range<Anchor>,
13735        display_snapshot: &DisplaySnapshot,
13736        cx: &App,
13737    ) -> Vec<Range<DisplayPoint>> {
13738        display_snapshot
13739            .buffer_snapshot
13740            .redacted_ranges(search_range, |file| {
13741                if let Some(file) = file {
13742                    file.is_private()
13743                        && EditorSettings::get(
13744                            Some(SettingsLocation {
13745                                worktree_id: file.worktree_id(cx),
13746                                path: file.path().as_ref(),
13747                            }),
13748                            cx,
13749                        )
13750                        .redact_private_values
13751                } else {
13752                    false
13753                }
13754            })
13755            .map(|range| {
13756                range.start.to_display_point(display_snapshot)
13757                    ..range.end.to_display_point(display_snapshot)
13758            })
13759            .collect()
13760    }
13761
13762    pub fn highlight_text<T: 'static>(
13763        &mut self,
13764        ranges: Vec<Range<Anchor>>,
13765        style: HighlightStyle,
13766        cx: &mut Context<Self>,
13767    ) {
13768        self.display_map.update(cx, |map, _| {
13769            map.highlight_text(TypeId::of::<T>(), ranges, style)
13770        });
13771        cx.notify();
13772    }
13773
13774    pub(crate) fn highlight_inlays<T: 'static>(
13775        &mut self,
13776        highlights: Vec<InlayHighlight>,
13777        style: HighlightStyle,
13778        cx: &mut Context<Self>,
13779    ) {
13780        self.display_map.update(cx, |map, _| {
13781            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13782        });
13783        cx.notify();
13784    }
13785
13786    pub fn text_highlights<'a, T: 'static>(
13787        &'a self,
13788        cx: &'a App,
13789    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13790        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13791    }
13792
13793    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13794        let cleared = self
13795            .display_map
13796            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13797        if cleared {
13798            cx.notify();
13799        }
13800    }
13801
13802    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13803        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13804            && self.focus_handle.is_focused(window)
13805    }
13806
13807    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13808        self.show_cursor_when_unfocused = is_enabled;
13809        cx.notify();
13810    }
13811
13812    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13813        self.project
13814            .as_ref()
13815            .map(|project| project.read(cx).lsp_store())
13816    }
13817
13818    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13819        cx.notify();
13820    }
13821
13822    fn on_buffer_event(
13823        &mut self,
13824        multibuffer: &Entity<MultiBuffer>,
13825        event: &multi_buffer::Event,
13826        window: &mut Window,
13827        cx: &mut Context<Self>,
13828    ) {
13829        match event {
13830            multi_buffer::Event::Edited {
13831                singleton_buffer_edited,
13832                edited_buffer: buffer_edited,
13833            } => {
13834                self.scrollbar_marker_state.dirty = true;
13835                self.active_indent_guides_state.dirty = true;
13836                self.refresh_active_diagnostics(cx);
13837                self.refresh_code_actions(window, cx);
13838                if self.has_active_inline_completion() {
13839                    self.update_visible_inline_completion(window, cx);
13840                }
13841                if let Some(buffer) = buffer_edited {
13842                    let buffer_id = buffer.read(cx).remote_id();
13843                    if !self.registered_buffers.contains_key(&buffer_id) {
13844                        if let Some(lsp_store) = self.lsp_store(cx) {
13845                            lsp_store.update(cx, |lsp_store, cx| {
13846                                self.registered_buffers.insert(
13847                                    buffer_id,
13848                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13849                                );
13850                            })
13851                        }
13852                    }
13853                }
13854                cx.emit(EditorEvent::BufferEdited);
13855                cx.emit(SearchEvent::MatchesInvalidated);
13856                if *singleton_buffer_edited {
13857                    if let Some(project) = &self.project {
13858                        let project = project.read(cx);
13859                        #[allow(clippy::mutable_key_type)]
13860                        let languages_affected = multibuffer
13861                            .read(cx)
13862                            .all_buffers()
13863                            .into_iter()
13864                            .filter_map(|buffer| {
13865                                let buffer = buffer.read(cx);
13866                                let language = buffer.language()?;
13867                                if project.is_local()
13868                                    && project
13869                                        .language_servers_for_local_buffer(buffer, cx)
13870                                        .count()
13871                                        == 0
13872                                {
13873                                    None
13874                                } else {
13875                                    Some(language)
13876                                }
13877                            })
13878                            .cloned()
13879                            .collect::<HashSet<_>>();
13880                        if !languages_affected.is_empty() {
13881                            self.refresh_inlay_hints(
13882                                InlayHintRefreshReason::BufferEdited(languages_affected),
13883                                cx,
13884                            );
13885                        }
13886                    }
13887                }
13888
13889                let Some(project) = &self.project else { return };
13890                let (telemetry, is_via_ssh) = {
13891                    let project = project.read(cx);
13892                    let telemetry = project.client().telemetry().clone();
13893                    let is_via_ssh = project.is_via_ssh();
13894                    (telemetry, is_via_ssh)
13895                };
13896                refresh_linked_ranges(self, window, cx);
13897                telemetry.log_edit_event("editor", is_via_ssh);
13898            }
13899            multi_buffer::Event::ExcerptsAdded {
13900                buffer,
13901                predecessor,
13902                excerpts,
13903            } => {
13904                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13905                let buffer_id = buffer.read(cx).remote_id();
13906                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13907                    if let Some(project) = &self.project {
13908                        get_uncommitted_diff_for_buffer(
13909                            project,
13910                            [buffer.clone()],
13911                            self.buffer.clone(),
13912                            cx,
13913                        );
13914                    }
13915                }
13916                cx.emit(EditorEvent::ExcerptsAdded {
13917                    buffer: buffer.clone(),
13918                    predecessor: *predecessor,
13919                    excerpts: excerpts.clone(),
13920                });
13921                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13922            }
13923            multi_buffer::Event::ExcerptsRemoved { ids } => {
13924                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13925                let buffer = self.buffer.read(cx);
13926                self.registered_buffers
13927                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13928                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13929            }
13930            multi_buffer::Event::ExcerptsEdited { ids } => {
13931                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13932            }
13933            multi_buffer::Event::ExcerptsExpanded { ids } => {
13934                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13935                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13936            }
13937            multi_buffer::Event::Reparsed(buffer_id) => {
13938                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13939
13940                cx.emit(EditorEvent::Reparsed(*buffer_id));
13941            }
13942            multi_buffer::Event::DiffHunksToggled => {
13943                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13944            }
13945            multi_buffer::Event::LanguageChanged(buffer_id) => {
13946                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13947                cx.emit(EditorEvent::Reparsed(*buffer_id));
13948                cx.notify();
13949            }
13950            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13951            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13952            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13953                cx.emit(EditorEvent::TitleChanged)
13954            }
13955            // multi_buffer::Event::DiffBaseChanged => {
13956            //     self.scrollbar_marker_state.dirty = true;
13957            //     cx.emit(EditorEvent::DiffBaseChanged);
13958            //     cx.notify();
13959            // }
13960            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13961            multi_buffer::Event::DiagnosticsUpdated => {
13962                self.refresh_active_diagnostics(cx);
13963                self.scrollbar_marker_state.dirty = true;
13964                cx.notify();
13965            }
13966            _ => {}
13967        };
13968    }
13969
13970    fn on_display_map_changed(
13971        &mut self,
13972        _: Entity<DisplayMap>,
13973        _: &mut Window,
13974        cx: &mut Context<Self>,
13975    ) {
13976        cx.notify();
13977    }
13978
13979    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13980        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13981        self.refresh_inline_completion(true, false, window, cx);
13982        self.refresh_inlay_hints(
13983            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13984                self.selections.newest_anchor().head(),
13985                &self.buffer.read(cx).snapshot(cx),
13986                cx,
13987            )),
13988            cx,
13989        );
13990
13991        let old_cursor_shape = self.cursor_shape;
13992
13993        {
13994            let editor_settings = EditorSettings::get_global(cx);
13995            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13996            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13997            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13998        }
13999
14000        if old_cursor_shape != self.cursor_shape {
14001            cx.emit(EditorEvent::CursorShapeChanged);
14002        }
14003
14004        let project_settings = ProjectSettings::get_global(cx);
14005        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14006
14007        if self.mode == EditorMode::Full {
14008            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14009            if self.git_blame_inline_enabled != inline_blame_enabled {
14010                self.toggle_git_blame_inline_internal(false, window, cx);
14011            }
14012        }
14013
14014        cx.notify();
14015    }
14016
14017    pub fn set_searchable(&mut self, searchable: bool) {
14018        self.searchable = searchable;
14019    }
14020
14021    pub fn searchable(&self) -> bool {
14022        self.searchable
14023    }
14024
14025    fn open_proposed_changes_editor(
14026        &mut self,
14027        _: &OpenProposedChangesEditor,
14028        window: &mut Window,
14029        cx: &mut Context<Self>,
14030    ) {
14031        let Some(workspace) = self.workspace() else {
14032            cx.propagate();
14033            return;
14034        };
14035
14036        let selections = self.selections.all::<usize>(cx);
14037        let multi_buffer = self.buffer.read(cx);
14038        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14039        let mut new_selections_by_buffer = HashMap::default();
14040        for selection in selections {
14041            for (buffer, range, _) in
14042                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14043            {
14044                let mut range = range.to_point(buffer);
14045                range.start.column = 0;
14046                range.end.column = buffer.line_len(range.end.row);
14047                new_selections_by_buffer
14048                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14049                    .or_insert(Vec::new())
14050                    .push(range)
14051            }
14052        }
14053
14054        let proposed_changes_buffers = new_selections_by_buffer
14055            .into_iter()
14056            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14057            .collect::<Vec<_>>();
14058        let proposed_changes_editor = cx.new(|cx| {
14059            ProposedChangesEditor::new(
14060                "Proposed changes",
14061                proposed_changes_buffers,
14062                self.project.clone(),
14063                window,
14064                cx,
14065            )
14066        });
14067
14068        window.defer(cx, move |window, cx| {
14069            workspace.update(cx, |workspace, cx| {
14070                workspace.active_pane().update(cx, |pane, cx| {
14071                    pane.add_item(
14072                        Box::new(proposed_changes_editor),
14073                        true,
14074                        true,
14075                        None,
14076                        window,
14077                        cx,
14078                    );
14079                });
14080            });
14081        });
14082    }
14083
14084    pub fn open_excerpts_in_split(
14085        &mut self,
14086        _: &OpenExcerptsSplit,
14087        window: &mut Window,
14088        cx: &mut Context<Self>,
14089    ) {
14090        self.open_excerpts_common(None, true, window, cx)
14091    }
14092
14093    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14094        self.open_excerpts_common(None, false, window, cx)
14095    }
14096
14097    fn open_excerpts_common(
14098        &mut self,
14099        jump_data: Option<JumpData>,
14100        split: bool,
14101        window: &mut Window,
14102        cx: &mut Context<Self>,
14103    ) {
14104        let Some(workspace) = self.workspace() else {
14105            cx.propagate();
14106            return;
14107        };
14108
14109        if self.buffer.read(cx).is_singleton() {
14110            cx.propagate();
14111            return;
14112        }
14113
14114        let mut new_selections_by_buffer = HashMap::default();
14115        match &jump_data {
14116            Some(JumpData::MultiBufferPoint {
14117                excerpt_id,
14118                position,
14119                anchor,
14120                line_offset_from_top,
14121            }) => {
14122                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14123                if let Some(buffer) = multi_buffer_snapshot
14124                    .buffer_id_for_excerpt(*excerpt_id)
14125                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14126                {
14127                    let buffer_snapshot = buffer.read(cx).snapshot();
14128                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14129                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14130                    } else {
14131                        buffer_snapshot.clip_point(*position, Bias::Left)
14132                    };
14133                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14134                    new_selections_by_buffer.insert(
14135                        buffer,
14136                        (
14137                            vec![jump_to_offset..jump_to_offset],
14138                            Some(*line_offset_from_top),
14139                        ),
14140                    );
14141                }
14142            }
14143            Some(JumpData::MultiBufferRow {
14144                row,
14145                line_offset_from_top,
14146            }) => {
14147                let point = MultiBufferPoint::new(row.0, 0);
14148                if let Some((buffer, buffer_point, _)) =
14149                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14150                {
14151                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14152                    new_selections_by_buffer
14153                        .entry(buffer)
14154                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14155                        .0
14156                        .push(buffer_offset..buffer_offset)
14157                }
14158            }
14159            None => {
14160                let selections = self.selections.all::<usize>(cx);
14161                let multi_buffer = self.buffer.read(cx);
14162                for selection in selections {
14163                    for (buffer, mut range, _) in multi_buffer
14164                        .snapshot(cx)
14165                        .range_to_buffer_ranges(selection.range())
14166                    {
14167                        // When editing branch buffers, jump to the corresponding location
14168                        // in their base buffer.
14169                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14170                        let buffer = buffer_handle.read(cx);
14171                        if let Some(base_buffer) = buffer.base_buffer() {
14172                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14173                            buffer_handle = base_buffer;
14174                        }
14175
14176                        if selection.reversed {
14177                            mem::swap(&mut range.start, &mut range.end);
14178                        }
14179                        new_selections_by_buffer
14180                            .entry(buffer_handle)
14181                            .or_insert((Vec::new(), None))
14182                            .0
14183                            .push(range)
14184                    }
14185                }
14186            }
14187        }
14188
14189        if new_selections_by_buffer.is_empty() {
14190            return;
14191        }
14192
14193        // We defer the pane interaction because we ourselves are a workspace item
14194        // and activating a new item causes the pane to call a method on us reentrantly,
14195        // which panics if we're on the stack.
14196        window.defer(cx, move |window, cx| {
14197            workspace.update(cx, |workspace, cx| {
14198                let pane = if split {
14199                    workspace.adjacent_pane(window, cx)
14200                } else {
14201                    workspace.active_pane().clone()
14202                };
14203
14204                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14205                    let editor = buffer
14206                        .read(cx)
14207                        .file()
14208                        .is_none()
14209                        .then(|| {
14210                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14211                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14212                            // Instead, we try to activate the existing editor in the pane first.
14213                            let (editor, pane_item_index) =
14214                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14215                                    let editor = item.downcast::<Editor>()?;
14216                                    let singleton_buffer =
14217                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14218                                    if singleton_buffer == buffer {
14219                                        Some((editor, i))
14220                                    } else {
14221                                        None
14222                                    }
14223                                })?;
14224                            pane.update(cx, |pane, cx| {
14225                                pane.activate_item(pane_item_index, true, true, window, cx)
14226                            });
14227                            Some(editor)
14228                        })
14229                        .flatten()
14230                        .unwrap_or_else(|| {
14231                            workspace.open_project_item::<Self>(
14232                                pane.clone(),
14233                                buffer,
14234                                true,
14235                                true,
14236                                window,
14237                                cx,
14238                            )
14239                        });
14240
14241                    editor.update(cx, |editor, cx| {
14242                        let autoscroll = match scroll_offset {
14243                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14244                            None => Autoscroll::newest(),
14245                        };
14246                        let nav_history = editor.nav_history.take();
14247                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14248                            s.select_ranges(ranges);
14249                        });
14250                        editor.nav_history = nav_history;
14251                    });
14252                }
14253            })
14254        });
14255    }
14256
14257    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14258        let snapshot = self.buffer.read(cx).read(cx);
14259        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14260        Some(
14261            ranges
14262                .iter()
14263                .map(move |range| {
14264                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14265                })
14266                .collect(),
14267        )
14268    }
14269
14270    fn selection_replacement_ranges(
14271        &self,
14272        range: Range<OffsetUtf16>,
14273        cx: &mut App,
14274    ) -> Vec<Range<OffsetUtf16>> {
14275        let selections = self.selections.all::<OffsetUtf16>(cx);
14276        let newest_selection = selections
14277            .iter()
14278            .max_by_key(|selection| selection.id)
14279            .unwrap();
14280        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14281        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14282        let snapshot = self.buffer.read(cx).read(cx);
14283        selections
14284            .into_iter()
14285            .map(|mut selection| {
14286                selection.start.0 =
14287                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14288                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14289                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14290                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14291            })
14292            .collect()
14293    }
14294
14295    fn report_editor_event(
14296        &self,
14297        event_type: &'static str,
14298        file_extension: Option<String>,
14299        cx: &App,
14300    ) {
14301        if cfg!(any(test, feature = "test-support")) {
14302            return;
14303        }
14304
14305        let Some(project) = &self.project else { return };
14306
14307        // If None, we are in a file without an extension
14308        let file = self
14309            .buffer
14310            .read(cx)
14311            .as_singleton()
14312            .and_then(|b| b.read(cx).file());
14313        let file_extension = file_extension.or(file
14314            .as_ref()
14315            .and_then(|file| Path::new(file.file_name(cx)).extension())
14316            .and_then(|e| e.to_str())
14317            .map(|a| a.to_string()));
14318
14319        let vim_mode = cx
14320            .global::<SettingsStore>()
14321            .raw_user_settings()
14322            .get("vim_mode")
14323            == Some(&serde_json::Value::Bool(true));
14324
14325        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14326        let copilot_enabled = edit_predictions_provider
14327            == language::language_settings::EditPredictionProvider::Copilot;
14328        let copilot_enabled_for_language = self
14329            .buffer
14330            .read(cx)
14331            .settings_at(0, cx)
14332            .show_edit_predictions;
14333
14334        let project = project.read(cx);
14335        telemetry::event!(
14336            event_type,
14337            file_extension,
14338            vim_mode,
14339            copilot_enabled,
14340            copilot_enabled_for_language,
14341            edit_predictions_provider,
14342            is_via_ssh = project.is_via_ssh(),
14343        );
14344    }
14345
14346    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14347    /// with each line being an array of {text, highlight} objects.
14348    fn copy_highlight_json(
14349        &mut self,
14350        _: &CopyHighlightJson,
14351        window: &mut Window,
14352        cx: &mut Context<Self>,
14353    ) {
14354        #[derive(Serialize)]
14355        struct Chunk<'a> {
14356            text: String,
14357            highlight: Option<&'a str>,
14358        }
14359
14360        let snapshot = self.buffer.read(cx).snapshot(cx);
14361        let range = self
14362            .selected_text_range(false, window, cx)
14363            .and_then(|selection| {
14364                if selection.range.is_empty() {
14365                    None
14366                } else {
14367                    Some(selection.range)
14368                }
14369            })
14370            .unwrap_or_else(|| 0..snapshot.len());
14371
14372        let chunks = snapshot.chunks(range, true);
14373        let mut lines = Vec::new();
14374        let mut line: VecDeque<Chunk> = VecDeque::new();
14375
14376        let Some(style) = self.style.as_ref() else {
14377            return;
14378        };
14379
14380        for chunk in chunks {
14381            let highlight = chunk
14382                .syntax_highlight_id
14383                .and_then(|id| id.name(&style.syntax));
14384            let mut chunk_lines = chunk.text.split('\n').peekable();
14385            while let Some(text) = chunk_lines.next() {
14386                let mut merged_with_last_token = false;
14387                if let Some(last_token) = line.back_mut() {
14388                    if last_token.highlight == highlight {
14389                        last_token.text.push_str(text);
14390                        merged_with_last_token = true;
14391                    }
14392                }
14393
14394                if !merged_with_last_token {
14395                    line.push_back(Chunk {
14396                        text: text.into(),
14397                        highlight,
14398                    });
14399                }
14400
14401                if chunk_lines.peek().is_some() {
14402                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14403                        line.pop_front();
14404                    }
14405                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14406                        line.pop_back();
14407                    }
14408
14409                    lines.push(mem::take(&mut line));
14410                }
14411            }
14412        }
14413
14414        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14415            return;
14416        };
14417        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14418    }
14419
14420    pub fn open_context_menu(
14421        &mut self,
14422        _: &OpenContextMenu,
14423        window: &mut Window,
14424        cx: &mut Context<Self>,
14425    ) {
14426        self.request_autoscroll(Autoscroll::newest(), cx);
14427        let position = self.selections.newest_display(cx).start;
14428        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14429    }
14430
14431    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14432        &self.inlay_hint_cache
14433    }
14434
14435    pub fn replay_insert_event(
14436        &mut self,
14437        text: &str,
14438        relative_utf16_range: Option<Range<isize>>,
14439        window: &mut Window,
14440        cx: &mut Context<Self>,
14441    ) {
14442        if !self.input_enabled {
14443            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14444            return;
14445        }
14446        if let Some(relative_utf16_range) = relative_utf16_range {
14447            let selections = self.selections.all::<OffsetUtf16>(cx);
14448            self.change_selections(None, window, cx, |s| {
14449                let new_ranges = selections.into_iter().map(|range| {
14450                    let start = OffsetUtf16(
14451                        range
14452                            .head()
14453                            .0
14454                            .saturating_add_signed(relative_utf16_range.start),
14455                    );
14456                    let end = OffsetUtf16(
14457                        range
14458                            .head()
14459                            .0
14460                            .saturating_add_signed(relative_utf16_range.end),
14461                    );
14462                    start..end
14463                });
14464                s.select_ranges(new_ranges);
14465            });
14466        }
14467
14468        self.handle_input(text, window, cx);
14469    }
14470
14471    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14472        let Some(provider) = self.semantics_provider.as_ref() else {
14473            return false;
14474        };
14475
14476        let mut supports = false;
14477        self.buffer().read(cx).for_each_buffer(|buffer| {
14478            supports |= provider.supports_inlay_hints(buffer, cx);
14479        });
14480        supports
14481    }
14482
14483    pub fn is_focused(&self, window: &Window) -> bool {
14484        self.focus_handle.is_focused(window)
14485    }
14486
14487    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14488        cx.emit(EditorEvent::Focused);
14489
14490        if let Some(descendant) = self
14491            .last_focused_descendant
14492            .take()
14493            .and_then(|descendant| descendant.upgrade())
14494        {
14495            window.focus(&descendant);
14496        } else {
14497            if let Some(blame) = self.blame.as_ref() {
14498                blame.update(cx, GitBlame::focus)
14499            }
14500
14501            self.blink_manager.update(cx, BlinkManager::enable);
14502            self.show_cursor_names(window, cx);
14503            self.buffer.update(cx, |buffer, cx| {
14504                buffer.finalize_last_transaction(cx);
14505                if self.leader_peer_id.is_none() {
14506                    buffer.set_active_selections(
14507                        &self.selections.disjoint_anchors(),
14508                        self.selections.line_mode,
14509                        self.cursor_shape,
14510                        cx,
14511                    );
14512                }
14513            });
14514        }
14515    }
14516
14517    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14518        cx.emit(EditorEvent::FocusedIn)
14519    }
14520
14521    fn handle_focus_out(
14522        &mut self,
14523        event: FocusOutEvent,
14524        _window: &mut Window,
14525        _cx: &mut Context<Self>,
14526    ) {
14527        if event.blurred != self.focus_handle {
14528            self.last_focused_descendant = Some(event.blurred);
14529        }
14530    }
14531
14532    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14533        self.blink_manager.update(cx, BlinkManager::disable);
14534        self.buffer
14535            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14536
14537        if let Some(blame) = self.blame.as_ref() {
14538            blame.update(cx, GitBlame::blur)
14539        }
14540        if !self.hover_state.focused(window, cx) {
14541            hide_hover(self, cx);
14542        }
14543
14544        self.hide_context_menu(window, cx);
14545        cx.emit(EditorEvent::Blurred);
14546        cx.notify();
14547    }
14548
14549    pub fn register_action<A: Action>(
14550        &mut self,
14551        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14552    ) -> Subscription {
14553        let id = self.next_editor_action_id.post_inc();
14554        let listener = Arc::new(listener);
14555        self.editor_actions.borrow_mut().insert(
14556            id,
14557            Box::new(move |window, _| {
14558                let listener = listener.clone();
14559                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14560                    let action = action.downcast_ref().unwrap();
14561                    if phase == DispatchPhase::Bubble {
14562                        listener(action, window, cx)
14563                    }
14564                })
14565            }),
14566        );
14567
14568        let editor_actions = self.editor_actions.clone();
14569        Subscription::new(move || {
14570            editor_actions.borrow_mut().remove(&id);
14571        })
14572    }
14573
14574    pub fn file_header_size(&self) -> u32 {
14575        FILE_HEADER_HEIGHT
14576    }
14577
14578    pub fn revert(
14579        &mut self,
14580        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14581        window: &mut Window,
14582        cx: &mut Context<Self>,
14583    ) {
14584        self.buffer().update(cx, |multi_buffer, cx| {
14585            for (buffer_id, changes) in revert_changes {
14586                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14587                    buffer.update(cx, |buffer, cx| {
14588                        buffer.edit(
14589                            changes.into_iter().map(|(range, text)| {
14590                                (range, text.to_string().map(Arc::<str>::from))
14591                            }),
14592                            None,
14593                            cx,
14594                        );
14595                    });
14596                }
14597            }
14598        });
14599        self.change_selections(None, window, cx, |selections| selections.refresh());
14600    }
14601
14602    pub fn to_pixel_point(
14603        &self,
14604        source: multi_buffer::Anchor,
14605        editor_snapshot: &EditorSnapshot,
14606        window: &mut Window,
14607    ) -> Option<gpui::Point<Pixels>> {
14608        let source_point = source.to_display_point(editor_snapshot);
14609        self.display_to_pixel_point(source_point, editor_snapshot, window)
14610    }
14611
14612    pub fn display_to_pixel_point(
14613        &self,
14614        source: DisplayPoint,
14615        editor_snapshot: &EditorSnapshot,
14616        window: &mut Window,
14617    ) -> Option<gpui::Point<Pixels>> {
14618        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14619        let text_layout_details = self.text_layout_details(window);
14620        let scroll_top = text_layout_details
14621            .scroll_anchor
14622            .scroll_position(editor_snapshot)
14623            .y;
14624
14625        if source.row().as_f32() < scroll_top.floor() {
14626            return None;
14627        }
14628        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14629        let source_y = line_height * (source.row().as_f32() - scroll_top);
14630        Some(gpui::Point::new(source_x, source_y))
14631    }
14632
14633    pub fn has_visible_completions_menu(&self) -> bool {
14634        !self.edit_prediction_preview_is_active()
14635            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14636                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14637            })
14638    }
14639
14640    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14641        self.addons
14642            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14643    }
14644
14645    pub fn unregister_addon<T: Addon>(&mut self) {
14646        self.addons.remove(&std::any::TypeId::of::<T>());
14647    }
14648
14649    pub fn addon<T: Addon>(&self) -> Option<&T> {
14650        let type_id = std::any::TypeId::of::<T>();
14651        self.addons
14652            .get(&type_id)
14653            .and_then(|item| item.to_any().downcast_ref::<T>())
14654    }
14655
14656    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14657        let text_layout_details = self.text_layout_details(window);
14658        let style = &text_layout_details.editor_style;
14659        let font_id = window.text_system().resolve_font(&style.text.font());
14660        let font_size = style.text.font_size.to_pixels(window.rem_size());
14661        let line_height = style.text.line_height_in_pixels(window.rem_size());
14662        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14663
14664        gpui::Size::new(em_width, line_height)
14665    }
14666}
14667
14668fn get_uncommitted_diff_for_buffer(
14669    project: &Entity<Project>,
14670    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14671    buffer: Entity<MultiBuffer>,
14672    cx: &mut App,
14673) {
14674    let mut tasks = Vec::new();
14675    project.update(cx, |project, cx| {
14676        for buffer in buffers {
14677            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14678        }
14679    });
14680    cx.spawn(|mut cx| async move {
14681        let diffs = futures::future::join_all(tasks).await;
14682        buffer
14683            .update(&mut cx, |buffer, cx| {
14684                for diff in diffs.into_iter().flatten() {
14685                    buffer.add_diff(diff, cx);
14686                }
14687            })
14688            .ok();
14689    })
14690    .detach();
14691}
14692
14693fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14694    let tab_size = tab_size.get() as usize;
14695    let mut width = offset;
14696
14697    for ch in text.chars() {
14698        width += if ch == '\t' {
14699            tab_size - (width % tab_size)
14700        } else {
14701            1
14702        };
14703    }
14704
14705    width - offset
14706}
14707
14708#[cfg(test)]
14709mod tests {
14710    use super::*;
14711
14712    #[test]
14713    fn test_string_size_with_expanded_tabs() {
14714        let nz = |val| NonZeroU32::new(val).unwrap();
14715        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14716        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14717        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14718        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14719        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14720        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14721        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14722        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14723    }
14724}
14725
14726/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14727struct WordBreakingTokenizer<'a> {
14728    input: &'a str,
14729}
14730
14731impl<'a> WordBreakingTokenizer<'a> {
14732    fn new(input: &'a str) -> Self {
14733        Self { input }
14734    }
14735}
14736
14737fn is_char_ideographic(ch: char) -> bool {
14738    use unicode_script::Script::*;
14739    use unicode_script::UnicodeScript;
14740    matches!(ch.script(), Han | Tangut | Yi)
14741}
14742
14743fn is_grapheme_ideographic(text: &str) -> bool {
14744    text.chars().any(is_char_ideographic)
14745}
14746
14747fn is_grapheme_whitespace(text: &str) -> bool {
14748    text.chars().any(|x| x.is_whitespace())
14749}
14750
14751fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14752    text.chars().next().map_or(false, |ch| {
14753        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14754    })
14755}
14756
14757#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14758struct WordBreakToken<'a> {
14759    token: &'a str,
14760    grapheme_len: usize,
14761    is_whitespace: bool,
14762}
14763
14764impl<'a> Iterator for WordBreakingTokenizer<'a> {
14765    /// Yields a span, the count of graphemes in the token, and whether it was
14766    /// whitespace. Note that it also breaks at word boundaries.
14767    type Item = WordBreakToken<'a>;
14768
14769    fn next(&mut self) -> Option<Self::Item> {
14770        use unicode_segmentation::UnicodeSegmentation;
14771        if self.input.is_empty() {
14772            return None;
14773        }
14774
14775        let mut iter = self.input.graphemes(true).peekable();
14776        let mut offset = 0;
14777        let mut graphemes = 0;
14778        if let Some(first_grapheme) = iter.next() {
14779            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14780            offset += first_grapheme.len();
14781            graphemes += 1;
14782            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14783                if let Some(grapheme) = iter.peek().copied() {
14784                    if should_stay_with_preceding_ideograph(grapheme) {
14785                        offset += grapheme.len();
14786                        graphemes += 1;
14787                    }
14788                }
14789            } else {
14790                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14791                let mut next_word_bound = words.peek().copied();
14792                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14793                    next_word_bound = words.next();
14794                }
14795                while let Some(grapheme) = iter.peek().copied() {
14796                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14797                        break;
14798                    };
14799                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14800                        break;
14801                    };
14802                    offset += grapheme.len();
14803                    graphemes += 1;
14804                    iter.next();
14805                }
14806            }
14807            let token = &self.input[..offset];
14808            self.input = &self.input[offset..];
14809            if is_whitespace {
14810                Some(WordBreakToken {
14811                    token: " ",
14812                    grapheme_len: 1,
14813                    is_whitespace: true,
14814                })
14815            } else {
14816                Some(WordBreakToken {
14817                    token,
14818                    grapheme_len: graphemes,
14819                    is_whitespace: false,
14820                })
14821            }
14822        } else {
14823            None
14824        }
14825    }
14826}
14827
14828#[test]
14829fn test_word_breaking_tokenizer() {
14830    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14831        ("", &[]),
14832        ("  ", &[(" ", 1, true)]),
14833        ("Ʒ", &[("Ʒ", 1, false)]),
14834        ("Ǽ", &[("Ǽ", 1, false)]),
14835        ("", &[("", 1, false)]),
14836        ("⋑⋑", &[("⋑⋑", 2, false)]),
14837        (
14838            "原理,进而",
14839            &[
14840                ("", 1, false),
14841                ("理,", 2, false),
14842                ("", 1, false),
14843                ("", 1, false),
14844            ],
14845        ),
14846        (
14847            "hello world",
14848            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14849        ),
14850        (
14851            "hello, world",
14852            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14853        ),
14854        (
14855            "  hello world",
14856            &[
14857                (" ", 1, true),
14858                ("hello", 5, false),
14859                (" ", 1, true),
14860                ("world", 5, false),
14861            ],
14862        ),
14863        (
14864            "这是什么 \n 钢笔",
14865            &[
14866                ("", 1, false),
14867                ("", 1, false),
14868                ("", 1, false),
14869                ("", 1, false),
14870                (" ", 1, true),
14871                ("", 1, false),
14872                ("", 1, false),
14873            ],
14874        ),
14875        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14876    ];
14877
14878    for (input, result) in tests {
14879        assert_eq!(
14880            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14881            result
14882                .iter()
14883                .copied()
14884                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14885                    token,
14886                    grapheme_len,
14887                    is_whitespace,
14888                })
14889                .collect::<Vec<_>>()
14890        );
14891    }
14892}
14893
14894fn wrap_with_prefix(
14895    line_prefix: String,
14896    unwrapped_text: String,
14897    wrap_column: usize,
14898    tab_size: NonZeroU32,
14899) -> String {
14900    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14901    let mut wrapped_text = String::new();
14902    let mut current_line = line_prefix.clone();
14903
14904    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14905    let mut current_line_len = line_prefix_len;
14906    for WordBreakToken {
14907        token,
14908        grapheme_len,
14909        is_whitespace,
14910    } in tokenizer
14911    {
14912        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14913            wrapped_text.push_str(current_line.trim_end());
14914            wrapped_text.push('\n');
14915            current_line.truncate(line_prefix.len());
14916            current_line_len = line_prefix_len;
14917            if !is_whitespace {
14918                current_line.push_str(token);
14919                current_line_len += grapheme_len;
14920            }
14921        } else if !is_whitespace {
14922            current_line.push_str(token);
14923            current_line_len += grapheme_len;
14924        } else if current_line_len != line_prefix_len {
14925            current_line.push(' ');
14926            current_line_len += 1;
14927        }
14928    }
14929
14930    if !current_line.is_empty() {
14931        wrapped_text.push_str(&current_line);
14932    }
14933    wrapped_text
14934}
14935
14936#[test]
14937fn test_wrap_with_prefix() {
14938    assert_eq!(
14939        wrap_with_prefix(
14940            "# ".to_string(),
14941            "abcdefg".to_string(),
14942            4,
14943            NonZeroU32::new(4).unwrap()
14944        ),
14945        "# abcdefg"
14946    );
14947    assert_eq!(
14948        wrap_with_prefix(
14949            "".to_string(),
14950            "\thello world".to_string(),
14951            8,
14952            NonZeroU32::new(4).unwrap()
14953        ),
14954        "hello\nworld"
14955    );
14956    assert_eq!(
14957        wrap_with_prefix(
14958            "// ".to_string(),
14959            "xx \nyy zz aa bb cc".to_string(),
14960            12,
14961            NonZeroU32::new(4).unwrap()
14962        ),
14963        "// xx yy zz\n// aa bb cc"
14964    );
14965    assert_eq!(
14966        wrap_with_prefix(
14967            String::new(),
14968            "这是什么 \n 钢笔".to_string(),
14969            3,
14970            NonZeroU32::new(4).unwrap()
14971        ),
14972        "这是什\n么 钢\n"
14973    );
14974}
14975
14976pub trait CollaborationHub {
14977    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14978    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14979    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14980}
14981
14982impl CollaborationHub for Entity<Project> {
14983    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14984        self.read(cx).collaborators()
14985    }
14986
14987    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14988        self.read(cx).user_store().read(cx).participant_indices()
14989    }
14990
14991    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14992        let this = self.read(cx);
14993        let user_ids = this.collaborators().values().map(|c| c.user_id);
14994        this.user_store().read_with(cx, |user_store, cx| {
14995            user_store.participant_names(user_ids, cx)
14996        })
14997    }
14998}
14999
15000pub trait SemanticsProvider {
15001    fn hover(
15002        &self,
15003        buffer: &Entity<Buffer>,
15004        position: text::Anchor,
15005        cx: &mut App,
15006    ) -> Option<Task<Vec<project::Hover>>>;
15007
15008    fn inlay_hints(
15009        &self,
15010        buffer_handle: Entity<Buffer>,
15011        range: Range<text::Anchor>,
15012        cx: &mut App,
15013    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15014
15015    fn resolve_inlay_hint(
15016        &self,
15017        hint: InlayHint,
15018        buffer_handle: Entity<Buffer>,
15019        server_id: LanguageServerId,
15020        cx: &mut App,
15021    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15022
15023    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15024
15025    fn document_highlights(
15026        &self,
15027        buffer: &Entity<Buffer>,
15028        position: text::Anchor,
15029        cx: &mut App,
15030    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15031
15032    fn definitions(
15033        &self,
15034        buffer: &Entity<Buffer>,
15035        position: text::Anchor,
15036        kind: GotoDefinitionKind,
15037        cx: &mut App,
15038    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15039
15040    fn range_for_rename(
15041        &self,
15042        buffer: &Entity<Buffer>,
15043        position: text::Anchor,
15044        cx: &mut App,
15045    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15046
15047    fn perform_rename(
15048        &self,
15049        buffer: &Entity<Buffer>,
15050        position: text::Anchor,
15051        new_name: String,
15052        cx: &mut App,
15053    ) -> Option<Task<Result<ProjectTransaction>>>;
15054}
15055
15056pub trait CompletionProvider {
15057    fn completions(
15058        &self,
15059        buffer: &Entity<Buffer>,
15060        buffer_position: text::Anchor,
15061        trigger: CompletionContext,
15062        window: &mut Window,
15063        cx: &mut Context<Editor>,
15064    ) -> Task<Result<Vec<Completion>>>;
15065
15066    fn resolve_completions(
15067        &self,
15068        buffer: Entity<Buffer>,
15069        completion_indices: Vec<usize>,
15070        completions: Rc<RefCell<Box<[Completion]>>>,
15071        cx: &mut Context<Editor>,
15072    ) -> Task<Result<bool>>;
15073
15074    fn apply_additional_edits_for_completion(
15075        &self,
15076        _buffer: Entity<Buffer>,
15077        _completions: Rc<RefCell<Box<[Completion]>>>,
15078        _completion_index: usize,
15079        _push_to_history: bool,
15080        _cx: &mut Context<Editor>,
15081    ) -> Task<Result<Option<language::Transaction>>> {
15082        Task::ready(Ok(None))
15083    }
15084
15085    fn is_completion_trigger(
15086        &self,
15087        buffer: &Entity<Buffer>,
15088        position: language::Anchor,
15089        text: &str,
15090        trigger_in_words: bool,
15091        cx: &mut Context<Editor>,
15092    ) -> bool;
15093
15094    fn sort_completions(&self) -> bool {
15095        true
15096    }
15097}
15098
15099pub trait CodeActionProvider {
15100    fn id(&self) -> Arc<str>;
15101
15102    fn code_actions(
15103        &self,
15104        buffer: &Entity<Buffer>,
15105        range: Range<text::Anchor>,
15106        window: &mut Window,
15107        cx: &mut App,
15108    ) -> Task<Result<Vec<CodeAction>>>;
15109
15110    fn apply_code_action(
15111        &self,
15112        buffer_handle: Entity<Buffer>,
15113        action: CodeAction,
15114        excerpt_id: ExcerptId,
15115        push_to_history: bool,
15116        window: &mut Window,
15117        cx: &mut App,
15118    ) -> Task<Result<ProjectTransaction>>;
15119}
15120
15121impl CodeActionProvider for Entity<Project> {
15122    fn id(&self) -> Arc<str> {
15123        "project".into()
15124    }
15125
15126    fn code_actions(
15127        &self,
15128        buffer: &Entity<Buffer>,
15129        range: Range<text::Anchor>,
15130        _window: &mut Window,
15131        cx: &mut App,
15132    ) -> Task<Result<Vec<CodeAction>>> {
15133        self.update(cx, |project, cx| {
15134            project.code_actions(buffer, range, None, cx)
15135        })
15136    }
15137
15138    fn apply_code_action(
15139        &self,
15140        buffer_handle: Entity<Buffer>,
15141        action: CodeAction,
15142        _excerpt_id: ExcerptId,
15143        push_to_history: bool,
15144        _window: &mut Window,
15145        cx: &mut App,
15146    ) -> Task<Result<ProjectTransaction>> {
15147        self.update(cx, |project, cx| {
15148            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15149        })
15150    }
15151}
15152
15153fn snippet_completions(
15154    project: &Project,
15155    buffer: &Entity<Buffer>,
15156    buffer_position: text::Anchor,
15157    cx: &mut App,
15158) -> Task<Result<Vec<Completion>>> {
15159    let language = buffer.read(cx).language_at(buffer_position);
15160    let language_name = language.as_ref().map(|language| language.lsp_id());
15161    let snippet_store = project.snippets().read(cx);
15162    let snippets = snippet_store.snippets_for(language_name, cx);
15163
15164    if snippets.is_empty() {
15165        return Task::ready(Ok(vec![]));
15166    }
15167    let snapshot = buffer.read(cx).text_snapshot();
15168    let chars: String = snapshot
15169        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15170        .collect();
15171
15172    let scope = language.map(|language| language.default_scope());
15173    let executor = cx.background_executor().clone();
15174
15175    cx.background_executor().spawn(async move {
15176        let classifier = CharClassifier::new(scope).for_completion(true);
15177        let mut last_word = chars
15178            .chars()
15179            .take_while(|c| classifier.is_word(*c))
15180            .collect::<String>();
15181        last_word = last_word.chars().rev().collect();
15182
15183        if last_word.is_empty() {
15184            return Ok(vec![]);
15185        }
15186
15187        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15188        let to_lsp = |point: &text::Anchor| {
15189            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15190            point_to_lsp(end)
15191        };
15192        let lsp_end = to_lsp(&buffer_position);
15193
15194        let candidates = snippets
15195            .iter()
15196            .enumerate()
15197            .flat_map(|(ix, snippet)| {
15198                snippet
15199                    .prefix
15200                    .iter()
15201                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15202            })
15203            .collect::<Vec<StringMatchCandidate>>();
15204
15205        let mut matches = fuzzy::match_strings(
15206            &candidates,
15207            &last_word,
15208            last_word.chars().any(|c| c.is_uppercase()),
15209            100,
15210            &Default::default(),
15211            executor,
15212        )
15213        .await;
15214
15215        // Remove all candidates where the query's start does not match the start of any word in the candidate
15216        if let Some(query_start) = last_word.chars().next() {
15217            matches.retain(|string_match| {
15218                split_words(&string_match.string).any(|word| {
15219                    // Check that the first codepoint of the word as lowercase matches the first
15220                    // codepoint of the query as lowercase
15221                    word.chars()
15222                        .flat_map(|codepoint| codepoint.to_lowercase())
15223                        .zip(query_start.to_lowercase())
15224                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15225                })
15226            });
15227        }
15228
15229        let matched_strings = matches
15230            .into_iter()
15231            .map(|m| m.string)
15232            .collect::<HashSet<_>>();
15233
15234        let result: Vec<Completion> = snippets
15235            .into_iter()
15236            .filter_map(|snippet| {
15237                let matching_prefix = snippet
15238                    .prefix
15239                    .iter()
15240                    .find(|prefix| matched_strings.contains(*prefix))?;
15241                let start = as_offset - last_word.len();
15242                let start = snapshot.anchor_before(start);
15243                let range = start..buffer_position;
15244                let lsp_start = to_lsp(&start);
15245                let lsp_range = lsp::Range {
15246                    start: lsp_start,
15247                    end: lsp_end,
15248                };
15249                Some(Completion {
15250                    old_range: range,
15251                    new_text: snippet.body.clone(),
15252                    resolved: false,
15253                    label: CodeLabel {
15254                        text: matching_prefix.clone(),
15255                        runs: vec![],
15256                        filter_range: 0..matching_prefix.len(),
15257                    },
15258                    server_id: LanguageServerId(usize::MAX),
15259                    documentation: snippet
15260                        .description
15261                        .clone()
15262                        .map(CompletionDocumentation::SingleLine),
15263                    lsp_completion: lsp::CompletionItem {
15264                        label: snippet.prefix.first().unwrap().clone(),
15265                        kind: Some(CompletionItemKind::SNIPPET),
15266                        label_details: snippet.description.as_ref().map(|description| {
15267                            lsp::CompletionItemLabelDetails {
15268                                detail: Some(description.clone()),
15269                                description: None,
15270                            }
15271                        }),
15272                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15273                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15274                            lsp::InsertReplaceEdit {
15275                                new_text: snippet.body.clone(),
15276                                insert: lsp_range,
15277                                replace: lsp_range,
15278                            },
15279                        )),
15280                        filter_text: Some(snippet.body.clone()),
15281                        sort_text: Some(char::MAX.to_string()),
15282                        ..Default::default()
15283                    },
15284                    confirm: None,
15285                })
15286            })
15287            .collect();
15288
15289        Ok(result)
15290    })
15291}
15292
15293impl CompletionProvider for Entity<Project> {
15294    fn completions(
15295        &self,
15296        buffer: &Entity<Buffer>,
15297        buffer_position: text::Anchor,
15298        options: CompletionContext,
15299        _window: &mut Window,
15300        cx: &mut Context<Editor>,
15301    ) -> Task<Result<Vec<Completion>>> {
15302        self.update(cx, |project, cx| {
15303            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15304            let project_completions = project.completions(buffer, buffer_position, options, cx);
15305            cx.background_executor().spawn(async move {
15306                let mut completions = project_completions.await?;
15307                let snippets_completions = snippets.await?;
15308                completions.extend(snippets_completions);
15309                Ok(completions)
15310            })
15311        })
15312    }
15313
15314    fn resolve_completions(
15315        &self,
15316        buffer: Entity<Buffer>,
15317        completion_indices: Vec<usize>,
15318        completions: Rc<RefCell<Box<[Completion]>>>,
15319        cx: &mut Context<Editor>,
15320    ) -> Task<Result<bool>> {
15321        self.update(cx, |project, cx| {
15322            project.lsp_store().update(cx, |lsp_store, cx| {
15323                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15324            })
15325        })
15326    }
15327
15328    fn apply_additional_edits_for_completion(
15329        &self,
15330        buffer: Entity<Buffer>,
15331        completions: Rc<RefCell<Box<[Completion]>>>,
15332        completion_index: usize,
15333        push_to_history: bool,
15334        cx: &mut Context<Editor>,
15335    ) -> Task<Result<Option<language::Transaction>>> {
15336        self.update(cx, |project, cx| {
15337            project.lsp_store().update(cx, |lsp_store, cx| {
15338                lsp_store.apply_additional_edits_for_completion(
15339                    buffer,
15340                    completions,
15341                    completion_index,
15342                    push_to_history,
15343                    cx,
15344                )
15345            })
15346        })
15347    }
15348
15349    fn is_completion_trigger(
15350        &self,
15351        buffer: &Entity<Buffer>,
15352        position: language::Anchor,
15353        text: &str,
15354        trigger_in_words: bool,
15355        cx: &mut Context<Editor>,
15356    ) -> bool {
15357        let mut chars = text.chars();
15358        let char = if let Some(char) = chars.next() {
15359            char
15360        } else {
15361            return false;
15362        };
15363        if chars.next().is_some() {
15364            return false;
15365        }
15366
15367        let buffer = buffer.read(cx);
15368        let snapshot = buffer.snapshot();
15369        if !snapshot.settings_at(position, cx).show_completions_on_input {
15370            return false;
15371        }
15372        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15373        if trigger_in_words && classifier.is_word(char) {
15374            return true;
15375        }
15376
15377        buffer.completion_triggers().contains(text)
15378    }
15379}
15380
15381impl SemanticsProvider for Entity<Project> {
15382    fn hover(
15383        &self,
15384        buffer: &Entity<Buffer>,
15385        position: text::Anchor,
15386        cx: &mut App,
15387    ) -> Option<Task<Vec<project::Hover>>> {
15388        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15389    }
15390
15391    fn document_highlights(
15392        &self,
15393        buffer: &Entity<Buffer>,
15394        position: text::Anchor,
15395        cx: &mut App,
15396    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15397        Some(self.update(cx, |project, cx| {
15398            project.document_highlights(buffer, position, cx)
15399        }))
15400    }
15401
15402    fn definitions(
15403        &self,
15404        buffer: &Entity<Buffer>,
15405        position: text::Anchor,
15406        kind: GotoDefinitionKind,
15407        cx: &mut App,
15408    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15409        Some(self.update(cx, |project, cx| match kind {
15410            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15411            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15412            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15413            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15414        }))
15415    }
15416
15417    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15418        // TODO: make this work for remote projects
15419        self.read(cx)
15420            .language_servers_for_local_buffer(buffer.read(cx), cx)
15421            .any(
15422                |(_, server)| match server.capabilities().inlay_hint_provider {
15423                    Some(lsp::OneOf::Left(enabled)) => enabled,
15424                    Some(lsp::OneOf::Right(_)) => true,
15425                    None => false,
15426                },
15427            )
15428    }
15429
15430    fn inlay_hints(
15431        &self,
15432        buffer_handle: Entity<Buffer>,
15433        range: Range<text::Anchor>,
15434        cx: &mut App,
15435    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15436        Some(self.update(cx, |project, cx| {
15437            project.inlay_hints(buffer_handle, range, cx)
15438        }))
15439    }
15440
15441    fn resolve_inlay_hint(
15442        &self,
15443        hint: InlayHint,
15444        buffer_handle: Entity<Buffer>,
15445        server_id: LanguageServerId,
15446        cx: &mut App,
15447    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15448        Some(self.update(cx, |project, cx| {
15449            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15450        }))
15451    }
15452
15453    fn range_for_rename(
15454        &self,
15455        buffer: &Entity<Buffer>,
15456        position: text::Anchor,
15457        cx: &mut App,
15458    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15459        Some(self.update(cx, |project, cx| {
15460            let buffer = buffer.clone();
15461            let task = project.prepare_rename(buffer.clone(), position, cx);
15462            cx.spawn(|_, mut cx| async move {
15463                Ok(match task.await? {
15464                    PrepareRenameResponse::Success(range) => Some(range),
15465                    PrepareRenameResponse::InvalidPosition => None,
15466                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15467                        // Fallback on using TreeSitter info to determine identifier range
15468                        buffer.update(&mut cx, |buffer, _| {
15469                            let snapshot = buffer.snapshot();
15470                            let (range, kind) = snapshot.surrounding_word(position);
15471                            if kind != Some(CharKind::Word) {
15472                                return None;
15473                            }
15474                            Some(
15475                                snapshot.anchor_before(range.start)
15476                                    ..snapshot.anchor_after(range.end),
15477                            )
15478                        })?
15479                    }
15480                })
15481            })
15482        }))
15483    }
15484
15485    fn perform_rename(
15486        &self,
15487        buffer: &Entity<Buffer>,
15488        position: text::Anchor,
15489        new_name: String,
15490        cx: &mut App,
15491    ) -> Option<Task<Result<ProjectTransaction>>> {
15492        Some(self.update(cx, |project, cx| {
15493            project.perform_rename(buffer.clone(), position, new_name, cx)
15494        }))
15495    }
15496}
15497
15498fn inlay_hint_settings(
15499    location: Anchor,
15500    snapshot: &MultiBufferSnapshot,
15501    cx: &mut Context<Editor>,
15502) -> InlayHintSettings {
15503    let file = snapshot.file_at(location);
15504    let language = snapshot.language_at(location).map(|l| l.name());
15505    language_settings(language, file, cx).inlay_hints
15506}
15507
15508fn consume_contiguous_rows(
15509    contiguous_row_selections: &mut Vec<Selection<Point>>,
15510    selection: &Selection<Point>,
15511    display_map: &DisplaySnapshot,
15512    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15513) -> (MultiBufferRow, MultiBufferRow) {
15514    contiguous_row_selections.push(selection.clone());
15515    let start_row = MultiBufferRow(selection.start.row);
15516    let mut end_row = ending_row(selection, display_map);
15517
15518    while let Some(next_selection) = selections.peek() {
15519        if next_selection.start.row <= end_row.0 {
15520            end_row = ending_row(next_selection, display_map);
15521            contiguous_row_selections.push(selections.next().unwrap().clone());
15522        } else {
15523            break;
15524        }
15525    }
15526    (start_row, end_row)
15527}
15528
15529fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15530    if next_selection.end.column > 0 || next_selection.is_empty() {
15531        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15532    } else {
15533        MultiBufferRow(next_selection.end.row)
15534    }
15535}
15536
15537impl EditorSnapshot {
15538    pub fn remote_selections_in_range<'a>(
15539        &'a self,
15540        range: &'a Range<Anchor>,
15541        collaboration_hub: &dyn CollaborationHub,
15542        cx: &'a App,
15543    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15544        let participant_names = collaboration_hub.user_names(cx);
15545        let participant_indices = collaboration_hub.user_participant_indices(cx);
15546        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15547        let collaborators_by_replica_id = collaborators_by_peer_id
15548            .iter()
15549            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15550            .collect::<HashMap<_, _>>();
15551        self.buffer_snapshot
15552            .selections_in_range(range, false)
15553            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15554                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15555                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15556                let user_name = participant_names.get(&collaborator.user_id).cloned();
15557                Some(RemoteSelection {
15558                    replica_id,
15559                    selection,
15560                    cursor_shape,
15561                    line_mode,
15562                    participant_index,
15563                    peer_id: collaborator.peer_id,
15564                    user_name,
15565                })
15566            })
15567    }
15568
15569    pub fn hunks_for_ranges(
15570        &self,
15571        ranges: impl Iterator<Item = Range<Point>>,
15572    ) -> Vec<MultiBufferDiffHunk> {
15573        let mut hunks = Vec::new();
15574        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15575            HashMap::default();
15576        for query_range in ranges {
15577            let query_rows =
15578                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15579            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15580                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15581            ) {
15582                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15583                // when the caret is just above or just below the deleted hunk.
15584                let allow_adjacent = hunk.status().is_removed();
15585                let related_to_selection = if allow_adjacent {
15586                    hunk.row_range.overlaps(&query_rows)
15587                        || hunk.row_range.start == query_rows.end
15588                        || hunk.row_range.end == query_rows.start
15589                } else {
15590                    hunk.row_range.overlaps(&query_rows)
15591                };
15592                if related_to_selection {
15593                    if !processed_buffer_rows
15594                        .entry(hunk.buffer_id)
15595                        .or_default()
15596                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15597                    {
15598                        continue;
15599                    }
15600                    hunks.push(hunk);
15601                }
15602            }
15603        }
15604
15605        hunks
15606    }
15607
15608    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15609        self.display_snapshot.buffer_snapshot.language_at(position)
15610    }
15611
15612    pub fn is_focused(&self) -> bool {
15613        self.is_focused
15614    }
15615
15616    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15617        self.placeholder_text.as_ref()
15618    }
15619
15620    pub fn scroll_position(&self) -> gpui::Point<f32> {
15621        self.scroll_anchor.scroll_position(&self.display_snapshot)
15622    }
15623
15624    fn gutter_dimensions(
15625        &self,
15626        font_id: FontId,
15627        font_size: Pixels,
15628        max_line_number_width: Pixels,
15629        cx: &App,
15630    ) -> Option<GutterDimensions> {
15631        if !self.show_gutter {
15632            return None;
15633        }
15634
15635        let descent = cx.text_system().descent(font_id, font_size);
15636        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15637        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15638
15639        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15640            matches!(
15641                ProjectSettings::get_global(cx).git.git_gutter,
15642                Some(GitGutterSetting::TrackedFiles)
15643            )
15644        });
15645        let gutter_settings = EditorSettings::get_global(cx).gutter;
15646        let show_line_numbers = self
15647            .show_line_numbers
15648            .unwrap_or(gutter_settings.line_numbers);
15649        let line_gutter_width = if show_line_numbers {
15650            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15651            let min_width_for_number_on_gutter = em_advance * 4.0;
15652            max_line_number_width.max(min_width_for_number_on_gutter)
15653        } else {
15654            0.0.into()
15655        };
15656
15657        let show_code_actions = self
15658            .show_code_actions
15659            .unwrap_or(gutter_settings.code_actions);
15660
15661        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15662
15663        let git_blame_entries_width =
15664            self.git_blame_gutter_max_author_length
15665                .map(|max_author_length| {
15666                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15667
15668                    /// The number of characters to dedicate to gaps and margins.
15669                    const SPACING_WIDTH: usize = 4;
15670
15671                    let max_char_count = max_author_length
15672                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15673                        + ::git::SHORT_SHA_LENGTH
15674                        + MAX_RELATIVE_TIMESTAMP.len()
15675                        + SPACING_WIDTH;
15676
15677                    em_advance * max_char_count
15678                });
15679
15680        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15681        left_padding += if show_code_actions || show_runnables {
15682            em_width * 3.0
15683        } else if show_git_gutter && show_line_numbers {
15684            em_width * 2.0
15685        } else if show_git_gutter || show_line_numbers {
15686            em_width
15687        } else {
15688            px(0.)
15689        };
15690
15691        let right_padding = if gutter_settings.folds && show_line_numbers {
15692            em_width * 4.0
15693        } else if gutter_settings.folds {
15694            em_width * 3.0
15695        } else if show_line_numbers {
15696            em_width
15697        } else {
15698            px(0.)
15699        };
15700
15701        Some(GutterDimensions {
15702            left_padding,
15703            right_padding,
15704            width: line_gutter_width + left_padding + right_padding,
15705            margin: -descent,
15706            git_blame_entries_width,
15707        })
15708    }
15709
15710    pub fn render_crease_toggle(
15711        &self,
15712        buffer_row: MultiBufferRow,
15713        row_contains_cursor: bool,
15714        editor: Entity<Editor>,
15715        window: &mut Window,
15716        cx: &mut App,
15717    ) -> Option<AnyElement> {
15718        let folded = self.is_line_folded(buffer_row);
15719        let mut is_foldable = false;
15720
15721        if let Some(crease) = self
15722            .crease_snapshot
15723            .query_row(buffer_row, &self.buffer_snapshot)
15724        {
15725            is_foldable = true;
15726            match crease {
15727                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15728                    if let Some(render_toggle) = render_toggle {
15729                        let toggle_callback =
15730                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15731                                if folded {
15732                                    editor.update(cx, |editor, cx| {
15733                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15734                                    });
15735                                } else {
15736                                    editor.update(cx, |editor, cx| {
15737                                        editor.unfold_at(
15738                                            &crate::UnfoldAt { buffer_row },
15739                                            window,
15740                                            cx,
15741                                        )
15742                                    });
15743                                }
15744                            });
15745                        return Some((render_toggle)(
15746                            buffer_row,
15747                            folded,
15748                            toggle_callback,
15749                            window,
15750                            cx,
15751                        ));
15752                    }
15753                }
15754            }
15755        }
15756
15757        is_foldable |= self.starts_indent(buffer_row);
15758
15759        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15760            Some(
15761                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15762                    .toggle_state(folded)
15763                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15764                        if folded {
15765                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15766                        } else {
15767                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15768                        }
15769                    }))
15770                    .into_any_element(),
15771            )
15772        } else {
15773            None
15774        }
15775    }
15776
15777    pub fn render_crease_trailer(
15778        &self,
15779        buffer_row: MultiBufferRow,
15780        window: &mut Window,
15781        cx: &mut App,
15782    ) -> Option<AnyElement> {
15783        let folded = self.is_line_folded(buffer_row);
15784        if let Crease::Inline { render_trailer, .. } = self
15785            .crease_snapshot
15786            .query_row(buffer_row, &self.buffer_snapshot)?
15787        {
15788            let render_trailer = render_trailer.as_ref()?;
15789            Some(render_trailer(buffer_row, folded, window, cx))
15790        } else {
15791            None
15792        }
15793    }
15794}
15795
15796impl Deref for EditorSnapshot {
15797    type Target = DisplaySnapshot;
15798
15799    fn deref(&self) -> &Self::Target {
15800        &self.display_snapshot
15801    }
15802}
15803
15804#[derive(Clone, Debug, PartialEq, Eq)]
15805pub enum EditorEvent {
15806    InputIgnored {
15807        text: Arc<str>,
15808    },
15809    InputHandled {
15810        utf16_range_to_replace: Option<Range<isize>>,
15811        text: Arc<str>,
15812    },
15813    ExcerptsAdded {
15814        buffer: Entity<Buffer>,
15815        predecessor: ExcerptId,
15816        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15817    },
15818    ExcerptsRemoved {
15819        ids: Vec<ExcerptId>,
15820    },
15821    BufferFoldToggled {
15822        ids: Vec<ExcerptId>,
15823        folded: bool,
15824    },
15825    ExcerptsEdited {
15826        ids: Vec<ExcerptId>,
15827    },
15828    ExcerptsExpanded {
15829        ids: Vec<ExcerptId>,
15830    },
15831    BufferEdited,
15832    Edited {
15833        transaction_id: clock::Lamport,
15834    },
15835    Reparsed(BufferId),
15836    Focused,
15837    FocusedIn,
15838    Blurred,
15839    DirtyChanged,
15840    Saved,
15841    TitleChanged,
15842    DiffBaseChanged,
15843    SelectionsChanged {
15844        local: bool,
15845    },
15846    ScrollPositionChanged {
15847        local: bool,
15848        autoscroll: bool,
15849    },
15850    Closed,
15851    TransactionUndone {
15852        transaction_id: clock::Lamport,
15853    },
15854    TransactionBegun {
15855        transaction_id: clock::Lamport,
15856    },
15857    Reloaded,
15858    CursorShapeChanged,
15859}
15860
15861impl EventEmitter<EditorEvent> for Editor {}
15862
15863impl Focusable for Editor {
15864    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15865        self.focus_handle.clone()
15866    }
15867}
15868
15869impl Render for Editor {
15870    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15871        let settings = ThemeSettings::get_global(cx);
15872
15873        let mut text_style = match self.mode {
15874            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15875                color: cx.theme().colors().editor_foreground,
15876                font_family: settings.ui_font.family.clone(),
15877                font_features: settings.ui_font.features.clone(),
15878                font_fallbacks: settings.ui_font.fallbacks.clone(),
15879                font_size: rems(0.875).into(),
15880                font_weight: settings.ui_font.weight,
15881                line_height: relative(settings.buffer_line_height.value()),
15882                ..Default::default()
15883            },
15884            EditorMode::Full => TextStyle {
15885                color: cx.theme().colors().editor_foreground,
15886                font_family: settings.buffer_font.family.clone(),
15887                font_features: settings.buffer_font.features.clone(),
15888                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15889                font_size: settings.buffer_font_size().into(),
15890                font_weight: settings.buffer_font.weight,
15891                line_height: relative(settings.buffer_line_height.value()),
15892                ..Default::default()
15893            },
15894        };
15895        if let Some(text_style_refinement) = &self.text_style_refinement {
15896            text_style.refine(text_style_refinement)
15897        }
15898
15899        let background = match self.mode {
15900            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15901            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15902            EditorMode::Full => cx.theme().colors().editor_background,
15903        };
15904
15905        EditorElement::new(
15906            &cx.entity(),
15907            EditorStyle {
15908                background,
15909                local_player: cx.theme().players().local(),
15910                text: text_style,
15911                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15912                syntax: cx.theme().syntax().clone(),
15913                status: cx.theme().status().clone(),
15914                inlay_hints_style: make_inlay_hints_style(cx),
15915                inline_completion_styles: make_suggestion_styles(cx),
15916                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15917            },
15918        )
15919    }
15920}
15921
15922impl EntityInputHandler for Editor {
15923    fn text_for_range(
15924        &mut self,
15925        range_utf16: Range<usize>,
15926        adjusted_range: &mut Option<Range<usize>>,
15927        _: &mut Window,
15928        cx: &mut Context<Self>,
15929    ) -> Option<String> {
15930        let snapshot = self.buffer.read(cx).read(cx);
15931        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15932        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15933        if (start.0..end.0) != range_utf16 {
15934            adjusted_range.replace(start.0..end.0);
15935        }
15936        Some(snapshot.text_for_range(start..end).collect())
15937    }
15938
15939    fn selected_text_range(
15940        &mut self,
15941        ignore_disabled_input: bool,
15942        _: &mut Window,
15943        cx: &mut Context<Self>,
15944    ) -> Option<UTF16Selection> {
15945        // Prevent the IME menu from appearing when holding down an alphabetic key
15946        // while input is disabled.
15947        if !ignore_disabled_input && !self.input_enabled {
15948            return None;
15949        }
15950
15951        let selection = self.selections.newest::<OffsetUtf16>(cx);
15952        let range = selection.range();
15953
15954        Some(UTF16Selection {
15955            range: range.start.0..range.end.0,
15956            reversed: selection.reversed,
15957        })
15958    }
15959
15960    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15961        let snapshot = self.buffer.read(cx).read(cx);
15962        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15963        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15964    }
15965
15966    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15967        self.clear_highlights::<InputComposition>(cx);
15968        self.ime_transaction.take();
15969    }
15970
15971    fn replace_text_in_range(
15972        &mut self,
15973        range_utf16: Option<Range<usize>>,
15974        text: &str,
15975        window: &mut Window,
15976        cx: &mut Context<Self>,
15977    ) {
15978        if !self.input_enabled {
15979            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15980            return;
15981        }
15982
15983        self.transact(window, cx, |this, window, cx| {
15984            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15985                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15986                Some(this.selection_replacement_ranges(range_utf16, cx))
15987            } else {
15988                this.marked_text_ranges(cx)
15989            };
15990
15991            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15992                let newest_selection_id = this.selections.newest_anchor().id;
15993                this.selections
15994                    .all::<OffsetUtf16>(cx)
15995                    .iter()
15996                    .zip(ranges_to_replace.iter())
15997                    .find_map(|(selection, range)| {
15998                        if selection.id == newest_selection_id {
15999                            Some(
16000                                (range.start.0 as isize - selection.head().0 as isize)
16001                                    ..(range.end.0 as isize - selection.head().0 as isize),
16002                            )
16003                        } else {
16004                            None
16005                        }
16006                    })
16007            });
16008
16009            cx.emit(EditorEvent::InputHandled {
16010                utf16_range_to_replace: range_to_replace,
16011                text: text.into(),
16012            });
16013
16014            if let Some(new_selected_ranges) = new_selected_ranges {
16015                this.change_selections(None, window, cx, |selections| {
16016                    selections.select_ranges(new_selected_ranges)
16017                });
16018                this.backspace(&Default::default(), window, cx);
16019            }
16020
16021            this.handle_input(text, window, cx);
16022        });
16023
16024        if let Some(transaction) = self.ime_transaction {
16025            self.buffer.update(cx, |buffer, cx| {
16026                buffer.group_until_transaction(transaction, cx);
16027            });
16028        }
16029
16030        self.unmark_text(window, cx);
16031    }
16032
16033    fn replace_and_mark_text_in_range(
16034        &mut self,
16035        range_utf16: Option<Range<usize>>,
16036        text: &str,
16037        new_selected_range_utf16: Option<Range<usize>>,
16038        window: &mut Window,
16039        cx: &mut Context<Self>,
16040    ) {
16041        if !self.input_enabled {
16042            return;
16043        }
16044
16045        let transaction = self.transact(window, cx, |this, window, cx| {
16046            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16047                let snapshot = this.buffer.read(cx).read(cx);
16048                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16049                    for marked_range in &mut marked_ranges {
16050                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16051                        marked_range.start.0 += relative_range_utf16.start;
16052                        marked_range.start =
16053                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16054                        marked_range.end =
16055                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16056                    }
16057                }
16058                Some(marked_ranges)
16059            } else if let Some(range_utf16) = range_utf16 {
16060                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16061                Some(this.selection_replacement_ranges(range_utf16, cx))
16062            } else {
16063                None
16064            };
16065
16066            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16067                let newest_selection_id = this.selections.newest_anchor().id;
16068                this.selections
16069                    .all::<OffsetUtf16>(cx)
16070                    .iter()
16071                    .zip(ranges_to_replace.iter())
16072                    .find_map(|(selection, range)| {
16073                        if selection.id == newest_selection_id {
16074                            Some(
16075                                (range.start.0 as isize - selection.head().0 as isize)
16076                                    ..(range.end.0 as isize - selection.head().0 as isize),
16077                            )
16078                        } else {
16079                            None
16080                        }
16081                    })
16082            });
16083
16084            cx.emit(EditorEvent::InputHandled {
16085                utf16_range_to_replace: range_to_replace,
16086                text: text.into(),
16087            });
16088
16089            if let Some(ranges) = ranges_to_replace {
16090                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16091            }
16092
16093            let marked_ranges = {
16094                let snapshot = this.buffer.read(cx).read(cx);
16095                this.selections
16096                    .disjoint_anchors()
16097                    .iter()
16098                    .map(|selection| {
16099                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16100                    })
16101                    .collect::<Vec<_>>()
16102            };
16103
16104            if text.is_empty() {
16105                this.unmark_text(window, cx);
16106            } else {
16107                this.highlight_text::<InputComposition>(
16108                    marked_ranges.clone(),
16109                    HighlightStyle {
16110                        underline: Some(UnderlineStyle {
16111                            thickness: px(1.),
16112                            color: None,
16113                            wavy: false,
16114                        }),
16115                        ..Default::default()
16116                    },
16117                    cx,
16118                );
16119            }
16120
16121            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16122            let use_autoclose = this.use_autoclose;
16123            let use_auto_surround = this.use_auto_surround;
16124            this.set_use_autoclose(false);
16125            this.set_use_auto_surround(false);
16126            this.handle_input(text, window, cx);
16127            this.set_use_autoclose(use_autoclose);
16128            this.set_use_auto_surround(use_auto_surround);
16129
16130            if let Some(new_selected_range) = new_selected_range_utf16 {
16131                let snapshot = this.buffer.read(cx).read(cx);
16132                let new_selected_ranges = marked_ranges
16133                    .into_iter()
16134                    .map(|marked_range| {
16135                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16136                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16137                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16138                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16139                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16140                    })
16141                    .collect::<Vec<_>>();
16142
16143                drop(snapshot);
16144                this.change_selections(None, window, cx, |selections| {
16145                    selections.select_ranges(new_selected_ranges)
16146                });
16147            }
16148        });
16149
16150        self.ime_transaction = self.ime_transaction.or(transaction);
16151        if let Some(transaction) = self.ime_transaction {
16152            self.buffer.update(cx, |buffer, cx| {
16153                buffer.group_until_transaction(transaction, cx);
16154            });
16155        }
16156
16157        if self.text_highlights::<InputComposition>(cx).is_none() {
16158            self.ime_transaction.take();
16159        }
16160    }
16161
16162    fn bounds_for_range(
16163        &mut self,
16164        range_utf16: Range<usize>,
16165        element_bounds: gpui::Bounds<Pixels>,
16166        window: &mut Window,
16167        cx: &mut Context<Self>,
16168    ) -> Option<gpui::Bounds<Pixels>> {
16169        let text_layout_details = self.text_layout_details(window);
16170        let gpui::Size {
16171            width: em_width,
16172            height: line_height,
16173        } = self.character_size(window);
16174
16175        let snapshot = self.snapshot(window, cx);
16176        let scroll_position = snapshot.scroll_position();
16177        let scroll_left = scroll_position.x * em_width;
16178
16179        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16180        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16181            + self.gutter_dimensions.width
16182            + self.gutter_dimensions.margin;
16183        let y = line_height * (start.row().as_f32() - scroll_position.y);
16184
16185        Some(Bounds {
16186            origin: element_bounds.origin + point(x, y),
16187            size: size(em_width, line_height),
16188        })
16189    }
16190
16191    fn character_index_for_point(
16192        &mut self,
16193        point: gpui::Point<Pixels>,
16194        _window: &mut Window,
16195        _cx: &mut Context<Self>,
16196    ) -> Option<usize> {
16197        let position_map = self.last_position_map.as_ref()?;
16198        if !position_map.text_hitbox.contains(&point) {
16199            return None;
16200        }
16201        let display_point = position_map.point_for_position(point).previous_valid;
16202        let anchor = position_map
16203            .snapshot
16204            .display_point_to_anchor(display_point, Bias::Left);
16205        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16206        Some(utf16_offset.0)
16207    }
16208}
16209
16210trait SelectionExt {
16211    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16212    fn spanned_rows(
16213        &self,
16214        include_end_if_at_line_start: bool,
16215        map: &DisplaySnapshot,
16216    ) -> Range<MultiBufferRow>;
16217}
16218
16219impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16220    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16221        let start = self
16222            .start
16223            .to_point(&map.buffer_snapshot)
16224            .to_display_point(map);
16225        let end = self
16226            .end
16227            .to_point(&map.buffer_snapshot)
16228            .to_display_point(map);
16229        if self.reversed {
16230            end..start
16231        } else {
16232            start..end
16233        }
16234    }
16235
16236    fn spanned_rows(
16237        &self,
16238        include_end_if_at_line_start: bool,
16239        map: &DisplaySnapshot,
16240    ) -> Range<MultiBufferRow> {
16241        let start = self.start.to_point(&map.buffer_snapshot);
16242        let mut end = self.end.to_point(&map.buffer_snapshot);
16243        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16244            end.row -= 1;
16245        }
16246
16247        let buffer_start = map.prev_line_boundary(start).0;
16248        let buffer_end = map.next_line_boundary(end).0;
16249        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16250    }
16251}
16252
16253impl<T: InvalidationRegion> InvalidationStack<T> {
16254    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16255    where
16256        S: Clone + ToOffset,
16257    {
16258        while let Some(region) = self.last() {
16259            let all_selections_inside_invalidation_ranges =
16260                if selections.len() == region.ranges().len() {
16261                    selections
16262                        .iter()
16263                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16264                        .all(|(selection, invalidation_range)| {
16265                            let head = selection.head().to_offset(buffer);
16266                            invalidation_range.start <= head && invalidation_range.end >= head
16267                        })
16268                } else {
16269                    false
16270                };
16271
16272            if all_selections_inside_invalidation_ranges {
16273                break;
16274            } else {
16275                self.pop();
16276            }
16277        }
16278    }
16279}
16280
16281impl<T> Default for InvalidationStack<T> {
16282    fn default() -> Self {
16283        Self(Default::default())
16284    }
16285}
16286
16287impl<T> Deref for InvalidationStack<T> {
16288    type Target = Vec<T>;
16289
16290    fn deref(&self) -> &Self::Target {
16291        &self.0
16292    }
16293}
16294
16295impl<T> DerefMut for InvalidationStack<T> {
16296    fn deref_mut(&mut self) -> &mut Self::Target {
16297        &mut self.0
16298    }
16299}
16300
16301impl InvalidationRegion for SnippetState {
16302    fn ranges(&self) -> &[Range<Anchor>] {
16303        &self.ranges[self.active_index]
16304    }
16305}
16306
16307pub fn diagnostic_block_renderer(
16308    diagnostic: Diagnostic,
16309    max_message_rows: Option<u8>,
16310    allow_closing: bool,
16311    _is_valid: bool,
16312) -> RenderBlock {
16313    let (text_without_backticks, code_ranges) =
16314        highlight_diagnostic_message(&diagnostic, max_message_rows);
16315
16316    Arc::new(move |cx: &mut BlockContext| {
16317        let group_id: SharedString = cx.block_id.to_string().into();
16318
16319        let mut text_style = cx.window.text_style().clone();
16320        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16321        let theme_settings = ThemeSettings::get_global(cx);
16322        text_style.font_family = theme_settings.buffer_font.family.clone();
16323        text_style.font_style = theme_settings.buffer_font.style;
16324        text_style.font_features = theme_settings.buffer_font.features.clone();
16325        text_style.font_weight = theme_settings.buffer_font.weight;
16326
16327        let multi_line_diagnostic = diagnostic.message.contains('\n');
16328
16329        let buttons = |diagnostic: &Diagnostic| {
16330            if multi_line_diagnostic {
16331                v_flex()
16332            } else {
16333                h_flex()
16334            }
16335            .when(allow_closing, |div| {
16336                div.children(diagnostic.is_primary.then(|| {
16337                    IconButton::new("close-block", IconName::XCircle)
16338                        .icon_color(Color::Muted)
16339                        .size(ButtonSize::Compact)
16340                        .style(ButtonStyle::Transparent)
16341                        .visible_on_hover(group_id.clone())
16342                        .on_click(move |_click, window, cx| {
16343                            window.dispatch_action(Box::new(Cancel), cx)
16344                        })
16345                        .tooltip(|window, cx| {
16346                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16347                        })
16348                }))
16349            })
16350            .child(
16351                IconButton::new("copy-block", IconName::Copy)
16352                    .icon_color(Color::Muted)
16353                    .size(ButtonSize::Compact)
16354                    .style(ButtonStyle::Transparent)
16355                    .visible_on_hover(group_id.clone())
16356                    .on_click({
16357                        let message = diagnostic.message.clone();
16358                        move |_click, _, cx| {
16359                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16360                        }
16361                    })
16362                    .tooltip(Tooltip::text("Copy diagnostic message")),
16363            )
16364        };
16365
16366        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16367            AvailableSpace::min_size(),
16368            cx.window,
16369            cx.app,
16370        );
16371
16372        h_flex()
16373            .id(cx.block_id)
16374            .group(group_id.clone())
16375            .relative()
16376            .size_full()
16377            .block_mouse_down()
16378            .pl(cx.gutter_dimensions.width)
16379            .w(cx.max_width - cx.gutter_dimensions.full_width())
16380            .child(
16381                div()
16382                    .flex()
16383                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16384                    .flex_shrink(),
16385            )
16386            .child(buttons(&diagnostic))
16387            .child(div().flex().flex_shrink_0().child(
16388                StyledText::new(text_without_backticks.clone()).with_highlights(
16389                    &text_style,
16390                    code_ranges.iter().map(|range| {
16391                        (
16392                            range.clone(),
16393                            HighlightStyle {
16394                                font_weight: Some(FontWeight::BOLD),
16395                                ..Default::default()
16396                            },
16397                        )
16398                    }),
16399                ),
16400            ))
16401            .into_any_element()
16402    })
16403}
16404
16405fn inline_completion_edit_text(
16406    current_snapshot: &BufferSnapshot,
16407    edits: &[(Range<Anchor>, String)],
16408    edit_preview: &EditPreview,
16409    include_deletions: bool,
16410    cx: &App,
16411) -> HighlightedText {
16412    let edits = edits
16413        .iter()
16414        .map(|(anchor, text)| {
16415            (
16416                anchor.start.text_anchor..anchor.end.text_anchor,
16417                text.clone(),
16418            )
16419        })
16420        .collect::<Vec<_>>();
16421
16422    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16423}
16424
16425pub fn highlight_diagnostic_message(
16426    diagnostic: &Diagnostic,
16427    mut max_message_rows: Option<u8>,
16428) -> (SharedString, Vec<Range<usize>>) {
16429    let mut text_without_backticks = String::new();
16430    let mut code_ranges = Vec::new();
16431
16432    if let Some(source) = &diagnostic.source {
16433        text_without_backticks.push_str(source);
16434        code_ranges.push(0..source.len());
16435        text_without_backticks.push_str(": ");
16436    }
16437
16438    let mut prev_offset = 0;
16439    let mut in_code_block = false;
16440    let has_row_limit = max_message_rows.is_some();
16441    let mut newline_indices = diagnostic
16442        .message
16443        .match_indices('\n')
16444        .filter(|_| has_row_limit)
16445        .map(|(ix, _)| ix)
16446        .fuse()
16447        .peekable();
16448
16449    for (quote_ix, _) in diagnostic
16450        .message
16451        .match_indices('`')
16452        .chain([(diagnostic.message.len(), "")])
16453    {
16454        let mut first_newline_ix = None;
16455        let mut last_newline_ix = None;
16456        while let Some(newline_ix) = newline_indices.peek() {
16457            if *newline_ix < quote_ix {
16458                if first_newline_ix.is_none() {
16459                    first_newline_ix = Some(*newline_ix);
16460                }
16461                last_newline_ix = Some(*newline_ix);
16462
16463                if let Some(rows_left) = &mut max_message_rows {
16464                    if *rows_left == 0 {
16465                        break;
16466                    } else {
16467                        *rows_left -= 1;
16468                    }
16469                }
16470                let _ = newline_indices.next();
16471            } else {
16472                break;
16473            }
16474        }
16475        let prev_len = text_without_backticks.len();
16476        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16477        text_without_backticks.push_str(new_text);
16478        if in_code_block {
16479            code_ranges.push(prev_len..text_without_backticks.len());
16480        }
16481        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16482        in_code_block = !in_code_block;
16483        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16484            text_without_backticks.push_str("...");
16485            break;
16486        }
16487    }
16488
16489    (text_without_backticks.into(), code_ranges)
16490}
16491
16492fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16493    match severity {
16494        DiagnosticSeverity::ERROR => colors.error,
16495        DiagnosticSeverity::WARNING => colors.warning,
16496        DiagnosticSeverity::INFORMATION => colors.info,
16497        DiagnosticSeverity::HINT => colors.info,
16498        _ => colors.ignored,
16499    }
16500}
16501
16502pub fn styled_runs_for_code_label<'a>(
16503    label: &'a CodeLabel,
16504    syntax_theme: &'a theme::SyntaxTheme,
16505) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16506    let fade_out = HighlightStyle {
16507        fade_out: Some(0.35),
16508        ..Default::default()
16509    };
16510
16511    let mut prev_end = label.filter_range.end;
16512    label
16513        .runs
16514        .iter()
16515        .enumerate()
16516        .flat_map(move |(ix, (range, highlight_id))| {
16517            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16518                style
16519            } else {
16520                return Default::default();
16521            };
16522            let mut muted_style = style;
16523            muted_style.highlight(fade_out);
16524
16525            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16526            if range.start >= label.filter_range.end {
16527                if range.start > prev_end {
16528                    runs.push((prev_end..range.start, fade_out));
16529                }
16530                runs.push((range.clone(), muted_style));
16531            } else if range.end <= label.filter_range.end {
16532                runs.push((range.clone(), style));
16533            } else {
16534                runs.push((range.start..label.filter_range.end, style));
16535                runs.push((label.filter_range.end..range.end, muted_style));
16536            }
16537            prev_end = cmp::max(prev_end, range.end);
16538
16539            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16540                runs.push((prev_end..label.text.len(), fade_out));
16541            }
16542
16543            runs
16544        })
16545}
16546
16547pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16548    let mut prev_index = 0;
16549    let mut prev_codepoint: Option<char> = None;
16550    text.char_indices()
16551        .chain([(text.len(), '\0')])
16552        .filter_map(move |(index, codepoint)| {
16553            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16554            let is_boundary = index == text.len()
16555                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16556                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16557            if is_boundary {
16558                let chunk = &text[prev_index..index];
16559                prev_index = index;
16560                Some(chunk)
16561            } else {
16562                None
16563            }
16564        })
16565}
16566
16567pub trait RangeToAnchorExt: Sized {
16568    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16569
16570    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16571        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16572        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16573    }
16574}
16575
16576impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16577    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16578        let start_offset = self.start.to_offset(snapshot);
16579        let end_offset = self.end.to_offset(snapshot);
16580        if start_offset == end_offset {
16581            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16582        } else {
16583            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16584        }
16585    }
16586}
16587
16588pub trait RowExt {
16589    fn as_f32(&self) -> f32;
16590
16591    fn next_row(&self) -> Self;
16592
16593    fn previous_row(&self) -> Self;
16594
16595    fn minus(&self, other: Self) -> u32;
16596}
16597
16598impl RowExt for DisplayRow {
16599    fn as_f32(&self) -> f32 {
16600        self.0 as f32
16601    }
16602
16603    fn next_row(&self) -> Self {
16604        Self(self.0 + 1)
16605    }
16606
16607    fn previous_row(&self) -> Self {
16608        Self(self.0.saturating_sub(1))
16609    }
16610
16611    fn minus(&self, other: Self) -> u32 {
16612        self.0 - other.0
16613    }
16614}
16615
16616impl RowExt for MultiBufferRow {
16617    fn as_f32(&self) -> f32 {
16618        self.0 as f32
16619    }
16620
16621    fn next_row(&self) -> Self {
16622        Self(self.0 + 1)
16623    }
16624
16625    fn previous_row(&self) -> Self {
16626        Self(self.0.saturating_sub(1))
16627    }
16628
16629    fn minus(&self, other: Self) -> u32 {
16630        self.0 - other.0
16631    }
16632}
16633
16634trait RowRangeExt {
16635    type Row;
16636
16637    fn len(&self) -> usize;
16638
16639    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16640}
16641
16642impl RowRangeExt for Range<MultiBufferRow> {
16643    type Row = MultiBufferRow;
16644
16645    fn len(&self) -> usize {
16646        (self.end.0 - self.start.0) as usize
16647    }
16648
16649    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16650        (self.start.0..self.end.0).map(MultiBufferRow)
16651    }
16652}
16653
16654impl RowRangeExt for Range<DisplayRow> {
16655    type Row = DisplayRow;
16656
16657    fn len(&self) -> usize {
16658        (self.end.0 - self.start.0) as usize
16659    }
16660
16661    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16662        (self.start.0..self.end.0).map(DisplayRow)
16663    }
16664}
16665
16666/// If select range has more than one line, we
16667/// just point the cursor to range.start.
16668fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16669    if range.start.row == range.end.row {
16670        range
16671    } else {
16672        range.start..range.start
16673    }
16674}
16675pub struct KillRing(ClipboardItem);
16676impl Global for KillRing {}
16677
16678const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16679
16680fn all_edits_insertions_or_deletions(
16681    edits: &Vec<(Range<Anchor>, String)>,
16682    snapshot: &MultiBufferSnapshot,
16683) -> bool {
16684    let mut all_insertions = true;
16685    let mut all_deletions = true;
16686
16687    for (range, new_text) in edits.iter() {
16688        let range_is_empty = range.to_offset(&snapshot).is_empty();
16689        let text_is_empty = new_text.is_empty();
16690
16691        if range_is_empty != text_is_empty {
16692            if range_is_empty {
16693                all_deletions = false;
16694            } else {
16695                all_insertions = false;
16696            }
16697        } else {
16698            return false;
16699        }
16700
16701        if !all_insertions && !all_deletions {
16702            return false;
16703        }
16704    }
16705    all_insertions || all_deletions
16706}