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
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::StringMatchCandidate;
   72use zed_predict_tos::ZedPredictTos;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, App,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   83    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  100    Point, Selection, 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 movement::TextLayoutDetails;
  120pub use multi_buffer::{
  121    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  122    ToOffset, ToPoint,
  123};
  124use multi_buffer::{
  125    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  126};
  127use project::{
  128    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  129    project_settings::{GitGutterSetting, ProjectSettings},
  130    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  131    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  132};
  133use rand::prelude::*;
  134use rpc::{proto::*, ErrorExt};
  135use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  136use selections_collection::{
  137    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  138};
  139use serde::{Deserialize, Serialize};
  140use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  141use smallvec::SmallVec;
  142use snippet::Snippet;
  143use std::{
  144    any::TypeId,
  145    borrow::Cow,
  146    cell::RefCell,
  147    cmp::{self, Ordering, Reverse},
  148    mem,
  149    num::NonZeroU32,
  150    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  151    path::{Path, PathBuf},
  152    rc::Rc,
  153    sync::Arc,
  154    time::{Duration, Instant},
  155};
  156pub use sum_tree::Bias;
  157use sum_tree::TreeMap;
  158use text::{BufferId, OffsetUtf16, Rope};
  159use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  160use ui::{
  161    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  162    Tooltip,
  163};
  164use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  165use workspace::item::{ItemHandle, PreviewTabsSettings};
  166use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  167use workspace::{
  168    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  169};
  170use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  171
  172use crate::hover_links::{find_url, find_url_from_range};
  173use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  174
  175pub const FILE_HEADER_HEIGHT: u32 = 2;
  176pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  177pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  178pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  179const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  180const MAX_LINE_LEN: usize = 1024;
  181const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  182const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  183pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  184#[doc(hidden)]
  185pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  186
  187pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  188pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  189
  190pub fn render_parsed_markdown(
  191    element_id: impl Into<ElementId>,
  192    parsed: &language::ParsedMarkdown,
  193    editor_style: &EditorStyle,
  194    workspace: Option<WeakEntity<Workspace>>,
  195    cx: &mut App,
  196) -> InteractiveText {
  197    let code_span_background_color = cx
  198        .theme()
  199        .colors()
  200        .editor_document_highlight_read_background;
  201
  202    let highlights = gpui::combine_highlights(
  203        parsed.highlights.iter().filter_map(|(range, highlight)| {
  204            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  205            Some((range.clone(), highlight))
  206        }),
  207        parsed
  208            .regions
  209            .iter()
  210            .zip(&parsed.region_ranges)
  211            .filter_map(|(region, range)| {
  212                if region.code {
  213                    Some((
  214                        range.clone(),
  215                        HighlightStyle {
  216                            background_color: Some(code_span_background_color),
  217                            ..Default::default()
  218                        },
  219                    ))
  220                } else {
  221                    None
  222                }
  223            }),
  224    );
  225
  226    let mut links = Vec::new();
  227    let mut link_ranges = Vec::new();
  228    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  229        if let Some(link) = region.link.clone() {
  230            links.push(link);
  231            link_ranges.push(range.clone());
  232        }
  233    }
  234
  235    InteractiveText::new(
  236        element_id,
  237        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  238    )
  239    .on_click(
  240        link_ranges,
  241        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  242            markdown::Link::Web { url } => cx.open_url(url),
  243            markdown::Link::Path { path } => {
  244                if let Some(workspace) = &workspace {
  245                    _ = workspace.update(cx, |workspace, cx| {
  246                        workspace
  247                            .open_abs_path(path.clone(), false, window, cx)
  248                            .detach();
  249                    });
  250                }
  251            }
  252        },
  253    )
  254}
  255
  256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  257pub enum InlayId {
  258    InlineCompletion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::InlineCompletion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DocumentHighlightRead {}
  272enum DocumentHighlightWrite {}
  273enum InputComposition {}
  274
  275#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  276pub enum Navigated {
  277    Yes,
  278    No,
  279}
  280
  281impl Navigated {
  282    pub fn from_bool(yes: bool) -> Navigated {
  283        if yes {
  284            Navigated::Yes
  285        } else {
  286            Navigated::No
  287        }
  288    }
  289}
  290
  291pub fn init_settings(cx: &mut App) {
  292    EditorSettings::register(cx);
  293}
  294
  295pub fn init(cx: &mut App) {
  296    init_settings(cx);
  297
  298    workspace::register_project_item::<Editor>(cx);
  299    workspace::FollowableViewRegistry::register::<Editor>(cx);
  300    workspace::register_serializable_item::<Editor>(cx);
  301
  302    cx.observe_new(
  303        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  304            workspace.register_action(Editor::new_file);
  305            workspace.register_action(Editor::new_file_vertical);
  306            workspace.register_action(Editor::new_file_horizontal);
  307        },
  308    )
  309    .detach();
  310
  311    cx.on_action(move |_: &workspace::NewFile, cx| {
  312        let app_state = workspace::AppState::global(cx);
  313        if let Some(app_state) = app_state.upgrade() {
  314            workspace::open_new(
  315                Default::default(),
  316                app_state,
  317                cx,
  318                |workspace, window, cx| {
  319                    Editor::new_file(workspace, &Default::default(), window, cx)
  320                },
  321            )
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(
  329                Default::default(),
  330                app_state,
  331                cx,
  332                |workspace, window, cx| {
  333                    Editor::new_file(workspace, &Default::default(), window, cx)
  334                },
  335            )
  336            .detach();
  337        }
  338    });
  339    git::project_diff::init(cx);
  340}
  341
  342pub struct SearchWithinRange;
  343
  344trait InvalidationRegion {
  345    fn ranges(&self) -> &[Range<Anchor>];
  346}
  347
  348#[derive(Clone, Debug, PartialEq)]
  349pub enum SelectPhase {
  350    Begin {
  351        position: DisplayPoint,
  352        add: bool,
  353        click_count: usize,
  354    },
  355    BeginColumnar {
  356        position: DisplayPoint,
  357        reset: bool,
  358        goal_column: u32,
  359    },
  360    Extend {
  361        position: DisplayPoint,
  362        click_count: usize,
  363    },
  364    Update {
  365        position: DisplayPoint,
  366        goal_column: u32,
  367        scroll_delta: gpui::Point<f32>,
  368    },
  369    End,
  370}
  371
  372#[derive(Clone, Debug)]
  373pub enum SelectMode {
  374    Character,
  375    Word(Range<Anchor>),
  376    Line(Range<Anchor>),
  377    All,
  378}
  379
  380#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  381pub enum EditorMode {
  382    SingleLine { auto_width: bool },
  383    AutoHeight { max_lines: usize },
  384    Full,
  385}
  386
  387#[derive(Copy, Clone, Debug)]
  388pub enum SoftWrap {
  389    /// Prefer not to wrap at all.
  390    ///
  391    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  392    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  393    GitDiff,
  394    /// Prefer a single line generally, unless an overly long line is encountered.
  395    None,
  396    /// Soft wrap lines that exceed the editor width.
  397    EditorWidth,
  398    /// Soft wrap lines at the preferred line length.
  399    Column(u32),
  400    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  401    Bounded(u32),
  402}
  403
  404#[derive(Clone)]
  405pub struct EditorStyle {
  406    pub background: Hsla,
  407    pub local_player: PlayerColor,
  408    pub text: TextStyle,
  409    pub scrollbar_width: Pixels,
  410    pub syntax: Arc<SyntaxTheme>,
  411    pub status: StatusColors,
  412    pub inlay_hints_style: HighlightStyle,
  413    pub inline_completion_styles: InlineCompletionStyles,
  414    pub unnecessary_code_fade: f32,
  415}
  416
  417impl Default for EditorStyle {
  418    fn default() -> Self {
  419        Self {
  420            background: Hsla::default(),
  421            local_player: PlayerColor::default(),
  422            text: TextStyle::default(),
  423            scrollbar_width: Pixels::default(),
  424            syntax: Default::default(),
  425            // HACK: Status colors don't have a real default.
  426            // We should look into removing the status colors from the editor
  427            // style and retrieve them directly from the theme.
  428            status: StatusColors::dark(),
  429            inlay_hints_style: HighlightStyle::default(),
  430            inline_completion_styles: InlineCompletionStyles {
  431                insertion: HighlightStyle::default(),
  432                whitespace: HighlightStyle::default(),
  433            },
  434            unnecessary_code_fade: Default::default(),
  435        }
  436    }
  437}
  438
  439pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  440    let show_background = language_settings::language_settings(None, None, cx)
  441        .inlay_hints
  442        .show_background;
  443
  444    HighlightStyle {
  445        color: Some(cx.theme().status().hint),
  446        background_color: show_background.then(|| cx.theme().status().hint_background),
  447        ..HighlightStyle::default()
  448    }
  449}
  450
  451pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  452    InlineCompletionStyles {
  453        insertion: HighlightStyle {
  454            color: Some(cx.theme().status().predictive),
  455            ..HighlightStyle::default()
  456        },
  457        whitespace: HighlightStyle {
  458            background_color: Some(cx.theme().status().created_background),
  459            ..HighlightStyle::default()
  460        },
  461    }
  462}
  463
  464type CompletionId = usize;
  465
  466#[derive(Debug, Clone)]
  467enum InlineCompletionMenuHint {
  468    Loading,
  469    Loaded { text: InlineCompletionText },
  470    PendingTermsAcceptance,
  471    None,
  472}
  473
  474impl InlineCompletionMenuHint {
  475    pub fn label(&self) -> &'static str {
  476        match self {
  477            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  478                "Edit Prediction"
  479            }
  480            InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
  481            InlineCompletionMenuHint::None => "No Prediction",
  482        }
  483    }
  484}
  485
  486#[derive(Clone, Debug)]
  487enum InlineCompletionText {
  488    Move(SharedString),
  489    Edit {
  490        text: SharedString,
  491        highlights: Vec<(Range<usize>, HighlightStyle)>,
  492    },
  493}
  494
  495pub(crate) enum EditDisplayMode {
  496    TabAccept,
  497    DiffPopover,
  498    Inline,
  499}
  500
  501enum InlineCompletion {
  502    Edit {
  503        edits: Vec<(Range<Anchor>, String)>,
  504        display_mode: EditDisplayMode,
  505    },
  506    Move(Anchor),
  507}
  508
  509struct InlineCompletionState {
  510    inlay_ids: Vec<InlayId>,
  511    completion: InlineCompletion,
  512    invalidation_range: Range<Anchor>,
  513}
  514
  515enum InlineCompletionHighlight {}
  516
  517pub enum MenuInlineCompletionsPolicy {
  518    Never,
  519    ByProvider,
  520}
  521
  522#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  523struct EditorActionId(usize);
  524
  525impl EditorActionId {
  526    pub fn post_inc(&mut self) -> Self {
  527        let answer = self.0;
  528
  529        *self = Self(answer + 1);
  530
  531        Self(answer)
  532    }
  533}
  534
  535// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  536// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  537
  538type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  539type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  540
  541#[derive(Default)]
  542struct ScrollbarMarkerState {
  543    scrollbar_size: Size<Pixels>,
  544    dirty: bool,
  545    markers: Arc<[PaintQuad]>,
  546    pending_refresh: Option<Task<Result<()>>>,
  547}
  548
  549impl ScrollbarMarkerState {
  550    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  551        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  552    }
  553}
  554
  555#[derive(Clone, Debug)]
  556struct RunnableTasks {
  557    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  558    offset: MultiBufferOffset,
  559    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  560    column: u32,
  561    // Values of all named captures, including those starting with '_'
  562    extra_variables: HashMap<String, String>,
  563    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  564    context_range: Range<BufferOffset>,
  565}
  566
  567impl RunnableTasks {
  568    fn resolve<'a>(
  569        &'a self,
  570        cx: &'a task::TaskContext,
  571    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  572        self.templates.iter().filter_map(|(kind, template)| {
  573            template
  574                .resolve_task(&kind.to_id_base(), cx)
  575                .map(|task| (kind.clone(), task))
  576        })
  577    }
  578}
  579
  580#[derive(Clone)]
  581struct ResolvedTasks {
  582    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  583    position: Anchor,
  584}
  585#[derive(Copy, Clone, Debug)]
  586struct MultiBufferOffset(usize);
  587#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  588struct BufferOffset(usize);
  589
  590// Addons allow storing per-editor state in other crates (e.g. Vim)
  591pub trait Addon: 'static {
  592    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  593
  594    fn to_any(&self) -> &dyn std::any::Any;
  595}
  596
  597#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  598pub enum IsVimMode {
  599    Yes,
  600    No,
  601}
  602
  603/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  604///
  605/// See the [module level documentation](self) for more information.
  606pub struct Editor {
  607    focus_handle: FocusHandle,
  608    last_focused_descendant: Option<WeakFocusHandle>,
  609    /// The text buffer being edited
  610    buffer: Entity<MultiBuffer>,
  611    /// Map of how text in the buffer should be displayed.
  612    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  613    pub display_map: Entity<DisplayMap>,
  614    pub selections: SelectionsCollection,
  615    pub scroll_manager: ScrollManager,
  616    /// When inline assist editors are linked, they all render cursors because
  617    /// typing enters text into each of them, even the ones that aren't focused.
  618    pub(crate) show_cursor_when_unfocused: bool,
  619    columnar_selection_tail: Option<Anchor>,
  620    add_selections_state: Option<AddSelectionsState>,
  621    select_next_state: Option<SelectNextState>,
  622    select_prev_state: Option<SelectNextState>,
  623    selection_history: SelectionHistory,
  624    autoclose_regions: Vec<AutocloseRegion>,
  625    snippet_stack: InvalidationStack<SnippetState>,
  626    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  627    ime_transaction: Option<TransactionId>,
  628    active_diagnostics: Option<ActiveDiagnosticGroup>,
  629    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  630
  631    project: Option<Entity<Project>>,
  632    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  633    completion_provider: Option<Box<dyn CompletionProvider>>,
  634    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  635    blink_manager: Entity<BlinkManager>,
  636    show_cursor_names: bool,
  637    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  638    pub show_local_selections: bool,
  639    mode: EditorMode,
  640    show_breadcrumbs: bool,
  641    show_gutter: bool,
  642    show_scrollbars: bool,
  643    show_line_numbers: Option<bool>,
  644    use_relative_line_numbers: Option<bool>,
  645    show_git_diff_gutter: Option<bool>,
  646    show_code_actions: Option<bool>,
  647    show_runnables: Option<bool>,
  648    show_wrap_guides: Option<bool>,
  649    show_indent_guides: Option<bool>,
  650    placeholder_text: Option<Arc<str>>,
  651    highlight_order: usize,
  652    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  653    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  654    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  655    scrollbar_marker_state: ScrollbarMarkerState,
  656    active_indent_guides_state: ActiveIndentGuidesState,
  657    nav_history: Option<ItemNavHistory>,
  658    context_menu: RefCell<Option<CodeContextMenu>>,
  659    mouse_context_menu: Option<MouseContextMenu>,
  660    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  661    signature_help_state: SignatureHelpState,
  662    auto_signature_help: Option<bool>,
  663    find_all_references_task_sources: Vec<Anchor>,
  664    next_completion_id: CompletionId,
  665    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  666    code_actions_task: Option<Task<Result<()>>>,
  667    document_highlights_task: Option<Task<()>>,
  668    linked_editing_range_task: Option<Task<Option<()>>>,
  669    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  670    pending_rename: Option<RenameState>,
  671    searchable: bool,
  672    cursor_shape: CursorShape,
  673    current_line_highlight: Option<CurrentLineHighlight>,
  674    collapse_matches: bool,
  675    autoindent_mode: Option<AutoindentMode>,
  676    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  677    input_enabled: bool,
  678    use_modal_editing: bool,
  679    read_only: bool,
  680    leader_peer_id: Option<PeerId>,
  681    remote_id: Option<ViewId>,
  682    hover_state: HoverState,
  683    gutter_hovered: bool,
  684    hovered_link_state: Option<HoveredLinkState>,
  685    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  686    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  687    active_inline_completion: Option<InlineCompletionState>,
  688    // enable_inline_completions is a switch that Vim can use to disable
  689    // inline completions based on its mode.
  690    enable_inline_completions: bool,
  691    show_inline_completions_override: Option<bool>,
  692    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  693    inlay_hint_cache: InlayHintCache,
  694    next_inlay_id: usize,
  695    _subscriptions: Vec<Subscription>,
  696    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  697    gutter_dimensions: GutterDimensions,
  698    style: Option<EditorStyle>,
  699    text_style_refinement: Option<TextStyleRefinement>,
  700    next_editor_action_id: EditorActionId,
  701    editor_actions:
  702        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  703    use_autoclose: bool,
  704    use_auto_surround: bool,
  705    auto_replace_emoji_shortcode: bool,
  706    show_git_blame_gutter: bool,
  707    show_git_blame_inline: bool,
  708    show_git_blame_inline_delay_task: Option<Task<()>>,
  709    git_blame_inline_enabled: bool,
  710    serialize_dirty_buffers: bool,
  711    show_selection_menu: Option<bool>,
  712    blame: Option<Entity<GitBlame>>,
  713    blame_subscription: Option<Subscription>,
  714    custom_context_menu: Option<
  715        Box<
  716            dyn 'static
  717                + Fn(
  718                    &mut Self,
  719                    DisplayPoint,
  720                    &mut Window,
  721                    &mut Context<Self>,
  722                ) -> Option<Entity<ui::ContextMenu>>,
  723        >,
  724    >,
  725    last_bounds: Option<Bounds<Pixels>>,
  726    expect_bounds_change: Option<Bounds<Pixels>>,
  727    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  728    tasks_update_task: Option<Task<()>>,
  729    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  730    breadcrumb_header: Option<String>,
  731    focused_block: Option<FocusedBlock>,
  732    next_scroll_position: NextScrollCursorCenterTopBottom,
  733    addons: HashMap<TypeId, Box<dyn Addon>>,
  734    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  735    selection_mark_mode: bool,
  736    toggle_fold_multiple_buffers: Task<()>,
  737    _scroll_cursor_center_top_bottom_task: Task<()>,
  738}
  739
  740#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  741enum NextScrollCursorCenterTopBottom {
  742    #[default]
  743    Center,
  744    Top,
  745    Bottom,
  746}
  747
  748impl NextScrollCursorCenterTopBottom {
  749    fn next(&self) -> Self {
  750        match self {
  751            Self::Center => Self::Top,
  752            Self::Top => Self::Bottom,
  753            Self::Bottom => Self::Center,
  754        }
  755    }
  756}
  757
  758#[derive(Clone)]
  759pub struct EditorSnapshot {
  760    pub mode: EditorMode,
  761    show_gutter: bool,
  762    show_line_numbers: Option<bool>,
  763    show_git_diff_gutter: Option<bool>,
  764    show_code_actions: Option<bool>,
  765    show_runnables: Option<bool>,
  766    git_blame_gutter_max_author_length: Option<usize>,
  767    pub display_snapshot: DisplaySnapshot,
  768    pub placeholder_text: Option<Arc<str>>,
  769    is_focused: bool,
  770    scroll_anchor: ScrollAnchor,
  771    ongoing_scroll: OngoingScroll,
  772    current_line_highlight: CurrentLineHighlight,
  773    gutter_hovered: bool,
  774}
  775
  776const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  777
  778#[derive(Default, Debug, Clone, Copy)]
  779pub struct GutterDimensions {
  780    pub left_padding: Pixels,
  781    pub right_padding: Pixels,
  782    pub width: Pixels,
  783    pub margin: Pixels,
  784    pub git_blame_entries_width: Option<Pixels>,
  785}
  786
  787impl GutterDimensions {
  788    /// The full width of the space taken up by the gutter.
  789    pub fn full_width(&self) -> Pixels {
  790        self.margin + self.width
  791    }
  792
  793    /// The width of the space reserved for the fold indicators,
  794    /// use alongside 'justify_end' and `gutter_width` to
  795    /// right align content with the line numbers
  796    pub fn fold_area_width(&self) -> Pixels {
  797        self.margin + self.right_padding
  798    }
  799}
  800
  801#[derive(Debug)]
  802pub struct RemoteSelection {
  803    pub replica_id: ReplicaId,
  804    pub selection: Selection<Anchor>,
  805    pub cursor_shape: CursorShape,
  806    pub peer_id: PeerId,
  807    pub line_mode: bool,
  808    pub participant_index: Option<ParticipantIndex>,
  809    pub user_name: Option<SharedString>,
  810}
  811
  812#[derive(Clone, Debug)]
  813struct SelectionHistoryEntry {
  814    selections: Arc<[Selection<Anchor>]>,
  815    select_next_state: Option<SelectNextState>,
  816    select_prev_state: Option<SelectNextState>,
  817    add_selections_state: Option<AddSelectionsState>,
  818}
  819
  820enum SelectionHistoryMode {
  821    Normal,
  822    Undoing,
  823    Redoing,
  824}
  825
  826#[derive(Clone, PartialEq, Eq, Hash)]
  827struct HoveredCursor {
  828    replica_id: u16,
  829    selection_id: usize,
  830}
  831
  832impl Default for SelectionHistoryMode {
  833    fn default() -> Self {
  834        Self::Normal
  835    }
  836}
  837
  838#[derive(Default)]
  839struct SelectionHistory {
  840    #[allow(clippy::type_complexity)]
  841    selections_by_transaction:
  842        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  843    mode: SelectionHistoryMode,
  844    undo_stack: VecDeque<SelectionHistoryEntry>,
  845    redo_stack: VecDeque<SelectionHistoryEntry>,
  846}
  847
  848impl SelectionHistory {
  849    fn insert_transaction(
  850        &mut self,
  851        transaction_id: TransactionId,
  852        selections: Arc<[Selection<Anchor>]>,
  853    ) {
  854        self.selections_by_transaction
  855            .insert(transaction_id, (selections, None));
  856    }
  857
  858    #[allow(clippy::type_complexity)]
  859    fn transaction(
  860        &self,
  861        transaction_id: TransactionId,
  862    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  863        self.selections_by_transaction.get(&transaction_id)
  864    }
  865
  866    #[allow(clippy::type_complexity)]
  867    fn transaction_mut(
  868        &mut self,
  869        transaction_id: TransactionId,
  870    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  871        self.selections_by_transaction.get_mut(&transaction_id)
  872    }
  873
  874    fn push(&mut self, entry: SelectionHistoryEntry) {
  875        if !entry.selections.is_empty() {
  876            match self.mode {
  877                SelectionHistoryMode::Normal => {
  878                    self.push_undo(entry);
  879                    self.redo_stack.clear();
  880                }
  881                SelectionHistoryMode::Undoing => self.push_redo(entry),
  882                SelectionHistoryMode::Redoing => self.push_undo(entry),
  883            }
  884        }
  885    }
  886
  887    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  888        if self
  889            .undo_stack
  890            .back()
  891            .map_or(true, |e| e.selections != entry.selections)
  892        {
  893            self.undo_stack.push_back(entry);
  894            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  895                self.undo_stack.pop_front();
  896            }
  897        }
  898    }
  899
  900    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  901        if self
  902            .redo_stack
  903            .back()
  904            .map_or(true, |e| e.selections != entry.selections)
  905        {
  906            self.redo_stack.push_back(entry);
  907            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  908                self.redo_stack.pop_front();
  909            }
  910        }
  911    }
  912}
  913
  914struct RowHighlight {
  915    index: usize,
  916    range: Range<Anchor>,
  917    color: Hsla,
  918    should_autoscroll: bool,
  919}
  920
  921#[derive(Clone, Debug)]
  922struct AddSelectionsState {
  923    above: bool,
  924    stack: Vec<usize>,
  925}
  926
  927#[derive(Clone)]
  928struct SelectNextState {
  929    query: AhoCorasick,
  930    wordwise: bool,
  931    done: bool,
  932}
  933
  934impl std::fmt::Debug for SelectNextState {
  935    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  936        f.debug_struct(std::any::type_name::<Self>())
  937            .field("wordwise", &self.wordwise)
  938            .field("done", &self.done)
  939            .finish()
  940    }
  941}
  942
  943#[derive(Debug)]
  944struct AutocloseRegion {
  945    selection_id: usize,
  946    range: Range<Anchor>,
  947    pair: BracketPair,
  948}
  949
  950#[derive(Debug)]
  951struct SnippetState {
  952    ranges: Vec<Vec<Range<Anchor>>>,
  953    active_index: usize,
  954    choices: Vec<Option<Vec<String>>>,
  955}
  956
  957#[doc(hidden)]
  958pub struct RenameState {
  959    pub range: Range<Anchor>,
  960    pub old_name: Arc<str>,
  961    pub editor: Entity<Editor>,
  962    block_id: CustomBlockId,
  963}
  964
  965struct InvalidationStack<T>(Vec<T>);
  966
  967struct RegisteredInlineCompletionProvider {
  968    provider: Arc<dyn InlineCompletionProviderHandle>,
  969    _subscription: Subscription,
  970}
  971
  972#[derive(Debug)]
  973struct ActiveDiagnosticGroup {
  974    primary_range: Range<Anchor>,
  975    primary_message: String,
  976    group_id: usize,
  977    blocks: HashMap<CustomBlockId, Diagnostic>,
  978    is_valid: bool,
  979}
  980
  981#[derive(Serialize, Deserialize, Clone, Debug)]
  982pub struct ClipboardSelection {
  983    pub len: usize,
  984    pub is_entire_line: bool,
  985    pub first_line_indent: u32,
  986}
  987
  988#[derive(Debug)]
  989pub(crate) struct NavigationData {
  990    cursor_anchor: Anchor,
  991    cursor_position: Point,
  992    scroll_anchor: ScrollAnchor,
  993    scroll_top_row: u32,
  994}
  995
  996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  997pub enum GotoDefinitionKind {
  998    Symbol,
  999    Declaration,
 1000    Type,
 1001    Implementation,
 1002}
 1003
 1004#[derive(Debug, Clone)]
 1005enum InlayHintRefreshReason {
 1006    Toggle(bool),
 1007    SettingsChange(InlayHintSettings),
 1008    NewLinesShown,
 1009    BufferEdited(HashSet<Arc<Language>>),
 1010    RefreshRequested,
 1011    ExcerptsRemoved(Vec<ExcerptId>),
 1012}
 1013
 1014impl InlayHintRefreshReason {
 1015    fn description(&self) -> &'static str {
 1016        match self {
 1017            Self::Toggle(_) => "toggle",
 1018            Self::SettingsChange(_) => "settings change",
 1019            Self::NewLinesShown => "new lines shown",
 1020            Self::BufferEdited(_) => "buffer edited",
 1021            Self::RefreshRequested => "refresh requested",
 1022            Self::ExcerptsRemoved(_) => "excerpts removed",
 1023        }
 1024    }
 1025}
 1026
 1027pub enum FormatTarget {
 1028    Buffers,
 1029    Ranges(Vec<Range<MultiBufferPoint>>),
 1030}
 1031
 1032pub(crate) struct FocusedBlock {
 1033    id: BlockId,
 1034    focus_handle: WeakFocusHandle,
 1035}
 1036
 1037#[derive(Clone)]
 1038enum JumpData {
 1039    MultiBufferRow {
 1040        row: MultiBufferRow,
 1041        line_offset_from_top: u32,
 1042    },
 1043    MultiBufferPoint {
 1044        excerpt_id: ExcerptId,
 1045        position: Point,
 1046        anchor: text::Anchor,
 1047        line_offset_from_top: u32,
 1048    },
 1049}
 1050
 1051pub enum MultibufferSelectionMode {
 1052    First,
 1053    All,
 1054}
 1055
 1056impl Editor {
 1057    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1058        let buffer = cx.new(|cx| Buffer::local("", cx));
 1059        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1060        Self::new(
 1061            EditorMode::SingleLine { auto_width: false },
 1062            buffer,
 1063            None,
 1064            false,
 1065            window,
 1066            cx,
 1067        )
 1068    }
 1069
 1070    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1071        let buffer = cx.new(|cx| Buffer::local("", cx));
 1072        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1073        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1074    }
 1075
 1076    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1077        let buffer = cx.new(|cx| Buffer::local("", cx));
 1078        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1079        Self::new(
 1080            EditorMode::SingleLine { auto_width: true },
 1081            buffer,
 1082            None,
 1083            false,
 1084            window,
 1085            cx,
 1086        )
 1087    }
 1088
 1089    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1090        let buffer = cx.new(|cx| Buffer::local("", cx));
 1091        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1092        Self::new(
 1093            EditorMode::AutoHeight { max_lines },
 1094            buffer,
 1095            None,
 1096            false,
 1097            window,
 1098            cx,
 1099        )
 1100    }
 1101
 1102    pub fn for_buffer(
 1103        buffer: Entity<Buffer>,
 1104        project: Option<Entity<Project>>,
 1105        window: &mut Window,
 1106        cx: &mut Context<Self>,
 1107    ) -> Self {
 1108        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1109        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1110    }
 1111
 1112    pub fn for_multibuffer(
 1113        buffer: Entity<MultiBuffer>,
 1114        project: Option<Entity<Project>>,
 1115        show_excerpt_controls: bool,
 1116        window: &mut Window,
 1117        cx: &mut Context<Self>,
 1118    ) -> Self {
 1119        Self::new(
 1120            EditorMode::Full,
 1121            buffer,
 1122            project,
 1123            show_excerpt_controls,
 1124            window,
 1125            cx,
 1126        )
 1127    }
 1128
 1129    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1130        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1131        let mut clone = Self::new(
 1132            self.mode,
 1133            self.buffer.clone(),
 1134            self.project.clone(),
 1135            show_excerpt_controls,
 1136            window,
 1137            cx,
 1138        );
 1139        self.display_map.update(cx, |display_map, cx| {
 1140            let snapshot = display_map.snapshot(cx);
 1141            clone.display_map.update(cx, |display_map, cx| {
 1142                display_map.set_state(&snapshot, cx);
 1143            });
 1144        });
 1145        clone.selections.clone_state(&self.selections);
 1146        clone.scroll_manager.clone_state(&self.scroll_manager);
 1147        clone.searchable = self.searchable;
 1148        clone
 1149    }
 1150
 1151    pub fn new(
 1152        mode: EditorMode,
 1153        buffer: Entity<MultiBuffer>,
 1154        project: Option<Entity<Project>>,
 1155        show_excerpt_controls: bool,
 1156        window: &mut Window,
 1157        cx: &mut Context<Self>,
 1158    ) -> Self {
 1159        let style = window.text_style();
 1160        let font_size = style.font_size.to_pixels(window.rem_size());
 1161        let editor = cx.entity().downgrade();
 1162        let fold_placeholder = FoldPlaceholder {
 1163            constrain_width: true,
 1164            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1165                let editor = editor.clone();
 1166                div()
 1167                    .id(fold_id)
 1168                    .bg(cx.theme().colors().ghost_element_background)
 1169                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1170                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1171                    .rounded_sm()
 1172                    .size_full()
 1173                    .cursor_pointer()
 1174                    .child("")
 1175                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1176                    .on_click(move |_, _window, cx| {
 1177                        editor
 1178                            .update(cx, |editor, cx| {
 1179                                editor.unfold_ranges(
 1180                                    &[fold_range.start..fold_range.end],
 1181                                    true,
 1182                                    false,
 1183                                    cx,
 1184                                );
 1185                                cx.stop_propagation();
 1186                            })
 1187                            .ok();
 1188                    })
 1189                    .into_any()
 1190            }),
 1191            merge_adjacent: true,
 1192            ..Default::default()
 1193        };
 1194        let display_map = cx.new(|cx| {
 1195            DisplayMap::new(
 1196                buffer.clone(),
 1197                style.font(),
 1198                font_size,
 1199                None,
 1200                show_excerpt_controls,
 1201                FILE_HEADER_HEIGHT,
 1202                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1203                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1204                fold_placeholder,
 1205                cx,
 1206            )
 1207        });
 1208
 1209        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1210
 1211        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1212
 1213        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1214            .then(|| language_settings::SoftWrap::None);
 1215
 1216        let mut project_subscriptions = Vec::new();
 1217        if mode == EditorMode::Full {
 1218            if let Some(project) = project.as_ref() {
 1219                if buffer.read(cx).is_singleton() {
 1220                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1221                        cx.emit(EditorEvent::TitleChanged);
 1222                    }));
 1223                }
 1224                project_subscriptions.push(cx.subscribe_in(
 1225                    project,
 1226                    window,
 1227                    |editor, _, event, window, cx| {
 1228                        if let project::Event::RefreshInlayHints = event {
 1229                            editor
 1230                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1231                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1232                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1233                                let focus_handle = editor.focus_handle(cx);
 1234                                if focus_handle.is_focused(window) {
 1235                                    let snapshot = buffer.read(cx).snapshot();
 1236                                    for (range, snippet) in snippet_edits {
 1237                                        let editor_range =
 1238                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1239                                        editor
 1240                                            .insert_snippet(
 1241                                                &[editor_range],
 1242                                                snippet.clone(),
 1243                                                window,
 1244                                                cx,
 1245                                            )
 1246                                            .ok();
 1247                                    }
 1248                                }
 1249                            }
 1250                        }
 1251                    },
 1252                ));
 1253                if let Some(task_inventory) = project
 1254                    .read(cx)
 1255                    .task_store()
 1256                    .read(cx)
 1257                    .task_inventory()
 1258                    .cloned()
 1259                {
 1260                    project_subscriptions.push(cx.observe_in(
 1261                        &task_inventory,
 1262                        window,
 1263                        |editor, _, window, cx| {
 1264                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1265                        },
 1266                    ));
 1267                }
 1268            }
 1269        }
 1270
 1271        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1272
 1273        let inlay_hint_settings =
 1274            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1275        let focus_handle = cx.focus_handle();
 1276        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1277            .detach();
 1278        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1279            .detach();
 1280        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1281            .detach();
 1282        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1283            .detach();
 1284
 1285        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1286            Some(false)
 1287        } else {
 1288            None
 1289        };
 1290
 1291        let mut code_action_providers = Vec::new();
 1292        if let Some(project) = project.clone() {
 1293            get_unstaged_changes_for_buffers(
 1294                &project,
 1295                buffer.read(cx).all_buffers(),
 1296                buffer.clone(),
 1297                cx,
 1298            );
 1299            code_action_providers.push(Rc::new(project) as Rc<_>);
 1300        }
 1301
 1302        let mut this = Self {
 1303            focus_handle,
 1304            show_cursor_when_unfocused: false,
 1305            last_focused_descendant: None,
 1306            buffer: buffer.clone(),
 1307            display_map: display_map.clone(),
 1308            selections,
 1309            scroll_manager: ScrollManager::new(cx),
 1310            columnar_selection_tail: None,
 1311            add_selections_state: None,
 1312            select_next_state: None,
 1313            select_prev_state: None,
 1314            selection_history: Default::default(),
 1315            autoclose_regions: Default::default(),
 1316            snippet_stack: Default::default(),
 1317            select_larger_syntax_node_stack: Vec::new(),
 1318            ime_transaction: Default::default(),
 1319            active_diagnostics: None,
 1320            soft_wrap_mode_override,
 1321            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1322            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1323            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1324            project,
 1325            blink_manager: blink_manager.clone(),
 1326            show_local_selections: true,
 1327            show_scrollbars: true,
 1328            mode,
 1329            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1330            show_gutter: mode == EditorMode::Full,
 1331            show_line_numbers: None,
 1332            use_relative_line_numbers: None,
 1333            show_git_diff_gutter: None,
 1334            show_code_actions: None,
 1335            show_runnables: None,
 1336            show_wrap_guides: None,
 1337            show_indent_guides,
 1338            placeholder_text: None,
 1339            highlight_order: 0,
 1340            highlighted_rows: HashMap::default(),
 1341            background_highlights: Default::default(),
 1342            gutter_highlights: TreeMap::default(),
 1343            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1344            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1345            nav_history: None,
 1346            context_menu: RefCell::new(None),
 1347            mouse_context_menu: None,
 1348            completion_tasks: Default::default(),
 1349            signature_help_state: SignatureHelpState::default(),
 1350            auto_signature_help: None,
 1351            find_all_references_task_sources: Vec::new(),
 1352            next_completion_id: 0,
 1353            next_inlay_id: 0,
 1354            code_action_providers,
 1355            available_code_actions: Default::default(),
 1356            code_actions_task: Default::default(),
 1357            document_highlights_task: Default::default(),
 1358            linked_editing_range_task: Default::default(),
 1359            pending_rename: Default::default(),
 1360            searchable: true,
 1361            cursor_shape: EditorSettings::get_global(cx)
 1362                .cursor_shape
 1363                .unwrap_or_default(),
 1364            current_line_highlight: None,
 1365            autoindent_mode: Some(AutoindentMode::EachLine),
 1366            collapse_matches: false,
 1367            workspace: None,
 1368            input_enabled: true,
 1369            use_modal_editing: mode == EditorMode::Full,
 1370            read_only: false,
 1371            use_autoclose: true,
 1372            use_auto_surround: true,
 1373            auto_replace_emoji_shortcode: false,
 1374            leader_peer_id: None,
 1375            remote_id: None,
 1376            hover_state: Default::default(),
 1377            hovered_link_state: Default::default(),
 1378            inline_completion_provider: None,
 1379            active_inline_completion: None,
 1380            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1381
 1382            gutter_hovered: false,
 1383            pixel_position_of_newest_cursor: None,
 1384            last_bounds: None,
 1385            expect_bounds_change: None,
 1386            gutter_dimensions: GutterDimensions::default(),
 1387            style: None,
 1388            show_cursor_names: false,
 1389            hovered_cursors: Default::default(),
 1390            next_editor_action_id: EditorActionId::default(),
 1391            editor_actions: Rc::default(),
 1392            show_inline_completions_override: None,
 1393            enable_inline_completions: true,
 1394            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1395            custom_context_menu: None,
 1396            show_git_blame_gutter: false,
 1397            show_git_blame_inline: false,
 1398            show_selection_menu: None,
 1399            show_git_blame_inline_delay_task: None,
 1400            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1401            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1402                .session
 1403                .restore_unsaved_buffers,
 1404            blame: None,
 1405            blame_subscription: None,
 1406            tasks: Default::default(),
 1407            _subscriptions: vec![
 1408                cx.observe(&buffer, Self::on_buffer_changed),
 1409                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1410                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1411                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1412                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1413                cx.observe_window_activation(window, |editor, window, cx| {
 1414                    let active = window.is_window_active();
 1415                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1416                        if active {
 1417                            blink_manager.enable(cx);
 1418                        } else {
 1419                            blink_manager.disable(cx);
 1420                        }
 1421                    });
 1422                }),
 1423            ],
 1424            tasks_update_task: None,
 1425            linked_edit_ranges: Default::default(),
 1426            previous_search_ranges: None,
 1427            breadcrumb_header: None,
 1428            focused_block: None,
 1429            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1430            addons: HashMap::default(),
 1431            registered_buffers: HashMap::default(),
 1432            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1433            selection_mark_mode: false,
 1434            toggle_fold_multiple_buffers: Task::ready(()),
 1435            text_style_refinement: None,
 1436        };
 1437        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1438        this._subscriptions.extend(project_subscriptions);
 1439
 1440        this.end_selection(window, cx);
 1441        this.scroll_manager.show_scrollbar(window, cx);
 1442
 1443        if mode == EditorMode::Full {
 1444            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1445            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1446
 1447            if this.git_blame_inline_enabled {
 1448                this.git_blame_inline_enabled = true;
 1449                this.start_git_blame_inline(false, window, cx);
 1450            }
 1451
 1452            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1453                if let Some(project) = this.project.as_ref() {
 1454                    let lsp_store = project.read(cx).lsp_store();
 1455                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1456                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1457                    });
 1458                    this.registered_buffers
 1459                        .insert(buffer.read(cx).remote_id(), handle);
 1460                }
 1461            }
 1462        }
 1463
 1464        this.report_editor_event("Editor Opened", None, cx);
 1465        this
 1466    }
 1467
 1468    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1469        self.mouse_context_menu
 1470            .as_ref()
 1471            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1472    }
 1473
 1474    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1475        let mut key_context = KeyContext::new_with_defaults();
 1476        key_context.add("Editor");
 1477        let mode = match self.mode {
 1478            EditorMode::SingleLine { .. } => "single_line",
 1479            EditorMode::AutoHeight { .. } => "auto_height",
 1480            EditorMode::Full => "full",
 1481        };
 1482
 1483        if EditorSettings::jupyter_enabled(cx) {
 1484            key_context.add("jupyter");
 1485        }
 1486
 1487        key_context.set("mode", mode);
 1488        if self.pending_rename.is_some() {
 1489            key_context.add("renaming");
 1490        }
 1491        match self.context_menu.borrow().as_ref() {
 1492            Some(CodeContextMenu::Completions(_)) => {
 1493                key_context.add("menu");
 1494                key_context.add("showing_completions")
 1495            }
 1496            Some(CodeContextMenu::CodeActions(_)) => {
 1497                key_context.add("menu");
 1498                key_context.add("showing_code_actions")
 1499            }
 1500            None => {}
 1501        }
 1502
 1503        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1504        if !self.focus_handle(cx).contains_focused(window, cx)
 1505            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1506        {
 1507            for addon in self.addons.values() {
 1508                addon.extend_key_context(&mut key_context, cx)
 1509            }
 1510        }
 1511
 1512        if let Some(extension) = self
 1513            .buffer
 1514            .read(cx)
 1515            .as_singleton()
 1516            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1517        {
 1518            key_context.set("extension", extension.to_string());
 1519        }
 1520
 1521        if self.has_active_inline_completion() {
 1522            key_context.add("copilot_suggestion");
 1523            key_context.add("inline_completion");
 1524        }
 1525
 1526        if self.selection_mark_mode {
 1527            key_context.add("selection_mode");
 1528        }
 1529
 1530        key_context
 1531    }
 1532
 1533    pub fn new_file(
 1534        workspace: &mut Workspace,
 1535        _: &workspace::NewFile,
 1536        window: &mut Window,
 1537        cx: &mut Context<Workspace>,
 1538    ) {
 1539        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1540            "Failed to create buffer",
 1541            window,
 1542            cx,
 1543            |e, _, _| match e.error_code() {
 1544                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1545                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1546                e.error_tag("required").unwrap_or("the latest version")
 1547            )),
 1548                _ => None,
 1549            },
 1550        );
 1551    }
 1552
 1553    pub fn new_in_workspace(
 1554        workspace: &mut Workspace,
 1555        window: &mut Window,
 1556        cx: &mut Context<Workspace>,
 1557    ) -> Task<Result<Entity<Editor>>> {
 1558        let project = workspace.project().clone();
 1559        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1560
 1561        cx.spawn_in(window, |workspace, mut cx| async move {
 1562            let buffer = create.await?;
 1563            workspace.update_in(&mut cx, |workspace, window, cx| {
 1564                let editor =
 1565                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1566                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1567                editor
 1568            })
 1569        })
 1570    }
 1571
 1572    fn new_file_vertical(
 1573        workspace: &mut Workspace,
 1574        _: &workspace::NewFileSplitVertical,
 1575        window: &mut Window,
 1576        cx: &mut Context<Workspace>,
 1577    ) {
 1578        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1579    }
 1580
 1581    fn new_file_horizontal(
 1582        workspace: &mut Workspace,
 1583        _: &workspace::NewFileSplitHorizontal,
 1584        window: &mut Window,
 1585        cx: &mut Context<Workspace>,
 1586    ) {
 1587        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1588    }
 1589
 1590    fn new_file_in_direction(
 1591        workspace: &mut Workspace,
 1592        direction: SplitDirection,
 1593        window: &mut Window,
 1594        cx: &mut Context<Workspace>,
 1595    ) {
 1596        let project = workspace.project().clone();
 1597        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1598
 1599        cx.spawn_in(window, |workspace, mut cx| async move {
 1600            let buffer = create.await?;
 1601            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1602                workspace.split_item(
 1603                    direction,
 1604                    Box::new(
 1605                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1606                    ),
 1607                    window,
 1608                    cx,
 1609                )
 1610            })?;
 1611            anyhow::Ok(())
 1612        })
 1613        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1614            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 leader_peer_id(&self) -> Option<PeerId> {
 1625        self.leader_peer_id
 1626    }
 1627
 1628    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1629        &self.buffer
 1630    }
 1631
 1632    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1633        self.workspace.as_ref()?.0.upgrade()
 1634    }
 1635
 1636    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1637        self.buffer().read(cx).title(cx)
 1638    }
 1639
 1640    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1641        let git_blame_gutter_max_author_length = self
 1642            .render_git_blame_gutter(cx)
 1643            .then(|| {
 1644                if let Some(blame) = self.blame.as_ref() {
 1645                    let max_author_length =
 1646                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1647                    Some(max_author_length)
 1648                } else {
 1649                    None
 1650                }
 1651            })
 1652            .flatten();
 1653
 1654        EditorSnapshot {
 1655            mode: self.mode,
 1656            show_gutter: self.show_gutter,
 1657            show_line_numbers: self.show_line_numbers,
 1658            show_git_diff_gutter: self.show_git_diff_gutter,
 1659            show_code_actions: self.show_code_actions,
 1660            show_runnables: self.show_runnables,
 1661            git_blame_gutter_max_author_length,
 1662            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1663            scroll_anchor: self.scroll_manager.anchor(),
 1664            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1665            placeholder_text: self.placeholder_text.clone(),
 1666            is_focused: self.focus_handle.is_focused(window),
 1667            current_line_highlight: self
 1668                .current_line_highlight
 1669                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1670            gutter_hovered: self.gutter_hovered,
 1671        }
 1672    }
 1673
 1674    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1675        self.buffer.read(cx).language_at(point, cx)
 1676    }
 1677
 1678    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1679        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1680    }
 1681
 1682    pub fn active_excerpt(
 1683        &self,
 1684        cx: &App,
 1685    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1686        self.buffer
 1687            .read(cx)
 1688            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1689    }
 1690
 1691    pub fn mode(&self) -> EditorMode {
 1692        self.mode
 1693    }
 1694
 1695    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1696        self.collaboration_hub.as_deref()
 1697    }
 1698
 1699    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1700        self.collaboration_hub = Some(hub);
 1701    }
 1702
 1703    pub fn set_custom_context_menu(
 1704        &mut self,
 1705        f: impl 'static
 1706            + Fn(
 1707                &mut Self,
 1708                DisplayPoint,
 1709                &mut Window,
 1710                &mut Context<Self>,
 1711            ) -> Option<Entity<ui::ContextMenu>>,
 1712    ) {
 1713        self.custom_context_menu = Some(Box::new(f))
 1714    }
 1715
 1716    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1717        self.completion_provider = provider;
 1718    }
 1719
 1720    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1721        self.semantics_provider.clone()
 1722    }
 1723
 1724    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1725        self.semantics_provider = provider;
 1726    }
 1727
 1728    pub fn set_inline_completion_provider<T>(
 1729        &mut self,
 1730        provider: Option<Entity<T>>,
 1731        window: &mut Window,
 1732        cx: &mut Context<Self>,
 1733    ) where
 1734        T: InlineCompletionProvider,
 1735    {
 1736        self.inline_completion_provider =
 1737            provider.map(|provider| RegisteredInlineCompletionProvider {
 1738                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1739                    if this.focus_handle.is_focused(window) {
 1740                        this.update_visible_inline_completion(window, cx);
 1741                    }
 1742                }),
 1743                provider: Arc::new(provider),
 1744            });
 1745        self.refresh_inline_completion(false, false, window, cx);
 1746    }
 1747
 1748    pub fn placeholder_text(&self) -> Option<&str> {
 1749        self.placeholder_text.as_deref()
 1750    }
 1751
 1752    pub fn set_placeholder_text(
 1753        &mut self,
 1754        placeholder_text: impl Into<Arc<str>>,
 1755        cx: &mut Context<Self>,
 1756    ) {
 1757        let placeholder_text = Some(placeholder_text.into());
 1758        if self.placeholder_text != placeholder_text {
 1759            self.placeholder_text = placeholder_text;
 1760            cx.notify();
 1761        }
 1762    }
 1763
 1764    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1765        self.cursor_shape = cursor_shape;
 1766
 1767        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1768        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1769
 1770        cx.notify();
 1771    }
 1772
 1773    pub fn set_current_line_highlight(
 1774        &mut self,
 1775        current_line_highlight: Option<CurrentLineHighlight>,
 1776    ) {
 1777        self.current_line_highlight = current_line_highlight;
 1778    }
 1779
 1780    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1781        self.collapse_matches = collapse_matches;
 1782    }
 1783
 1784    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1785        let buffers = self.buffer.read(cx).all_buffers();
 1786        let Some(lsp_store) = self.lsp_store(cx) else {
 1787            return;
 1788        };
 1789        lsp_store.update(cx, |lsp_store, cx| {
 1790            for buffer in buffers {
 1791                self.registered_buffers
 1792                    .entry(buffer.read(cx).remote_id())
 1793                    .or_insert_with(|| {
 1794                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1795                    });
 1796            }
 1797        })
 1798    }
 1799
 1800    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1801        if self.collapse_matches {
 1802            return range.start..range.start;
 1803        }
 1804        range.clone()
 1805    }
 1806
 1807    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1808        if self.display_map.read(cx).clip_at_line_ends != clip {
 1809            self.display_map
 1810                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1811        }
 1812    }
 1813
 1814    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1815        self.input_enabled = input_enabled;
 1816    }
 1817
 1818    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1819        self.enable_inline_completions = enabled;
 1820        if !self.enable_inline_completions {
 1821            self.take_active_inline_completion(cx);
 1822            cx.notify();
 1823        }
 1824    }
 1825
 1826    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1827        self.menu_inline_completions_policy = value;
 1828    }
 1829
 1830    pub fn set_autoindent(&mut self, autoindent: bool) {
 1831        if autoindent {
 1832            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1833        } else {
 1834            self.autoindent_mode = None;
 1835        }
 1836    }
 1837
 1838    pub fn read_only(&self, cx: &App) -> bool {
 1839        self.read_only || self.buffer.read(cx).read_only()
 1840    }
 1841
 1842    pub fn set_read_only(&mut self, read_only: bool) {
 1843        self.read_only = read_only;
 1844    }
 1845
 1846    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1847        self.use_autoclose = autoclose;
 1848    }
 1849
 1850    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1851        self.use_auto_surround = auto_surround;
 1852    }
 1853
 1854    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1855        self.auto_replace_emoji_shortcode = auto_replace;
 1856    }
 1857
 1858    pub fn toggle_inline_completions(
 1859        &mut self,
 1860        _: &ToggleInlineCompletions,
 1861        window: &mut Window,
 1862        cx: &mut Context<Self>,
 1863    ) {
 1864        if self.show_inline_completions_override.is_some() {
 1865            self.set_show_inline_completions(None, window, cx);
 1866        } else {
 1867            let cursor = self.selections.newest_anchor().head();
 1868            if let Some((buffer, cursor_buffer_position)) =
 1869                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1870            {
 1871                let show_inline_completions =
 1872                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1873                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1874            }
 1875        }
 1876    }
 1877
 1878    pub fn set_show_inline_completions(
 1879        &mut self,
 1880        show_inline_completions: Option<bool>,
 1881        window: &mut Window,
 1882        cx: &mut Context<Self>,
 1883    ) {
 1884        self.show_inline_completions_override = show_inline_completions;
 1885        self.refresh_inline_completion(false, true, window, cx);
 1886    }
 1887
 1888    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1889        let cursor = self.selections.newest_anchor().head();
 1890        if let Some((buffer, buffer_position)) =
 1891            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1892        {
 1893            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1894        } else {
 1895            false
 1896        }
 1897    }
 1898
 1899    fn should_show_inline_completions(
 1900        &self,
 1901        buffer: &Entity<Buffer>,
 1902        buffer_position: language::Anchor,
 1903        cx: &App,
 1904    ) -> bool {
 1905        if !self.snippet_stack.is_empty() {
 1906            return false;
 1907        }
 1908
 1909        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1910            return false;
 1911        }
 1912
 1913        if let Some(provider) = self.inline_completion_provider() {
 1914            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1915                show_inline_completions
 1916            } else {
 1917                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1918            }
 1919        } else {
 1920            false
 1921        }
 1922    }
 1923
 1924    fn inline_completions_disabled_in_scope(
 1925        &self,
 1926        buffer: &Entity<Buffer>,
 1927        buffer_position: language::Anchor,
 1928        cx: &App,
 1929    ) -> bool {
 1930        let snapshot = buffer.read(cx).snapshot();
 1931        let settings = snapshot.settings_at(buffer_position, cx);
 1932
 1933        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1934            return false;
 1935        };
 1936
 1937        scope.override_name().map_or(false, |scope_name| {
 1938            settings
 1939                .inline_completions_disabled_in
 1940                .iter()
 1941                .any(|s| s == scope_name)
 1942        })
 1943    }
 1944
 1945    pub fn set_use_modal_editing(&mut self, to: bool) {
 1946        self.use_modal_editing = to;
 1947    }
 1948
 1949    pub fn use_modal_editing(&self) -> bool {
 1950        self.use_modal_editing
 1951    }
 1952
 1953    fn selections_did_change(
 1954        &mut self,
 1955        local: bool,
 1956        old_cursor_position: &Anchor,
 1957        show_completions: bool,
 1958        window: &mut Window,
 1959        cx: &mut Context<Self>,
 1960    ) {
 1961        window.invalidate_character_coordinates();
 1962
 1963        // Copy selections to primary selection buffer
 1964        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1965        if local {
 1966            let selections = self.selections.all::<usize>(cx);
 1967            let buffer_handle = self.buffer.read(cx).read(cx);
 1968
 1969            let mut text = String::new();
 1970            for (index, selection) in selections.iter().enumerate() {
 1971                let text_for_selection = buffer_handle
 1972                    .text_for_range(selection.start..selection.end)
 1973                    .collect::<String>();
 1974
 1975                text.push_str(&text_for_selection);
 1976                if index != selections.len() - 1 {
 1977                    text.push('\n');
 1978                }
 1979            }
 1980
 1981            if !text.is_empty() {
 1982                cx.write_to_primary(ClipboardItem::new_string(text));
 1983            }
 1984        }
 1985
 1986        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1987            self.buffer.update(cx, |buffer, cx| {
 1988                buffer.set_active_selections(
 1989                    &self.selections.disjoint_anchors(),
 1990                    self.selections.line_mode,
 1991                    self.cursor_shape,
 1992                    cx,
 1993                )
 1994            });
 1995        }
 1996        let display_map = self
 1997            .display_map
 1998            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1999        let buffer = &display_map.buffer_snapshot;
 2000        self.add_selections_state = None;
 2001        self.select_next_state = None;
 2002        self.select_prev_state = None;
 2003        self.select_larger_syntax_node_stack.clear();
 2004        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2005        self.snippet_stack
 2006            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2007        self.take_rename(false, window, cx);
 2008
 2009        let new_cursor_position = self.selections.newest_anchor().head();
 2010
 2011        self.push_to_nav_history(
 2012            *old_cursor_position,
 2013            Some(new_cursor_position.to_point(buffer)),
 2014            cx,
 2015        );
 2016
 2017        if local {
 2018            let new_cursor_position = self.selections.newest_anchor().head();
 2019            let mut context_menu = self.context_menu.borrow_mut();
 2020            let completion_menu = match context_menu.as_ref() {
 2021                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2022                _ => {
 2023                    *context_menu = None;
 2024                    None
 2025                }
 2026            };
 2027
 2028            if let Some(completion_menu) = completion_menu {
 2029                let cursor_position = new_cursor_position.to_offset(buffer);
 2030                let (word_range, kind) =
 2031                    buffer.surrounding_word(completion_menu.initial_position, true);
 2032                if kind == Some(CharKind::Word)
 2033                    && word_range.to_inclusive().contains(&cursor_position)
 2034                {
 2035                    let mut completion_menu = completion_menu.clone();
 2036                    drop(context_menu);
 2037
 2038                    let query = Self::completion_query(buffer, cursor_position);
 2039                    cx.spawn(move |this, mut cx| async move {
 2040                        completion_menu
 2041                            .filter(query.as_deref(), cx.background_executor().clone())
 2042                            .await;
 2043
 2044                        this.update(&mut cx, |this, cx| {
 2045                            let mut context_menu = this.context_menu.borrow_mut();
 2046                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2047                            else {
 2048                                return;
 2049                            };
 2050
 2051                            if menu.id > completion_menu.id {
 2052                                return;
 2053                            }
 2054
 2055                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2056                            drop(context_menu);
 2057                            cx.notify();
 2058                        })
 2059                    })
 2060                    .detach();
 2061
 2062                    if show_completions {
 2063                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2064                    }
 2065                } else {
 2066                    drop(context_menu);
 2067                    self.hide_context_menu(window, cx);
 2068                }
 2069            } else {
 2070                drop(context_menu);
 2071            }
 2072
 2073            hide_hover(self, cx);
 2074
 2075            if old_cursor_position.to_display_point(&display_map).row()
 2076                != new_cursor_position.to_display_point(&display_map).row()
 2077            {
 2078                self.available_code_actions.take();
 2079            }
 2080            self.refresh_code_actions(window, cx);
 2081            self.refresh_document_highlights(cx);
 2082            refresh_matching_bracket_highlights(self, window, cx);
 2083            self.update_visible_inline_completion(window, cx);
 2084            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2085            if self.git_blame_inline_enabled {
 2086                self.start_inline_blame_timer(window, cx);
 2087            }
 2088        }
 2089
 2090        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2091        cx.emit(EditorEvent::SelectionsChanged { local });
 2092
 2093        if self.selections.disjoint_anchors().len() == 1 {
 2094            cx.emit(SearchEvent::ActiveMatchChanged)
 2095        }
 2096        cx.notify();
 2097    }
 2098
 2099    pub fn change_selections<R>(
 2100        &mut self,
 2101        autoscroll: Option<Autoscroll>,
 2102        window: &mut Window,
 2103        cx: &mut Context<Self>,
 2104        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2105    ) -> R {
 2106        self.change_selections_inner(autoscroll, true, window, cx, change)
 2107    }
 2108
 2109    pub fn change_selections_inner<R>(
 2110        &mut self,
 2111        autoscroll: Option<Autoscroll>,
 2112        request_completions: bool,
 2113        window: &mut Window,
 2114        cx: &mut Context<Self>,
 2115        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2116    ) -> R {
 2117        let old_cursor_position = self.selections.newest_anchor().head();
 2118        self.push_to_selection_history();
 2119
 2120        let (changed, result) = self.selections.change_with(cx, change);
 2121
 2122        if changed {
 2123            if let Some(autoscroll) = autoscroll {
 2124                self.request_autoscroll(autoscroll, cx);
 2125            }
 2126            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2127
 2128            if self.should_open_signature_help_automatically(
 2129                &old_cursor_position,
 2130                self.signature_help_state.backspace_pressed(),
 2131                cx,
 2132            ) {
 2133                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2134            }
 2135            self.signature_help_state.set_backspace_pressed(false);
 2136        }
 2137
 2138        result
 2139    }
 2140
 2141    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2142    where
 2143        I: IntoIterator<Item = (Range<S>, T)>,
 2144        S: ToOffset,
 2145        T: Into<Arc<str>>,
 2146    {
 2147        if self.read_only(cx) {
 2148            return;
 2149        }
 2150
 2151        self.buffer
 2152            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2153    }
 2154
 2155    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2156    where
 2157        I: IntoIterator<Item = (Range<S>, T)>,
 2158        S: ToOffset,
 2159        T: Into<Arc<str>>,
 2160    {
 2161        if self.read_only(cx) {
 2162            return;
 2163        }
 2164
 2165        self.buffer.update(cx, |buffer, cx| {
 2166            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2167        });
 2168    }
 2169
 2170    pub fn edit_with_block_indent<I, S, T>(
 2171        &mut self,
 2172        edits: I,
 2173        original_indent_columns: Vec<u32>,
 2174        cx: &mut Context<Self>,
 2175    ) where
 2176        I: IntoIterator<Item = (Range<S>, T)>,
 2177        S: ToOffset,
 2178        T: Into<Arc<str>>,
 2179    {
 2180        if self.read_only(cx) {
 2181            return;
 2182        }
 2183
 2184        self.buffer.update(cx, |buffer, cx| {
 2185            buffer.edit(
 2186                edits,
 2187                Some(AutoindentMode::Block {
 2188                    original_indent_columns,
 2189                }),
 2190                cx,
 2191            )
 2192        });
 2193    }
 2194
 2195    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2196        self.hide_context_menu(window, cx);
 2197
 2198        match phase {
 2199            SelectPhase::Begin {
 2200                position,
 2201                add,
 2202                click_count,
 2203            } => self.begin_selection(position, add, click_count, window, cx),
 2204            SelectPhase::BeginColumnar {
 2205                position,
 2206                goal_column,
 2207                reset,
 2208            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2209            SelectPhase::Extend {
 2210                position,
 2211                click_count,
 2212            } => self.extend_selection(position, click_count, window, cx),
 2213            SelectPhase::Update {
 2214                position,
 2215                goal_column,
 2216                scroll_delta,
 2217            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2218            SelectPhase::End => self.end_selection(window, cx),
 2219        }
 2220    }
 2221
 2222    fn extend_selection(
 2223        &mut self,
 2224        position: DisplayPoint,
 2225        click_count: usize,
 2226        window: &mut Window,
 2227        cx: &mut Context<Self>,
 2228    ) {
 2229        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2230        let tail = self.selections.newest::<usize>(cx).tail();
 2231        self.begin_selection(position, false, click_count, window, cx);
 2232
 2233        let position = position.to_offset(&display_map, Bias::Left);
 2234        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2235
 2236        let mut pending_selection = self
 2237            .selections
 2238            .pending_anchor()
 2239            .expect("extend_selection not called with pending selection");
 2240        if position >= tail {
 2241            pending_selection.start = tail_anchor;
 2242        } else {
 2243            pending_selection.end = tail_anchor;
 2244            pending_selection.reversed = true;
 2245        }
 2246
 2247        let mut pending_mode = self.selections.pending_mode().unwrap();
 2248        match &mut pending_mode {
 2249            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2250            _ => {}
 2251        }
 2252
 2253        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2254            s.set_pending(pending_selection, pending_mode)
 2255        });
 2256    }
 2257
 2258    fn begin_selection(
 2259        &mut self,
 2260        position: DisplayPoint,
 2261        add: bool,
 2262        click_count: usize,
 2263        window: &mut Window,
 2264        cx: &mut Context<Self>,
 2265    ) {
 2266        if !self.focus_handle.is_focused(window) {
 2267            self.last_focused_descendant = None;
 2268            window.focus(&self.focus_handle);
 2269        }
 2270
 2271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2272        let buffer = &display_map.buffer_snapshot;
 2273        let newest_selection = self.selections.newest_anchor().clone();
 2274        let position = display_map.clip_point(position, Bias::Left);
 2275
 2276        let start;
 2277        let end;
 2278        let mode;
 2279        let mut auto_scroll;
 2280        match click_count {
 2281            1 => {
 2282                start = buffer.anchor_before(position.to_point(&display_map));
 2283                end = start;
 2284                mode = SelectMode::Character;
 2285                auto_scroll = true;
 2286            }
 2287            2 => {
 2288                let range = movement::surrounding_word(&display_map, position);
 2289                start = buffer.anchor_before(range.start.to_point(&display_map));
 2290                end = buffer.anchor_before(range.end.to_point(&display_map));
 2291                mode = SelectMode::Word(start..end);
 2292                auto_scroll = true;
 2293            }
 2294            3 => {
 2295                let position = display_map
 2296                    .clip_point(position, Bias::Left)
 2297                    .to_point(&display_map);
 2298                let line_start = display_map.prev_line_boundary(position).0;
 2299                let next_line_start = buffer.clip_point(
 2300                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2301                    Bias::Left,
 2302                );
 2303                start = buffer.anchor_before(line_start);
 2304                end = buffer.anchor_before(next_line_start);
 2305                mode = SelectMode::Line(start..end);
 2306                auto_scroll = true;
 2307            }
 2308            _ => {
 2309                start = buffer.anchor_before(0);
 2310                end = buffer.anchor_before(buffer.len());
 2311                mode = SelectMode::All;
 2312                auto_scroll = false;
 2313            }
 2314        }
 2315        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2316
 2317        let point_to_delete: Option<usize> = {
 2318            let selected_points: Vec<Selection<Point>> =
 2319                self.selections.disjoint_in_range(start..end, cx);
 2320
 2321            if !add || click_count > 1 {
 2322                None
 2323            } else if !selected_points.is_empty() {
 2324                Some(selected_points[0].id)
 2325            } else {
 2326                let clicked_point_already_selected =
 2327                    self.selections.disjoint.iter().find(|selection| {
 2328                        selection.start.to_point(buffer) == start.to_point(buffer)
 2329                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2330                    });
 2331
 2332                clicked_point_already_selected.map(|selection| selection.id)
 2333            }
 2334        };
 2335
 2336        let selections_count = self.selections.count();
 2337
 2338        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2339            if let Some(point_to_delete) = point_to_delete {
 2340                s.delete(point_to_delete);
 2341
 2342                if selections_count == 1 {
 2343                    s.set_pending_anchor_range(start..end, mode);
 2344                }
 2345            } else {
 2346                if !add {
 2347                    s.clear_disjoint();
 2348                } else if click_count > 1 {
 2349                    s.delete(newest_selection.id)
 2350                }
 2351
 2352                s.set_pending_anchor_range(start..end, mode);
 2353            }
 2354        });
 2355    }
 2356
 2357    fn begin_columnar_selection(
 2358        &mut self,
 2359        position: DisplayPoint,
 2360        goal_column: u32,
 2361        reset: bool,
 2362        window: &mut Window,
 2363        cx: &mut Context<Self>,
 2364    ) {
 2365        if !self.focus_handle.is_focused(window) {
 2366            self.last_focused_descendant = None;
 2367            window.focus(&self.focus_handle);
 2368        }
 2369
 2370        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2371
 2372        if reset {
 2373            let pointer_position = display_map
 2374                .buffer_snapshot
 2375                .anchor_before(position.to_point(&display_map));
 2376
 2377            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2378                s.clear_disjoint();
 2379                s.set_pending_anchor_range(
 2380                    pointer_position..pointer_position,
 2381                    SelectMode::Character,
 2382                );
 2383            });
 2384        }
 2385
 2386        let tail = self.selections.newest::<Point>(cx).tail();
 2387        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2388
 2389        if !reset {
 2390            self.select_columns(
 2391                tail.to_display_point(&display_map),
 2392                position,
 2393                goal_column,
 2394                &display_map,
 2395                window,
 2396                cx,
 2397            );
 2398        }
 2399    }
 2400
 2401    fn update_selection(
 2402        &mut self,
 2403        position: DisplayPoint,
 2404        goal_column: u32,
 2405        scroll_delta: gpui::Point<f32>,
 2406        window: &mut Window,
 2407        cx: &mut Context<Self>,
 2408    ) {
 2409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2410
 2411        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2412            let tail = tail.to_display_point(&display_map);
 2413            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2414        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2415            let buffer = self.buffer.read(cx).snapshot(cx);
 2416            let head;
 2417            let tail;
 2418            let mode = self.selections.pending_mode().unwrap();
 2419            match &mode {
 2420                SelectMode::Character => {
 2421                    head = position.to_point(&display_map);
 2422                    tail = pending.tail().to_point(&buffer);
 2423                }
 2424                SelectMode::Word(original_range) => {
 2425                    let original_display_range = original_range.start.to_display_point(&display_map)
 2426                        ..original_range.end.to_display_point(&display_map);
 2427                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2428                        ..original_display_range.end.to_point(&display_map);
 2429                    if movement::is_inside_word(&display_map, position)
 2430                        || original_display_range.contains(&position)
 2431                    {
 2432                        let word_range = movement::surrounding_word(&display_map, position);
 2433                        if word_range.start < original_display_range.start {
 2434                            head = word_range.start.to_point(&display_map);
 2435                        } else {
 2436                            head = word_range.end.to_point(&display_map);
 2437                        }
 2438                    } else {
 2439                        head = position.to_point(&display_map);
 2440                    }
 2441
 2442                    if head <= original_buffer_range.start {
 2443                        tail = original_buffer_range.end;
 2444                    } else {
 2445                        tail = original_buffer_range.start;
 2446                    }
 2447                }
 2448                SelectMode::Line(original_range) => {
 2449                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2450
 2451                    let position = display_map
 2452                        .clip_point(position, Bias::Left)
 2453                        .to_point(&display_map);
 2454                    let line_start = display_map.prev_line_boundary(position).0;
 2455                    let next_line_start = buffer.clip_point(
 2456                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2457                        Bias::Left,
 2458                    );
 2459
 2460                    if line_start < original_range.start {
 2461                        head = line_start
 2462                    } else {
 2463                        head = next_line_start
 2464                    }
 2465
 2466                    if head <= original_range.start {
 2467                        tail = original_range.end;
 2468                    } else {
 2469                        tail = original_range.start;
 2470                    }
 2471                }
 2472                SelectMode::All => {
 2473                    return;
 2474                }
 2475            };
 2476
 2477            if head < tail {
 2478                pending.start = buffer.anchor_before(head);
 2479                pending.end = buffer.anchor_before(tail);
 2480                pending.reversed = true;
 2481            } else {
 2482                pending.start = buffer.anchor_before(tail);
 2483                pending.end = buffer.anchor_before(head);
 2484                pending.reversed = false;
 2485            }
 2486
 2487            self.change_selections(None, window, cx, |s| {
 2488                s.set_pending(pending, mode);
 2489            });
 2490        } else {
 2491            log::error!("update_selection dispatched with no pending selection");
 2492            return;
 2493        }
 2494
 2495        self.apply_scroll_delta(scroll_delta, window, cx);
 2496        cx.notify();
 2497    }
 2498
 2499    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2500        self.columnar_selection_tail.take();
 2501        if self.selections.pending_anchor().is_some() {
 2502            let selections = self.selections.all::<usize>(cx);
 2503            self.change_selections(None, window, cx, |s| {
 2504                s.select(selections);
 2505                s.clear_pending();
 2506            });
 2507        }
 2508    }
 2509
 2510    fn select_columns(
 2511        &mut self,
 2512        tail: DisplayPoint,
 2513        head: DisplayPoint,
 2514        goal_column: u32,
 2515        display_map: &DisplaySnapshot,
 2516        window: &mut Window,
 2517        cx: &mut Context<Self>,
 2518    ) {
 2519        let start_row = cmp::min(tail.row(), head.row());
 2520        let end_row = cmp::max(tail.row(), head.row());
 2521        let start_column = cmp::min(tail.column(), goal_column);
 2522        let end_column = cmp::max(tail.column(), goal_column);
 2523        let reversed = start_column < tail.column();
 2524
 2525        let selection_ranges = (start_row.0..=end_row.0)
 2526            .map(DisplayRow)
 2527            .filter_map(|row| {
 2528                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2529                    let start = display_map
 2530                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2531                        .to_point(display_map);
 2532                    let end = display_map
 2533                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2534                        .to_point(display_map);
 2535                    if reversed {
 2536                        Some(end..start)
 2537                    } else {
 2538                        Some(start..end)
 2539                    }
 2540                } else {
 2541                    None
 2542                }
 2543            })
 2544            .collect::<Vec<_>>();
 2545
 2546        self.change_selections(None, window, cx, |s| {
 2547            s.select_ranges(selection_ranges);
 2548        });
 2549        cx.notify();
 2550    }
 2551
 2552    pub fn has_pending_nonempty_selection(&self) -> bool {
 2553        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2554            Some(Selection { start, end, .. }) => start != end,
 2555            None => false,
 2556        };
 2557
 2558        pending_nonempty_selection
 2559            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2560    }
 2561
 2562    pub fn has_pending_selection(&self) -> bool {
 2563        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2564    }
 2565
 2566    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2567        self.selection_mark_mode = false;
 2568
 2569        if self.clear_expanded_diff_hunks(cx) {
 2570            cx.notify();
 2571            return;
 2572        }
 2573        if self.dismiss_menus_and_popups(true, window, cx) {
 2574            return;
 2575        }
 2576
 2577        if self.mode == EditorMode::Full
 2578            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2579        {
 2580            return;
 2581        }
 2582
 2583        cx.propagate();
 2584    }
 2585
 2586    pub fn dismiss_menus_and_popups(
 2587        &mut self,
 2588        should_report_inline_completion_event: bool,
 2589        window: &mut Window,
 2590        cx: &mut Context<Self>,
 2591    ) -> bool {
 2592        if self.take_rename(false, window, cx).is_some() {
 2593            return true;
 2594        }
 2595
 2596        if hide_hover(self, cx) {
 2597            return true;
 2598        }
 2599
 2600        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2601            return true;
 2602        }
 2603
 2604        if self.hide_context_menu(window, cx).is_some() {
 2605            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2606                self.update_visible_inline_completion(window, cx);
 2607            }
 2608            return true;
 2609        }
 2610
 2611        if self.mouse_context_menu.take().is_some() {
 2612            return true;
 2613        }
 2614
 2615        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2616            return true;
 2617        }
 2618
 2619        if self.snippet_stack.pop().is_some() {
 2620            return true;
 2621        }
 2622
 2623        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2624            self.dismiss_diagnostics(cx);
 2625            return true;
 2626        }
 2627
 2628        false
 2629    }
 2630
 2631    fn linked_editing_ranges_for(
 2632        &self,
 2633        selection: Range<text::Anchor>,
 2634        cx: &App,
 2635    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2636        if self.linked_edit_ranges.is_empty() {
 2637            return None;
 2638        }
 2639        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2640            selection.end.buffer_id.and_then(|end_buffer_id| {
 2641                if selection.start.buffer_id != Some(end_buffer_id) {
 2642                    return None;
 2643                }
 2644                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2645                let snapshot = buffer.read(cx).snapshot();
 2646                self.linked_edit_ranges
 2647                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2648                    .map(|ranges| (ranges, snapshot, buffer))
 2649            })?;
 2650        use text::ToOffset as TO;
 2651        // find offset from the start of current range to current cursor position
 2652        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2653
 2654        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2655        let start_difference = start_offset - start_byte_offset;
 2656        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2657        let end_difference = end_offset - start_byte_offset;
 2658        // Current range has associated linked ranges.
 2659        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2660        for range in linked_ranges.iter() {
 2661            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2662            let end_offset = start_offset + end_difference;
 2663            let start_offset = start_offset + start_difference;
 2664            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2665                continue;
 2666            }
 2667            if self.selections.disjoint_anchor_ranges().any(|s| {
 2668                if s.start.buffer_id != selection.start.buffer_id
 2669                    || s.end.buffer_id != selection.end.buffer_id
 2670                {
 2671                    return false;
 2672                }
 2673                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2674                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2675            }) {
 2676                continue;
 2677            }
 2678            let start = buffer_snapshot.anchor_after(start_offset);
 2679            let end = buffer_snapshot.anchor_after(end_offset);
 2680            linked_edits
 2681                .entry(buffer.clone())
 2682                .or_default()
 2683                .push(start..end);
 2684        }
 2685        Some(linked_edits)
 2686    }
 2687
 2688    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2689        let text: Arc<str> = text.into();
 2690
 2691        if self.read_only(cx) {
 2692            return;
 2693        }
 2694
 2695        let selections = self.selections.all_adjusted(cx);
 2696        let mut bracket_inserted = false;
 2697        let mut edits = Vec::new();
 2698        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2699        let mut new_selections = Vec::with_capacity(selections.len());
 2700        let mut new_autoclose_regions = Vec::new();
 2701        let snapshot = self.buffer.read(cx).read(cx);
 2702
 2703        for (selection, autoclose_region) in
 2704            self.selections_with_autoclose_regions(selections, &snapshot)
 2705        {
 2706            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2707                // Determine if the inserted text matches the opening or closing
 2708                // bracket of any of this language's bracket pairs.
 2709                let mut bracket_pair = None;
 2710                let mut is_bracket_pair_start = false;
 2711                let mut is_bracket_pair_end = false;
 2712                if !text.is_empty() {
 2713                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2714                    //  and they are removing the character that triggered IME popup.
 2715                    for (pair, enabled) in scope.brackets() {
 2716                        if !pair.close && !pair.surround {
 2717                            continue;
 2718                        }
 2719
 2720                        if enabled && pair.start.ends_with(text.as_ref()) {
 2721                            let prefix_len = pair.start.len() - text.len();
 2722                            let preceding_text_matches_prefix = prefix_len == 0
 2723                                || (selection.start.column >= (prefix_len as u32)
 2724                                    && snapshot.contains_str_at(
 2725                                        Point::new(
 2726                                            selection.start.row,
 2727                                            selection.start.column - (prefix_len as u32),
 2728                                        ),
 2729                                        &pair.start[..prefix_len],
 2730                                    ));
 2731                            if preceding_text_matches_prefix {
 2732                                bracket_pair = Some(pair.clone());
 2733                                is_bracket_pair_start = true;
 2734                                break;
 2735                            }
 2736                        }
 2737                        if pair.end.as_str() == text.as_ref() {
 2738                            bracket_pair = Some(pair.clone());
 2739                            is_bracket_pair_end = true;
 2740                            break;
 2741                        }
 2742                    }
 2743                }
 2744
 2745                if let Some(bracket_pair) = bracket_pair {
 2746                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2747                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2748                    let auto_surround =
 2749                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2750                    if selection.is_empty() {
 2751                        if is_bracket_pair_start {
 2752                            // If the inserted text is a suffix of an opening bracket and the
 2753                            // selection is preceded by the rest of the opening bracket, then
 2754                            // insert the closing bracket.
 2755                            let following_text_allows_autoclose = snapshot
 2756                                .chars_at(selection.start)
 2757                                .next()
 2758                                .map_or(true, |c| scope.should_autoclose_before(c));
 2759
 2760                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2761                                && bracket_pair.start.len() == 1
 2762                            {
 2763                                let target = bracket_pair.start.chars().next().unwrap();
 2764                                let current_line_count = snapshot
 2765                                    .reversed_chars_at(selection.start)
 2766                                    .take_while(|&c| c != '\n')
 2767                                    .filter(|&c| c == target)
 2768                                    .count();
 2769                                current_line_count % 2 == 1
 2770                            } else {
 2771                                false
 2772                            };
 2773
 2774                            if autoclose
 2775                                && bracket_pair.close
 2776                                && following_text_allows_autoclose
 2777                                && !is_closing_quote
 2778                            {
 2779                                let anchor = snapshot.anchor_before(selection.end);
 2780                                new_selections.push((selection.map(|_| anchor), text.len()));
 2781                                new_autoclose_regions.push((
 2782                                    anchor,
 2783                                    text.len(),
 2784                                    selection.id,
 2785                                    bracket_pair.clone(),
 2786                                ));
 2787                                edits.push((
 2788                                    selection.range(),
 2789                                    format!("{}{}", text, bracket_pair.end).into(),
 2790                                ));
 2791                                bracket_inserted = true;
 2792                                continue;
 2793                            }
 2794                        }
 2795
 2796                        if let Some(region) = autoclose_region {
 2797                            // If the selection is followed by an auto-inserted closing bracket,
 2798                            // then don't insert that closing bracket again; just move the selection
 2799                            // past the closing bracket.
 2800                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2801                                && text.as_ref() == region.pair.end.as_str();
 2802                            if should_skip {
 2803                                let anchor = snapshot.anchor_after(selection.end);
 2804                                new_selections
 2805                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2806                                continue;
 2807                            }
 2808                        }
 2809
 2810                        let always_treat_brackets_as_autoclosed = snapshot
 2811                            .settings_at(selection.start, cx)
 2812                            .always_treat_brackets_as_autoclosed;
 2813                        if always_treat_brackets_as_autoclosed
 2814                            && is_bracket_pair_end
 2815                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2816                        {
 2817                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2818                            // and the inserted text is a closing bracket and the selection is followed
 2819                            // by the closing bracket then move the selection past the closing bracket.
 2820                            let anchor = snapshot.anchor_after(selection.end);
 2821                            new_selections.push((selection.map(|_| anchor), text.len()));
 2822                            continue;
 2823                        }
 2824                    }
 2825                    // If an opening bracket is 1 character long and is typed while
 2826                    // text is selected, then surround that text with the bracket pair.
 2827                    else if auto_surround
 2828                        && bracket_pair.surround
 2829                        && is_bracket_pair_start
 2830                        && bracket_pair.start.chars().count() == 1
 2831                    {
 2832                        edits.push((selection.start..selection.start, text.clone()));
 2833                        edits.push((
 2834                            selection.end..selection.end,
 2835                            bracket_pair.end.as_str().into(),
 2836                        ));
 2837                        bracket_inserted = true;
 2838                        new_selections.push((
 2839                            Selection {
 2840                                id: selection.id,
 2841                                start: snapshot.anchor_after(selection.start),
 2842                                end: snapshot.anchor_before(selection.end),
 2843                                reversed: selection.reversed,
 2844                                goal: selection.goal,
 2845                            },
 2846                            0,
 2847                        ));
 2848                        continue;
 2849                    }
 2850                }
 2851            }
 2852
 2853            if self.auto_replace_emoji_shortcode
 2854                && selection.is_empty()
 2855                && text.as_ref().ends_with(':')
 2856            {
 2857                if let Some(possible_emoji_short_code) =
 2858                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2859                {
 2860                    if !possible_emoji_short_code.is_empty() {
 2861                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2862                            let emoji_shortcode_start = Point::new(
 2863                                selection.start.row,
 2864                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2865                            );
 2866
 2867                            // Remove shortcode from buffer
 2868                            edits.push((
 2869                                emoji_shortcode_start..selection.start,
 2870                                "".to_string().into(),
 2871                            ));
 2872                            new_selections.push((
 2873                                Selection {
 2874                                    id: selection.id,
 2875                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2876                                    end: snapshot.anchor_before(selection.start),
 2877                                    reversed: selection.reversed,
 2878                                    goal: selection.goal,
 2879                                },
 2880                                0,
 2881                            ));
 2882
 2883                            // Insert emoji
 2884                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2885                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2886                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2887
 2888                            continue;
 2889                        }
 2890                    }
 2891                }
 2892            }
 2893
 2894            // If not handling any auto-close operation, then just replace the selected
 2895            // text with the given input and move the selection to the end of the
 2896            // newly inserted text.
 2897            let anchor = snapshot.anchor_after(selection.end);
 2898            if !self.linked_edit_ranges.is_empty() {
 2899                let start_anchor = snapshot.anchor_before(selection.start);
 2900
 2901                let is_word_char = text.chars().next().map_or(true, |char| {
 2902                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2903                    classifier.is_word(char)
 2904                });
 2905
 2906                if is_word_char {
 2907                    if let Some(ranges) = self
 2908                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2909                    {
 2910                        for (buffer, edits) in ranges {
 2911                            linked_edits
 2912                                .entry(buffer.clone())
 2913                                .or_default()
 2914                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2915                        }
 2916                    }
 2917                }
 2918            }
 2919
 2920            new_selections.push((selection.map(|_| anchor), 0));
 2921            edits.push((selection.start..selection.end, text.clone()));
 2922        }
 2923
 2924        drop(snapshot);
 2925
 2926        self.transact(window, cx, |this, window, cx| {
 2927            this.buffer.update(cx, |buffer, cx| {
 2928                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2929            });
 2930            for (buffer, edits) in linked_edits {
 2931                buffer.update(cx, |buffer, cx| {
 2932                    let snapshot = buffer.snapshot();
 2933                    let edits = edits
 2934                        .into_iter()
 2935                        .map(|(range, text)| {
 2936                            use text::ToPoint as TP;
 2937                            let end_point = TP::to_point(&range.end, &snapshot);
 2938                            let start_point = TP::to_point(&range.start, &snapshot);
 2939                            (start_point..end_point, text)
 2940                        })
 2941                        .sorted_by_key(|(range, _)| range.start)
 2942                        .collect::<Vec<_>>();
 2943                    buffer.edit(edits, None, cx);
 2944                })
 2945            }
 2946            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2947            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2948            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2949            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2950                .zip(new_selection_deltas)
 2951                .map(|(selection, delta)| Selection {
 2952                    id: selection.id,
 2953                    start: selection.start + delta,
 2954                    end: selection.end + delta,
 2955                    reversed: selection.reversed,
 2956                    goal: SelectionGoal::None,
 2957                })
 2958                .collect::<Vec<_>>();
 2959
 2960            let mut i = 0;
 2961            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2962                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2963                let start = map.buffer_snapshot.anchor_before(position);
 2964                let end = map.buffer_snapshot.anchor_after(position);
 2965                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2966                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2967                        Ordering::Less => i += 1,
 2968                        Ordering::Greater => break,
 2969                        Ordering::Equal => {
 2970                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2971                                Ordering::Less => i += 1,
 2972                                Ordering::Equal => break,
 2973                                Ordering::Greater => break,
 2974                            }
 2975                        }
 2976                    }
 2977                }
 2978                this.autoclose_regions.insert(
 2979                    i,
 2980                    AutocloseRegion {
 2981                        selection_id,
 2982                        range: start..end,
 2983                        pair,
 2984                    },
 2985                );
 2986            }
 2987
 2988            let had_active_inline_completion = this.has_active_inline_completion();
 2989            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2990                s.select(new_selections)
 2991            });
 2992
 2993            if !bracket_inserted {
 2994                if let Some(on_type_format_task) =
 2995                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2996                {
 2997                    on_type_format_task.detach_and_log_err(cx);
 2998                }
 2999            }
 3000
 3001            let editor_settings = EditorSettings::get_global(cx);
 3002            if bracket_inserted
 3003                && (editor_settings.auto_signature_help
 3004                    || editor_settings.show_signature_help_after_edits)
 3005            {
 3006                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3007            }
 3008
 3009            let trigger_in_words =
 3010                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3011            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3012            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3013            this.refresh_inline_completion(true, false, window, cx);
 3014        });
 3015    }
 3016
 3017    fn find_possible_emoji_shortcode_at_position(
 3018        snapshot: &MultiBufferSnapshot,
 3019        position: Point,
 3020    ) -> Option<String> {
 3021        let mut chars = Vec::new();
 3022        let mut found_colon = false;
 3023        for char in snapshot.reversed_chars_at(position).take(100) {
 3024            // Found a possible emoji shortcode in the middle of the buffer
 3025            if found_colon {
 3026                if char.is_whitespace() {
 3027                    chars.reverse();
 3028                    return Some(chars.iter().collect());
 3029                }
 3030                // If the previous character is not a whitespace, we are in the middle of a word
 3031                // and we only want to complete the shortcode if the word is made up of other emojis
 3032                let mut containing_word = String::new();
 3033                for ch in snapshot
 3034                    .reversed_chars_at(position)
 3035                    .skip(chars.len() + 1)
 3036                    .take(100)
 3037                {
 3038                    if ch.is_whitespace() {
 3039                        break;
 3040                    }
 3041                    containing_word.push(ch);
 3042                }
 3043                let containing_word = containing_word.chars().rev().collect::<String>();
 3044                if util::word_consists_of_emojis(containing_word.as_str()) {
 3045                    chars.reverse();
 3046                    return Some(chars.iter().collect());
 3047                }
 3048            }
 3049
 3050            if char.is_whitespace() || !char.is_ascii() {
 3051                return None;
 3052            }
 3053            if char == ':' {
 3054                found_colon = true;
 3055            } else {
 3056                chars.push(char);
 3057            }
 3058        }
 3059        // Found a possible emoji shortcode at the beginning of the buffer
 3060        chars.reverse();
 3061        Some(chars.iter().collect())
 3062    }
 3063
 3064    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3065        self.transact(window, cx, |this, window, cx| {
 3066            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3067                let selections = this.selections.all::<usize>(cx);
 3068                let multi_buffer = this.buffer.read(cx);
 3069                let buffer = multi_buffer.snapshot(cx);
 3070                selections
 3071                    .iter()
 3072                    .map(|selection| {
 3073                        let start_point = selection.start.to_point(&buffer);
 3074                        let mut indent =
 3075                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3076                        indent.len = cmp::min(indent.len, start_point.column);
 3077                        let start = selection.start;
 3078                        let end = selection.end;
 3079                        let selection_is_empty = start == end;
 3080                        let language_scope = buffer.language_scope_at(start);
 3081                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3082                            &language_scope
 3083                        {
 3084                            let leading_whitespace_len = buffer
 3085                                .reversed_chars_at(start)
 3086                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3087                                .map(|c| c.len_utf8())
 3088                                .sum::<usize>();
 3089
 3090                            let trailing_whitespace_len = buffer
 3091                                .chars_at(end)
 3092                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3093                                .map(|c| c.len_utf8())
 3094                                .sum::<usize>();
 3095
 3096                            let insert_extra_newline =
 3097                                language.brackets().any(|(pair, enabled)| {
 3098                                    let pair_start = pair.start.trim_end();
 3099                                    let pair_end = pair.end.trim_start();
 3100
 3101                                    enabled
 3102                                        && pair.newline
 3103                                        && buffer.contains_str_at(
 3104                                            end + trailing_whitespace_len,
 3105                                            pair_end,
 3106                                        )
 3107                                        && buffer.contains_str_at(
 3108                                            (start - leading_whitespace_len)
 3109                                                .saturating_sub(pair_start.len()),
 3110                                            pair_start,
 3111                                        )
 3112                                });
 3113
 3114                            // Comment extension on newline is allowed only for cursor selections
 3115                            let comment_delimiter = maybe!({
 3116                                if !selection_is_empty {
 3117                                    return None;
 3118                                }
 3119
 3120                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3121                                    return None;
 3122                                }
 3123
 3124                                let delimiters = language.line_comment_prefixes();
 3125                                let max_len_of_delimiter =
 3126                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3127                                let (snapshot, range) =
 3128                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3129
 3130                                let mut index_of_first_non_whitespace = 0;
 3131                                let comment_candidate = snapshot
 3132                                    .chars_for_range(range)
 3133                                    .skip_while(|c| {
 3134                                        let should_skip = c.is_whitespace();
 3135                                        if should_skip {
 3136                                            index_of_first_non_whitespace += 1;
 3137                                        }
 3138                                        should_skip
 3139                                    })
 3140                                    .take(max_len_of_delimiter)
 3141                                    .collect::<String>();
 3142                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3143                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3144                                })?;
 3145                                let cursor_is_placed_after_comment_marker =
 3146                                    index_of_first_non_whitespace + comment_prefix.len()
 3147                                        <= start_point.column as usize;
 3148                                if cursor_is_placed_after_comment_marker {
 3149                                    Some(comment_prefix.clone())
 3150                                } else {
 3151                                    None
 3152                                }
 3153                            });
 3154                            (comment_delimiter, insert_extra_newline)
 3155                        } else {
 3156                            (None, false)
 3157                        };
 3158
 3159                        let capacity_for_delimiter = comment_delimiter
 3160                            .as_deref()
 3161                            .map(str::len)
 3162                            .unwrap_or_default();
 3163                        let mut new_text =
 3164                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3165                        new_text.push('\n');
 3166                        new_text.extend(indent.chars());
 3167                        if let Some(delimiter) = &comment_delimiter {
 3168                            new_text.push_str(delimiter);
 3169                        }
 3170                        if insert_extra_newline {
 3171                            new_text = new_text.repeat(2);
 3172                        }
 3173
 3174                        let anchor = buffer.anchor_after(end);
 3175                        let new_selection = selection.map(|_| anchor);
 3176                        (
 3177                            (start..end, new_text),
 3178                            (insert_extra_newline, new_selection),
 3179                        )
 3180                    })
 3181                    .unzip()
 3182            };
 3183
 3184            this.edit_with_autoindent(edits, cx);
 3185            let buffer = this.buffer.read(cx).snapshot(cx);
 3186            let new_selections = selection_fixup_info
 3187                .into_iter()
 3188                .map(|(extra_newline_inserted, new_selection)| {
 3189                    let mut cursor = new_selection.end.to_point(&buffer);
 3190                    if extra_newline_inserted {
 3191                        cursor.row -= 1;
 3192                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3193                    }
 3194                    new_selection.map(|_| cursor)
 3195                })
 3196                .collect();
 3197
 3198            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3199                s.select(new_selections)
 3200            });
 3201            this.refresh_inline_completion(true, false, window, cx);
 3202        });
 3203    }
 3204
 3205    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3206        let buffer = self.buffer.read(cx);
 3207        let snapshot = buffer.snapshot(cx);
 3208
 3209        let mut edits = Vec::new();
 3210        let mut rows = Vec::new();
 3211
 3212        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3213            let cursor = selection.head();
 3214            let row = cursor.row;
 3215
 3216            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3217
 3218            let newline = "\n".to_string();
 3219            edits.push((start_of_line..start_of_line, newline));
 3220
 3221            rows.push(row + rows_inserted as u32);
 3222        }
 3223
 3224        self.transact(window, cx, |editor, window, cx| {
 3225            editor.edit(edits, cx);
 3226
 3227            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3228                let mut index = 0;
 3229                s.move_cursors_with(|map, _, _| {
 3230                    let row = rows[index];
 3231                    index += 1;
 3232
 3233                    let point = Point::new(row, 0);
 3234                    let boundary = map.next_line_boundary(point).1;
 3235                    let clipped = map.clip_point(boundary, Bias::Left);
 3236
 3237                    (clipped, SelectionGoal::None)
 3238                });
 3239            });
 3240
 3241            let mut indent_edits = Vec::new();
 3242            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3243            for row in rows {
 3244                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3245                for (row, indent) in indents {
 3246                    if indent.len == 0 {
 3247                        continue;
 3248                    }
 3249
 3250                    let text = match indent.kind {
 3251                        IndentKind::Space => " ".repeat(indent.len as usize),
 3252                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3253                    };
 3254                    let point = Point::new(row.0, 0);
 3255                    indent_edits.push((point..point, text));
 3256                }
 3257            }
 3258            editor.edit(indent_edits, cx);
 3259        });
 3260    }
 3261
 3262    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3263        let buffer = self.buffer.read(cx);
 3264        let snapshot = buffer.snapshot(cx);
 3265
 3266        let mut edits = Vec::new();
 3267        let mut rows = Vec::new();
 3268        let mut rows_inserted = 0;
 3269
 3270        for selection in self.selections.all_adjusted(cx) {
 3271            let cursor = selection.head();
 3272            let row = cursor.row;
 3273
 3274            let point = Point::new(row + 1, 0);
 3275            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3276
 3277            let newline = "\n".to_string();
 3278            edits.push((start_of_line..start_of_line, newline));
 3279
 3280            rows_inserted += 1;
 3281            rows.push(row + rows_inserted);
 3282        }
 3283
 3284        self.transact(window, cx, |editor, window, cx| {
 3285            editor.edit(edits, cx);
 3286
 3287            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3288                let mut index = 0;
 3289                s.move_cursors_with(|map, _, _| {
 3290                    let row = rows[index];
 3291                    index += 1;
 3292
 3293                    let point = Point::new(row, 0);
 3294                    let boundary = map.next_line_boundary(point).1;
 3295                    let clipped = map.clip_point(boundary, Bias::Left);
 3296
 3297                    (clipped, SelectionGoal::None)
 3298                });
 3299            });
 3300
 3301            let mut indent_edits = Vec::new();
 3302            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3303            for row in rows {
 3304                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3305                for (row, indent) in indents {
 3306                    if indent.len == 0 {
 3307                        continue;
 3308                    }
 3309
 3310                    let text = match indent.kind {
 3311                        IndentKind::Space => " ".repeat(indent.len as usize),
 3312                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3313                    };
 3314                    let point = Point::new(row.0, 0);
 3315                    indent_edits.push((point..point, text));
 3316                }
 3317            }
 3318            editor.edit(indent_edits, cx);
 3319        });
 3320    }
 3321
 3322    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3323        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3324            original_indent_columns: Vec::new(),
 3325        });
 3326        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3327    }
 3328
 3329    fn insert_with_autoindent_mode(
 3330        &mut self,
 3331        text: &str,
 3332        autoindent_mode: Option<AutoindentMode>,
 3333        window: &mut Window,
 3334        cx: &mut Context<Self>,
 3335    ) {
 3336        if self.read_only(cx) {
 3337            return;
 3338        }
 3339
 3340        let text: Arc<str> = text.into();
 3341        self.transact(window, cx, |this, window, cx| {
 3342            let old_selections = this.selections.all_adjusted(cx);
 3343            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3344                let anchors = {
 3345                    let snapshot = buffer.read(cx);
 3346                    old_selections
 3347                        .iter()
 3348                        .map(|s| {
 3349                            let anchor = snapshot.anchor_after(s.head());
 3350                            s.map(|_| anchor)
 3351                        })
 3352                        .collect::<Vec<_>>()
 3353                };
 3354                buffer.edit(
 3355                    old_selections
 3356                        .iter()
 3357                        .map(|s| (s.start..s.end, text.clone())),
 3358                    autoindent_mode,
 3359                    cx,
 3360                );
 3361                anchors
 3362            });
 3363
 3364            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3365                s.select_anchors(selection_anchors);
 3366            });
 3367
 3368            cx.notify();
 3369        });
 3370    }
 3371
 3372    fn trigger_completion_on_input(
 3373        &mut self,
 3374        text: &str,
 3375        trigger_in_words: bool,
 3376        window: &mut Window,
 3377        cx: &mut Context<Self>,
 3378    ) {
 3379        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3380            self.show_completions(
 3381                &ShowCompletions {
 3382                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3383                },
 3384                window,
 3385                cx,
 3386            );
 3387        } else {
 3388            self.hide_context_menu(window, cx);
 3389        }
 3390    }
 3391
 3392    fn is_completion_trigger(
 3393        &self,
 3394        text: &str,
 3395        trigger_in_words: bool,
 3396        cx: &mut Context<Self>,
 3397    ) -> bool {
 3398        let position = self.selections.newest_anchor().head();
 3399        let multibuffer = self.buffer.read(cx);
 3400        let Some(buffer) = position
 3401            .buffer_id
 3402            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3403        else {
 3404            return false;
 3405        };
 3406
 3407        if let Some(completion_provider) = &self.completion_provider {
 3408            completion_provider.is_completion_trigger(
 3409                &buffer,
 3410                position.text_anchor,
 3411                text,
 3412                trigger_in_words,
 3413                cx,
 3414            )
 3415        } else {
 3416            false
 3417        }
 3418    }
 3419
 3420    /// If any empty selections is touching the start of its innermost containing autoclose
 3421    /// region, expand it to select the brackets.
 3422    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3423        let selections = self.selections.all::<usize>(cx);
 3424        let buffer = self.buffer.read(cx).read(cx);
 3425        let new_selections = self
 3426            .selections_with_autoclose_regions(selections, &buffer)
 3427            .map(|(mut selection, region)| {
 3428                if !selection.is_empty() {
 3429                    return selection;
 3430                }
 3431
 3432                if let Some(region) = region {
 3433                    let mut range = region.range.to_offset(&buffer);
 3434                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3435                        range.start -= region.pair.start.len();
 3436                        if buffer.contains_str_at(range.start, &region.pair.start)
 3437                            && buffer.contains_str_at(range.end, &region.pair.end)
 3438                        {
 3439                            range.end += region.pair.end.len();
 3440                            selection.start = range.start;
 3441                            selection.end = range.end;
 3442
 3443                            return selection;
 3444                        }
 3445                    }
 3446                }
 3447
 3448                let always_treat_brackets_as_autoclosed = buffer
 3449                    .settings_at(selection.start, cx)
 3450                    .always_treat_brackets_as_autoclosed;
 3451
 3452                if !always_treat_brackets_as_autoclosed {
 3453                    return selection;
 3454                }
 3455
 3456                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3457                    for (pair, enabled) in scope.brackets() {
 3458                        if !enabled || !pair.close {
 3459                            continue;
 3460                        }
 3461
 3462                        if buffer.contains_str_at(selection.start, &pair.end) {
 3463                            let pair_start_len = pair.start.len();
 3464                            if buffer.contains_str_at(
 3465                                selection.start.saturating_sub(pair_start_len),
 3466                                &pair.start,
 3467                            ) {
 3468                                selection.start -= pair_start_len;
 3469                                selection.end += pair.end.len();
 3470
 3471                                return selection;
 3472                            }
 3473                        }
 3474                    }
 3475                }
 3476
 3477                selection
 3478            })
 3479            .collect();
 3480
 3481        drop(buffer);
 3482        self.change_selections(None, window, cx, |selections| {
 3483            selections.select(new_selections)
 3484        });
 3485    }
 3486
 3487    /// Iterate the given selections, and for each one, find the smallest surrounding
 3488    /// autoclose region. This uses the ordering of the selections and the autoclose
 3489    /// regions to avoid repeated comparisons.
 3490    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3491        &'a self,
 3492        selections: impl IntoIterator<Item = Selection<D>>,
 3493        buffer: &'a MultiBufferSnapshot,
 3494    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3495        let mut i = 0;
 3496        let mut regions = self.autoclose_regions.as_slice();
 3497        selections.into_iter().map(move |selection| {
 3498            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3499
 3500            let mut enclosing = None;
 3501            while let Some(pair_state) = regions.get(i) {
 3502                if pair_state.range.end.to_offset(buffer) < range.start {
 3503                    regions = &regions[i + 1..];
 3504                    i = 0;
 3505                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3506                    break;
 3507                } else {
 3508                    if pair_state.selection_id == selection.id {
 3509                        enclosing = Some(pair_state);
 3510                    }
 3511                    i += 1;
 3512                }
 3513            }
 3514
 3515            (selection, enclosing)
 3516        })
 3517    }
 3518
 3519    /// Remove any autoclose regions that no longer contain their selection.
 3520    fn invalidate_autoclose_regions(
 3521        &mut self,
 3522        mut selections: &[Selection<Anchor>],
 3523        buffer: &MultiBufferSnapshot,
 3524    ) {
 3525        self.autoclose_regions.retain(|state| {
 3526            let mut i = 0;
 3527            while let Some(selection) = selections.get(i) {
 3528                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3529                    selections = &selections[1..];
 3530                    continue;
 3531                }
 3532                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3533                    break;
 3534                }
 3535                if selection.id == state.selection_id {
 3536                    return true;
 3537                } else {
 3538                    i += 1;
 3539                }
 3540            }
 3541            false
 3542        });
 3543    }
 3544
 3545    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3546        let offset = position.to_offset(buffer);
 3547        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3548        if offset > word_range.start && kind == Some(CharKind::Word) {
 3549            Some(
 3550                buffer
 3551                    .text_for_range(word_range.start..offset)
 3552                    .collect::<String>(),
 3553            )
 3554        } else {
 3555            None
 3556        }
 3557    }
 3558
 3559    pub fn toggle_inlay_hints(
 3560        &mut self,
 3561        _: &ToggleInlayHints,
 3562        _: &mut Window,
 3563        cx: &mut Context<Self>,
 3564    ) {
 3565        self.refresh_inlay_hints(
 3566            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3567            cx,
 3568        );
 3569    }
 3570
 3571    pub fn inlay_hints_enabled(&self) -> bool {
 3572        self.inlay_hint_cache.enabled
 3573    }
 3574
 3575    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3576        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3577            return;
 3578        }
 3579
 3580        let reason_description = reason.description();
 3581        let ignore_debounce = matches!(
 3582            reason,
 3583            InlayHintRefreshReason::SettingsChange(_)
 3584                | InlayHintRefreshReason::Toggle(_)
 3585                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3586        );
 3587        let (invalidate_cache, required_languages) = match reason {
 3588            InlayHintRefreshReason::Toggle(enabled) => {
 3589                self.inlay_hint_cache.enabled = enabled;
 3590                if enabled {
 3591                    (InvalidationStrategy::RefreshRequested, None)
 3592                } else {
 3593                    self.inlay_hint_cache.clear();
 3594                    self.splice_inlays(
 3595                        self.visible_inlay_hints(cx)
 3596                            .iter()
 3597                            .map(|inlay| inlay.id)
 3598                            .collect(),
 3599                        Vec::new(),
 3600                        cx,
 3601                    );
 3602                    return;
 3603                }
 3604            }
 3605            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3606                match self.inlay_hint_cache.update_settings(
 3607                    &self.buffer,
 3608                    new_settings,
 3609                    self.visible_inlay_hints(cx),
 3610                    cx,
 3611                ) {
 3612                    ControlFlow::Break(Some(InlaySplice {
 3613                        to_remove,
 3614                        to_insert,
 3615                    })) => {
 3616                        self.splice_inlays(to_remove, to_insert, cx);
 3617                        return;
 3618                    }
 3619                    ControlFlow::Break(None) => return,
 3620                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3621                }
 3622            }
 3623            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3624                if let Some(InlaySplice {
 3625                    to_remove,
 3626                    to_insert,
 3627                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3628                {
 3629                    self.splice_inlays(to_remove, to_insert, cx);
 3630                }
 3631                return;
 3632            }
 3633            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3634            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3635                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3636            }
 3637            InlayHintRefreshReason::RefreshRequested => {
 3638                (InvalidationStrategy::RefreshRequested, None)
 3639            }
 3640        };
 3641
 3642        if let Some(InlaySplice {
 3643            to_remove,
 3644            to_insert,
 3645        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3646            reason_description,
 3647            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3648            invalidate_cache,
 3649            ignore_debounce,
 3650            cx,
 3651        ) {
 3652            self.splice_inlays(to_remove, to_insert, cx);
 3653        }
 3654    }
 3655
 3656    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3657        self.display_map
 3658            .read(cx)
 3659            .current_inlays()
 3660            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3661            .cloned()
 3662            .collect()
 3663    }
 3664
 3665    pub fn excerpts_for_inlay_hints_query(
 3666        &self,
 3667        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3668        cx: &mut Context<Editor>,
 3669    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3670        let Some(project) = self.project.as_ref() else {
 3671            return HashMap::default();
 3672        };
 3673        let project = project.read(cx);
 3674        let multi_buffer = self.buffer().read(cx);
 3675        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3676        let multi_buffer_visible_start = self
 3677            .scroll_manager
 3678            .anchor()
 3679            .anchor
 3680            .to_point(&multi_buffer_snapshot);
 3681        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3682            multi_buffer_visible_start
 3683                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3684            Bias::Left,
 3685        );
 3686        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3687        multi_buffer_snapshot
 3688            .range_to_buffer_ranges(multi_buffer_visible_range)
 3689            .into_iter()
 3690            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3691            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3692                let buffer_file = project::File::from_dyn(buffer.file())?;
 3693                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3694                let worktree_entry = buffer_worktree
 3695                    .read(cx)
 3696                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3697                if worktree_entry.is_ignored {
 3698                    return None;
 3699                }
 3700
 3701                let language = buffer.language()?;
 3702                if let Some(restrict_to_languages) = restrict_to_languages {
 3703                    if !restrict_to_languages.contains(language) {
 3704                        return None;
 3705                    }
 3706                }
 3707                Some((
 3708                    excerpt_id,
 3709                    (
 3710                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3711                        buffer.version().clone(),
 3712                        excerpt_visible_range,
 3713                    ),
 3714                ))
 3715            })
 3716            .collect()
 3717    }
 3718
 3719    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3720        TextLayoutDetails {
 3721            text_system: window.text_system().clone(),
 3722            editor_style: self.style.clone().unwrap(),
 3723            rem_size: window.rem_size(),
 3724            scroll_anchor: self.scroll_manager.anchor(),
 3725            visible_rows: self.visible_line_count(),
 3726            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3727        }
 3728    }
 3729
 3730    pub fn splice_inlays(
 3731        &self,
 3732        to_remove: Vec<InlayId>,
 3733        to_insert: Vec<Inlay>,
 3734        cx: &mut Context<Self>,
 3735    ) {
 3736        self.display_map.update(cx, |display_map, cx| {
 3737            display_map.splice_inlays(to_remove, to_insert, cx)
 3738        });
 3739        cx.notify();
 3740    }
 3741
 3742    fn trigger_on_type_formatting(
 3743        &self,
 3744        input: String,
 3745        window: &mut Window,
 3746        cx: &mut Context<Self>,
 3747    ) -> Option<Task<Result<()>>> {
 3748        if input.len() != 1 {
 3749            return None;
 3750        }
 3751
 3752        let project = self.project.as_ref()?;
 3753        let position = self.selections.newest_anchor().head();
 3754        let (buffer, buffer_position) = self
 3755            .buffer
 3756            .read(cx)
 3757            .text_anchor_for_position(position, cx)?;
 3758
 3759        let settings = language_settings::language_settings(
 3760            buffer
 3761                .read(cx)
 3762                .language_at(buffer_position)
 3763                .map(|l| l.name()),
 3764            buffer.read(cx).file(),
 3765            cx,
 3766        );
 3767        if !settings.use_on_type_format {
 3768            return None;
 3769        }
 3770
 3771        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3772        // hence we do LSP request & edit on host side only — add formats to host's history.
 3773        let push_to_lsp_host_history = true;
 3774        // If this is not the host, append its history with new edits.
 3775        let push_to_client_history = project.read(cx).is_via_collab();
 3776
 3777        let on_type_formatting = project.update(cx, |project, cx| {
 3778            project.on_type_format(
 3779                buffer.clone(),
 3780                buffer_position,
 3781                input,
 3782                push_to_lsp_host_history,
 3783                cx,
 3784            )
 3785        });
 3786        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3787            if let Some(transaction) = on_type_formatting.await? {
 3788                if push_to_client_history {
 3789                    buffer
 3790                        .update(&mut cx, |buffer, _| {
 3791                            buffer.push_transaction(transaction, Instant::now());
 3792                        })
 3793                        .ok();
 3794                }
 3795                editor.update(&mut cx, |editor, cx| {
 3796                    editor.refresh_document_highlights(cx);
 3797                })?;
 3798            }
 3799            Ok(())
 3800        }))
 3801    }
 3802
 3803    pub fn show_completions(
 3804        &mut self,
 3805        options: &ShowCompletions,
 3806        window: &mut Window,
 3807        cx: &mut Context<Self>,
 3808    ) {
 3809        if self.pending_rename.is_some() {
 3810            return;
 3811        }
 3812
 3813        let Some(provider) = self.completion_provider.as_ref() else {
 3814            return;
 3815        };
 3816
 3817        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3818            return;
 3819        }
 3820
 3821        let position = self.selections.newest_anchor().head();
 3822        if position.diff_base_anchor.is_some() {
 3823            return;
 3824        }
 3825        let (buffer, buffer_position) =
 3826            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3827                output
 3828            } else {
 3829                return;
 3830            };
 3831        let show_completion_documentation = buffer
 3832            .read(cx)
 3833            .snapshot()
 3834            .settings_at(buffer_position, cx)
 3835            .show_completion_documentation;
 3836
 3837        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3838
 3839        let trigger_kind = match &options.trigger {
 3840            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3841                CompletionTriggerKind::TRIGGER_CHARACTER
 3842            }
 3843            _ => CompletionTriggerKind::INVOKED,
 3844        };
 3845        let completion_context = CompletionContext {
 3846            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3847                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3848                    Some(String::from(trigger))
 3849                } else {
 3850                    None
 3851                }
 3852            }),
 3853            trigger_kind,
 3854        };
 3855        let completions =
 3856            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3857        let sort_completions = provider.sort_completions();
 3858
 3859        let id = post_inc(&mut self.next_completion_id);
 3860        let task = cx.spawn_in(window, |editor, mut cx| {
 3861            async move {
 3862                editor.update(&mut cx, |this, _| {
 3863                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3864                })?;
 3865                let completions = completions.await.log_err();
 3866                let menu = if let Some(completions) = completions {
 3867                    let mut menu = CompletionsMenu::new(
 3868                        id,
 3869                        sort_completions,
 3870                        show_completion_documentation,
 3871                        position,
 3872                        buffer.clone(),
 3873                        completions.into(),
 3874                    );
 3875
 3876                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3877                        .await;
 3878
 3879                    menu.visible().then_some(menu)
 3880                } else {
 3881                    None
 3882                };
 3883
 3884                editor.update_in(&mut cx, |editor, window, cx| {
 3885                    match editor.context_menu.borrow().as_ref() {
 3886                        None => {}
 3887                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3888                            if prev_menu.id > id {
 3889                                return;
 3890                            }
 3891                        }
 3892                        _ => return,
 3893                    }
 3894
 3895                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3896                        let mut menu = menu.unwrap();
 3897                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3898
 3899                        if editor.show_inline_completions_in_menu(cx) {
 3900                            if let Some(hint) = editor.inline_completion_menu_hint(window, cx) {
 3901                                menu.show_inline_completion_hint(hint);
 3902                            }
 3903                        } else {
 3904                            editor.discard_inline_completion(false, cx);
 3905                        }
 3906
 3907                        *editor.context_menu.borrow_mut() =
 3908                            Some(CodeContextMenu::Completions(menu));
 3909
 3910                        cx.notify();
 3911                    } else if editor.completion_tasks.len() <= 1 {
 3912                        // If there are no more completion tasks and the last menu was
 3913                        // empty, we should hide it.
 3914                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3915                        // If it was already hidden and we don't show inline
 3916                        // completions in the menu, we should also show the
 3917                        // inline-completion when available.
 3918                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3919                            editor.update_visible_inline_completion(window, cx);
 3920                        }
 3921                    }
 3922                })?;
 3923
 3924                Ok::<_, anyhow::Error>(())
 3925            }
 3926            .log_err()
 3927        });
 3928
 3929        self.completion_tasks.push((id, task));
 3930    }
 3931
 3932    pub fn confirm_completion(
 3933        &mut self,
 3934        action: &ConfirmCompletion,
 3935        window: &mut Window,
 3936        cx: &mut Context<Self>,
 3937    ) -> Option<Task<Result<()>>> {
 3938        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3939    }
 3940
 3941    pub fn compose_completion(
 3942        &mut self,
 3943        action: &ComposeCompletion,
 3944        window: &mut Window,
 3945        cx: &mut Context<Self>,
 3946    ) -> Option<Task<Result<()>>> {
 3947        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3948    }
 3949
 3950    fn toggle_zed_predict_tos(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3951        let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
 3952            return;
 3953        };
 3954
 3955        ZedPredictTos::toggle(workspace, project.read(cx).user_store().clone(), window, cx);
 3956    }
 3957
 3958    fn do_completion(
 3959        &mut self,
 3960        item_ix: Option<usize>,
 3961        intent: CompletionIntent,
 3962        window: &mut Window,
 3963        cx: &mut Context<Editor>,
 3964    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3965        use language::ToOffset as _;
 3966
 3967        {
 3968            let context_menu = self.context_menu.borrow();
 3969            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3970                let entries = menu.entries.borrow();
 3971                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3972                match entry {
 3973                    Some(CompletionEntry::InlineCompletionHint(
 3974                        InlineCompletionMenuHint::Loading,
 3975                    )) => return Some(Task::ready(Ok(()))),
 3976                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3977                        drop(entries);
 3978                        drop(context_menu);
 3979                        self.context_menu_next(&Default::default(), window, cx);
 3980                        return Some(Task::ready(Ok(())));
 3981                    }
 3982                    Some(CompletionEntry::InlineCompletionHint(
 3983                        InlineCompletionMenuHint::PendingTermsAcceptance,
 3984                    )) => {
 3985                        drop(entries);
 3986                        drop(context_menu);
 3987                        self.toggle_zed_predict_tos(window, cx);
 3988                        return Some(Task::ready(Ok(())));
 3989                    }
 3990                    _ => {}
 3991                }
 3992            }
 3993        }
 3994
 3995        let completions_menu =
 3996            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3997                menu
 3998            } else {
 3999                return None;
 4000            };
 4001
 4002        let entries = completions_menu.entries.borrow();
 4003        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4004        let mat = match mat {
 4005            CompletionEntry::InlineCompletionHint(_) => {
 4006                self.accept_inline_completion(&AcceptInlineCompletion, window, cx);
 4007                cx.stop_propagation();
 4008                return Some(Task::ready(Ok(())));
 4009            }
 4010            CompletionEntry::Match(mat) => {
 4011                if self.show_inline_completions_in_menu(cx) {
 4012                    self.discard_inline_completion(true, cx);
 4013                }
 4014                mat
 4015            }
 4016        };
 4017        let candidate_id = mat.candidate_id;
 4018        drop(entries);
 4019
 4020        let buffer_handle = completions_menu.buffer;
 4021        let completion = completions_menu
 4022            .completions
 4023            .borrow()
 4024            .get(candidate_id)?
 4025            .clone();
 4026        cx.stop_propagation();
 4027
 4028        let snippet;
 4029        let text;
 4030
 4031        if completion.is_snippet() {
 4032            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4033            text = snippet.as_ref().unwrap().text.clone();
 4034        } else {
 4035            snippet = None;
 4036            text = completion.new_text.clone();
 4037        };
 4038        let selections = self.selections.all::<usize>(cx);
 4039        let buffer = buffer_handle.read(cx);
 4040        let old_range = completion.old_range.to_offset(buffer);
 4041        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4042
 4043        let newest_selection = self.selections.newest_anchor();
 4044        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4045            return None;
 4046        }
 4047
 4048        let lookbehind = newest_selection
 4049            .start
 4050            .text_anchor
 4051            .to_offset(buffer)
 4052            .saturating_sub(old_range.start);
 4053        let lookahead = old_range
 4054            .end
 4055            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4056        let mut common_prefix_len = old_text
 4057            .bytes()
 4058            .zip(text.bytes())
 4059            .take_while(|(a, b)| a == b)
 4060            .count();
 4061
 4062        let snapshot = self.buffer.read(cx).snapshot(cx);
 4063        let mut range_to_replace: Option<Range<isize>> = None;
 4064        let mut ranges = Vec::new();
 4065        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4066        for selection in &selections {
 4067            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4068                let start = selection.start.saturating_sub(lookbehind);
 4069                let end = selection.end + lookahead;
 4070                if selection.id == newest_selection.id {
 4071                    range_to_replace = Some(
 4072                        ((start + common_prefix_len) as isize - selection.start as isize)
 4073                            ..(end as isize - selection.start as isize),
 4074                    );
 4075                }
 4076                ranges.push(start + common_prefix_len..end);
 4077            } else {
 4078                common_prefix_len = 0;
 4079                ranges.clear();
 4080                ranges.extend(selections.iter().map(|s| {
 4081                    if s.id == newest_selection.id {
 4082                        range_to_replace = Some(
 4083                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4084                                - selection.start as isize
 4085                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4086                                    - selection.start as isize,
 4087                        );
 4088                        old_range.clone()
 4089                    } else {
 4090                        s.start..s.end
 4091                    }
 4092                }));
 4093                break;
 4094            }
 4095            if !self.linked_edit_ranges.is_empty() {
 4096                let start_anchor = snapshot.anchor_before(selection.head());
 4097                let end_anchor = snapshot.anchor_after(selection.tail());
 4098                if let Some(ranges) = self
 4099                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4100                {
 4101                    for (buffer, edits) in ranges {
 4102                        linked_edits.entry(buffer.clone()).or_default().extend(
 4103                            edits
 4104                                .into_iter()
 4105                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4106                        );
 4107                    }
 4108                }
 4109            }
 4110        }
 4111        let text = &text[common_prefix_len..];
 4112
 4113        cx.emit(EditorEvent::InputHandled {
 4114            utf16_range_to_replace: range_to_replace,
 4115            text: text.into(),
 4116        });
 4117
 4118        self.transact(window, cx, |this, window, cx| {
 4119            if let Some(mut snippet) = snippet {
 4120                snippet.text = text.to_string();
 4121                for tabstop in snippet
 4122                    .tabstops
 4123                    .iter_mut()
 4124                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4125                {
 4126                    tabstop.start -= common_prefix_len as isize;
 4127                    tabstop.end -= common_prefix_len as isize;
 4128                }
 4129
 4130                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4131            } else {
 4132                this.buffer.update(cx, |buffer, cx| {
 4133                    buffer.edit(
 4134                        ranges.iter().map(|range| (range.clone(), text)),
 4135                        this.autoindent_mode.clone(),
 4136                        cx,
 4137                    );
 4138                });
 4139            }
 4140            for (buffer, edits) in linked_edits {
 4141                buffer.update(cx, |buffer, cx| {
 4142                    let snapshot = buffer.snapshot();
 4143                    let edits = edits
 4144                        .into_iter()
 4145                        .map(|(range, text)| {
 4146                            use text::ToPoint as TP;
 4147                            let end_point = TP::to_point(&range.end, &snapshot);
 4148                            let start_point = TP::to_point(&range.start, &snapshot);
 4149                            (start_point..end_point, text)
 4150                        })
 4151                        .sorted_by_key(|(range, _)| range.start)
 4152                        .collect::<Vec<_>>();
 4153                    buffer.edit(edits, None, cx);
 4154                })
 4155            }
 4156
 4157            this.refresh_inline_completion(true, false, window, cx);
 4158        });
 4159
 4160        let show_new_completions_on_confirm = completion
 4161            .confirm
 4162            .as_ref()
 4163            .map_or(false, |confirm| confirm(intent, window, cx));
 4164        if show_new_completions_on_confirm {
 4165            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4166        }
 4167
 4168        let provider = self.completion_provider.as_ref()?;
 4169        drop(completion);
 4170        let apply_edits = provider.apply_additional_edits_for_completion(
 4171            buffer_handle,
 4172            completions_menu.completions.clone(),
 4173            candidate_id,
 4174            true,
 4175            cx,
 4176        );
 4177
 4178        let editor_settings = EditorSettings::get_global(cx);
 4179        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4180            // After the code completion is finished, users often want to know what signatures are needed.
 4181            // so we should automatically call signature_help
 4182            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4183        }
 4184
 4185        Some(cx.foreground_executor().spawn(async move {
 4186            apply_edits.await?;
 4187            Ok(())
 4188        }))
 4189    }
 4190
 4191    pub fn toggle_code_actions(
 4192        &mut self,
 4193        action: &ToggleCodeActions,
 4194        window: &mut Window,
 4195        cx: &mut Context<Self>,
 4196    ) {
 4197        let mut context_menu = self.context_menu.borrow_mut();
 4198        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4199            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4200                // Toggle if we're selecting the same one
 4201                *context_menu = None;
 4202                cx.notify();
 4203                return;
 4204            } else {
 4205                // Otherwise, clear it and start a new one
 4206                *context_menu = None;
 4207                cx.notify();
 4208            }
 4209        }
 4210        drop(context_menu);
 4211        let snapshot = self.snapshot(window, cx);
 4212        let deployed_from_indicator = action.deployed_from_indicator;
 4213        let mut task = self.code_actions_task.take();
 4214        let action = action.clone();
 4215        cx.spawn_in(window, |editor, mut cx| async move {
 4216            while let Some(prev_task) = task {
 4217                prev_task.await.log_err();
 4218                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4219            }
 4220
 4221            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4222                if editor.focus_handle.is_focused(window) {
 4223                    let multibuffer_point = action
 4224                        .deployed_from_indicator
 4225                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4226                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4227                    let (buffer, buffer_row) = snapshot
 4228                        .buffer_snapshot
 4229                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4230                        .and_then(|(buffer_snapshot, range)| {
 4231                            editor
 4232                                .buffer
 4233                                .read(cx)
 4234                                .buffer(buffer_snapshot.remote_id())
 4235                                .map(|buffer| (buffer, range.start.row))
 4236                        })?;
 4237                    let (_, code_actions) = editor
 4238                        .available_code_actions
 4239                        .clone()
 4240                        .and_then(|(location, code_actions)| {
 4241                            let snapshot = location.buffer.read(cx).snapshot();
 4242                            let point_range = location.range.to_point(&snapshot);
 4243                            let point_range = point_range.start.row..=point_range.end.row;
 4244                            if point_range.contains(&buffer_row) {
 4245                                Some((location, code_actions))
 4246                            } else {
 4247                                None
 4248                            }
 4249                        })
 4250                        .unzip();
 4251                    let buffer_id = buffer.read(cx).remote_id();
 4252                    let tasks = editor
 4253                        .tasks
 4254                        .get(&(buffer_id, buffer_row))
 4255                        .map(|t| Arc::new(t.to_owned()));
 4256                    if tasks.is_none() && code_actions.is_none() {
 4257                        return None;
 4258                    }
 4259
 4260                    editor.completion_tasks.clear();
 4261                    editor.discard_inline_completion(false, cx);
 4262                    let task_context =
 4263                        tasks
 4264                            .as_ref()
 4265                            .zip(editor.project.clone())
 4266                            .map(|(tasks, project)| {
 4267                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4268                            });
 4269
 4270                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4271                        let task_context = match task_context {
 4272                            Some(task_context) => task_context.await,
 4273                            None => None,
 4274                        };
 4275                        let resolved_tasks =
 4276                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4277                                Rc::new(ResolvedTasks {
 4278                                    templates: tasks.resolve(&task_context).collect(),
 4279                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4280                                        multibuffer_point.row,
 4281                                        tasks.column,
 4282                                    )),
 4283                                })
 4284                            });
 4285                        let spawn_straight_away = resolved_tasks
 4286                            .as_ref()
 4287                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4288                            && code_actions
 4289                                .as_ref()
 4290                                .map_or(true, |actions| actions.is_empty());
 4291                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4292                            *editor.context_menu.borrow_mut() =
 4293                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4294                                    buffer,
 4295                                    actions: CodeActionContents {
 4296                                        tasks: resolved_tasks,
 4297                                        actions: code_actions,
 4298                                    },
 4299                                    selected_item: Default::default(),
 4300                                    scroll_handle: UniformListScrollHandle::default(),
 4301                                    deployed_from_indicator,
 4302                                }));
 4303                            if spawn_straight_away {
 4304                                if let Some(task) = editor.confirm_code_action(
 4305                                    &ConfirmCodeAction { item_ix: Some(0) },
 4306                                    window,
 4307                                    cx,
 4308                                ) {
 4309                                    cx.notify();
 4310                                    return task;
 4311                                }
 4312                            }
 4313                            cx.notify();
 4314                            Task::ready(Ok(()))
 4315                        }) {
 4316                            task.await
 4317                        } else {
 4318                            Ok(())
 4319                        }
 4320                    }))
 4321                } else {
 4322                    Some(Task::ready(Ok(())))
 4323                }
 4324            })?;
 4325            if let Some(task) = spawned_test_task {
 4326                task.await?;
 4327            }
 4328
 4329            Ok::<_, anyhow::Error>(())
 4330        })
 4331        .detach_and_log_err(cx);
 4332    }
 4333
 4334    pub fn confirm_code_action(
 4335        &mut self,
 4336        action: &ConfirmCodeAction,
 4337        window: &mut Window,
 4338        cx: &mut Context<Self>,
 4339    ) -> Option<Task<Result<()>>> {
 4340        let actions_menu =
 4341            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4342                menu
 4343            } else {
 4344                return None;
 4345            };
 4346        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4347        let action = actions_menu.actions.get(action_ix)?;
 4348        let title = action.label();
 4349        let buffer = actions_menu.buffer;
 4350        let workspace = self.workspace()?;
 4351
 4352        match action {
 4353            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4354                workspace.update(cx, |workspace, cx| {
 4355                    workspace::tasks::schedule_resolved_task(
 4356                        workspace,
 4357                        task_source_kind,
 4358                        resolved_task,
 4359                        false,
 4360                        cx,
 4361                    );
 4362
 4363                    Some(Task::ready(Ok(())))
 4364                })
 4365            }
 4366            CodeActionsItem::CodeAction {
 4367                excerpt_id,
 4368                action,
 4369                provider,
 4370            } => {
 4371                let apply_code_action =
 4372                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4373                let workspace = workspace.downgrade();
 4374                Some(cx.spawn_in(window, |editor, cx| async move {
 4375                    let project_transaction = apply_code_action.await?;
 4376                    Self::open_project_transaction(
 4377                        &editor,
 4378                        workspace,
 4379                        project_transaction,
 4380                        title,
 4381                        cx,
 4382                    )
 4383                    .await
 4384                }))
 4385            }
 4386        }
 4387    }
 4388
 4389    pub async fn open_project_transaction(
 4390        this: &WeakEntity<Editor>,
 4391        workspace: WeakEntity<Workspace>,
 4392        transaction: ProjectTransaction,
 4393        title: String,
 4394        mut cx: AsyncWindowContext,
 4395    ) -> Result<()> {
 4396        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4397        cx.update(|_, cx| {
 4398            entries.sort_unstable_by_key(|(buffer, _)| {
 4399                buffer.read(cx).file().map(|f| f.path().clone())
 4400            });
 4401        })?;
 4402
 4403        // If the project transaction's edits are all contained within this editor, then
 4404        // avoid opening a new editor to display them.
 4405
 4406        if let Some((buffer, transaction)) = entries.first() {
 4407            if entries.len() == 1 {
 4408                let excerpt = this.update(&mut cx, |editor, cx| {
 4409                    editor
 4410                        .buffer()
 4411                        .read(cx)
 4412                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4413                })?;
 4414                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4415                    if excerpted_buffer == *buffer {
 4416                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4417                            let excerpt_range = excerpt_range.to_offset(buffer);
 4418                            buffer
 4419                                .edited_ranges_for_transaction::<usize>(transaction)
 4420                                .all(|range| {
 4421                                    excerpt_range.start <= range.start
 4422                                        && excerpt_range.end >= range.end
 4423                                })
 4424                        })?;
 4425
 4426                        if all_edits_within_excerpt {
 4427                            return Ok(());
 4428                        }
 4429                    }
 4430                }
 4431            }
 4432        } else {
 4433            return Ok(());
 4434        }
 4435
 4436        let mut ranges_to_highlight = Vec::new();
 4437        let excerpt_buffer = cx.new(|cx| {
 4438            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4439            for (buffer_handle, transaction) in &entries {
 4440                let buffer = buffer_handle.read(cx);
 4441                ranges_to_highlight.extend(
 4442                    multibuffer.push_excerpts_with_context_lines(
 4443                        buffer_handle.clone(),
 4444                        buffer
 4445                            .edited_ranges_for_transaction::<usize>(transaction)
 4446                            .collect(),
 4447                        DEFAULT_MULTIBUFFER_CONTEXT,
 4448                        cx,
 4449                    ),
 4450                );
 4451            }
 4452            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4453            multibuffer
 4454        })?;
 4455
 4456        workspace.update_in(&mut cx, |workspace, window, cx| {
 4457            let project = workspace.project().clone();
 4458            let editor = cx
 4459                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4460            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4461            editor.update(cx, |editor, cx| {
 4462                editor.highlight_background::<Self>(
 4463                    &ranges_to_highlight,
 4464                    |theme| theme.editor_highlighted_line_background,
 4465                    cx,
 4466                );
 4467            });
 4468        })?;
 4469
 4470        Ok(())
 4471    }
 4472
 4473    pub fn clear_code_action_providers(&mut self) {
 4474        self.code_action_providers.clear();
 4475        self.available_code_actions.take();
 4476    }
 4477
 4478    pub fn add_code_action_provider(
 4479        &mut self,
 4480        provider: Rc<dyn CodeActionProvider>,
 4481        window: &mut Window,
 4482        cx: &mut Context<Self>,
 4483    ) {
 4484        if self
 4485            .code_action_providers
 4486            .iter()
 4487            .any(|existing_provider| existing_provider.id() == provider.id())
 4488        {
 4489            return;
 4490        }
 4491
 4492        self.code_action_providers.push(provider);
 4493        self.refresh_code_actions(window, cx);
 4494    }
 4495
 4496    pub fn remove_code_action_provider(
 4497        &mut self,
 4498        id: Arc<str>,
 4499        window: &mut Window,
 4500        cx: &mut Context<Self>,
 4501    ) {
 4502        self.code_action_providers
 4503            .retain(|provider| provider.id() != id);
 4504        self.refresh_code_actions(window, cx);
 4505    }
 4506
 4507    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4508        let buffer = self.buffer.read(cx);
 4509        let newest_selection = self.selections.newest_anchor().clone();
 4510        if newest_selection.head().diff_base_anchor.is_some() {
 4511            return None;
 4512        }
 4513        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4514        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4515        if start_buffer != end_buffer {
 4516            return None;
 4517        }
 4518
 4519        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4520            cx.background_executor()
 4521                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4522                .await;
 4523
 4524            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4525                let providers = this.code_action_providers.clone();
 4526                let tasks = this
 4527                    .code_action_providers
 4528                    .iter()
 4529                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4530                    .collect::<Vec<_>>();
 4531                (providers, tasks)
 4532            })?;
 4533
 4534            let mut actions = Vec::new();
 4535            for (provider, provider_actions) in
 4536                providers.into_iter().zip(future::join_all(tasks).await)
 4537            {
 4538                if let Some(provider_actions) = provider_actions.log_err() {
 4539                    actions.extend(provider_actions.into_iter().map(|action| {
 4540                        AvailableCodeAction {
 4541                            excerpt_id: newest_selection.start.excerpt_id,
 4542                            action,
 4543                            provider: provider.clone(),
 4544                        }
 4545                    }));
 4546                }
 4547            }
 4548
 4549            this.update(&mut cx, |this, cx| {
 4550                this.available_code_actions = if actions.is_empty() {
 4551                    None
 4552                } else {
 4553                    Some((
 4554                        Location {
 4555                            buffer: start_buffer,
 4556                            range: start..end,
 4557                        },
 4558                        actions.into(),
 4559                    ))
 4560                };
 4561                cx.notify();
 4562            })
 4563        }));
 4564        None
 4565    }
 4566
 4567    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4568        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4569            self.show_git_blame_inline = false;
 4570
 4571            self.show_git_blame_inline_delay_task =
 4572                Some(cx.spawn_in(window, |this, mut cx| async move {
 4573                    cx.background_executor().timer(delay).await;
 4574
 4575                    this.update(&mut cx, |this, cx| {
 4576                        this.show_git_blame_inline = true;
 4577                        cx.notify();
 4578                    })
 4579                    .log_err();
 4580                }));
 4581        }
 4582    }
 4583
 4584    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4585        if self.pending_rename.is_some() {
 4586            return None;
 4587        }
 4588
 4589        let provider = self.semantics_provider.clone()?;
 4590        let buffer = self.buffer.read(cx);
 4591        let newest_selection = self.selections.newest_anchor().clone();
 4592        let cursor_position = newest_selection.head();
 4593        let (cursor_buffer, cursor_buffer_position) =
 4594            buffer.text_anchor_for_position(cursor_position, cx)?;
 4595        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4596        if cursor_buffer != tail_buffer {
 4597            return None;
 4598        }
 4599        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4600        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4601            cx.background_executor()
 4602                .timer(Duration::from_millis(debounce))
 4603                .await;
 4604
 4605            let highlights = if let Some(highlights) = cx
 4606                .update(|cx| {
 4607                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4608                })
 4609                .ok()
 4610                .flatten()
 4611            {
 4612                highlights.await.log_err()
 4613            } else {
 4614                None
 4615            };
 4616
 4617            if let Some(highlights) = highlights {
 4618                this.update(&mut cx, |this, cx| {
 4619                    if this.pending_rename.is_some() {
 4620                        return;
 4621                    }
 4622
 4623                    let buffer_id = cursor_position.buffer_id;
 4624                    let buffer = this.buffer.read(cx);
 4625                    if !buffer
 4626                        .text_anchor_for_position(cursor_position, cx)
 4627                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4628                    {
 4629                        return;
 4630                    }
 4631
 4632                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4633                    let mut write_ranges = Vec::new();
 4634                    let mut read_ranges = Vec::new();
 4635                    for highlight in highlights {
 4636                        for (excerpt_id, excerpt_range) in
 4637                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4638                        {
 4639                            let start = highlight
 4640                                .range
 4641                                .start
 4642                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4643                            let end = highlight
 4644                                .range
 4645                                .end
 4646                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4647                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4648                                continue;
 4649                            }
 4650
 4651                            let range = Anchor {
 4652                                buffer_id,
 4653                                excerpt_id,
 4654                                text_anchor: start,
 4655                                diff_base_anchor: None,
 4656                            }..Anchor {
 4657                                buffer_id,
 4658                                excerpt_id,
 4659                                text_anchor: end,
 4660                                diff_base_anchor: None,
 4661                            };
 4662                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4663                                write_ranges.push(range);
 4664                            } else {
 4665                                read_ranges.push(range);
 4666                            }
 4667                        }
 4668                    }
 4669
 4670                    this.highlight_background::<DocumentHighlightRead>(
 4671                        &read_ranges,
 4672                        |theme| theme.editor_document_highlight_read_background,
 4673                        cx,
 4674                    );
 4675                    this.highlight_background::<DocumentHighlightWrite>(
 4676                        &write_ranges,
 4677                        |theme| theme.editor_document_highlight_write_background,
 4678                        cx,
 4679                    );
 4680                    cx.notify();
 4681                })
 4682                .log_err();
 4683            }
 4684        }));
 4685        None
 4686    }
 4687
 4688    pub fn refresh_inline_completion(
 4689        &mut self,
 4690        debounce: bool,
 4691        user_requested: bool,
 4692        window: &mut Window,
 4693        cx: &mut Context<Self>,
 4694    ) -> Option<()> {
 4695        let provider = self.inline_completion_provider()?;
 4696        let cursor = self.selections.newest_anchor().head();
 4697        let (buffer, cursor_buffer_position) =
 4698            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4699
 4700        if !user_requested
 4701            && (!self.enable_inline_completions
 4702                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4703                || !self.is_focused(window)
 4704                || buffer.read(cx).is_empty())
 4705        {
 4706            self.discard_inline_completion(false, cx);
 4707            return None;
 4708        }
 4709
 4710        self.update_visible_inline_completion(window, cx);
 4711        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4712        Some(())
 4713    }
 4714
 4715    fn cycle_inline_completion(
 4716        &mut self,
 4717        direction: Direction,
 4718        window: &mut Window,
 4719        cx: &mut Context<Self>,
 4720    ) -> Option<()> {
 4721        let provider = self.inline_completion_provider()?;
 4722        let cursor = self.selections.newest_anchor().head();
 4723        let (buffer, cursor_buffer_position) =
 4724            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4725        if !self.enable_inline_completions
 4726            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4727        {
 4728            return None;
 4729        }
 4730
 4731        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4732        self.update_visible_inline_completion(window, cx);
 4733
 4734        Some(())
 4735    }
 4736
 4737    pub fn show_inline_completion(
 4738        &mut self,
 4739        _: &ShowInlineCompletion,
 4740        window: &mut Window,
 4741        cx: &mut Context<Self>,
 4742    ) {
 4743        if !self.has_active_inline_completion() {
 4744            self.refresh_inline_completion(false, true, window, cx);
 4745            return;
 4746        }
 4747
 4748        self.update_visible_inline_completion(window, cx);
 4749    }
 4750
 4751    pub fn display_cursor_names(
 4752        &mut self,
 4753        _: &DisplayCursorNames,
 4754        window: &mut Window,
 4755        cx: &mut Context<Self>,
 4756    ) {
 4757        self.show_cursor_names(window, cx);
 4758    }
 4759
 4760    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4761        self.show_cursor_names = true;
 4762        cx.notify();
 4763        cx.spawn_in(window, |this, mut cx| async move {
 4764            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4765            this.update(&mut cx, |this, cx| {
 4766                this.show_cursor_names = false;
 4767                cx.notify()
 4768            })
 4769            .ok()
 4770        })
 4771        .detach();
 4772    }
 4773
 4774    pub fn next_inline_completion(
 4775        &mut self,
 4776        _: &NextInlineCompletion,
 4777        window: &mut Window,
 4778        cx: &mut Context<Self>,
 4779    ) {
 4780        if self.has_active_inline_completion() {
 4781            self.cycle_inline_completion(Direction::Next, window, cx);
 4782        } else {
 4783            let is_copilot_disabled = self
 4784                .refresh_inline_completion(false, true, window, cx)
 4785                .is_none();
 4786            if is_copilot_disabled {
 4787                cx.propagate();
 4788            }
 4789        }
 4790    }
 4791
 4792    pub fn previous_inline_completion(
 4793        &mut self,
 4794        _: &PreviousInlineCompletion,
 4795        window: &mut Window,
 4796        cx: &mut Context<Self>,
 4797    ) {
 4798        if self.has_active_inline_completion() {
 4799            self.cycle_inline_completion(Direction::Prev, window, cx);
 4800        } else {
 4801            let is_copilot_disabled = self
 4802                .refresh_inline_completion(false, true, window, cx)
 4803                .is_none();
 4804            if is_copilot_disabled {
 4805                cx.propagate();
 4806            }
 4807        }
 4808    }
 4809
 4810    pub fn accept_inline_completion(
 4811        &mut self,
 4812        _: &AcceptInlineCompletion,
 4813        window: &mut Window,
 4814        cx: &mut Context<Self>,
 4815    ) {
 4816        let buffer = self.buffer.read(cx);
 4817        let snapshot = buffer.snapshot(cx);
 4818        let selection = self.selections.newest_adjusted(cx);
 4819        let cursor = selection.head();
 4820        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4821        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4822        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4823        {
 4824            if cursor.column < suggested_indent.len
 4825                && cursor.column <= current_indent.len
 4826                && current_indent.len <= suggested_indent.len
 4827            {
 4828                self.tab(&Default::default(), window, cx);
 4829                return;
 4830            }
 4831        }
 4832
 4833        if self.show_inline_completions_in_menu(cx) {
 4834            self.hide_context_menu(window, cx);
 4835        }
 4836
 4837        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4838            return;
 4839        };
 4840
 4841        self.report_inline_completion_event(true, cx);
 4842
 4843        match &active_inline_completion.completion {
 4844            InlineCompletion::Move(position) => {
 4845                let position = *position;
 4846                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4847                    selections.select_anchor_ranges([position..position]);
 4848                });
 4849            }
 4850            InlineCompletion::Edit {
 4851                edits,
 4852                display_mode: _,
 4853            } => {
 4854                if let Some(provider) = self.inline_completion_provider() {
 4855                    provider.accept(cx);
 4856                }
 4857
 4858                let snapshot = self.buffer.read(cx).snapshot(cx);
 4859                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4860
 4861                self.buffer.update(cx, |buffer, cx| {
 4862                    buffer.edit(edits.iter().cloned(), None, cx)
 4863                });
 4864
 4865                self.change_selections(None, window, cx, |s| {
 4866                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4867                });
 4868
 4869                self.update_visible_inline_completion(window, cx);
 4870                if self.active_inline_completion.is_none() {
 4871                    self.refresh_inline_completion(true, true, window, cx);
 4872                }
 4873
 4874                cx.notify();
 4875            }
 4876        }
 4877    }
 4878
 4879    pub fn accept_partial_inline_completion(
 4880        &mut self,
 4881        _: &AcceptPartialInlineCompletion,
 4882        window: &mut Window,
 4883        cx: &mut Context<Self>,
 4884    ) {
 4885        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4886            return;
 4887        };
 4888        if self.selections.count() != 1 {
 4889            return;
 4890        }
 4891
 4892        self.report_inline_completion_event(true, cx);
 4893
 4894        match &active_inline_completion.completion {
 4895            InlineCompletion::Move(position) => {
 4896                let position = *position;
 4897                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4898                    selections.select_anchor_ranges([position..position]);
 4899                });
 4900            }
 4901            InlineCompletion::Edit {
 4902                edits,
 4903                display_mode: _,
 4904            } => {
 4905                // Find an insertion that starts at the cursor position.
 4906                let snapshot = self.buffer.read(cx).snapshot(cx);
 4907                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4908                let insertion = edits.iter().find_map(|(range, text)| {
 4909                    let range = range.to_offset(&snapshot);
 4910                    if range.is_empty() && range.start == cursor_offset {
 4911                        Some(text)
 4912                    } else {
 4913                        None
 4914                    }
 4915                });
 4916
 4917                if let Some(text) = insertion {
 4918                    let mut partial_completion = text
 4919                        .chars()
 4920                        .by_ref()
 4921                        .take_while(|c| c.is_alphabetic())
 4922                        .collect::<String>();
 4923                    if partial_completion.is_empty() {
 4924                        partial_completion = text
 4925                            .chars()
 4926                            .by_ref()
 4927                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4928                            .collect::<String>();
 4929                    }
 4930
 4931                    cx.emit(EditorEvent::InputHandled {
 4932                        utf16_range_to_replace: None,
 4933                        text: partial_completion.clone().into(),
 4934                    });
 4935
 4936                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4937
 4938                    self.refresh_inline_completion(true, true, window, cx);
 4939                    cx.notify();
 4940                } else {
 4941                    self.accept_inline_completion(&Default::default(), window, cx);
 4942                }
 4943            }
 4944        }
 4945    }
 4946
 4947    fn discard_inline_completion(
 4948        &mut self,
 4949        should_report_inline_completion_event: bool,
 4950        cx: &mut Context<Self>,
 4951    ) -> bool {
 4952        if should_report_inline_completion_event {
 4953            self.report_inline_completion_event(false, cx);
 4954        }
 4955
 4956        if let Some(provider) = self.inline_completion_provider() {
 4957            provider.discard(cx);
 4958        }
 4959
 4960        self.take_active_inline_completion(cx).is_some()
 4961    }
 4962
 4963    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4964        let Some(provider) = self.inline_completion_provider() else {
 4965            return;
 4966        };
 4967
 4968        let Some((_, buffer, _)) = self
 4969            .buffer
 4970            .read(cx)
 4971            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4972        else {
 4973            return;
 4974        };
 4975
 4976        let extension = buffer
 4977            .read(cx)
 4978            .file()
 4979            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4980
 4981        let event_type = match accepted {
 4982            true => "Inline Completion Accepted",
 4983            false => "Inline Completion Discarded",
 4984        };
 4985        telemetry::event!(
 4986            event_type,
 4987            provider = provider.name(),
 4988            suggestion_accepted = accepted,
 4989            file_extension = extension,
 4990        );
 4991    }
 4992
 4993    pub fn has_active_inline_completion(&self) -> bool {
 4994        self.active_inline_completion.is_some()
 4995    }
 4996
 4997    fn take_active_inline_completion(
 4998        &mut self,
 4999        cx: &mut Context<Self>,
 5000    ) -> Option<InlineCompletion> {
 5001        let active_inline_completion = self.active_inline_completion.take()?;
 5002        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 5003        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5004        Some(active_inline_completion.completion)
 5005    }
 5006
 5007    fn update_visible_inline_completion(
 5008        &mut self,
 5009        window: &mut Window,
 5010        cx: &mut Context<Self>,
 5011    ) -> Option<()> {
 5012        let selection = self.selections.newest_anchor();
 5013        let cursor = selection.head();
 5014        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5015        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5016        let excerpt_id = cursor.excerpt_id;
 5017
 5018        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 5019            && (self.context_menu.borrow().is_some()
 5020                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5021        if completions_menu_has_precedence
 5022            || !offset_selection.is_empty()
 5023            || !self.enable_inline_completions
 5024            || self
 5025                .active_inline_completion
 5026                .as_ref()
 5027                .map_or(false, |completion| {
 5028                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5029                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5030                    !invalidation_range.contains(&offset_selection.head())
 5031                })
 5032        {
 5033            self.discard_inline_completion(false, cx);
 5034            return None;
 5035        }
 5036
 5037        self.take_active_inline_completion(cx);
 5038        let provider = self.inline_completion_provider()?;
 5039
 5040        let (buffer, cursor_buffer_position) =
 5041            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5042
 5043        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5044        let edits = completion
 5045            .edits
 5046            .into_iter()
 5047            .flat_map(|(range, new_text)| {
 5048                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5049                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5050                Some((start..end, new_text))
 5051            })
 5052            .collect::<Vec<_>>();
 5053        if edits.is_empty() {
 5054            return None;
 5055        }
 5056
 5057        let first_edit_start = edits.first().unwrap().0.start;
 5058        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5059        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5060
 5061        let last_edit_end = edits.last().unwrap().0.end;
 5062        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5063        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5064
 5065        let cursor_row = cursor.to_point(&multibuffer).row;
 5066
 5067        let mut inlay_ids = Vec::new();
 5068        let invalidation_row_range;
 5069        let completion;
 5070        if cursor_row < edit_start_row {
 5071            invalidation_row_range = cursor_row..edit_end_row;
 5072            completion = InlineCompletion::Move(first_edit_start);
 5073        } else if cursor_row > edit_end_row {
 5074            invalidation_row_range = edit_start_row..cursor_row;
 5075            completion = InlineCompletion::Move(first_edit_start);
 5076        } else {
 5077            if edits
 5078                .iter()
 5079                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5080            {
 5081                let mut inlays = Vec::new();
 5082                for (range, new_text) in &edits {
 5083                    let inlay = Inlay::inline_completion(
 5084                        post_inc(&mut self.next_inlay_id),
 5085                        range.start,
 5086                        new_text.as_str(),
 5087                    );
 5088                    inlay_ids.push(inlay.id);
 5089                    inlays.push(inlay);
 5090                }
 5091
 5092                self.splice_inlays(vec![], inlays, cx);
 5093            } else {
 5094                let background_color = cx.theme().status().deleted_background;
 5095                self.highlight_text::<InlineCompletionHighlight>(
 5096                    edits.iter().map(|(range, _)| range.clone()).collect(),
 5097                    HighlightStyle {
 5098                        background_color: Some(background_color),
 5099                        ..Default::default()
 5100                    },
 5101                    cx,
 5102                );
 5103            }
 5104
 5105            invalidation_row_range = edit_start_row..edit_end_row;
 5106
 5107            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5108                if provider.show_tab_accept_marker()
 5109                    && first_edit_start_point.row == last_edit_end_point.row
 5110                    && !edits.iter().any(|(_, edit)| edit.contains('\n'))
 5111                {
 5112                    EditDisplayMode::TabAccept
 5113                } else {
 5114                    EditDisplayMode::Inline
 5115                }
 5116            } else {
 5117                EditDisplayMode::DiffPopover
 5118            };
 5119
 5120            completion = InlineCompletion::Edit {
 5121                edits,
 5122                display_mode,
 5123            };
 5124        };
 5125
 5126        let invalidation_range = multibuffer
 5127            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5128            ..multibuffer.anchor_after(Point::new(
 5129                invalidation_row_range.end,
 5130                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5131            ));
 5132
 5133        self.active_inline_completion = Some(InlineCompletionState {
 5134            inlay_ids,
 5135            completion,
 5136            invalidation_range,
 5137        });
 5138
 5139        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 5140            if let Some(hint) = self.inline_completion_menu_hint(window, cx) {
 5141                match self.context_menu.borrow_mut().as_mut() {
 5142                    Some(CodeContextMenu::Completions(menu)) => {
 5143                        menu.show_inline_completion_hint(hint);
 5144                    }
 5145                    _ => {}
 5146                }
 5147            }
 5148        }
 5149
 5150        cx.notify();
 5151
 5152        Some(())
 5153    }
 5154
 5155    fn inline_completion_menu_hint(
 5156        &self,
 5157        window: &mut Window,
 5158        cx: &mut Context<Self>,
 5159    ) -> Option<InlineCompletionMenuHint> {
 5160        let provider = self.inline_completion_provider()?;
 5161        if self.has_active_inline_completion() {
 5162            let editor_snapshot = self.snapshot(window, cx);
 5163
 5164            let text = match &self.active_inline_completion.as_ref()?.completion {
 5165                InlineCompletion::Edit {
 5166                    edits,
 5167                    display_mode: _,
 5168                } => inline_completion_edit_text(&editor_snapshot, edits, true, cx),
 5169                InlineCompletion::Move(target) => {
 5170                    let target_point =
 5171                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 5172                    let target_line = target_point.row + 1;
 5173                    InlineCompletionText::Move(
 5174                        format!("Jump to edit in line {}", target_line).into(),
 5175                    )
 5176                }
 5177            };
 5178
 5179            Some(InlineCompletionMenuHint::Loaded { text })
 5180        } else if provider.is_refreshing(cx) {
 5181            Some(InlineCompletionMenuHint::Loading)
 5182        } else if provider.needs_terms_acceptance(cx) {
 5183            Some(InlineCompletionMenuHint::PendingTermsAcceptance)
 5184        } else {
 5185            Some(InlineCompletionMenuHint::None)
 5186        }
 5187    }
 5188
 5189    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5190        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5191    }
 5192
 5193    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5194        let by_provider = matches!(
 5195            self.menu_inline_completions_policy,
 5196            MenuInlineCompletionsPolicy::ByProvider
 5197        );
 5198
 5199        by_provider
 5200            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5201            && self
 5202                .inline_completion_provider()
 5203                .map_or(false, |provider| provider.show_completions_in_menu())
 5204    }
 5205
 5206    fn render_code_actions_indicator(
 5207        &self,
 5208        _style: &EditorStyle,
 5209        row: DisplayRow,
 5210        is_active: bool,
 5211        cx: &mut Context<Self>,
 5212    ) -> Option<IconButton> {
 5213        if self.available_code_actions.is_some() {
 5214            Some(
 5215                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5216                    .shape(ui::IconButtonShape::Square)
 5217                    .icon_size(IconSize::XSmall)
 5218                    .icon_color(Color::Muted)
 5219                    .toggle_state(is_active)
 5220                    .tooltip({
 5221                        let focus_handle = self.focus_handle.clone();
 5222                        move |window, cx| {
 5223                            Tooltip::for_action_in(
 5224                                "Toggle Code Actions",
 5225                                &ToggleCodeActions {
 5226                                    deployed_from_indicator: None,
 5227                                },
 5228                                &focus_handle,
 5229                                window,
 5230                                cx,
 5231                            )
 5232                        }
 5233                    })
 5234                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5235                        window.focus(&editor.focus_handle(cx));
 5236                        editor.toggle_code_actions(
 5237                            &ToggleCodeActions {
 5238                                deployed_from_indicator: Some(row),
 5239                            },
 5240                            window,
 5241                            cx,
 5242                        );
 5243                    })),
 5244            )
 5245        } else {
 5246            None
 5247        }
 5248    }
 5249
 5250    fn clear_tasks(&mut self) {
 5251        self.tasks.clear()
 5252    }
 5253
 5254    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5255        if self.tasks.insert(key, value).is_some() {
 5256            // This case should hopefully be rare, but just in case...
 5257            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5258        }
 5259    }
 5260
 5261    fn build_tasks_context(
 5262        project: &Entity<Project>,
 5263        buffer: &Entity<Buffer>,
 5264        buffer_row: u32,
 5265        tasks: &Arc<RunnableTasks>,
 5266        cx: &mut Context<Self>,
 5267    ) -> Task<Option<task::TaskContext>> {
 5268        let position = Point::new(buffer_row, tasks.column);
 5269        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5270        let location = Location {
 5271            buffer: buffer.clone(),
 5272            range: range_start..range_start,
 5273        };
 5274        // Fill in the environmental variables from the tree-sitter captures
 5275        let mut captured_task_variables = TaskVariables::default();
 5276        for (capture_name, value) in tasks.extra_variables.clone() {
 5277            captured_task_variables.insert(
 5278                task::VariableName::Custom(capture_name.into()),
 5279                value.clone(),
 5280            );
 5281        }
 5282        project.update(cx, |project, cx| {
 5283            project.task_store().update(cx, |task_store, cx| {
 5284                task_store.task_context_for_location(captured_task_variables, location, cx)
 5285            })
 5286        })
 5287    }
 5288
 5289    pub fn spawn_nearest_task(
 5290        &mut self,
 5291        action: &SpawnNearestTask,
 5292        window: &mut Window,
 5293        cx: &mut Context<Self>,
 5294    ) {
 5295        let Some((workspace, _)) = self.workspace.clone() else {
 5296            return;
 5297        };
 5298        let Some(project) = self.project.clone() else {
 5299            return;
 5300        };
 5301
 5302        // Try to find a closest, enclosing node using tree-sitter that has a
 5303        // task
 5304        let Some((buffer, buffer_row, tasks)) = self
 5305            .find_enclosing_node_task(cx)
 5306            // Or find the task that's closest in row-distance.
 5307            .or_else(|| self.find_closest_task(cx))
 5308        else {
 5309            return;
 5310        };
 5311
 5312        let reveal_strategy = action.reveal;
 5313        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5314        cx.spawn_in(window, |_, mut cx| async move {
 5315            let context = task_context.await?;
 5316            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5317
 5318            let resolved = resolved_task.resolved.as_mut()?;
 5319            resolved.reveal = reveal_strategy;
 5320
 5321            workspace
 5322                .update(&mut cx, |workspace, cx| {
 5323                    workspace::tasks::schedule_resolved_task(
 5324                        workspace,
 5325                        task_source_kind,
 5326                        resolved_task,
 5327                        false,
 5328                        cx,
 5329                    );
 5330                })
 5331                .ok()
 5332        })
 5333        .detach();
 5334    }
 5335
 5336    fn find_closest_task(
 5337        &mut self,
 5338        cx: &mut Context<Self>,
 5339    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5340        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5341
 5342        let ((buffer_id, row), tasks) = self
 5343            .tasks
 5344            .iter()
 5345            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5346
 5347        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5348        let tasks = Arc::new(tasks.to_owned());
 5349        Some((buffer, *row, tasks))
 5350    }
 5351
 5352    fn find_enclosing_node_task(
 5353        &mut self,
 5354        cx: &mut Context<Self>,
 5355    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5356        let snapshot = self.buffer.read(cx).snapshot(cx);
 5357        let offset = self.selections.newest::<usize>(cx).head();
 5358        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5359        let buffer_id = excerpt.buffer().remote_id();
 5360
 5361        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5362        let mut cursor = layer.node().walk();
 5363
 5364        while cursor.goto_first_child_for_byte(offset).is_some() {
 5365            if cursor.node().end_byte() == offset {
 5366                cursor.goto_next_sibling();
 5367            }
 5368        }
 5369
 5370        // Ascend to the smallest ancestor that contains the range and has a task.
 5371        loop {
 5372            let node = cursor.node();
 5373            let node_range = node.byte_range();
 5374            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5375
 5376            // Check if this node contains our offset
 5377            if node_range.start <= offset && node_range.end >= offset {
 5378                // If it contains offset, check for task
 5379                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5380                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5381                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5382                }
 5383            }
 5384
 5385            if !cursor.goto_parent() {
 5386                break;
 5387            }
 5388        }
 5389        None
 5390    }
 5391
 5392    fn render_run_indicator(
 5393        &self,
 5394        _style: &EditorStyle,
 5395        is_active: bool,
 5396        row: DisplayRow,
 5397        cx: &mut Context<Self>,
 5398    ) -> IconButton {
 5399        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5400            .shape(ui::IconButtonShape::Square)
 5401            .icon_size(IconSize::XSmall)
 5402            .icon_color(Color::Muted)
 5403            .toggle_state(is_active)
 5404            .on_click(cx.listener(move |editor, _e, window, cx| {
 5405                window.focus(&editor.focus_handle(cx));
 5406                editor.toggle_code_actions(
 5407                    &ToggleCodeActions {
 5408                        deployed_from_indicator: Some(row),
 5409                    },
 5410                    window,
 5411                    cx,
 5412                );
 5413            }))
 5414    }
 5415
 5416    #[cfg(any(test, feature = "test-support"))]
 5417    pub fn context_menu_visible(&self) -> bool {
 5418        self.context_menu
 5419            .borrow()
 5420            .as_ref()
 5421            .map_or(false, |menu| menu.visible())
 5422    }
 5423
 5424    #[cfg(feature = "test-support")]
 5425    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5426        self.context_menu
 5427            .borrow()
 5428            .as_ref()
 5429            .map_or(false, |menu| match menu {
 5430                CodeContextMenu::Completions(menu) => {
 5431                    menu.entries.borrow().first().map_or(false, |entry| {
 5432                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5433                    })
 5434                }
 5435                CodeContextMenu::CodeActions(_) => false,
 5436            })
 5437    }
 5438
 5439    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5440        self.context_menu
 5441            .borrow()
 5442            .as_ref()
 5443            .map(|menu| menu.origin(cursor_position))
 5444    }
 5445
 5446    fn render_context_menu(
 5447        &self,
 5448        style: &EditorStyle,
 5449        max_height_in_lines: u32,
 5450        y_flipped: bool,
 5451        window: &mut Window,
 5452        cx: &mut Context<Editor>,
 5453    ) -> Option<AnyElement> {
 5454        self.context_menu.borrow().as_ref().and_then(|menu| {
 5455            if menu.visible() {
 5456                Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5457            } else {
 5458                None
 5459            }
 5460        })
 5461    }
 5462
 5463    fn render_context_menu_aside(
 5464        &self,
 5465        style: &EditorStyle,
 5466        max_size: Size<Pixels>,
 5467        cx: &mut Context<Editor>,
 5468    ) -> Option<AnyElement> {
 5469        self.context_menu.borrow().as_ref().and_then(|menu| {
 5470            if menu.visible() {
 5471                menu.render_aside(
 5472                    style,
 5473                    max_size,
 5474                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5475                    cx,
 5476                )
 5477            } else {
 5478                None
 5479            }
 5480        })
 5481    }
 5482
 5483    fn hide_context_menu(
 5484        &mut self,
 5485        window: &mut Window,
 5486        cx: &mut Context<Self>,
 5487    ) -> Option<CodeContextMenu> {
 5488        cx.notify();
 5489        self.completion_tasks.clear();
 5490        let context_menu = self.context_menu.borrow_mut().take();
 5491        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5492            self.update_visible_inline_completion(window, cx);
 5493        }
 5494        context_menu
 5495    }
 5496
 5497    fn show_snippet_choices(
 5498        &mut self,
 5499        choices: &Vec<String>,
 5500        selection: Range<Anchor>,
 5501        cx: &mut Context<Self>,
 5502    ) {
 5503        if selection.start.buffer_id.is_none() {
 5504            return;
 5505        }
 5506        let buffer_id = selection.start.buffer_id.unwrap();
 5507        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5508        let id = post_inc(&mut self.next_completion_id);
 5509
 5510        if let Some(buffer) = buffer {
 5511            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5512                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5513            ));
 5514        }
 5515    }
 5516
 5517    pub fn insert_snippet(
 5518        &mut self,
 5519        insertion_ranges: &[Range<usize>],
 5520        snippet: Snippet,
 5521        window: &mut Window,
 5522        cx: &mut Context<Self>,
 5523    ) -> Result<()> {
 5524        struct Tabstop<T> {
 5525            is_end_tabstop: bool,
 5526            ranges: Vec<Range<T>>,
 5527            choices: Option<Vec<String>>,
 5528        }
 5529
 5530        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5531            let snippet_text: Arc<str> = snippet.text.clone().into();
 5532            buffer.edit(
 5533                insertion_ranges
 5534                    .iter()
 5535                    .cloned()
 5536                    .map(|range| (range, snippet_text.clone())),
 5537                Some(AutoindentMode::EachLine),
 5538                cx,
 5539            );
 5540
 5541            let snapshot = &*buffer.read(cx);
 5542            let snippet = &snippet;
 5543            snippet
 5544                .tabstops
 5545                .iter()
 5546                .map(|tabstop| {
 5547                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5548                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5549                    });
 5550                    let mut tabstop_ranges = tabstop
 5551                        .ranges
 5552                        .iter()
 5553                        .flat_map(|tabstop_range| {
 5554                            let mut delta = 0_isize;
 5555                            insertion_ranges.iter().map(move |insertion_range| {
 5556                                let insertion_start = insertion_range.start as isize + delta;
 5557                                delta +=
 5558                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5559
 5560                                let start = ((insertion_start + tabstop_range.start) as usize)
 5561                                    .min(snapshot.len());
 5562                                let end = ((insertion_start + tabstop_range.end) as usize)
 5563                                    .min(snapshot.len());
 5564                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5565                            })
 5566                        })
 5567                        .collect::<Vec<_>>();
 5568                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5569
 5570                    Tabstop {
 5571                        is_end_tabstop,
 5572                        ranges: tabstop_ranges,
 5573                        choices: tabstop.choices.clone(),
 5574                    }
 5575                })
 5576                .collect::<Vec<_>>()
 5577        });
 5578        if let Some(tabstop) = tabstops.first() {
 5579            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5580                s.select_ranges(tabstop.ranges.iter().cloned());
 5581            });
 5582
 5583            if let Some(choices) = &tabstop.choices {
 5584                if let Some(selection) = tabstop.ranges.first() {
 5585                    self.show_snippet_choices(choices, selection.clone(), cx)
 5586                }
 5587            }
 5588
 5589            // If we're already at the last tabstop and it's at the end of the snippet,
 5590            // we're done, we don't need to keep the state around.
 5591            if !tabstop.is_end_tabstop {
 5592                let choices = tabstops
 5593                    .iter()
 5594                    .map(|tabstop| tabstop.choices.clone())
 5595                    .collect();
 5596
 5597                let ranges = tabstops
 5598                    .into_iter()
 5599                    .map(|tabstop| tabstop.ranges)
 5600                    .collect::<Vec<_>>();
 5601
 5602                self.snippet_stack.push(SnippetState {
 5603                    active_index: 0,
 5604                    ranges,
 5605                    choices,
 5606                });
 5607            }
 5608
 5609            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5610            if self.autoclose_regions.is_empty() {
 5611                let snapshot = self.buffer.read(cx).snapshot(cx);
 5612                for selection in &mut self.selections.all::<Point>(cx) {
 5613                    let selection_head = selection.head();
 5614                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5615                        continue;
 5616                    };
 5617
 5618                    let mut bracket_pair = None;
 5619                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5620                    let prev_chars = snapshot
 5621                        .reversed_chars_at(selection_head)
 5622                        .collect::<String>();
 5623                    for (pair, enabled) in scope.brackets() {
 5624                        if enabled
 5625                            && pair.close
 5626                            && prev_chars.starts_with(pair.start.as_str())
 5627                            && next_chars.starts_with(pair.end.as_str())
 5628                        {
 5629                            bracket_pair = Some(pair.clone());
 5630                            break;
 5631                        }
 5632                    }
 5633                    if let Some(pair) = bracket_pair {
 5634                        let start = snapshot.anchor_after(selection_head);
 5635                        let end = snapshot.anchor_after(selection_head);
 5636                        self.autoclose_regions.push(AutocloseRegion {
 5637                            selection_id: selection.id,
 5638                            range: start..end,
 5639                            pair,
 5640                        });
 5641                    }
 5642                }
 5643            }
 5644        }
 5645        Ok(())
 5646    }
 5647
 5648    pub fn move_to_next_snippet_tabstop(
 5649        &mut self,
 5650        window: &mut Window,
 5651        cx: &mut Context<Self>,
 5652    ) -> bool {
 5653        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5654    }
 5655
 5656    pub fn move_to_prev_snippet_tabstop(
 5657        &mut self,
 5658        window: &mut Window,
 5659        cx: &mut Context<Self>,
 5660    ) -> bool {
 5661        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5662    }
 5663
 5664    pub fn move_to_snippet_tabstop(
 5665        &mut self,
 5666        bias: Bias,
 5667        window: &mut Window,
 5668        cx: &mut Context<Self>,
 5669    ) -> bool {
 5670        if let Some(mut snippet) = self.snippet_stack.pop() {
 5671            match bias {
 5672                Bias::Left => {
 5673                    if snippet.active_index > 0 {
 5674                        snippet.active_index -= 1;
 5675                    } else {
 5676                        self.snippet_stack.push(snippet);
 5677                        return false;
 5678                    }
 5679                }
 5680                Bias::Right => {
 5681                    if snippet.active_index + 1 < snippet.ranges.len() {
 5682                        snippet.active_index += 1;
 5683                    } else {
 5684                        self.snippet_stack.push(snippet);
 5685                        return false;
 5686                    }
 5687                }
 5688            }
 5689            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5690                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5691                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5692                });
 5693
 5694                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5695                    if let Some(selection) = current_ranges.first() {
 5696                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5697                    }
 5698                }
 5699
 5700                // If snippet state is not at the last tabstop, push it back on the stack
 5701                if snippet.active_index + 1 < snippet.ranges.len() {
 5702                    self.snippet_stack.push(snippet);
 5703                }
 5704                return true;
 5705            }
 5706        }
 5707
 5708        false
 5709    }
 5710
 5711    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5712        self.transact(window, cx, |this, window, cx| {
 5713            this.select_all(&SelectAll, window, cx);
 5714            this.insert("", window, cx);
 5715        });
 5716    }
 5717
 5718    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 5719        self.transact(window, cx, |this, window, cx| {
 5720            this.select_autoclose_pair(window, cx);
 5721            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5722            if !this.linked_edit_ranges.is_empty() {
 5723                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5724                let snapshot = this.buffer.read(cx).snapshot(cx);
 5725
 5726                for selection in selections.iter() {
 5727                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5728                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5729                    if selection_start.buffer_id != selection_end.buffer_id {
 5730                        continue;
 5731                    }
 5732                    if let Some(ranges) =
 5733                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5734                    {
 5735                        for (buffer, entries) in ranges {
 5736                            linked_ranges.entry(buffer).or_default().extend(entries);
 5737                        }
 5738                    }
 5739                }
 5740            }
 5741
 5742            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5743            if !this.selections.line_mode {
 5744                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5745                for selection in &mut selections {
 5746                    if selection.is_empty() {
 5747                        let old_head = selection.head();
 5748                        let mut new_head =
 5749                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5750                                .to_point(&display_map);
 5751                        if let Some((buffer, line_buffer_range)) = display_map
 5752                            .buffer_snapshot
 5753                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5754                        {
 5755                            let indent_size =
 5756                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5757                            let indent_len = match indent_size.kind {
 5758                                IndentKind::Space => {
 5759                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5760                                }
 5761                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5762                            };
 5763                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5764                                let indent_len = indent_len.get();
 5765                                new_head = cmp::min(
 5766                                    new_head,
 5767                                    MultiBufferPoint::new(
 5768                                        old_head.row,
 5769                                        ((old_head.column - 1) / indent_len) * indent_len,
 5770                                    ),
 5771                                );
 5772                            }
 5773                        }
 5774
 5775                        selection.set_head(new_head, SelectionGoal::None);
 5776                    }
 5777                }
 5778            }
 5779
 5780            this.signature_help_state.set_backspace_pressed(true);
 5781            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5782                s.select(selections)
 5783            });
 5784            this.insert("", window, cx);
 5785            let empty_str: Arc<str> = Arc::from("");
 5786            for (buffer, edits) in linked_ranges {
 5787                let snapshot = buffer.read(cx).snapshot();
 5788                use text::ToPoint as TP;
 5789
 5790                let edits = edits
 5791                    .into_iter()
 5792                    .map(|range| {
 5793                        let end_point = TP::to_point(&range.end, &snapshot);
 5794                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5795
 5796                        if end_point == start_point {
 5797                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5798                                .saturating_sub(1);
 5799                            start_point =
 5800                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5801                        };
 5802
 5803                        (start_point..end_point, empty_str.clone())
 5804                    })
 5805                    .sorted_by_key(|(range, _)| range.start)
 5806                    .collect::<Vec<_>>();
 5807                buffer.update(cx, |this, cx| {
 5808                    this.edit(edits, None, cx);
 5809                })
 5810            }
 5811            this.refresh_inline_completion(true, false, window, cx);
 5812            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 5813        });
 5814    }
 5815
 5816    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 5817        self.transact(window, cx, |this, window, cx| {
 5818            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5819                let line_mode = s.line_mode;
 5820                s.move_with(|map, selection| {
 5821                    if selection.is_empty() && !line_mode {
 5822                        let cursor = movement::right(map, selection.head());
 5823                        selection.end = cursor;
 5824                        selection.reversed = true;
 5825                        selection.goal = SelectionGoal::None;
 5826                    }
 5827                })
 5828            });
 5829            this.insert("", window, cx);
 5830            this.refresh_inline_completion(true, false, window, cx);
 5831        });
 5832    }
 5833
 5834    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 5835        if self.move_to_prev_snippet_tabstop(window, cx) {
 5836            return;
 5837        }
 5838
 5839        self.outdent(&Outdent, window, cx);
 5840    }
 5841
 5842    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 5843        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 5844            return;
 5845        }
 5846
 5847        let mut selections = self.selections.all_adjusted(cx);
 5848        let buffer = self.buffer.read(cx);
 5849        let snapshot = buffer.snapshot(cx);
 5850        let rows_iter = selections.iter().map(|s| s.head().row);
 5851        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5852
 5853        let mut edits = Vec::new();
 5854        let mut prev_edited_row = 0;
 5855        let mut row_delta = 0;
 5856        for selection in &mut selections {
 5857            if selection.start.row != prev_edited_row {
 5858                row_delta = 0;
 5859            }
 5860            prev_edited_row = selection.end.row;
 5861
 5862            // If the selection is non-empty, then increase the indentation of the selected lines.
 5863            if !selection.is_empty() {
 5864                row_delta =
 5865                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5866                continue;
 5867            }
 5868
 5869            // If the selection is empty and the cursor is in the leading whitespace before the
 5870            // suggested indentation, then auto-indent the line.
 5871            let cursor = selection.head();
 5872            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5873            if let Some(suggested_indent) =
 5874                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5875            {
 5876                if cursor.column < suggested_indent.len
 5877                    && cursor.column <= current_indent.len
 5878                    && current_indent.len <= suggested_indent.len
 5879                {
 5880                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5881                    selection.end = selection.start;
 5882                    if row_delta == 0 {
 5883                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5884                            cursor.row,
 5885                            current_indent,
 5886                            suggested_indent,
 5887                        ));
 5888                        row_delta = suggested_indent.len - current_indent.len;
 5889                    }
 5890                    continue;
 5891                }
 5892            }
 5893
 5894            // Otherwise, insert a hard or soft tab.
 5895            let settings = buffer.settings_at(cursor, cx);
 5896            let tab_size = if settings.hard_tabs {
 5897                IndentSize::tab()
 5898            } else {
 5899                let tab_size = settings.tab_size.get();
 5900                let char_column = snapshot
 5901                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5902                    .flat_map(str::chars)
 5903                    .count()
 5904                    + row_delta as usize;
 5905                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5906                IndentSize::spaces(chars_to_next_tab_stop)
 5907            };
 5908            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5909            selection.end = selection.start;
 5910            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5911            row_delta += tab_size.len;
 5912        }
 5913
 5914        self.transact(window, cx, |this, window, cx| {
 5915            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5916            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5917                s.select(selections)
 5918            });
 5919            this.refresh_inline_completion(true, false, window, cx);
 5920        });
 5921    }
 5922
 5923    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 5924        if self.read_only(cx) {
 5925            return;
 5926        }
 5927        let mut selections = self.selections.all::<Point>(cx);
 5928        let mut prev_edited_row = 0;
 5929        let mut row_delta = 0;
 5930        let mut edits = Vec::new();
 5931        let buffer = self.buffer.read(cx);
 5932        let snapshot = buffer.snapshot(cx);
 5933        for selection in &mut selections {
 5934            if selection.start.row != prev_edited_row {
 5935                row_delta = 0;
 5936            }
 5937            prev_edited_row = selection.end.row;
 5938
 5939            row_delta =
 5940                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5941        }
 5942
 5943        self.transact(window, cx, |this, window, cx| {
 5944            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5945            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5946                s.select(selections)
 5947            });
 5948        });
 5949    }
 5950
 5951    fn indent_selection(
 5952        buffer: &MultiBuffer,
 5953        snapshot: &MultiBufferSnapshot,
 5954        selection: &mut Selection<Point>,
 5955        edits: &mut Vec<(Range<Point>, String)>,
 5956        delta_for_start_row: u32,
 5957        cx: &App,
 5958    ) -> u32 {
 5959        let settings = buffer.settings_at(selection.start, cx);
 5960        let tab_size = settings.tab_size.get();
 5961        let indent_kind = if settings.hard_tabs {
 5962            IndentKind::Tab
 5963        } else {
 5964            IndentKind::Space
 5965        };
 5966        let mut start_row = selection.start.row;
 5967        let mut end_row = selection.end.row + 1;
 5968
 5969        // If a selection ends at the beginning of a line, don't indent
 5970        // that last line.
 5971        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5972            end_row -= 1;
 5973        }
 5974
 5975        // Avoid re-indenting a row that has already been indented by a
 5976        // previous selection, but still update this selection's column
 5977        // to reflect that indentation.
 5978        if delta_for_start_row > 0 {
 5979            start_row += 1;
 5980            selection.start.column += delta_for_start_row;
 5981            if selection.end.row == selection.start.row {
 5982                selection.end.column += delta_for_start_row;
 5983            }
 5984        }
 5985
 5986        let mut delta_for_end_row = 0;
 5987        let has_multiple_rows = start_row + 1 != end_row;
 5988        for row in start_row..end_row {
 5989            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5990            let indent_delta = match (current_indent.kind, indent_kind) {
 5991                (IndentKind::Space, IndentKind::Space) => {
 5992                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5993                    IndentSize::spaces(columns_to_next_tab_stop)
 5994                }
 5995                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5996                (_, IndentKind::Tab) => IndentSize::tab(),
 5997            };
 5998
 5999            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6000                0
 6001            } else {
 6002                selection.start.column
 6003            };
 6004            let row_start = Point::new(row, start);
 6005            edits.push((
 6006                row_start..row_start,
 6007                indent_delta.chars().collect::<String>(),
 6008            ));
 6009
 6010            // Update this selection's endpoints to reflect the indentation.
 6011            if row == selection.start.row {
 6012                selection.start.column += indent_delta.len;
 6013            }
 6014            if row == selection.end.row {
 6015                selection.end.column += indent_delta.len;
 6016                delta_for_end_row = indent_delta.len;
 6017            }
 6018        }
 6019
 6020        if selection.start.row == selection.end.row {
 6021            delta_for_start_row + delta_for_end_row
 6022        } else {
 6023            delta_for_end_row
 6024        }
 6025    }
 6026
 6027    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6028        if self.read_only(cx) {
 6029            return;
 6030        }
 6031        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6032        let selections = self.selections.all::<Point>(cx);
 6033        let mut deletion_ranges = Vec::new();
 6034        let mut last_outdent = None;
 6035        {
 6036            let buffer = self.buffer.read(cx);
 6037            let snapshot = buffer.snapshot(cx);
 6038            for selection in &selections {
 6039                let settings = buffer.settings_at(selection.start, cx);
 6040                let tab_size = settings.tab_size.get();
 6041                let mut rows = selection.spanned_rows(false, &display_map);
 6042
 6043                // Avoid re-outdenting a row that has already been outdented by a
 6044                // previous selection.
 6045                if let Some(last_row) = last_outdent {
 6046                    if last_row == rows.start {
 6047                        rows.start = rows.start.next_row();
 6048                    }
 6049                }
 6050                let has_multiple_rows = rows.len() > 1;
 6051                for row in rows.iter_rows() {
 6052                    let indent_size = snapshot.indent_size_for_line(row);
 6053                    if indent_size.len > 0 {
 6054                        let deletion_len = match indent_size.kind {
 6055                            IndentKind::Space => {
 6056                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6057                                if columns_to_prev_tab_stop == 0 {
 6058                                    tab_size
 6059                                } else {
 6060                                    columns_to_prev_tab_stop
 6061                                }
 6062                            }
 6063                            IndentKind::Tab => 1,
 6064                        };
 6065                        let start = if has_multiple_rows
 6066                            || deletion_len > selection.start.column
 6067                            || indent_size.len < selection.start.column
 6068                        {
 6069                            0
 6070                        } else {
 6071                            selection.start.column - deletion_len
 6072                        };
 6073                        deletion_ranges.push(
 6074                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6075                        );
 6076                        last_outdent = Some(row);
 6077                    }
 6078                }
 6079            }
 6080        }
 6081
 6082        self.transact(window, cx, |this, window, cx| {
 6083            this.buffer.update(cx, |buffer, cx| {
 6084                let empty_str: Arc<str> = Arc::default();
 6085                buffer.edit(
 6086                    deletion_ranges
 6087                        .into_iter()
 6088                        .map(|range| (range, empty_str.clone())),
 6089                    None,
 6090                    cx,
 6091                );
 6092            });
 6093            let selections = this.selections.all::<usize>(cx);
 6094            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6095                s.select(selections)
 6096            });
 6097        });
 6098    }
 6099
 6100    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6101        if self.read_only(cx) {
 6102            return;
 6103        }
 6104        let selections = self
 6105            .selections
 6106            .all::<usize>(cx)
 6107            .into_iter()
 6108            .map(|s| s.range());
 6109
 6110        self.transact(window, cx, |this, window, cx| {
 6111            this.buffer.update(cx, |buffer, cx| {
 6112                buffer.autoindent_ranges(selections, cx);
 6113            });
 6114            let selections = this.selections.all::<usize>(cx);
 6115            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6116                s.select(selections)
 6117            });
 6118        });
 6119    }
 6120
 6121    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6122        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6123        let selections = self.selections.all::<Point>(cx);
 6124
 6125        let mut new_cursors = Vec::new();
 6126        let mut edit_ranges = Vec::new();
 6127        let mut selections = selections.iter().peekable();
 6128        while let Some(selection) = selections.next() {
 6129            let mut rows = selection.spanned_rows(false, &display_map);
 6130            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6131
 6132            // Accumulate contiguous regions of rows that we want to delete.
 6133            while let Some(next_selection) = selections.peek() {
 6134                let next_rows = next_selection.spanned_rows(false, &display_map);
 6135                if next_rows.start <= rows.end {
 6136                    rows.end = next_rows.end;
 6137                    selections.next().unwrap();
 6138                } else {
 6139                    break;
 6140                }
 6141            }
 6142
 6143            let buffer = &display_map.buffer_snapshot;
 6144            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6145            let edit_end;
 6146            let cursor_buffer_row;
 6147            if buffer.max_point().row >= rows.end.0 {
 6148                // If there's a line after the range, delete the \n from the end of the row range
 6149                // and position the cursor on the next line.
 6150                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6151                cursor_buffer_row = rows.end;
 6152            } else {
 6153                // If there isn't a line after the range, delete the \n from the line before the
 6154                // start of the row range and position the cursor there.
 6155                edit_start = edit_start.saturating_sub(1);
 6156                edit_end = buffer.len();
 6157                cursor_buffer_row = rows.start.previous_row();
 6158            }
 6159
 6160            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6161            *cursor.column_mut() =
 6162                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6163
 6164            new_cursors.push((
 6165                selection.id,
 6166                buffer.anchor_after(cursor.to_point(&display_map)),
 6167            ));
 6168            edit_ranges.push(edit_start..edit_end);
 6169        }
 6170
 6171        self.transact(window, cx, |this, window, cx| {
 6172            let buffer = this.buffer.update(cx, |buffer, cx| {
 6173                let empty_str: Arc<str> = Arc::default();
 6174                buffer.edit(
 6175                    edit_ranges
 6176                        .into_iter()
 6177                        .map(|range| (range, empty_str.clone())),
 6178                    None,
 6179                    cx,
 6180                );
 6181                buffer.snapshot(cx)
 6182            });
 6183            let new_selections = new_cursors
 6184                .into_iter()
 6185                .map(|(id, cursor)| {
 6186                    let cursor = cursor.to_point(&buffer);
 6187                    Selection {
 6188                        id,
 6189                        start: cursor,
 6190                        end: cursor,
 6191                        reversed: false,
 6192                        goal: SelectionGoal::None,
 6193                    }
 6194                })
 6195                .collect();
 6196
 6197            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6198                s.select(new_selections);
 6199            });
 6200        });
 6201    }
 6202
 6203    pub fn join_lines_impl(
 6204        &mut self,
 6205        insert_whitespace: bool,
 6206        window: &mut Window,
 6207        cx: &mut Context<Self>,
 6208    ) {
 6209        if self.read_only(cx) {
 6210            return;
 6211        }
 6212        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6213        for selection in self.selections.all::<Point>(cx) {
 6214            let start = MultiBufferRow(selection.start.row);
 6215            // Treat single line selections as if they include the next line. Otherwise this action
 6216            // would do nothing for single line selections individual cursors.
 6217            let end = if selection.start.row == selection.end.row {
 6218                MultiBufferRow(selection.start.row + 1)
 6219            } else {
 6220                MultiBufferRow(selection.end.row)
 6221            };
 6222
 6223            if let Some(last_row_range) = row_ranges.last_mut() {
 6224                if start <= last_row_range.end {
 6225                    last_row_range.end = end;
 6226                    continue;
 6227                }
 6228            }
 6229            row_ranges.push(start..end);
 6230        }
 6231
 6232        let snapshot = self.buffer.read(cx).snapshot(cx);
 6233        let mut cursor_positions = Vec::new();
 6234        for row_range in &row_ranges {
 6235            let anchor = snapshot.anchor_before(Point::new(
 6236                row_range.end.previous_row().0,
 6237                snapshot.line_len(row_range.end.previous_row()),
 6238            ));
 6239            cursor_positions.push(anchor..anchor);
 6240        }
 6241
 6242        self.transact(window, cx, |this, window, cx| {
 6243            for row_range in row_ranges.into_iter().rev() {
 6244                for row in row_range.iter_rows().rev() {
 6245                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6246                    let next_line_row = row.next_row();
 6247                    let indent = snapshot.indent_size_for_line(next_line_row);
 6248                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6249
 6250                    let replace =
 6251                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6252                            " "
 6253                        } else {
 6254                            ""
 6255                        };
 6256
 6257                    this.buffer.update(cx, |buffer, cx| {
 6258                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6259                    });
 6260                }
 6261            }
 6262
 6263            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6264                s.select_anchor_ranges(cursor_positions)
 6265            });
 6266        });
 6267    }
 6268
 6269    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6270        self.join_lines_impl(true, window, cx);
 6271    }
 6272
 6273    pub fn sort_lines_case_sensitive(
 6274        &mut self,
 6275        _: &SortLinesCaseSensitive,
 6276        window: &mut Window,
 6277        cx: &mut Context<Self>,
 6278    ) {
 6279        self.manipulate_lines(window, cx, |lines| lines.sort())
 6280    }
 6281
 6282    pub fn sort_lines_case_insensitive(
 6283        &mut self,
 6284        _: &SortLinesCaseInsensitive,
 6285        window: &mut Window,
 6286        cx: &mut Context<Self>,
 6287    ) {
 6288        self.manipulate_lines(window, cx, |lines| {
 6289            lines.sort_by_key(|line| line.to_lowercase())
 6290        })
 6291    }
 6292
 6293    pub fn unique_lines_case_insensitive(
 6294        &mut self,
 6295        _: &UniqueLinesCaseInsensitive,
 6296        window: &mut Window,
 6297        cx: &mut Context<Self>,
 6298    ) {
 6299        self.manipulate_lines(window, cx, |lines| {
 6300            let mut seen = HashSet::default();
 6301            lines.retain(|line| seen.insert(line.to_lowercase()));
 6302        })
 6303    }
 6304
 6305    pub fn unique_lines_case_sensitive(
 6306        &mut self,
 6307        _: &UniqueLinesCaseSensitive,
 6308        window: &mut Window,
 6309        cx: &mut Context<Self>,
 6310    ) {
 6311        self.manipulate_lines(window, cx, |lines| {
 6312            let mut seen = HashSet::default();
 6313            lines.retain(|line| seen.insert(*line));
 6314        })
 6315    }
 6316
 6317    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6318        let mut revert_changes = HashMap::default();
 6319        let snapshot = self.snapshot(window, cx);
 6320        for hunk in snapshot
 6321            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6322        {
 6323            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6324        }
 6325        if !revert_changes.is_empty() {
 6326            self.transact(window, cx, |editor, window, cx| {
 6327                editor.revert(revert_changes, window, cx);
 6328            });
 6329        }
 6330    }
 6331
 6332    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6333        let Some(project) = self.project.clone() else {
 6334            return;
 6335        };
 6336        self.reload(project, window, cx)
 6337            .detach_and_notify_err(window, cx);
 6338    }
 6339
 6340    pub fn revert_selected_hunks(
 6341        &mut self,
 6342        _: &RevertSelectedHunks,
 6343        window: &mut Window,
 6344        cx: &mut Context<Self>,
 6345    ) {
 6346        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6347        self.revert_hunks_in_ranges(selections, window, cx);
 6348    }
 6349
 6350    fn revert_hunks_in_ranges(
 6351        &mut self,
 6352        ranges: impl Iterator<Item = Range<Point>>,
 6353        window: &mut Window,
 6354        cx: &mut Context<Editor>,
 6355    ) {
 6356        let mut revert_changes = HashMap::default();
 6357        let snapshot = self.snapshot(window, cx);
 6358        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6359            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6360        }
 6361        if !revert_changes.is_empty() {
 6362            self.transact(window, cx, |editor, window, cx| {
 6363                editor.revert(revert_changes, window, cx);
 6364            });
 6365        }
 6366    }
 6367
 6368    pub fn open_active_item_in_terminal(
 6369        &mut self,
 6370        _: &OpenInTerminal,
 6371        window: &mut Window,
 6372        cx: &mut Context<Self>,
 6373    ) {
 6374        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6375            let project_path = buffer.read(cx).project_path(cx)?;
 6376            let project = self.project.as_ref()?.read(cx);
 6377            let entry = project.entry_for_path(&project_path, cx)?;
 6378            let parent = match &entry.canonical_path {
 6379                Some(canonical_path) => canonical_path.to_path_buf(),
 6380                None => project.absolute_path(&project_path, cx)?,
 6381            }
 6382            .parent()?
 6383            .to_path_buf();
 6384            Some(parent)
 6385        }) {
 6386            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6387        }
 6388    }
 6389
 6390    pub fn prepare_revert_change(
 6391        &self,
 6392        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6393        hunk: &MultiBufferDiffHunk,
 6394        cx: &mut App,
 6395    ) -> Option<()> {
 6396        let buffer = self.buffer.read(cx);
 6397        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6398        let buffer = buffer.buffer(hunk.buffer_id)?;
 6399        let buffer = buffer.read(cx);
 6400        let original_text = change_set
 6401            .read(cx)
 6402            .base_text
 6403            .as_ref()?
 6404            .as_rope()
 6405            .slice(hunk.diff_base_byte_range.clone());
 6406        let buffer_snapshot = buffer.snapshot();
 6407        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6408        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6409            probe
 6410                .0
 6411                .start
 6412                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6413                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6414        }) {
 6415            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6416            Some(())
 6417        } else {
 6418            None
 6419        }
 6420    }
 6421
 6422    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6423        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6424    }
 6425
 6426    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6427        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6428    }
 6429
 6430    fn manipulate_lines<Fn>(
 6431        &mut self,
 6432        window: &mut Window,
 6433        cx: &mut Context<Self>,
 6434        mut callback: Fn,
 6435    ) where
 6436        Fn: FnMut(&mut Vec<&str>),
 6437    {
 6438        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6439        let buffer = self.buffer.read(cx).snapshot(cx);
 6440
 6441        let mut edits = Vec::new();
 6442
 6443        let selections = self.selections.all::<Point>(cx);
 6444        let mut selections = selections.iter().peekable();
 6445        let mut contiguous_row_selections = Vec::new();
 6446        let mut new_selections = Vec::new();
 6447        let mut added_lines = 0;
 6448        let mut removed_lines = 0;
 6449
 6450        while let Some(selection) = selections.next() {
 6451            let (start_row, end_row) = consume_contiguous_rows(
 6452                &mut contiguous_row_selections,
 6453                selection,
 6454                &display_map,
 6455                &mut selections,
 6456            );
 6457
 6458            let start_point = Point::new(start_row.0, 0);
 6459            let end_point = Point::new(
 6460                end_row.previous_row().0,
 6461                buffer.line_len(end_row.previous_row()),
 6462            );
 6463            let text = buffer
 6464                .text_for_range(start_point..end_point)
 6465                .collect::<String>();
 6466
 6467            let mut lines = text.split('\n').collect_vec();
 6468
 6469            let lines_before = lines.len();
 6470            callback(&mut lines);
 6471            let lines_after = lines.len();
 6472
 6473            edits.push((start_point..end_point, lines.join("\n")));
 6474
 6475            // Selections must change based on added and removed line count
 6476            let start_row =
 6477                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6478            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6479            new_selections.push(Selection {
 6480                id: selection.id,
 6481                start: start_row,
 6482                end: end_row,
 6483                goal: SelectionGoal::None,
 6484                reversed: selection.reversed,
 6485            });
 6486
 6487            if lines_after > lines_before {
 6488                added_lines += lines_after - lines_before;
 6489            } else if lines_before > lines_after {
 6490                removed_lines += lines_before - lines_after;
 6491            }
 6492        }
 6493
 6494        self.transact(window, cx, |this, window, cx| {
 6495            let buffer = this.buffer.update(cx, |buffer, cx| {
 6496                buffer.edit(edits, None, cx);
 6497                buffer.snapshot(cx)
 6498            });
 6499
 6500            // Recalculate offsets on newly edited buffer
 6501            let new_selections = new_selections
 6502                .iter()
 6503                .map(|s| {
 6504                    let start_point = Point::new(s.start.0, 0);
 6505                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6506                    Selection {
 6507                        id: s.id,
 6508                        start: buffer.point_to_offset(start_point),
 6509                        end: buffer.point_to_offset(end_point),
 6510                        goal: s.goal,
 6511                        reversed: s.reversed,
 6512                    }
 6513                })
 6514                .collect();
 6515
 6516            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6517                s.select(new_selections);
 6518            });
 6519
 6520            this.request_autoscroll(Autoscroll::fit(), cx);
 6521        });
 6522    }
 6523
 6524    pub fn convert_to_upper_case(
 6525        &mut self,
 6526        _: &ConvertToUpperCase,
 6527        window: &mut Window,
 6528        cx: &mut Context<Self>,
 6529    ) {
 6530        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6531    }
 6532
 6533    pub fn convert_to_lower_case(
 6534        &mut self,
 6535        _: &ConvertToLowerCase,
 6536        window: &mut Window,
 6537        cx: &mut Context<Self>,
 6538    ) {
 6539        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6540    }
 6541
 6542    pub fn convert_to_title_case(
 6543        &mut self,
 6544        _: &ConvertToTitleCase,
 6545        window: &mut Window,
 6546        cx: &mut Context<Self>,
 6547    ) {
 6548        self.manipulate_text(window, cx, |text| {
 6549            text.split('\n')
 6550                .map(|line| line.to_case(Case::Title))
 6551                .join("\n")
 6552        })
 6553    }
 6554
 6555    pub fn convert_to_snake_case(
 6556        &mut self,
 6557        _: &ConvertToSnakeCase,
 6558        window: &mut Window,
 6559        cx: &mut Context<Self>,
 6560    ) {
 6561        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6562    }
 6563
 6564    pub fn convert_to_kebab_case(
 6565        &mut self,
 6566        _: &ConvertToKebabCase,
 6567        window: &mut Window,
 6568        cx: &mut Context<Self>,
 6569    ) {
 6570        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6571    }
 6572
 6573    pub fn convert_to_upper_camel_case(
 6574        &mut self,
 6575        _: &ConvertToUpperCamelCase,
 6576        window: &mut Window,
 6577        cx: &mut Context<Self>,
 6578    ) {
 6579        self.manipulate_text(window, cx, |text| {
 6580            text.split('\n')
 6581                .map(|line| line.to_case(Case::UpperCamel))
 6582                .join("\n")
 6583        })
 6584    }
 6585
 6586    pub fn convert_to_lower_camel_case(
 6587        &mut self,
 6588        _: &ConvertToLowerCamelCase,
 6589        window: &mut Window,
 6590        cx: &mut Context<Self>,
 6591    ) {
 6592        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6593    }
 6594
 6595    pub fn convert_to_opposite_case(
 6596        &mut self,
 6597        _: &ConvertToOppositeCase,
 6598        window: &mut Window,
 6599        cx: &mut Context<Self>,
 6600    ) {
 6601        self.manipulate_text(window, cx, |text| {
 6602            text.chars()
 6603                .fold(String::with_capacity(text.len()), |mut t, c| {
 6604                    if c.is_uppercase() {
 6605                        t.extend(c.to_lowercase());
 6606                    } else {
 6607                        t.extend(c.to_uppercase());
 6608                    }
 6609                    t
 6610                })
 6611        })
 6612    }
 6613
 6614    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6615    where
 6616        Fn: FnMut(&str) -> String,
 6617    {
 6618        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6619        let buffer = self.buffer.read(cx).snapshot(cx);
 6620
 6621        let mut new_selections = Vec::new();
 6622        let mut edits = Vec::new();
 6623        let mut selection_adjustment = 0i32;
 6624
 6625        for selection in self.selections.all::<usize>(cx) {
 6626            let selection_is_empty = selection.is_empty();
 6627
 6628            let (start, end) = if selection_is_empty {
 6629                let word_range = movement::surrounding_word(
 6630                    &display_map,
 6631                    selection.start.to_display_point(&display_map),
 6632                );
 6633                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6634                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6635                (start, end)
 6636            } else {
 6637                (selection.start, selection.end)
 6638            };
 6639
 6640            let text = buffer.text_for_range(start..end).collect::<String>();
 6641            let old_length = text.len() as i32;
 6642            let text = callback(&text);
 6643
 6644            new_selections.push(Selection {
 6645                start: (start as i32 - selection_adjustment) as usize,
 6646                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6647                goal: SelectionGoal::None,
 6648                ..selection
 6649            });
 6650
 6651            selection_adjustment += old_length - text.len() as i32;
 6652
 6653            edits.push((start..end, text));
 6654        }
 6655
 6656        self.transact(window, cx, |this, window, cx| {
 6657            this.buffer.update(cx, |buffer, cx| {
 6658                buffer.edit(edits, None, cx);
 6659            });
 6660
 6661            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6662                s.select(new_selections);
 6663            });
 6664
 6665            this.request_autoscroll(Autoscroll::fit(), cx);
 6666        });
 6667    }
 6668
 6669    pub fn duplicate(
 6670        &mut self,
 6671        upwards: bool,
 6672        whole_lines: bool,
 6673        window: &mut Window,
 6674        cx: &mut Context<Self>,
 6675    ) {
 6676        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6677        let buffer = &display_map.buffer_snapshot;
 6678        let selections = self.selections.all::<Point>(cx);
 6679
 6680        let mut edits = Vec::new();
 6681        let mut selections_iter = selections.iter().peekable();
 6682        while let Some(selection) = selections_iter.next() {
 6683            let mut rows = selection.spanned_rows(false, &display_map);
 6684            // duplicate line-wise
 6685            if whole_lines || selection.start == selection.end {
 6686                // Avoid duplicating the same lines twice.
 6687                while let Some(next_selection) = selections_iter.peek() {
 6688                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6689                    if next_rows.start < rows.end {
 6690                        rows.end = next_rows.end;
 6691                        selections_iter.next().unwrap();
 6692                    } else {
 6693                        break;
 6694                    }
 6695                }
 6696
 6697                // Copy the text from the selected row region and splice it either at the start
 6698                // or end of the region.
 6699                let start = Point::new(rows.start.0, 0);
 6700                let end = Point::new(
 6701                    rows.end.previous_row().0,
 6702                    buffer.line_len(rows.end.previous_row()),
 6703                );
 6704                let text = buffer
 6705                    .text_for_range(start..end)
 6706                    .chain(Some("\n"))
 6707                    .collect::<String>();
 6708                let insert_location = if upwards {
 6709                    Point::new(rows.end.0, 0)
 6710                } else {
 6711                    start
 6712                };
 6713                edits.push((insert_location..insert_location, text));
 6714            } else {
 6715                // duplicate character-wise
 6716                let start = selection.start;
 6717                let end = selection.end;
 6718                let text = buffer.text_for_range(start..end).collect::<String>();
 6719                edits.push((selection.end..selection.end, text));
 6720            }
 6721        }
 6722
 6723        self.transact(window, cx, |this, _, cx| {
 6724            this.buffer.update(cx, |buffer, cx| {
 6725                buffer.edit(edits, None, cx);
 6726            });
 6727
 6728            this.request_autoscroll(Autoscroll::fit(), cx);
 6729        });
 6730    }
 6731
 6732    pub fn duplicate_line_up(
 6733        &mut self,
 6734        _: &DuplicateLineUp,
 6735        window: &mut Window,
 6736        cx: &mut Context<Self>,
 6737    ) {
 6738        self.duplicate(true, true, window, cx);
 6739    }
 6740
 6741    pub fn duplicate_line_down(
 6742        &mut self,
 6743        _: &DuplicateLineDown,
 6744        window: &mut Window,
 6745        cx: &mut Context<Self>,
 6746    ) {
 6747        self.duplicate(false, true, window, cx);
 6748    }
 6749
 6750    pub fn duplicate_selection(
 6751        &mut self,
 6752        _: &DuplicateSelection,
 6753        window: &mut Window,
 6754        cx: &mut Context<Self>,
 6755    ) {
 6756        self.duplicate(false, false, window, cx);
 6757    }
 6758
 6759    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 6760        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6761        let buffer = self.buffer.read(cx).snapshot(cx);
 6762
 6763        let mut edits = Vec::new();
 6764        let mut unfold_ranges = Vec::new();
 6765        let mut refold_creases = Vec::new();
 6766
 6767        let selections = self.selections.all::<Point>(cx);
 6768        let mut selections = selections.iter().peekable();
 6769        let mut contiguous_row_selections = Vec::new();
 6770        let mut new_selections = Vec::new();
 6771
 6772        while let Some(selection) = selections.next() {
 6773            // Find all the selections that span a contiguous row range
 6774            let (start_row, end_row) = consume_contiguous_rows(
 6775                &mut contiguous_row_selections,
 6776                selection,
 6777                &display_map,
 6778                &mut selections,
 6779            );
 6780
 6781            // Move the text spanned by the row range to be before the line preceding the row range
 6782            if start_row.0 > 0 {
 6783                let range_to_move = Point::new(
 6784                    start_row.previous_row().0,
 6785                    buffer.line_len(start_row.previous_row()),
 6786                )
 6787                    ..Point::new(
 6788                        end_row.previous_row().0,
 6789                        buffer.line_len(end_row.previous_row()),
 6790                    );
 6791                let insertion_point = display_map
 6792                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6793                    .0;
 6794
 6795                // Don't move lines across excerpts
 6796                if buffer
 6797                    .excerpt_containing(insertion_point..range_to_move.end)
 6798                    .is_some()
 6799                {
 6800                    let text = buffer
 6801                        .text_for_range(range_to_move.clone())
 6802                        .flat_map(|s| s.chars())
 6803                        .skip(1)
 6804                        .chain(['\n'])
 6805                        .collect::<String>();
 6806
 6807                    edits.push((
 6808                        buffer.anchor_after(range_to_move.start)
 6809                            ..buffer.anchor_before(range_to_move.end),
 6810                        String::new(),
 6811                    ));
 6812                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6813                    edits.push((insertion_anchor..insertion_anchor, text));
 6814
 6815                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6816
 6817                    // Move selections up
 6818                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6819                        |mut selection| {
 6820                            selection.start.row -= row_delta;
 6821                            selection.end.row -= row_delta;
 6822                            selection
 6823                        },
 6824                    ));
 6825
 6826                    // Move folds up
 6827                    unfold_ranges.push(range_to_move.clone());
 6828                    for fold in display_map.folds_in_range(
 6829                        buffer.anchor_before(range_to_move.start)
 6830                            ..buffer.anchor_after(range_to_move.end),
 6831                    ) {
 6832                        let mut start = fold.range.start.to_point(&buffer);
 6833                        let mut end = fold.range.end.to_point(&buffer);
 6834                        start.row -= row_delta;
 6835                        end.row -= row_delta;
 6836                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6837                    }
 6838                }
 6839            }
 6840
 6841            // If we didn't move line(s), preserve the existing selections
 6842            new_selections.append(&mut contiguous_row_selections);
 6843        }
 6844
 6845        self.transact(window, cx, |this, window, cx| {
 6846            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6847            this.buffer.update(cx, |buffer, cx| {
 6848                for (range, text) in edits {
 6849                    buffer.edit([(range, text)], None, cx);
 6850                }
 6851            });
 6852            this.fold_creases(refold_creases, true, window, cx);
 6853            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6854                s.select(new_selections);
 6855            })
 6856        });
 6857    }
 6858
 6859    pub fn move_line_down(
 6860        &mut self,
 6861        _: &MoveLineDown,
 6862        window: &mut Window,
 6863        cx: &mut Context<Self>,
 6864    ) {
 6865        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6866        let buffer = self.buffer.read(cx).snapshot(cx);
 6867
 6868        let mut edits = Vec::new();
 6869        let mut unfold_ranges = Vec::new();
 6870        let mut refold_creases = Vec::new();
 6871
 6872        let selections = self.selections.all::<Point>(cx);
 6873        let mut selections = selections.iter().peekable();
 6874        let mut contiguous_row_selections = Vec::new();
 6875        let mut new_selections = Vec::new();
 6876
 6877        while let Some(selection) = selections.next() {
 6878            // Find all the selections that span a contiguous row range
 6879            let (start_row, end_row) = consume_contiguous_rows(
 6880                &mut contiguous_row_selections,
 6881                selection,
 6882                &display_map,
 6883                &mut selections,
 6884            );
 6885
 6886            // Move the text spanned by the row range to be after the last line of the row range
 6887            if end_row.0 <= buffer.max_point().row {
 6888                let range_to_move =
 6889                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6890                let insertion_point = display_map
 6891                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6892                    .0;
 6893
 6894                // Don't move lines across excerpt boundaries
 6895                if buffer
 6896                    .excerpt_containing(range_to_move.start..insertion_point)
 6897                    .is_some()
 6898                {
 6899                    let mut text = String::from("\n");
 6900                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6901                    text.pop(); // Drop trailing newline
 6902                    edits.push((
 6903                        buffer.anchor_after(range_to_move.start)
 6904                            ..buffer.anchor_before(range_to_move.end),
 6905                        String::new(),
 6906                    ));
 6907                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6908                    edits.push((insertion_anchor..insertion_anchor, text));
 6909
 6910                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6911
 6912                    // Move selections down
 6913                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6914                        |mut selection| {
 6915                            selection.start.row += row_delta;
 6916                            selection.end.row += row_delta;
 6917                            selection
 6918                        },
 6919                    ));
 6920
 6921                    // Move folds down
 6922                    unfold_ranges.push(range_to_move.clone());
 6923                    for fold in display_map.folds_in_range(
 6924                        buffer.anchor_before(range_to_move.start)
 6925                            ..buffer.anchor_after(range_to_move.end),
 6926                    ) {
 6927                        let mut start = fold.range.start.to_point(&buffer);
 6928                        let mut end = fold.range.end.to_point(&buffer);
 6929                        start.row += row_delta;
 6930                        end.row += row_delta;
 6931                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6932                    }
 6933                }
 6934            }
 6935
 6936            // If we didn't move line(s), preserve the existing selections
 6937            new_selections.append(&mut contiguous_row_selections);
 6938        }
 6939
 6940        self.transact(window, cx, |this, window, cx| {
 6941            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6942            this.buffer.update(cx, |buffer, cx| {
 6943                for (range, text) in edits {
 6944                    buffer.edit([(range, text)], None, cx);
 6945                }
 6946            });
 6947            this.fold_creases(refold_creases, true, window, cx);
 6948            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6949                s.select(new_selections)
 6950            });
 6951        });
 6952    }
 6953
 6954    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 6955        let text_layout_details = &self.text_layout_details(window);
 6956        self.transact(window, cx, |this, window, cx| {
 6957            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6958                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6959                let line_mode = s.line_mode;
 6960                s.move_with(|display_map, selection| {
 6961                    if !selection.is_empty() || line_mode {
 6962                        return;
 6963                    }
 6964
 6965                    let mut head = selection.head();
 6966                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6967                    if head.column() == display_map.line_len(head.row()) {
 6968                        transpose_offset = display_map
 6969                            .buffer_snapshot
 6970                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6971                    }
 6972
 6973                    if transpose_offset == 0 {
 6974                        return;
 6975                    }
 6976
 6977                    *head.column_mut() += 1;
 6978                    head = display_map.clip_point(head, Bias::Right);
 6979                    let goal = SelectionGoal::HorizontalPosition(
 6980                        display_map
 6981                            .x_for_display_point(head, text_layout_details)
 6982                            .into(),
 6983                    );
 6984                    selection.collapse_to(head, goal);
 6985
 6986                    let transpose_start = display_map
 6987                        .buffer_snapshot
 6988                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6989                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6990                        let transpose_end = display_map
 6991                            .buffer_snapshot
 6992                            .clip_offset(transpose_offset + 1, Bias::Right);
 6993                        if let Some(ch) =
 6994                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6995                        {
 6996                            edits.push((transpose_start..transpose_offset, String::new()));
 6997                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6998                        }
 6999                    }
 7000                });
 7001                edits
 7002            });
 7003            this.buffer
 7004                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7005            let selections = this.selections.all::<usize>(cx);
 7006            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7007                s.select(selections);
 7008            });
 7009        });
 7010    }
 7011
 7012    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7013        self.rewrap_impl(IsVimMode::No, cx)
 7014    }
 7015
 7016    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7017        let buffer = self.buffer.read(cx).snapshot(cx);
 7018        let selections = self.selections.all::<Point>(cx);
 7019        let mut selections = selections.iter().peekable();
 7020
 7021        let mut edits = Vec::new();
 7022        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7023
 7024        while let Some(selection) = selections.next() {
 7025            let mut start_row = selection.start.row;
 7026            let mut end_row = selection.end.row;
 7027
 7028            // Skip selections that overlap with a range that has already been rewrapped.
 7029            let selection_range = start_row..end_row;
 7030            if rewrapped_row_ranges
 7031                .iter()
 7032                .any(|range| range.overlaps(&selection_range))
 7033            {
 7034                continue;
 7035            }
 7036
 7037            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7038
 7039            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7040                match language_scope.language_name().as_ref() {
 7041                    "Markdown" | "Plain Text" => {
 7042                        should_rewrap = true;
 7043                    }
 7044                    _ => {}
 7045                }
 7046            }
 7047
 7048            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7049
 7050            // Since not all lines in the selection may be at the same indent
 7051            // level, choose the indent size that is the most common between all
 7052            // of the lines.
 7053            //
 7054            // If there is a tie, we use the deepest indent.
 7055            let (indent_size, indent_end) = {
 7056                let mut indent_size_occurrences = HashMap::default();
 7057                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7058
 7059                for row in start_row..=end_row {
 7060                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7061                    rows_by_indent_size.entry(indent).or_default().push(row);
 7062                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7063                }
 7064
 7065                let indent_size = indent_size_occurrences
 7066                    .into_iter()
 7067                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7068                    .map(|(indent, _)| indent)
 7069                    .unwrap_or_default();
 7070                let row = rows_by_indent_size[&indent_size][0];
 7071                let indent_end = Point::new(row, indent_size.len);
 7072
 7073                (indent_size, indent_end)
 7074            };
 7075
 7076            let mut line_prefix = indent_size.chars().collect::<String>();
 7077
 7078            if let Some(comment_prefix) =
 7079                buffer
 7080                    .language_scope_at(selection.head())
 7081                    .and_then(|language| {
 7082                        language
 7083                            .line_comment_prefixes()
 7084                            .iter()
 7085                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7086                            .cloned()
 7087                    })
 7088            {
 7089                line_prefix.push_str(&comment_prefix);
 7090                should_rewrap = true;
 7091            }
 7092
 7093            if !should_rewrap {
 7094                continue;
 7095            }
 7096
 7097            if selection.is_empty() {
 7098                'expand_upwards: while start_row > 0 {
 7099                    let prev_row = start_row - 1;
 7100                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7101                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7102                    {
 7103                        start_row = prev_row;
 7104                    } else {
 7105                        break 'expand_upwards;
 7106                    }
 7107                }
 7108
 7109                'expand_downwards: while end_row < buffer.max_point().row {
 7110                    let next_row = end_row + 1;
 7111                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7112                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7113                    {
 7114                        end_row = next_row;
 7115                    } else {
 7116                        break 'expand_downwards;
 7117                    }
 7118                }
 7119            }
 7120
 7121            let start = Point::new(start_row, 0);
 7122            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7123            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7124            let Some(lines_without_prefixes) = selection_text
 7125                .lines()
 7126                .map(|line| {
 7127                    line.strip_prefix(&line_prefix)
 7128                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7129                        .ok_or_else(|| {
 7130                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7131                        })
 7132                })
 7133                .collect::<Result<Vec<_>, _>>()
 7134                .log_err()
 7135            else {
 7136                continue;
 7137            };
 7138
 7139            let wrap_column = buffer
 7140                .settings_at(Point::new(start_row, 0), cx)
 7141                .preferred_line_length as usize;
 7142            let wrapped_text = wrap_with_prefix(
 7143                line_prefix,
 7144                lines_without_prefixes.join(" "),
 7145                wrap_column,
 7146                tab_size,
 7147            );
 7148
 7149            // TODO: should always use char-based diff while still supporting cursor behavior that
 7150            // matches vim.
 7151            let diff = match is_vim_mode {
 7152                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7153                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7154            };
 7155            let mut offset = start.to_offset(&buffer);
 7156            let mut moved_since_edit = true;
 7157
 7158            for change in diff.iter_all_changes() {
 7159                let value = change.value();
 7160                match change.tag() {
 7161                    ChangeTag::Equal => {
 7162                        offset += value.len();
 7163                        moved_since_edit = true;
 7164                    }
 7165                    ChangeTag::Delete => {
 7166                        let start = buffer.anchor_after(offset);
 7167                        let end = buffer.anchor_before(offset + value.len());
 7168
 7169                        if moved_since_edit {
 7170                            edits.push((start..end, String::new()));
 7171                        } else {
 7172                            edits.last_mut().unwrap().0.end = end;
 7173                        }
 7174
 7175                        offset += value.len();
 7176                        moved_since_edit = false;
 7177                    }
 7178                    ChangeTag::Insert => {
 7179                        if moved_since_edit {
 7180                            let anchor = buffer.anchor_after(offset);
 7181                            edits.push((anchor..anchor, value.to_string()));
 7182                        } else {
 7183                            edits.last_mut().unwrap().1.push_str(value);
 7184                        }
 7185
 7186                        moved_since_edit = false;
 7187                    }
 7188                }
 7189            }
 7190
 7191            rewrapped_row_ranges.push(start_row..=end_row);
 7192        }
 7193
 7194        self.buffer
 7195            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7196    }
 7197
 7198    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7199        let mut text = String::new();
 7200        let buffer = self.buffer.read(cx).snapshot(cx);
 7201        let mut selections = self.selections.all::<Point>(cx);
 7202        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7203        {
 7204            let max_point = buffer.max_point();
 7205            let mut is_first = true;
 7206            for selection in &mut selections {
 7207                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7208                if is_entire_line {
 7209                    selection.start = Point::new(selection.start.row, 0);
 7210                    if !selection.is_empty() && selection.end.column == 0 {
 7211                        selection.end = cmp::min(max_point, selection.end);
 7212                    } else {
 7213                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7214                    }
 7215                    selection.goal = SelectionGoal::None;
 7216                }
 7217                if is_first {
 7218                    is_first = false;
 7219                } else {
 7220                    text += "\n";
 7221                }
 7222                let mut len = 0;
 7223                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7224                    text.push_str(chunk);
 7225                    len += chunk.len();
 7226                }
 7227                clipboard_selections.push(ClipboardSelection {
 7228                    len,
 7229                    is_entire_line,
 7230                    first_line_indent: buffer
 7231                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7232                        .len,
 7233                });
 7234            }
 7235        }
 7236
 7237        self.transact(window, cx, |this, window, cx| {
 7238            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7239                s.select(selections);
 7240            });
 7241            this.insert("", window, cx);
 7242        });
 7243        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7244    }
 7245
 7246    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7247        let item = self.cut_common(window, cx);
 7248        cx.write_to_clipboard(item);
 7249    }
 7250
 7251    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7252        self.change_selections(None, window, cx, |s| {
 7253            s.move_with(|snapshot, sel| {
 7254                if sel.is_empty() {
 7255                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7256                }
 7257            });
 7258        });
 7259        let item = self.cut_common(window, cx);
 7260        cx.set_global(KillRing(item))
 7261    }
 7262
 7263    pub fn kill_ring_yank(
 7264        &mut self,
 7265        _: &KillRingYank,
 7266        window: &mut Window,
 7267        cx: &mut Context<Self>,
 7268    ) {
 7269        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7270            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7271                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7272            } else {
 7273                return;
 7274            }
 7275        } else {
 7276            return;
 7277        };
 7278        self.do_paste(&text, metadata, false, window, cx);
 7279    }
 7280
 7281    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7282        let selections = self.selections.all::<Point>(cx);
 7283        let buffer = self.buffer.read(cx).read(cx);
 7284        let mut text = String::new();
 7285
 7286        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7287        {
 7288            let max_point = buffer.max_point();
 7289            let mut is_first = true;
 7290            for selection in selections.iter() {
 7291                let mut start = selection.start;
 7292                let mut end = selection.end;
 7293                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7294                if is_entire_line {
 7295                    start = Point::new(start.row, 0);
 7296                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7297                }
 7298                if is_first {
 7299                    is_first = false;
 7300                } else {
 7301                    text += "\n";
 7302                }
 7303                let mut len = 0;
 7304                for chunk in buffer.text_for_range(start..end) {
 7305                    text.push_str(chunk);
 7306                    len += chunk.len();
 7307                }
 7308                clipboard_selections.push(ClipboardSelection {
 7309                    len,
 7310                    is_entire_line,
 7311                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7312                });
 7313            }
 7314        }
 7315
 7316        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7317            text,
 7318            clipboard_selections,
 7319        ));
 7320    }
 7321
 7322    pub fn do_paste(
 7323        &mut self,
 7324        text: &String,
 7325        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7326        handle_entire_lines: bool,
 7327        window: &mut Window,
 7328        cx: &mut Context<Self>,
 7329    ) {
 7330        if self.read_only(cx) {
 7331            return;
 7332        }
 7333
 7334        let clipboard_text = Cow::Borrowed(text);
 7335
 7336        self.transact(window, cx, |this, window, cx| {
 7337            if let Some(mut clipboard_selections) = clipboard_selections {
 7338                let old_selections = this.selections.all::<usize>(cx);
 7339                let all_selections_were_entire_line =
 7340                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7341                let first_selection_indent_column =
 7342                    clipboard_selections.first().map(|s| s.first_line_indent);
 7343                if clipboard_selections.len() != old_selections.len() {
 7344                    clipboard_selections.drain(..);
 7345                }
 7346                let cursor_offset = this.selections.last::<usize>(cx).head();
 7347                let mut auto_indent_on_paste = true;
 7348
 7349                this.buffer.update(cx, |buffer, cx| {
 7350                    let snapshot = buffer.read(cx);
 7351                    auto_indent_on_paste =
 7352                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7353
 7354                    let mut start_offset = 0;
 7355                    let mut edits = Vec::new();
 7356                    let mut original_indent_columns = Vec::new();
 7357                    for (ix, selection) in old_selections.iter().enumerate() {
 7358                        let to_insert;
 7359                        let entire_line;
 7360                        let original_indent_column;
 7361                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7362                            let end_offset = start_offset + clipboard_selection.len;
 7363                            to_insert = &clipboard_text[start_offset..end_offset];
 7364                            entire_line = clipboard_selection.is_entire_line;
 7365                            start_offset = end_offset + 1;
 7366                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7367                        } else {
 7368                            to_insert = clipboard_text.as_str();
 7369                            entire_line = all_selections_were_entire_line;
 7370                            original_indent_column = first_selection_indent_column
 7371                        }
 7372
 7373                        // If the corresponding selection was empty when this slice of the
 7374                        // clipboard text was written, then the entire line containing the
 7375                        // selection was copied. If this selection is also currently empty,
 7376                        // then paste the line before the current line of the buffer.
 7377                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7378                            let column = selection.start.to_point(&snapshot).column as usize;
 7379                            let line_start = selection.start - column;
 7380                            line_start..line_start
 7381                        } else {
 7382                            selection.range()
 7383                        };
 7384
 7385                        edits.push((range, to_insert));
 7386                        original_indent_columns.extend(original_indent_column);
 7387                    }
 7388                    drop(snapshot);
 7389
 7390                    buffer.edit(
 7391                        edits,
 7392                        if auto_indent_on_paste {
 7393                            Some(AutoindentMode::Block {
 7394                                original_indent_columns,
 7395                            })
 7396                        } else {
 7397                            None
 7398                        },
 7399                        cx,
 7400                    );
 7401                });
 7402
 7403                let selections = this.selections.all::<usize>(cx);
 7404                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7405                    s.select(selections)
 7406                });
 7407            } else {
 7408                this.insert(&clipboard_text, window, cx);
 7409            }
 7410        });
 7411    }
 7412
 7413    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7414        if let Some(item) = cx.read_from_clipboard() {
 7415            let entries = item.entries();
 7416
 7417            match entries.first() {
 7418                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7419                // of all the pasted entries.
 7420                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7421                    .do_paste(
 7422                        clipboard_string.text(),
 7423                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7424                        true,
 7425                        window,
 7426                        cx,
 7427                    ),
 7428                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7429            }
 7430        }
 7431    }
 7432
 7433    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7434        if self.read_only(cx) {
 7435            return;
 7436        }
 7437
 7438        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7439            if let Some((selections, _)) =
 7440                self.selection_history.transaction(transaction_id).cloned()
 7441            {
 7442                self.change_selections(None, window, cx, |s| {
 7443                    s.select_anchors(selections.to_vec());
 7444                });
 7445            }
 7446            self.request_autoscroll(Autoscroll::fit(), cx);
 7447            self.unmark_text(window, cx);
 7448            self.refresh_inline_completion(true, false, window, cx);
 7449            cx.emit(EditorEvent::Edited { transaction_id });
 7450            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7451        }
 7452    }
 7453
 7454    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7455        if self.read_only(cx) {
 7456            return;
 7457        }
 7458
 7459        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7460            if let Some((_, Some(selections))) =
 7461                self.selection_history.transaction(transaction_id).cloned()
 7462            {
 7463                self.change_selections(None, window, cx, |s| {
 7464                    s.select_anchors(selections.to_vec());
 7465                });
 7466            }
 7467            self.request_autoscroll(Autoscroll::fit(), cx);
 7468            self.unmark_text(window, cx);
 7469            self.refresh_inline_completion(true, false, window, cx);
 7470            cx.emit(EditorEvent::Edited { transaction_id });
 7471        }
 7472    }
 7473
 7474    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7475        self.buffer
 7476            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7477    }
 7478
 7479    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7480        self.buffer
 7481            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7482    }
 7483
 7484    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7485        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7486            let line_mode = s.line_mode;
 7487            s.move_with(|map, selection| {
 7488                let cursor = if selection.is_empty() && !line_mode {
 7489                    movement::left(map, selection.start)
 7490                } else {
 7491                    selection.start
 7492                };
 7493                selection.collapse_to(cursor, SelectionGoal::None);
 7494            });
 7495        })
 7496    }
 7497
 7498    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7499        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7500            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7501        })
 7502    }
 7503
 7504    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7505        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7506            let line_mode = s.line_mode;
 7507            s.move_with(|map, selection| {
 7508                let cursor = if selection.is_empty() && !line_mode {
 7509                    movement::right(map, selection.end)
 7510                } else {
 7511                    selection.end
 7512                };
 7513                selection.collapse_to(cursor, SelectionGoal::None)
 7514            });
 7515        })
 7516    }
 7517
 7518    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7519        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7520            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7521        })
 7522    }
 7523
 7524    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7525        if self.take_rename(true, window, cx).is_some() {
 7526            return;
 7527        }
 7528
 7529        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7530            cx.propagate();
 7531            return;
 7532        }
 7533
 7534        let text_layout_details = &self.text_layout_details(window);
 7535        let selection_count = self.selections.count();
 7536        let first_selection = self.selections.first_anchor();
 7537
 7538        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7539            let line_mode = s.line_mode;
 7540            s.move_with(|map, selection| {
 7541                if !selection.is_empty() && !line_mode {
 7542                    selection.goal = SelectionGoal::None;
 7543                }
 7544                let (cursor, goal) = movement::up(
 7545                    map,
 7546                    selection.start,
 7547                    selection.goal,
 7548                    false,
 7549                    text_layout_details,
 7550                );
 7551                selection.collapse_to(cursor, goal);
 7552            });
 7553        });
 7554
 7555        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7556        {
 7557            cx.propagate();
 7558        }
 7559    }
 7560
 7561    pub fn move_up_by_lines(
 7562        &mut self,
 7563        action: &MoveUpByLines,
 7564        window: &mut Window,
 7565        cx: &mut Context<Self>,
 7566    ) {
 7567        if self.take_rename(true, window, cx).is_some() {
 7568            return;
 7569        }
 7570
 7571        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7572            cx.propagate();
 7573            return;
 7574        }
 7575
 7576        let text_layout_details = &self.text_layout_details(window);
 7577
 7578        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7579            let line_mode = s.line_mode;
 7580            s.move_with(|map, selection| {
 7581                if !selection.is_empty() && !line_mode {
 7582                    selection.goal = SelectionGoal::None;
 7583                }
 7584                let (cursor, goal) = movement::up_by_rows(
 7585                    map,
 7586                    selection.start,
 7587                    action.lines,
 7588                    selection.goal,
 7589                    false,
 7590                    text_layout_details,
 7591                );
 7592                selection.collapse_to(cursor, goal);
 7593            });
 7594        })
 7595    }
 7596
 7597    pub fn move_down_by_lines(
 7598        &mut self,
 7599        action: &MoveDownByLines,
 7600        window: &mut Window,
 7601        cx: &mut Context<Self>,
 7602    ) {
 7603        if self.take_rename(true, window, cx).is_some() {
 7604            return;
 7605        }
 7606
 7607        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7608            cx.propagate();
 7609            return;
 7610        }
 7611
 7612        let text_layout_details = &self.text_layout_details(window);
 7613
 7614        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7615            let line_mode = s.line_mode;
 7616            s.move_with(|map, selection| {
 7617                if !selection.is_empty() && !line_mode {
 7618                    selection.goal = SelectionGoal::None;
 7619                }
 7620                let (cursor, goal) = movement::down_by_rows(
 7621                    map,
 7622                    selection.start,
 7623                    action.lines,
 7624                    selection.goal,
 7625                    false,
 7626                    text_layout_details,
 7627                );
 7628                selection.collapse_to(cursor, goal);
 7629            });
 7630        })
 7631    }
 7632
 7633    pub fn select_down_by_lines(
 7634        &mut self,
 7635        action: &SelectDownByLines,
 7636        window: &mut Window,
 7637        cx: &mut Context<Self>,
 7638    ) {
 7639        let text_layout_details = &self.text_layout_details(window);
 7640        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7641            s.move_heads_with(|map, head, goal| {
 7642                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7643            })
 7644        })
 7645    }
 7646
 7647    pub fn select_up_by_lines(
 7648        &mut self,
 7649        action: &SelectUpByLines,
 7650        window: &mut Window,
 7651        cx: &mut Context<Self>,
 7652    ) {
 7653        let text_layout_details = &self.text_layout_details(window);
 7654        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7655            s.move_heads_with(|map, head, goal| {
 7656                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7657            })
 7658        })
 7659    }
 7660
 7661    pub fn select_page_up(
 7662        &mut self,
 7663        _: &SelectPageUp,
 7664        window: &mut Window,
 7665        cx: &mut Context<Self>,
 7666    ) {
 7667        let Some(row_count) = self.visible_row_count() else {
 7668            return;
 7669        };
 7670
 7671        let text_layout_details = &self.text_layout_details(window);
 7672
 7673        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7674            s.move_heads_with(|map, head, goal| {
 7675                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7676            })
 7677        })
 7678    }
 7679
 7680    pub fn move_page_up(
 7681        &mut self,
 7682        action: &MovePageUp,
 7683        window: &mut Window,
 7684        cx: &mut Context<Self>,
 7685    ) {
 7686        if self.take_rename(true, window, cx).is_some() {
 7687            return;
 7688        }
 7689
 7690        if self
 7691            .context_menu
 7692            .borrow_mut()
 7693            .as_mut()
 7694            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7695            .unwrap_or(false)
 7696        {
 7697            return;
 7698        }
 7699
 7700        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7701            cx.propagate();
 7702            return;
 7703        }
 7704
 7705        let Some(row_count) = self.visible_row_count() else {
 7706            return;
 7707        };
 7708
 7709        let autoscroll = if action.center_cursor {
 7710            Autoscroll::center()
 7711        } else {
 7712            Autoscroll::fit()
 7713        };
 7714
 7715        let text_layout_details = &self.text_layout_details(window);
 7716
 7717        self.change_selections(Some(autoscroll), window, cx, |s| {
 7718            let line_mode = s.line_mode;
 7719            s.move_with(|map, selection| {
 7720                if !selection.is_empty() && !line_mode {
 7721                    selection.goal = SelectionGoal::None;
 7722                }
 7723                let (cursor, goal) = movement::up_by_rows(
 7724                    map,
 7725                    selection.end,
 7726                    row_count,
 7727                    selection.goal,
 7728                    false,
 7729                    text_layout_details,
 7730                );
 7731                selection.collapse_to(cursor, goal);
 7732            });
 7733        });
 7734    }
 7735
 7736    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 7737        let text_layout_details = &self.text_layout_details(window);
 7738        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7739            s.move_heads_with(|map, head, goal| {
 7740                movement::up(map, head, goal, false, text_layout_details)
 7741            })
 7742        })
 7743    }
 7744
 7745    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 7746        self.take_rename(true, window, cx);
 7747
 7748        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7749            cx.propagate();
 7750            return;
 7751        }
 7752
 7753        let text_layout_details = &self.text_layout_details(window);
 7754        let selection_count = self.selections.count();
 7755        let first_selection = self.selections.first_anchor();
 7756
 7757        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7758            let line_mode = s.line_mode;
 7759            s.move_with(|map, selection| {
 7760                if !selection.is_empty() && !line_mode {
 7761                    selection.goal = SelectionGoal::None;
 7762                }
 7763                let (cursor, goal) = movement::down(
 7764                    map,
 7765                    selection.end,
 7766                    selection.goal,
 7767                    false,
 7768                    text_layout_details,
 7769                );
 7770                selection.collapse_to(cursor, goal);
 7771            });
 7772        });
 7773
 7774        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7775        {
 7776            cx.propagate();
 7777        }
 7778    }
 7779
 7780    pub fn select_page_down(
 7781        &mut self,
 7782        _: &SelectPageDown,
 7783        window: &mut Window,
 7784        cx: &mut Context<Self>,
 7785    ) {
 7786        let Some(row_count) = self.visible_row_count() else {
 7787            return;
 7788        };
 7789
 7790        let text_layout_details = &self.text_layout_details(window);
 7791
 7792        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7793            s.move_heads_with(|map, head, goal| {
 7794                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7795            })
 7796        })
 7797    }
 7798
 7799    pub fn move_page_down(
 7800        &mut self,
 7801        action: &MovePageDown,
 7802        window: &mut Window,
 7803        cx: &mut Context<Self>,
 7804    ) {
 7805        if self.take_rename(true, window, cx).is_some() {
 7806            return;
 7807        }
 7808
 7809        if self
 7810            .context_menu
 7811            .borrow_mut()
 7812            .as_mut()
 7813            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7814            .unwrap_or(false)
 7815        {
 7816            return;
 7817        }
 7818
 7819        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7820            cx.propagate();
 7821            return;
 7822        }
 7823
 7824        let Some(row_count) = self.visible_row_count() else {
 7825            return;
 7826        };
 7827
 7828        let autoscroll = if action.center_cursor {
 7829            Autoscroll::center()
 7830        } else {
 7831            Autoscroll::fit()
 7832        };
 7833
 7834        let text_layout_details = &self.text_layout_details(window);
 7835        self.change_selections(Some(autoscroll), window, cx, |s| {
 7836            let line_mode = s.line_mode;
 7837            s.move_with(|map, selection| {
 7838                if !selection.is_empty() && !line_mode {
 7839                    selection.goal = SelectionGoal::None;
 7840                }
 7841                let (cursor, goal) = movement::down_by_rows(
 7842                    map,
 7843                    selection.end,
 7844                    row_count,
 7845                    selection.goal,
 7846                    false,
 7847                    text_layout_details,
 7848                );
 7849                selection.collapse_to(cursor, goal);
 7850            });
 7851        });
 7852    }
 7853
 7854    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 7855        let text_layout_details = &self.text_layout_details(window);
 7856        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7857            s.move_heads_with(|map, head, goal| {
 7858                movement::down(map, head, goal, false, text_layout_details)
 7859            })
 7860        });
 7861    }
 7862
 7863    pub fn context_menu_first(
 7864        &mut self,
 7865        _: &ContextMenuFirst,
 7866        _window: &mut Window,
 7867        cx: &mut Context<Self>,
 7868    ) {
 7869        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7870            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7871        }
 7872    }
 7873
 7874    pub fn context_menu_prev(
 7875        &mut self,
 7876        _: &ContextMenuPrev,
 7877        _window: &mut Window,
 7878        cx: &mut Context<Self>,
 7879    ) {
 7880        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7881            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7882        }
 7883    }
 7884
 7885    pub fn context_menu_next(
 7886        &mut self,
 7887        _: &ContextMenuNext,
 7888        _window: &mut Window,
 7889        cx: &mut Context<Self>,
 7890    ) {
 7891        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7892            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7893        }
 7894    }
 7895
 7896    pub fn context_menu_last(
 7897        &mut self,
 7898        _: &ContextMenuLast,
 7899        _window: &mut Window,
 7900        cx: &mut Context<Self>,
 7901    ) {
 7902        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7903            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7904        }
 7905    }
 7906
 7907    pub fn move_to_previous_word_start(
 7908        &mut self,
 7909        _: &MoveToPreviousWordStart,
 7910        window: &mut Window,
 7911        cx: &mut Context<Self>,
 7912    ) {
 7913        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7914            s.move_cursors_with(|map, head, _| {
 7915                (
 7916                    movement::previous_word_start(map, head),
 7917                    SelectionGoal::None,
 7918                )
 7919            });
 7920        })
 7921    }
 7922
 7923    pub fn move_to_previous_subword_start(
 7924        &mut self,
 7925        _: &MoveToPreviousSubwordStart,
 7926        window: &mut Window,
 7927        cx: &mut Context<Self>,
 7928    ) {
 7929        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7930            s.move_cursors_with(|map, head, _| {
 7931                (
 7932                    movement::previous_subword_start(map, head),
 7933                    SelectionGoal::None,
 7934                )
 7935            });
 7936        })
 7937    }
 7938
 7939    pub fn select_to_previous_word_start(
 7940        &mut self,
 7941        _: &SelectToPreviousWordStart,
 7942        window: &mut Window,
 7943        cx: &mut Context<Self>,
 7944    ) {
 7945        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7946            s.move_heads_with(|map, head, _| {
 7947                (
 7948                    movement::previous_word_start(map, head),
 7949                    SelectionGoal::None,
 7950                )
 7951            });
 7952        })
 7953    }
 7954
 7955    pub fn select_to_previous_subword_start(
 7956        &mut self,
 7957        _: &SelectToPreviousSubwordStart,
 7958        window: &mut Window,
 7959        cx: &mut Context<Self>,
 7960    ) {
 7961        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7962            s.move_heads_with(|map, head, _| {
 7963                (
 7964                    movement::previous_subword_start(map, head),
 7965                    SelectionGoal::None,
 7966                )
 7967            });
 7968        })
 7969    }
 7970
 7971    pub fn delete_to_previous_word_start(
 7972        &mut self,
 7973        action: &DeleteToPreviousWordStart,
 7974        window: &mut Window,
 7975        cx: &mut Context<Self>,
 7976    ) {
 7977        self.transact(window, cx, |this, window, cx| {
 7978            this.select_autoclose_pair(window, cx);
 7979            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7980                let line_mode = s.line_mode;
 7981                s.move_with(|map, selection| {
 7982                    if selection.is_empty() && !line_mode {
 7983                        let cursor = if action.ignore_newlines {
 7984                            movement::previous_word_start(map, selection.head())
 7985                        } else {
 7986                            movement::previous_word_start_or_newline(map, selection.head())
 7987                        };
 7988                        selection.set_head(cursor, SelectionGoal::None);
 7989                    }
 7990                });
 7991            });
 7992            this.insert("", window, cx);
 7993        });
 7994    }
 7995
 7996    pub fn delete_to_previous_subword_start(
 7997        &mut self,
 7998        _: &DeleteToPreviousSubwordStart,
 7999        window: &mut Window,
 8000        cx: &mut Context<Self>,
 8001    ) {
 8002        self.transact(window, cx, |this, window, cx| {
 8003            this.select_autoclose_pair(window, cx);
 8004            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8005                let line_mode = s.line_mode;
 8006                s.move_with(|map, selection| {
 8007                    if selection.is_empty() && !line_mode {
 8008                        let cursor = movement::previous_subword_start(map, selection.head());
 8009                        selection.set_head(cursor, SelectionGoal::None);
 8010                    }
 8011                });
 8012            });
 8013            this.insert("", window, cx);
 8014        });
 8015    }
 8016
 8017    pub fn move_to_next_word_end(
 8018        &mut self,
 8019        _: &MoveToNextWordEnd,
 8020        window: &mut Window,
 8021        cx: &mut Context<Self>,
 8022    ) {
 8023        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8024            s.move_cursors_with(|map, head, _| {
 8025                (movement::next_word_end(map, head), SelectionGoal::None)
 8026            });
 8027        })
 8028    }
 8029
 8030    pub fn move_to_next_subword_end(
 8031        &mut self,
 8032        _: &MoveToNextSubwordEnd,
 8033        window: &mut Window,
 8034        cx: &mut Context<Self>,
 8035    ) {
 8036        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8037            s.move_cursors_with(|map, head, _| {
 8038                (movement::next_subword_end(map, head), SelectionGoal::None)
 8039            });
 8040        })
 8041    }
 8042
 8043    pub fn select_to_next_word_end(
 8044        &mut self,
 8045        _: &SelectToNextWordEnd,
 8046        window: &mut Window,
 8047        cx: &mut Context<Self>,
 8048    ) {
 8049        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8050            s.move_heads_with(|map, head, _| {
 8051                (movement::next_word_end(map, head), SelectionGoal::None)
 8052            });
 8053        })
 8054    }
 8055
 8056    pub fn select_to_next_subword_end(
 8057        &mut self,
 8058        _: &SelectToNextSubwordEnd,
 8059        window: &mut Window,
 8060        cx: &mut Context<Self>,
 8061    ) {
 8062        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8063            s.move_heads_with(|map, head, _| {
 8064                (movement::next_subword_end(map, head), SelectionGoal::None)
 8065            });
 8066        })
 8067    }
 8068
 8069    pub fn delete_to_next_word_end(
 8070        &mut self,
 8071        action: &DeleteToNextWordEnd,
 8072        window: &mut Window,
 8073        cx: &mut Context<Self>,
 8074    ) {
 8075        self.transact(window, cx, |this, window, cx| {
 8076            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8077                let line_mode = s.line_mode;
 8078                s.move_with(|map, selection| {
 8079                    if selection.is_empty() && !line_mode {
 8080                        let cursor = if action.ignore_newlines {
 8081                            movement::next_word_end(map, selection.head())
 8082                        } else {
 8083                            movement::next_word_end_or_newline(map, selection.head())
 8084                        };
 8085                        selection.set_head(cursor, SelectionGoal::None);
 8086                    }
 8087                });
 8088            });
 8089            this.insert("", window, cx);
 8090        });
 8091    }
 8092
 8093    pub fn delete_to_next_subword_end(
 8094        &mut self,
 8095        _: &DeleteToNextSubwordEnd,
 8096        window: &mut Window,
 8097        cx: &mut Context<Self>,
 8098    ) {
 8099        self.transact(window, cx, |this, window, cx| {
 8100            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8101                s.move_with(|map, selection| {
 8102                    if selection.is_empty() {
 8103                        let cursor = movement::next_subword_end(map, selection.head());
 8104                        selection.set_head(cursor, SelectionGoal::None);
 8105                    }
 8106                });
 8107            });
 8108            this.insert("", window, cx);
 8109        });
 8110    }
 8111
 8112    pub fn move_to_beginning_of_line(
 8113        &mut self,
 8114        action: &MoveToBeginningOfLine,
 8115        window: &mut Window,
 8116        cx: &mut Context<Self>,
 8117    ) {
 8118        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8119            s.move_cursors_with(|map, head, _| {
 8120                (
 8121                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8122                    SelectionGoal::None,
 8123                )
 8124            });
 8125        })
 8126    }
 8127
 8128    pub fn select_to_beginning_of_line(
 8129        &mut self,
 8130        action: &SelectToBeginningOfLine,
 8131        window: &mut Window,
 8132        cx: &mut Context<Self>,
 8133    ) {
 8134        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8135            s.move_heads_with(|map, head, _| {
 8136                (
 8137                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8138                    SelectionGoal::None,
 8139                )
 8140            });
 8141        });
 8142    }
 8143
 8144    pub fn delete_to_beginning_of_line(
 8145        &mut self,
 8146        _: &DeleteToBeginningOfLine,
 8147        window: &mut Window,
 8148        cx: &mut Context<Self>,
 8149    ) {
 8150        self.transact(window, cx, |this, window, cx| {
 8151            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8152                s.move_with(|_, selection| {
 8153                    selection.reversed = true;
 8154                });
 8155            });
 8156
 8157            this.select_to_beginning_of_line(
 8158                &SelectToBeginningOfLine {
 8159                    stop_at_soft_wraps: false,
 8160                },
 8161                window,
 8162                cx,
 8163            );
 8164            this.backspace(&Backspace, window, cx);
 8165        });
 8166    }
 8167
 8168    pub fn move_to_end_of_line(
 8169        &mut self,
 8170        action: &MoveToEndOfLine,
 8171        window: &mut Window,
 8172        cx: &mut Context<Self>,
 8173    ) {
 8174        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8175            s.move_cursors_with(|map, head, _| {
 8176                (
 8177                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8178                    SelectionGoal::None,
 8179                )
 8180            });
 8181        })
 8182    }
 8183
 8184    pub fn select_to_end_of_line(
 8185        &mut self,
 8186        action: &SelectToEndOfLine,
 8187        window: &mut Window,
 8188        cx: &mut Context<Self>,
 8189    ) {
 8190        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8191            s.move_heads_with(|map, head, _| {
 8192                (
 8193                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8194                    SelectionGoal::None,
 8195                )
 8196            });
 8197        })
 8198    }
 8199
 8200    pub fn delete_to_end_of_line(
 8201        &mut self,
 8202        _: &DeleteToEndOfLine,
 8203        window: &mut Window,
 8204        cx: &mut Context<Self>,
 8205    ) {
 8206        self.transact(window, cx, |this, window, cx| {
 8207            this.select_to_end_of_line(
 8208                &SelectToEndOfLine {
 8209                    stop_at_soft_wraps: false,
 8210                },
 8211                window,
 8212                cx,
 8213            );
 8214            this.delete(&Delete, window, cx);
 8215        });
 8216    }
 8217
 8218    pub fn cut_to_end_of_line(
 8219        &mut self,
 8220        _: &CutToEndOfLine,
 8221        window: &mut Window,
 8222        cx: &mut Context<Self>,
 8223    ) {
 8224        self.transact(window, cx, |this, window, cx| {
 8225            this.select_to_end_of_line(
 8226                &SelectToEndOfLine {
 8227                    stop_at_soft_wraps: false,
 8228                },
 8229                window,
 8230                cx,
 8231            );
 8232            this.cut(&Cut, window, cx);
 8233        });
 8234    }
 8235
 8236    pub fn move_to_start_of_paragraph(
 8237        &mut self,
 8238        _: &MoveToStartOfParagraph,
 8239        window: &mut Window,
 8240        cx: &mut Context<Self>,
 8241    ) {
 8242        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8243            cx.propagate();
 8244            return;
 8245        }
 8246
 8247        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8248            s.move_with(|map, selection| {
 8249                selection.collapse_to(
 8250                    movement::start_of_paragraph(map, selection.head(), 1),
 8251                    SelectionGoal::None,
 8252                )
 8253            });
 8254        })
 8255    }
 8256
 8257    pub fn move_to_end_of_paragraph(
 8258        &mut self,
 8259        _: &MoveToEndOfParagraph,
 8260        window: &mut Window,
 8261        cx: &mut Context<Self>,
 8262    ) {
 8263        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8264            cx.propagate();
 8265            return;
 8266        }
 8267
 8268        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8269            s.move_with(|map, selection| {
 8270                selection.collapse_to(
 8271                    movement::end_of_paragraph(map, selection.head(), 1),
 8272                    SelectionGoal::None,
 8273                )
 8274            });
 8275        })
 8276    }
 8277
 8278    pub fn select_to_start_of_paragraph(
 8279        &mut self,
 8280        _: &SelectToStartOfParagraph,
 8281        window: &mut Window,
 8282        cx: &mut Context<Self>,
 8283    ) {
 8284        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8285            cx.propagate();
 8286            return;
 8287        }
 8288
 8289        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8290            s.move_heads_with(|map, head, _| {
 8291                (
 8292                    movement::start_of_paragraph(map, head, 1),
 8293                    SelectionGoal::None,
 8294                )
 8295            });
 8296        })
 8297    }
 8298
 8299    pub fn select_to_end_of_paragraph(
 8300        &mut self,
 8301        _: &SelectToEndOfParagraph,
 8302        window: &mut Window,
 8303        cx: &mut Context<Self>,
 8304    ) {
 8305        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8306            cx.propagate();
 8307            return;
 8308        }
 8309
 8310        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8311            s.move_heads_with(|map, head, _| {
 8312                (
 8313                    movement::end_of_paragraph(map, head, 1),
 8314                    SelectionGoal::None,
 8315                )
 8316            });
 8317        })
 8318    }
 8319
 8320    pub fn move_to_beginning(
 8321        &mut self,
 8322        _: &MoveToBeginning,
 8323        window: &mut Window,
 8324        cx: &mut Context<Self>,
 8325    ) {
 8326        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8327            cx.propagate();
 8328            return;
 8329        }
 8330
 8331        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8332            s.select_ranges(vec![0..0]);
 8333        });
 8334    }
 8335
 8336    pub fn select_to_beginning(
 8337        &mut self,
 8338        _: &SelectToBeginning,
 8339        window: &mut Window,
 8340        cx: &mut Context<Self>,
 8341    ) {
 8342        let mut selection = self.selections.last::<Point>(cx);
 8343        selection.set_head(Point::zero(), SelectionGoal::None);
 8344
 8345        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8346            s.select(vec![selection]);
 8347        });
 8348    }
 8349
 8350    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8351        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8352            cx.propagate();
 8353            return;
 8354        }
 8355
 8356        let cursor = self.buffer.read(cx).read(cx).len();
 8357        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8358            s.select_ranges(vec![cursor..cursor])
 8359        });
 8360    }
 8361
 8362    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8363        self.nav_history = nav_history;
 8364    }
 8365
 8366    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8367        self.nav_history.as_ref()
 8368    }
 8369
 8370    fn push_to_nav_history(
 8371        &mut self,
 8372        cursor_anchor: Anchor,
 8373        new_position: Option<Point>,
 8374        cx: &mut Context<Self>,
 8375    ) {
 8376        if let Some(nav_history) = self.nav_history.as_mut() {
 8377            let buffer = self.buffer.read(cx).read(cx);
 8378            let cursor_position = cursor_anchor.to_point(&buffer);
 8379            let scroll_state = self.scroll_manager.anchor();
 8380            let scroll_top_row = scroll_state.top_row(&buffer);
 8381            drop(buffer);
 8382
 8383            if let Some(new_position) = new_position {
 8384                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8385                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8386                    return;
 8387                }
 8388            }
 8389
 8390            nav_history.push(
 8391                Some(NavigationData {
 8392                    cursor_anchor,
 8393                    cursor_position,
 8394                    scroll_anchor: scroll_state,
 8395                    scroll_top_row,
 8396                }),
 8397                cx,
 8398            );
 8399        }
 8400    }
 8401
 8402    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8403        let buffer = self.buffer.read(cx).snapshot(cx);
 8404        let mut selection = self.selections.first::<usize>(cx);
 8405        selection.set_head(buffer.len(), SelectionGoal::None);
 8406        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8407            s.select(vec![selection]);
 8408        });
 8409    }
 8410
 8411    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8412        let end = self.buffer.read(cx).read(cx).len();
 8413        self.change_selections(None, window, cx, |s| {
 8414            s.select_ranges(vec![0..end]);
 8415        });
 8416    }
 8417
 8418    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8419        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8420        let mut selections = self.selections.all::<Point>(cx);
 8421        let max_point = display_map.buffer_snapshot.max_point();
 8422        for selection in &mut selections {
 8423            let rows = selection.spanned_rows(true, &display_map);
 8424            selection.start = Point::new(rows.start.0, 0);
 8425            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8426            selection.reversed = false;
 8427        }
 8428        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8429            s.select(selections);
 8430        });
 8431    }
 8432
 8433    pub fn split_selection_into_lines(
 8434        &mut self,
 8435        _: &SplitSelectionIntoLines,
 8436        window: &mut Window,
 8437        cx: &mut Context<Self>,
 8438    ) {
 8439        let mut to_unfold = Vec::new();
 8440        let mut new_selection_ranges = Vec::new();
 8441        {
 8442            let selections = self.selections.all::<Point>(cx);
 8443            let buffer = self.buffer.read(cx).read(cx);
 8444            for selection in selections {
 8445                for row in selection.start.row..selection.end.row {
 8446                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8447                    new_selection_ranges.push(cursor..cursor);
 8448                }
 8449                new_selection_ranges.push(selection.end..selection.end);
 8450                to_unfold.push(selection.start..selection.end);
 8451            }
 8452        }
 8453        self.unfold_ranges(&to_unfold, true, true, cx);
 8454        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8455            s.select_ranges(new_selection_ranges);
 8456        });
 8457    }
 8458
 8459    pub fn add_selection_above(
 8460        &mut self,
 8461        _: &AddSelectionAbove,
 8462        window: &mut Window,
 8463        cx: &mut Context<Self>,
 8464    ) {
 8465        self.add_selection(true, window, cx);
 8466    }
 8467
 8468    pub fn add_selection_below(
 8469        &mut self,
 8470        _: &AddSelectionBelow,
 8471        window: &mut Window,
 8472        cx: &mut Context<Self>,
 8473    ) {
 8474        self.add_selection(false, window, cx);
 8475    }
 8476
 8477    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8478        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8479        let mut selections = self.selections.all::<Point>(cx);
 8480        let text_layout_details = self.text_layout_details(window);
 8481        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8482            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8483            let range = oldest_selection.display_range(&display_map).sorted();
 8484
 8485            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8486            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8487            let positions = start_x.min(end_x)..start_x.max(end_x);
 8488
 8489            selections.clear();
 8490            let mut stack = Vec::new();
 8491            for row in range.start.row().0..=range.end.row().0 {
 8492                if let Some(selection) = self.selections.build_columnar_selection(
 8493                    &display_map,
 8494                    DisplayRow(row),
 8495                    &positions,
 8496                    oldest_selection.reversed,
 8497                    &text_layout_details,
 8498                ) {
 8499                    stack.push(selection.id);
 8500                    selections.push(selection);
 8501                }
 8502            }
 8503
 8504            if above {
 8505                stack.reverse();
 8506            }
 8507
 8508            AddSelectionsState { above, stack }
 8509        });
 8510
 8511        let last_added_selection = *state.stack.last().unwrap();
 8512        let mut new_selections = Vec::new();
 8513        if above == state.above {
 8514            let end_row = if above {
 8515                DisplayRow(0)
 8516            } else {
 8517                display_map.max_point().row()
 8518            };
 8519
 8520            'outer: for selection in selections {
 8521                if selection.id == last_added_selection {
 8522                    let range = selection.display_range(&display_map).sorted();
 8523                    debug_assert_eq!(range.start.row(), range.end.row());
 8524                    let mut row = range.start.row();
 8525                    let positions =
 8526                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8527                            px(start)..px(end)
 8528                        } else {
 8529                            let start_x =
 8530                                display_map.x_for_display_point(range.start, &text_layout_details);
 8531                            let end_x =
 8532                                display_map.x_for_display_point(range.end, &text_layout_details);
 8533                            start_x.min(end_x)..start_x.max(end_x)
 8534                        };
 8535
 8536                    while row != end_row {
 8537                        if above {
 8538                            row.0 -= 1;
 8539                        } else {
 8540                            row.0 += 1;
 8541                        }
 8542
 8543                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8544                            &display_map,
 8545                            row,
 8546                            &positions,
 8547                            selection.reversed,
 8548                            &text_layout_details,
 8549                        ) {
 8550                            state.stack.push(new_selection.id);
 8551                            if above {
 8552                                new_selections.push(new_selection);
 8553                                new_selections.push(selection);
 8554                            } else {
 8555                                new_selections.push(selection);
 8556                                new_selections.push(new_selection);
 8557                            }
 8558
 8559                            continue 'outer;
 8560                        }
 8561                    }
 8562                }
 8563
 8564                new_selections.push(selection);
 8565            }
 8566        } else {
 8567            new_selections = selections;
 8568            new_selections.retain(|s| s.id != last_added_selection);
 8569            state.stack.pop();
 8570        }
 8571
 8572        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8573            s.select(new_selections);
 8574        });
 8575        if state.stack.len() > 1 {
 8576            self.add_selections_state = Some(state);
 8577        }
 8578    }
 8579
 8580    pub fn select_next_match_internal(
 8581        &mut self,
 8582        display_map: &DisplaySnapshot,
 8583        replace_newest: bool,
 8584        autoscroll: Option<Autoscroll>,
 8585        window: &mut Window,
 8586        cx: &mut Context<Self>,
 8587    ) -> Result<()> {
 8588        fn select_next_match_ranges(
 8589            this: &mut Editor,
 8590            range: Range<usize>,
 8591            replace_newest: bool,
 8592            auto_scroll: Option<Autoscroll>,
 8593            window: &mut Window,
 8594            cx: &mut Context<Editor>,
 8595        ) {
 8596            this.unfold_ranges(&[range.clone()], false, true, cx);
 8597            this.change_selections(auto_scroll, window, cx, |s| {
 8598                if replace_newest {
 8599                    s.delete(s.newest_anchor().id);
 8600                }
 8601                s.insert_range(range.clone());
 8602            });
 8603        }
 8604
 8605        let buffer = &display_map.buffer_snapshot;
 8606        let mut selections = self.selections.all::<usize>(cx);
 8607        if let Some(mut select_next_state) = self.select_next_state.take() {
 8608            let query = &select_next_state.query;
 8609            if !select_next_state.done {
 8610                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8611                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8612                let mut next_selected_range = None;
 8613
 8614                let bytes_after_last_selection =
 8615                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8616                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8617                let query_matches = query
 8618                    .stream_find_iter(bytes_after_last_selection)
 8619                    .map(|result| (last_selection.end, result))
 8620                    .chain(
 8621                        query
 8622                            .stream_find_iter(bytes_before_first_selection)
 8623                            .map(|result| (0, result)),
 8624                    );
 8625
 8626                for (start_offset, query_match) in query_matches {
 8627                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8628                    let offset_range =
 8629                        start_offset + query_match.start()..start_offset + query_match.end();
 8630                    let display_range = offset_range.start.to_display_point(display_map)
 8631                        ..offset_range.end.to_display_point(display_map);
 8632
 8633                    if !select_next_state.wordwise
 8634                        || (!movement::is_inside_word(display_map, display_range.start)
 8635                            && !movement::is_inside_word(display_map, display_range.end))
 8636                    {
 8637                        // TODO: This is n^2, because we might check all the selections
 8638                        if !selections
 8639                            .iter()
 8640                            .any(|selection| selection.range().overlaps(&offset_range))
 8641                        {
 8642                            next_selected_range = Some(offset_range);
 8643                            break;
 8644                        }
 8645                    }
 8646                }
 8647
 8648                if let Some(next_selected_range) = next_selected_range {
 8649                    select_next_match_ranges(
 8650                        self,
 8651                        next_selected_range,
 8652                        replace_newest,
 8653                        autoscroll,
 8654                        window,
 8655                        cx,
 8656                    );
 8657                } else {
 8658                    select_next_state.done = true;
 8659                }
 8660            }
 8661
 8662            self.select_next_state = Some(select_next_state);
 8663        } else {
 8664            let mut only_carets = true;
 8665            let mut same_text_selected = true;
 8666            let mut selected_text = None;
 8667
 8668            let mut selections_iter = selections.iter().peekable();
 8669            while let Some(selection) = selections_iter.next() {
 8670                if selection.start != selection.end {
 8671                    only_carets = false;
 8672                }
 8673
 8674                if same_text_selected {
 8675                    if selected_text.is_none() {
 8676                        selected_text =
 8677                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8678                    }
 8679
 8680                    if let Some(next_selection) = selections_iter.peek() {
 8681                        if next_selection.range().len() == selection.range().len() {
 8682                            let next_selected_text = buffer
 8683                                .text_for_range(next_selection.range())
 8684                                .collect::<String>();
 8685                            if Some(next_selected_text) != selected_text {
 8686                                same_text_selected = false;
 8687                                selected_text = None;
 8688                            }
 8689                        } else {
 8690                            same_text_selected = false;
 8691                            selected_text = None;
 8692                        }
 8693                    }
 8694                }
 8695            }
 8696
 8697            if only_carets {
 8698                for selection in &mut selections {
 8699                    let word_range = movement::surrounding_word(
 8700                        display_map,
 8701                        selection.start.to_display_point(display_map),
 8702                    );
 8703                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8704                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8705                    selection.goal = SelectionGoal::None;
 8706                    selection.reversed = false;
 8707                    select_next_match_ranges(
 8708                        self,
 8709                        selection.start..selection.end,
 8710                        replace_newest,
 8711                        autoscroll,
 8712                        window,
 8713                        cx,
 8714                    );
 8715                }
 8716
 8717                if selections.len() == 1 {
 8718                    let selection = selections
 8719                        .last()
 8720                        .expect("ensured that there's only one selection");
 8721                    let query = buffer
 8722                        .text_for_range(selection.start..selection.end)
 8723                        .collect::<String>();
 8724                    let is_empty = query.is_empty();
 8725                    let select_state = SelectNextState {
 8726                        query: AhoCorasick::new(&[query])?,
 8727                        wordwise: true,
 8728                        done: is_empty,
 8729                    };
 8730                    self.select_next_state = Some(select_state);
 8731                } else {
 8732                    self.select_next_state = None;
 8733                }
 8734            } else if let Some(selected_text) = selected_text {
 8735                self.select_next_state = Some(SelectNextState {
 8736                    query: AhoCorasick::new(&[selected_text])?,
 8737                    wordwise: false,
 8738                    done: false,
 8739                });
 8740                self.select_next_match_internal(
 8741                    display_map,
 8742                    replace_newest,
 8743                    autoscroll,
 8744                    window,
 8745                    cx,
 8746                )?;
 8747            }
 8748        }
 8749        Ok(())
 8750    }
 8751
 8752    pub fn select_all_matches(
 8753        &mut self,
 8754        _action: &SelectAllMatches,
 8755        window: &mut Window,
 8756        cx: &mut Context<Self>,
 8757    ) -> Result<()> {
 8758        self.push_to_selection_history();
 8759        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8760
 8761        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 8762        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8763            return Ok(());
 8764        };
 8765        if select_next_state.done {
 8766            return Ok(());
 8767        }
 8768
 8769        let mut new_selections = self.selections.all::<usize>(cx);
 8770
 8771        let buffer = &display_map.buffer_snapshot;
 8772        let query_matches = select_next_state
 8773            .query
 8774            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8775
 8776        for query_match in query_matches {
 8777            let query_match = query_match.unwrap(); // can only fail due to I/O
 8778            let offset_range = query_match.start()..query_match.end();
 8779            let display_range = offset_range.start.to_display_point(&display_map)
 8780                ..offset_range.end.to_display_point(&display_map);
 8781
 8782            if !select_next_state.wordwise
 8783                || (!movement::is_inside_word(&display_map, display_range.start)
 8784                    && !movement::is_inside_word(&display_map, display_range.end))
 8785            {
 8786                self.selections.change_with(cx, |selections| {
 8787                    new_selections.push(Selection {
 8788                        id: selections.new_selection_id(),
 8789                        start: offset_range.start,
 8790                        end: offset_range.end,
 8791                        reversed: false,
 8792                        goal: SelectionGoal::None,
 8793                    });
 8794                });
 8795            }
 8796        }
 8797
 8798        new_selections.sort_by_key(|selection| selection.start);
 8799        let mut ix = 0;
 8800        while ix + 1 < new_selections.len() {
 8801            let current_selection = &new_selections[ix];
 8802            let next_selection = &new_selections[ix + 1];
 8803            if current_selection.range().overlaps(&next_selection.range()) {
 8804                if current_selection.id < next_selection.id {
 8805                    new_selections.remove(ix + 1);
 8806                } else {
 8807                    new_selections.remove(ix);
 8808                }
 8809            } else {
 8810                ix += 1;
 8811            }
 8812        }
 8813
 8814        select_next_state.done = true;
 8815        self.unfold_ranges(
 8816            &new_selections
 8817                .iter()
 8818                .map(|selection| selection.range())
 8819                .collect::<Vec<_>>(),
 8820            false,
 8821            false,
 8822            cx,
 8823        );
 8824        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 8825            selections.select(new_selections)
 8826        });
 8827
 8828        Ok(())
 8829    }
 8830
 8831    pub fn select_next(
 8832        &mut self,
 8833        action: &SelectNext,
 8834        window: &mut Window,
 8835        cx: &mut Context<Self>,
 8836    ) -> Result<()> {
 8837        self.push_to_selection_history();
 8838        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8839        self.select_next_match_internal(
 8840            &display_map,
 8841            action.replace_newest,
 8842            Some(Autoscroll::newest()),
 8843            window,
 8844            cx,
 8845        )?;
 8846        Ok(())
 8847    }
 8848
 8849    pub fn select_previous(
 8850        &mut self,
 8851        action: &SelectPrevious,
 8852        window: &mut Window,
 8853        cx: &mut Context<Self>,
 8854    ) -> Result<()> {
 8855        self.push_to_selection_history();
 8856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8857        let buffer = &display_map.buffer_snapshot;
 8858        let mut selections = self.selections.all::<usize>(cx);
 8859        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8860            let query = &select_prev_state.query;
 8861            if !select_prev_state.done {
 8862                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8863                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8864                let mut next_selected_range = None;
 8865                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8866                let bytes_before_last_selection =
 8867                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8868                let bytes_after_first_selection =
 8869                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8870                let query_matches = query
 8871                    .stream_find_iter(bytes_before_last_selection)
 8872                    .map(|result| (last_selection.start, result))
 8873                    .chain(
 8874                        query
 8875                            .stream_find_iter(bytes_after_first_selection)
 8876                            .map(|result| (buffer.len(), result)),
 8877                    );
 8878                for (end_offset, query_match) in query_matches {
 8879                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8880                    let offset_range =
 8881                        end_offset - query_match.end()..end_offset - query_match.start();
 8882                    let display_range = offset_range.start.to_display_point(&display_map)
 8883                        ..offset_range.end.to_display_point(&display_map);
 8884
 8885                    if !select_prev_state.wordwise
 8886                        || (!movement::is_inside_word(&display_map, display_range.start)
 8887                            && !movement::is_inside_word(&display_map, display_range.end))
 8888                    {
 8889                        next_selected_range = Some(offset_range);
 8890                        break;
 8891                    }
 8892                }
 8893
 8894                if let Some(next_selected_range) = next_selected_range {
 8895                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8896                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8897                        if action.replace_newest {
 8898                            s.delete(s.newest_anchor().id);
 8899                        }
 8900                        s.insert_range(next_selected_range);
 8901                    });
 8902                } else {
 8903                    select_prev_state.done = true;
 8904                }
 8905            }
 8906
 8907            self.select_prev_state = Some(select_prev_state);
 8908        } else {
 8909            let mut only_carets = true;
 8910            let mut same_text_selected = true;
 8911            let mut selected_text = None;
 8912
 8913            let mut selections_iter = selections.iter().peekable();
 8914            while let Some(selection) = selections_iter.next() {
 8915                if selection.start != selection.end {
 8916                    only_carets = false;
 8917                }
 8918
 8919                if same_text_selected {
 8920                    if selected_text.is_none() {
 8921                        selected_text =
 8922                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8923                    }
 8924
 8925                    if let Some(next_selection) = selections_iter.peek() {
 8926                        if next_selection.range().len() == selection.range().len() {
 8927                            let next_selected_text = buffer
 8928                                .text_for_range(next_selection.range())
 8929                                .collect::<String>();
 8930                            if Some(next_selected_text) != selected_text {
 8931                                same_text_selected = false;
 8932                                selected_text = None;
 8933                            }
 8934                        } else {
 8935                            same_text_selected = false;
 8936                            selected_text = None;
 8937                        }
 8938                    }
 8939                }
 8940            }
 8941
 8942            if only_carets {
 8943                for selection in &mut selections {
 8944                    let word_range = movement::surrounding_word(
 8945                        &display_map,
 8946                        selection.start.to_display_point(&display_map),
 8947                    );
 8948                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8949                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8950                    selection.goal = SelectionGoal::None;
 8951                    selection.reversed = false;
 8952                }
 8953                if selections.len() == 1 {
 8954                    let selection = selections
 8955                        .last()
 8956                        .expect("ensured that there's only one selection");
 8957                    let query = buffer
 8958                        .text_for_range(selection.start..selection.end)
 8959                        .collect::<String>();
 8960                    let is_empty = query.is_empty();
 8961                    let select_state = SelectNextState {
 8962                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8963                        wordwise: true,
 8964                        done: is_empty,
 8965                    };
 8966                    self.select_prev_state = Some(select_state);
 8967                } else {
 8968                    self.select_prev_state = None;
 8969                }
 8970
 8971                self.unfold_ranges(
 8972                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8973                    false,
 8974                    true,
 8975                    cx,
 8976                );
 8977                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8978                    s.select(selections);
 8979                });
 8980            } else if let Some(selected_text) = selected_text {
 8981                self.select_prev_state = Some(SelectNextState {
 8982                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8983                    wordwise: false,
 8984                    done: false,
 8985                });
 8986                self.select_previous(action, window, cx)?;
 8987            }
 8988        }
 8989        Ok(())
 8990    }
 8991
 8992    pub fn toggle_comments(
 8993        &mut self,
 8994        action: &ToggleComments,
 8995        window: &mut Window,
 8996        cx: &mut Context<Self>,
 8997    ) {
 8998        if self.read_only(cx) {
 8999            return;
 9000        }
 9001        let text_layout_details = &self.text_layout_details(window);
 9002        self.transact(window, cx, |this, window, cx| {
 9003            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9004            let mut edits = Vec::new();
 9005            let mut selection_edit_ranges = Vec::new();
 9006            let mut last_toggled_row = None;
 9007            let snapshot = this.buffer.read(cx).read(cx);
 9008            let empty_str: Arc<str> = Arc::default();
 9009            let mut suffixes_inserted = Vec::new();
 9010            let ignore_indent = action.ignore_indent;
 9011
 9012            fn comment_prefix_range(
 9013                snapshot: &MultiBufferSnapshot,
 9014                row: MultiBufferRow,
 9015                comment_prefix: &str,
 9016                comment_prefix_whitespace: &str,
 9017                ignore_indent: bool,
 9018            ) -> Range<Point> {
 9019                let indent_size = if ignore_indent {
 9020                    0
 9021                } else {
 9022                    snapshot.indent_size_for_line(row).len
 9023                };
 9024
 9025                let start = Point::new(row.0, indent_size);
 9026
 9027                let mut line_bytes = snapshot
 9028                    .bytes_in_range(start..snapshot.max_point())
 9029                    .flatten()
 9030                    .copied();
 9031
 9032                // If this line currently begins with the line comment prefix, then record
 9033                // the range containing the prefix.
 9034                if line_bytes
 9035                    .by_ref()
 9036                    .take(comment_prefix.len())
 9037                    .eq(comment_prefix.bytes())
 9038                {
 9039                    // Include any whitespace that matches the comment prefix.
 9040                    let matching_whitespace_len = line_bytes
 9041                        .zip(comment_prefix_whitespace.bytes())
 9042                        .take_while(|(a, b)| a == b)
 9043                        .count() as u32;
 9044                    let end = Point::new(
 9045                        start.row,
 9046                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9047                    );
 9048                    start..end
 9049                } else {
 9050                    start..start
 9051                }
 9052            }
 9053
 9054            fn comment_suffix_range(
 9055                snapshot: &MultiBufferSnapshot,
 9056                row: MultiBufferRow,
 9057                comment_suffix: &str,
 9058                comment_suffix_has_leading_space: bool,
 9059            ) -> Range<Point> {
 9060                let end = Point::new(row.0, snapshot.line_len(row));
 9061                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9062
 9063                let mut line_end_bytes = snapshot
 9064                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9065                    .flatten()
 9066                    .copied();
 9067
 9068                let leading_space_len = if suffix_start_column > 0
 9069                    && line_end_bytes.next() == Some(b' ')
 9070                    && comment_suffix_has_leading_space
 9071                {
 9072                    1
 9073                } else {
 9074                    0
 9075                };
 9076
 9077                // If this line currently begins with the line comment prefix, then record
 9078                // the range containing the prefix.
 9079                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9080                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9081                    start..end
 9082                } else {
 9083                    end..end
 9084                }
 9085            }
 9086
 9087            // TODO: Handle selections that cross excerpts
 9088            for selection in &mut selections {
 9089                let start_column = snapshot
 9090                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9091                    .len;
 9092                let language = if let Some(language) =
 9093                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9094                {
 9095                    language
 9096                } else {
 9097                    continue;
 9098                };
 9099
 9100                selection_edit_ranges.clear();
 9101
 9102                // If multiple selections contain a given row, avoid processing that
 9103                // row more than once.
 9104                let mut start_row = MultiBufferRow(selection.start.row);
 9105                if last_toggled_row == Some(start_row) {
 9106                    start_row = start_row.next_row();
 9107                }
 9108                let end_row =
 9109                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9110                        MultiBufferRow(selection.end.row - 1)
 9111                    } else {
 9112                        MultiBufferRow(selection.end.row)
 9113                    };
 9114                last_toggled_row = Some(end_row);
 9115
 9116                if start_row > end_row {
 9117                    continue;
 9118                }
 9119
 9120                // If the language has line comments, toggle those.
 9121                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9122
 9123                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9124                if ignore_indent {
 9125                    full_comment_prefixes = full_comment_prefixes
 9126                        .into_iter()
 9127                        .map(|s| Arc::from(s.trim_end()))
 9128                        .collect();
 9129                }
 9130
 9131                if !full_comment_prefixes.is_empty() {
 9132                    let first_prefix = full_comment_prefixes
 9133                        .first()
 9134                        .expect("prefixes is non-empty");
 9135                    let prefix_trimmed_lengths = full_comment_prefixes
 9136                        .iter()
 9137                        .map(|p| p.trim_end_matches(' ').len())
 9138                        .collect::<SmallVec<[usize; 4]>>();
 9139
 9140                    let mut all_selection_lines_are_comments = true;
 9141
 9142                    for row in start_row.0..=end_row.0 {
 9143                        let row = MultiBufferRow(row);
 9144                        if start_row < end_row && snapshot.is_line_blank(row) {
 9145                            continue;
 9146                        }
 9147
 9148                        let prefix_range = full_comment_prefixes
 9149                            .iter()
 9150                            .zip(prefix_trimmed_lengths.iter().copied())
 9151                            .map(|(prefix, trimmed_prefix_len)| {
 9152                                comment_prefix_range(
 9153                                    snapshot.deref(),
 9154                                    row,
 9155                                    &prefix[..trimmed_prefix_len],
 9156                                    &prefix[trimmed_prefix_len..],
 9157                                    ignore_indent,
 9158                                )
 9159                            })
 9160                            .max_by_key(|range| range.end.column - range.start.column)
 9161                            .expect("prefixes is non-empty");
 9162
 9163                        if prefix_range.is_empty() {
 9164                            all_selection_lines_are_comments = false;
 9165                        }
 9166
 9167                        selection_edit_ranges.push(prefix_range);
 9168                    }
 9169
 9170                    if all_selection_lines_are_comments {
 9171                        edits.extend(
 9172                            selection_edit_ranges
 9173                                .iter()
 9174                                .cloned()
 9175                                .map(|range| (range, empty_str.clone())),
 9176                        );
 9177                    } else {
 9178                        let min_column = selection_edit_ranges
 9179                            .iter()
 9180                            .map(|range| range.start.column)
 9181                            .min()
 9182                            .unwrap_or(0);
 9183                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9184                            let position = Point::new(range.start.row, min_column);
 9185                            (position..position, first_prefix.clone())
 9186                        }));
 9187                    }
 9188                } else if let Some((full_comment_prefix, comment_suffix)) =
 9189                    language.block_comment_delimiters()
 9190                {
 9191                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9192                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9193                    let prefix_range = comment_prefix_range(
 9194                        snapshot.deref(),
 9195                        start_row,
 9196                        comment_prefix,
 9197                        comment_prefix_whitespace,
 9198                        ignore_indent,
 9199                    );
 9200                    let suffix_range = comment_suffix_range(
 9201                        snapshot.deref(),
 9202                        end_row,
 9203                        comment_suffix.trim_start_matches(' '),
 9204                        comment_suffix.starts_with(' '),
 9205                    );
 9206
 9207                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9208                        edits.push((
 9209                            prefix_range.start..prefix_range.start,
 9210                            full_comment_prefix.clone(),
 9211                        ));
 9212                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9213                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9214                    } else {
 9215                        edits.push((prefix_range, empty_str.clone()));
 9216                        edits.push((suffix_range, empty_str.clone()));
 9217                    }
 9218                } else {
 9219                    continue;
 9220                }
 9221            }
 9222
 9223            drop(snapshot);
 9224            this.buffer.update(cx, |buffer, cx| {
 9225                buffer.edit(edits, None, cx);
 9226            });
 9227
 9228            // Adjust selections so that they end before any comment suffixes that
 9229            // were inserted.
 9230            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9231            let mut selections = this.selections.all::<Point>(cx);
 9232            let snapshot = this.buffer.read(cx).read(cx);
 9233            for selection in &mut selections {
 9234                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9235                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9236                        Ordering::Less => {
 9237                            suffixes_inserted.next();
 9238                            continue;
 9239                        }
 9240                        Ordering::Greater => break,
 9241                        Ordering::Equal => {
 9242                            if selection.end.column == snapshot.line_len(row) {
 9243                                if selection.is_empty() {
 9244                                    selection.start.column -= suffix_len as u32;
 9245                                }
 9246                                selection.end.column -= suffix_len as u32;
 9247                            }
 9248                            break;
 9249                        }
 9250                    }
 9251                }
 9252            }
 9253
 9254            drop(snapshot);
 9255            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9256                s.select(selections)
 9257            });
 9258
 9259            let selections = this.selections.all::<Point>(cx);
 9260            let selections_on_single_row = selections.windows(2).all(|selections| {
 9261                selections[0].start.row == selections[1].start.row
 9262                    && selections[0].end.row == selections[1].end.row
 9263                    && selections[0].start.row == selections[0].end.row
 9264            });
 9265            let selections_selecting = selections
 9266                .iter()
 9267                .any(|selection| selection.start != selection.end);
 9268            let advance_downwards = action.advance_downwards
 9269                && selections_on_single_row
 9270                && !selections_selecting
 9271                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9272
 9273            if advance_downwards {
 9274                let snapshot = this.buffer.read(cx).snapshot(cx);
 9275
 9276                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9277                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9278                        let mut point = display_point.to_point(display_snapshot);
 9279                        point.row += 1;
 9280                        point = snapshot.clip_point(point, Bias::Left);
 9281                        let display_point = point.to_display_point(display_snapshot);
 9282                        let goal = SelectionGoal::HorizontalPosition(
 9283                            display_snapshot
 9284                                .x_for_display_point(display_point, text_layout_details)
 9285                                .into(),
 9286                        );
 9287                        (display_point, goal)
 9288                    })
 9289                });
 9290            }
 9291        });
 9292    }
 9293
 9294    pub fn select_enclosing_symbol(
 9295        &mut self,
 9296        _: &SelectEnclosingSymbol,
 9297        window: &mut Window,
 9298        cx: &mut Context<Self>,
 9299    ) {
 9300        let buffer = self.buffer.read(cx).snapshot(cx);
 9301        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9302
 9303        fn update_selection(
 9304            selection: &Selection<usize>,
 9305            buffer_snap: &MultiBufferSnapshot,
 9306        ) -> Option<Selection<usize>> {
 9307            let cursor = selection.head();
 9308            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9309            for symbol in symbols.iter().rev() {
 9310                let start = symbol.range.start.to_offset(buffer_snap);
 9311                let end = symbol.range.end.to_offset(buffer_snap);
 9312                let new_range = start..end;
 9313                if start < selection.start || end > selection.end {
 9314                    return Some(Selection {
 9315                        id: selection.id,
 9316                        start: new_range.start,
 9317                        end: new_range.end,
 9318                        goal: SelectionGoal::None,
 9319                        reversed: selection.reversed,
 9320                    });
 9321                }
 9322            }
 9323            None
 9324        }
 9325
 9326        let mut selected_larger_symbol = false;
 9327        let new_selections = old_selections
 9328            .iter()
 9329            .map(|selection| match update_selection(selection, &buffer) {
 9330                Some(new_selection) => {
 9331                    if new_selection.range() != selection.range() {
 9332                        selected_larger_symbol = true;
 9333                    }
 9334                    new_selection
 9335                }
 9336                None => selection.clone(),
 9337            })
 9338            .collect::<Vec<_>>();
 9339
 9340        if selected_larger_symbol {
 9341            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9342                s.select(new_selections);
 9343            });
 9344        }
 9345    }
 9346
 9347    pub fn select_larger_syntax_node(
 9348        &mut self,
 9349        _: &SelectLargerSyntaxNode,
 9350        window: &mut Window,
 9351        cx: &mut Context<Self>,
 9352    ) {
 9353        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9354        let buffer = self.buffer.read(cx).snapshot(cx);
 9355        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9356
 9357        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9358        let mut selected_larger_node = false;
 9359        let new_selections = old_selections
 9360            .iter()
 9361            .map(|selection| {
 9362                let old_range = selection.start..selection.end;
 9363                let mut new_range = old_range.clone();
 9364                let mut new_node = None;
 9365                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9366                {
 9367                    new_node = Some(node);
 9368                    new_range = containing_range;
 9369                    if !display_map.intersects_fold(new_range.start)
 9370                        && !display_map.intersects_fold(new_range.end)
 9371                    {
 9372                        break;
 9373                    }
 9374                }
 9375
 9376                if let Some(node) = new_node {
 9377                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9378                    // nodes. Parent and grandparent are also logged because this operation will not
 9379                    // visit nodes that have the same range as their parent.
 9380                    log::info!("Node: {node:?}");
 9381                    let parent = node.parent();
 9382                    log::info!("Parent: {parent:?}");
 9383                    let grandparent = parent.and_then(|x| x.parent());
 9384                    log::info!("Grandparent: {grandparent:?}");
 9385                }
 9386
 9387                selected_larger_node |= new_range != old_range;
 9388                Selection {
 9389                    id: selection.id,
 9390                    start: new_range.start,
 9391                    end: new_range.end,
 9392                    goal: SelectionGoal::None,
 9393                    reversed: selection.reversed,
 9394                }
 9395            })
 9396            .collect::<Vec<_>>();
 9397
 9398        if selected_larger_node {
 9399            stack.push(old_selections);
 9400            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9401                s.select(new_selections);
 9402            });
 9403        }
 9404        self.select_larger_syntax_node_stack = stack;
 9405    }
 9406
 9407    pub fn select_smaller_syntax_node(
 9408        &mut self,
 9409        _: &SelectSmallerSyntaxNode,
 9410        window: &mut Window,
 9411        cx: &mut Context<Self>,
 9412    ) {
 9413        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9414        if let Some(selections) = stack.pop() {
 9415            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9416                s.select(selections.to_vec());
 9417            });
 9418        }
 9419        self.select_larger_syntax_node_stack = stack;
 9420    }
 9421
 9422    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9423        if !EditorSettings::get_global(cx).gutter.runnables {
 9424            self.clear_tasks();
 9425            return Task::ready(());
 9426        }
 9427        let project = self.project.as_ref().map(Entity::downgrade);
 9428        cx.spawn_in(window, |this, mut cx| async move {
 9429            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9430            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9431                return;
 9432            };
 9433            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9434                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9435            }) else {
 9436                return;
 9437            };
 9438
 9439            let hide_runnables = project
 9440                .update(&mut cx, |project, cx| {
 9441                    // Do not display any test indicators in non-dev server remote projects.
 9442                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9443                })
 9444                .unwrap_or(true);
 9445            if hide_runnables {
 9446                return;
 9447            }
 9448            let new_rows =
 9449                cx.background_executor()
 9450                    .spawn({
 9451                        let snapshot = display_snapshot.clone();
 9452                        async move {
 9453                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9454                        }
 9455                    })
 9456                    .await;
 9457
 9458            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9459            this.update(&mut cx, |this, _| {
 9460                this.clear_tasks();
 9461                for (key, value) in rows {
 9462                    this.insert_tasks(key, value);
 9463                }
 9464            })
 9465            .ok();
 9466        })
 9467    }
 9468    fn fetch_runnable_ranges(
 9469        snapshot: &DisplaySnapshot,
 9470        range: Range<Anchor>,
 9471    ) -> Vec<language::RunnableRange> {
 9472        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9473    }
 9474
 9475    fn runnable_rows(
 9476        project: Entity<Project>,
 9477        snapshot: DisplaySnapshot,
 9478        runnable_ranges: Vec<RunnableRange>,
 9479        mut cx: AsyncWindowContext,
 9480    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9481        runnable_ranges
 9482            .into_iter()
 9483            .filter_map(|mut runnable| {
 9484                let tasks = cx
 9485                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9486                    .ok()?;
 9487                if tasks.is_empty() {
 9488                    return None;
 9489                }
 9490
 9491                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9492
 9493                let row = snapshot
 9494                    .buffer_snapshot
 9495                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9496                    .1
 9497                    .start
 9498                    .row;
 9499
 9500                let context_range =
 9501                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9502                Some((
 9503                    (runnable.buffer_id, row),
 9504                    RunnableTasks {
 9505                        templates: tasks,
 9506                        offset: MultiBufferOffset(runnable.run_range.start),
 9507                        context_range,
 9508                        column: point.column,
 9509                        extra_variables: runnable.extra_captures,
 9510                    },
 9511                ))
 9512            })
 9513            .collect()
 9514    }
 9515
 9516    fn templates_with_tags(
 9517        project: &Entity<Project>,
 9518        runnable: &mut Runnable,
 9519        cx: &mut App,
 9520    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9521        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9522            let (worktree_id, file) = project
 9523                .buffer_for_id(runnable.buffer, cx)
 9524                .and_then(|buffer| buffer.read(cx).file())
 9525                .map(|file| (file.worktree_id(cx), file.clone()))
 9526                .unzip();
 9527
 9528            (
 9529                project.task_store().read(cx).task_inventory().cloned(),
 9530                worktree_id,
 9531                file,
 9532            )
 9533        });
 9534
 9535        let tags = mem::take(&mut runnable.tags);
 9536        let mut tags: Vec<_> = tags
 9537            .into_iter()
 9538            .flat_map(|tag| {
 9539                let tag = tag.0.clone();
 9540                inventory
 9541                    .as_ref()
 9542                    .into_iter()
 9543                    .flat_map(|inventory| {
 9544                        inventory.read(cx).list_tasks(
 9545                            file.clone(),
 9546                            Some(runnable.language.clone()),
 9547                            worktree_id,
 9548                            cx,
 9549                        )
 9550                    })
 9551                    .filter(move |(_, template)| {
 9552                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9553                    })
 9554            })
 9555            .sorted_by_key(|(kind, _)| kind.to_owned())
 9556            .collect();
 9557        if let Some((leading_tag_source, _)) = tags.first() {
 9558            // Strongest source wins; if we have worktree tag binding, prefer that to
 9559            // global and language bindings;
 9560            // if we have a global binding, prefer that to language binding.
 9561            let first_mismatch = tags
 9562                .iter()
 9563                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9564            if let Some(index) = first_mismatch {
 9565                tags.truncate(index);
 9566            }
 9567        }
 9568
 9569        tags
 9570    }
 9571
 9572    pub fn move_to_enclosing_bracket(
 9573        &mut self,
 9574        _: &MoveToEnclosingBracket,
 9575        window: &mut Window,
 9576        cx: &mut Context<Self>,
 9577    ) {
 9578        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9579            s.move_offsets_with(|snapshot, selection| {
 9580                let Some(enclosing_bracket_ranges) =
 9581                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9582                else {
 9583                    return;
 9584                };
 9585
 9586                let mut best_length = usize::MAX;
 9587                let mut best_inside = false;
 9588                let mut best_in_bracket_range = false;
 9589                let mut best_destination = None;
 9590                for (open, close) in enclosing_bracket_ranges {
 9591                    let close = close.to_inclusive();
 9592                    let length = close.end() - open.start;
 9593                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9594                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9595                        || close.contains(&selection.head());
 9596
 9597                    // If best is next to a bracket and current isn't, skip
 9598                    if !in_bracket_range && best_in_bracket_range {
 9599                        continue;
 9600                    }
 9601
 9602                    // Prefer smaller lengths unless best is inside and current isn't
 9603                    if length > best_length && (best_inside || !inside) {
 9604                        continue;
 9605                    }
 9606
 9607                    best_length = length;
 9608                    best_inside = inside;
 9609                    best_in_bracket_range = in_bracket_range;
 9610                    best_destination = Some(
 9611                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9612                            if inside {
 9613                                open.end
 9614                            } else {
 9615                                open.start
 9616                            }
 9617                        } else if inside {
 9618                            *close.start()
 9619                        } else {
 9620                            *close.end()
 9621                        },
 9622                    );
 9623                }
 9624
 9625                if let Some(destination) = best_destination {
 9626                    selection.collapse_to(destination, SelectionGoal::None);
 9627                }
 9628            })
 9629        });
 9630    }
 9631
 9632    pub fn undo_selection(
 9633        &mut self,
 9634        _: &UndoSelection,
 9635        window: &mut Window,
 9636        cx: &mut Context<Self>,
 9637    ) {
 9638        self.end_selection(window, cx);
 9639        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9640        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9641            self.change_selections(None, window, cx, |s| {
 9642                s.select_anchors(entry.selections.to_vec())
 9643            });
 9644            self.select_next_state = entry.select_next_state;
 9645            self.select_prev_state = entry.select_prev_state;
 9646            self.add_selections_state = entry.add_selections_state;
 9647            self.request_autoscroll(Autoscroll::newest(), cx);
 9648        }
 9649        self.selection_history.mode = SelectionHistoryMode::Normal;
 9650    }
 9651
 9652    pub fn redo_selection(
 9653        &mut self,
 9654        _: &RedoSelection,
 9655        window: &mut Window,
 9656        cx: &mut Context<Self>,
 9657    ) {
 9658        self.end_selection(window, cx);
 9659        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9660        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9661            self.change_selections(None, window, cx, |s| {
 9662                s.select_anchors(entry.selections.to_vec())
 9663            });
 9664            self.select_next_state = entry.select_next_state;
 9665            self.select_prev_state = entry.select_prev_state;
 9666            self.add_selections_state = entry.add_selections_state;
 9667            self.request_autoscroll(Autoscroll::newest(), cx);
 9668        }
 9669        self.selection_history.mode = SelectionHistoryMode::Normal;
 9670    }
 9671
 9672    pub fn expand_excerpts(
 9673        &mut self,
 9674        action: &ExpandExcerpts,
 9675        _: &mut Window,
 9676        cx: &mut Context<Self>,
 9677    ) {
 9678        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9679    }
 9680
 9681    pub fn expand_excerpts_down(
 9682        &mut self,
 9683        action: &ExpandExcerptsDown,
 9684        _: &mut Window,
 9685        cx: &mut Context<Self>,
 9686    ) {
 9687        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9688    }
 9689
 9690    pub fn expand_excerpts_up(
 9691        &mut self,
 9692        action: &ExpandExcerptsUp,
 9693        _: &mut Window,
 9694        cx: &mut Context<Self>,
 9695    ) {
 9696        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9697    }
 9698
 9699    pub fn expand_excerpts_for_direction(
 9700        &mut self,
 9701        lines: u32,
 9702        direction: ExpandExcerptDirection,
 9703
 9704        cx: &mut Context<Self>,
 9705    ) {
 9706        let selections = self.selections.disjoint_anchors();
 9707
 9708        let lines = if lines == 0 {
 9709            EditorSettings::get_global(cx).expand_excerpt_lines
 9710        } else {
 9711            lines
 9712        };
 9713
 9714        self.buffer.update(cx, |buffer, cx| {
 9715            let snapshot = buffer.snapshot(cx);
 9716            let mut excerpt_ids = selections
 9717                .iter()
 9718                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
 9719                .collect::<Vec<_>>();
 9720            excerpt_ids.sort();
 9721            excerpt_ids.dedup();
 9722            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9723        })
 9724    }
 9725
 9726    pub fn expand_excerpt(
 9727        &mut self,
 9728        excerpt: ExcerptId,
 9729        direction: ExpandExcerptDirection,
 9730        cx: &mut Context<Self>,
 9731    ) {
 9732        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9733        self.buffer.update(cx, |buffer, cx| {
 9734            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9735        })
 9736    }
 9737
 9738    pub fn go_to_singleton_buffer_point(
 9739        &mut self,
 9740        point: Point,
 9741        window: &mut Window,
 9742        cx: &mut Context<Self>,
 9743    ) {
 9744        self.go_to_singleton_buffer_range(point..point, window, cx);
 9745    }
 9746
 9747    pub fn go_to_singleton_buffer_range(
 9748        &mut self,
 9749        range: Range<Point>,
 9750        window: &mut Window,
 9751        cx: &mut Context<Self>,
 9752    ) {
 9753        let multibuffer = self.buffer().read(cx);
 9754        let Some(buffer) = multibuffer.as_singleton() else {
 9755            return;
 9756        };
 9757        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
 9758            return;
 9759        };
 9760        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
 9761            return;
 9762        };
 9763        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
 9764            s.select_anchor_ranges([start..end])
 9765        });
 9766    }
 9767
 9768    fn go_to_diagnostic(
 9769        &mut self,
 9770        _: &GoToDiagnostic,
 9771        window: &mut Window,
 9772        cx: &mut Context<Self>,
 9773    ) {
 9774        self.go_to_diagnostic_impl(Direction::Next, window, cx)
 9775    }
 9776
 9777    fn go_to_prev_diagnostic(
 9778        &mut self,
 9779        _: &GoToPrevDiagnostic,
 9780        window: &mut Window,
 9781        cx: &mut Context<Self>,
 9782    ) {
 9783        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
 9784    }
 9785
 9786    pub fn go_to_diagnostic_impl(
 9787        &mut self,
 9788        direction: Direction,
 9789        window: &mut Window,
 9790        cx: &mut Context<Self>,
 9791    ) {
 9792        let buffer = self.buffer.read(cx).snapshot(cx);
 9793        let selection = self.selections.newest::<usize>(cx);
 9794
 9795        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9796        if direction == Direction::Next {
 9797            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9798                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
 9799                    return;
 9800                };
 9801                self.activate_diagnostics(
 9802                    buffer_id,
 9803                    popover.local_diagnostic.diagnostic.group_id,
 9804                    window,
 9805                    cx,
 9806                );
 9807                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9808                    let primary_range_start = active_diagnostics.primary_range.start;
 9809                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9810                        let mut new_selection = s.newest_anchor().clone();
 9811                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9812                        s.select_anchors(vec![new_selection.clone()]);
 9813                    });
 9814                    self.refresh_inline_completion(false, true, window, cx);
 9815                }
 9816                return;
 9817            }
 9818        }
 9819
 9820        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9821            active_diagnostics
 9822                .primary_range
 9823                .to_offset(&buffer)
 9824                .to_inclusive()
 9825        });
 9826        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9827            if active_primary_range.contains(&selection.head()) {
 9828                *active_primary_range.start()
 9829            } else {
 9830                selection.head()
 9831            }
 9832        } else {
 9833            selection.head()
 9834        };
 9835        let snapshot = self.snapshot(window, cx);
 9836        loop {
 9837            let mut diagnostics;
 9838            if direction == Direction::Prev {
 9839                diagnostics = buffer
 9840                    .diagnostics_in_range::<_, usize>(0..search_start)
 9841                    .collect::<Vec<_>>();
 9842                diagnostics.reverse();
 9843            } else {
 9844                diagnostics = buffer
 9845                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
 9846                    .collect::<Vec<_>>();
 9847            };
 9848            let group = diagnostics
 9849                .into_iter()
 9850                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
 9851                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9852                // be sorted in a stable way
 9853                // skip until we are at current active diagnostic, if it exists
 9854                .skip_while(|entry| {
 9855                    let is_in_range = match direction {
 9856                        Direction::Prev => entry.range.end > search_start,
 9857                        Direction::Next => entry.range.start < search_start,
 9858                    };
 9859                    is_in_range
 9860                        && self
 9861                            .active_diagnostics
 9862                            .as_ref()
 9863                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9864                })
 9865                .find_map(|entry| {
 9866                    if entry.diagnostic.is_primary
 9867                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9868                        && entry.range.start != entry.range.end
 9869                        // if we match with the active diagnostic, skip it
 9870                        && Some(entry.diagnostic.group_id)
 9871                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9872                    {
 9873                        Some((entry.range, entry.diagnostic.group_id))
 9874                    } else {
 9875                        None
 9876                    }
 9877                });
 9878
 9879            if let Some((primary_range, group_id)) = group {
 9880                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
 9881                    return;
 9882                };
 9883                self.activate_diagnostics(buffer_id, group_id, window, cx);
 9884                if self.active_diagnostics.is_some() {
 9885                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9886                        s.select(vec![Selection {
 9887                            id: selection.id,
 9888                            start: primary_range.start,
 9889                            end: primary_range.start,
 9890                            reversed: false,
 9891                            goal: SelectionGoal::None,
 9892                        }]);
 9893                    });
 9894                    self.refresh_inline_completion(false, true, window, cx);
 9895                }
 9896                break;
 9897            } else {
 9898                // Cycle around to the start of the buffer, potentially moving back to the start of
 9899                // the currently active diagnostic.
 9900                active_primary_range.take();
 9901                if direction == Direction::Prev {
 9902                    if search_start == buffer.len() {
 9903                        break;
 9904                    } else {
 9905                        search_start = buffer.len();
 9906                    }
 9907                } else if search_start == 0 {
 9908                    break;
 9909                } else {
 9910                    search_start = 0;
 9911                }
 9912            }
 9913        }
 9914    }
 9915
 9916    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
 9917        let snapshot = self.snapshot(window, cx);
 9918        let selection = self.selections.newest::<Point>(cx);
 9919        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
 9920    }
 9921
 9922    fn go_to_hunk_after_position(
 9923        &mut self,
 9924        snapshot: &EditorSnapshot,
 9925        position: Point,
 9926        window: &mut Window,
 9927        cx: &mut Context<Editor>,
 9928    ) -> Option<MultiBufferDiffHunk> {
 9929        let mut hunk = snapshot
 9930            .buffer_snapshot
 9931            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
 9932            .find(|hunk| hunk.row_range.start.0 > position.row);
 9933        if hunk.is_none() {
 9934            hunk = snapshot
 9935                .buffer_snapshot
 9936                .diff_hunks_in_range(Point::zero()..position)
 9937                .find(|hunk| hunk.row_range.end.0 < position.row)
 9938        }
 9939        if let Some(hunk) = &hunk {
 9940            let destination = Point::new(hunk.row_range.start.0, 0);
 9941            self.unfold_ranges(&[destination..destination], false, false, cx);
 9942            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9943                s.select_ranges(vec![destination..destination]);
 9944            });
 9945        }
 9946
 9947        hunk
 9948    }
 9949
 9950    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
 9951        let snapshot = self.snapshot(window, cx);
 9952        let selection = self.selections.newest::<Point>(cx);
 9953        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
 9954    }
 9955
 9956    fn go_to_hunk_before_position(
 9957        &mut self,
 9958        snapshot: &EditorSnapshot,
 9959        position: Point,
 9960        window: &mut Window,
 9961        cx: &mut Context<Editor>,
 9962    ) -> Option<MultiBufferDiffHunk> {
 9963        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
 9964        if hunk.is_none() {
 9965            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
 9966        }
 9967        if let Some(hunk) = &hunk {
 9968            let destination = Point::new(hunk.row_range.start.0, 0);
 9969            self.unfold_ranges(&[destination..destination], false, false, cx);
 9970            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9971                s.select_ranges(vec![destination..destination]);
 9972            });
 9973        }
 9974
 9975        hunk
 9976    }
 9977
 9978    pub fn go_to_definition(
 9979        &mut self,
 9980        _: &GoToDefinition,
 9981        window: &mut Window,
 9982        cx: &mut Context<Self>,
 9983    ) -> Task<Result<Navigated>> {
 9984        let definition =
 9985            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
 9986        cx.spawn_in(window, |editor, mut cx| async move {
 9987            if definition.await? == Navigated::Yes {
 9988                return Ok(Navigated::Yes);
 9989            }
 9990            match editor.update_in(&mut cx, |editor, window, cx| {
 9991                editor.find_all_references(&FindAllReferences, window, cx)
 9992            })? {
 9993                Some(references) => references.await,
 9994                None => Ok(Navigated::No),
 9995            }
 9996        })
 9997    }
 9998
 9999    pub fn go_to_declaration(
10000        &mut self,
10001        _: &GoToDeclaration,
10002        window: &mut Window,
10003        cx: &mut Context<Self>,
10004    ) -> Task<Result<Navigated>> {
10005        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10006    }
10007
10008    pub fn go_to_declaration_split(
10009        &mut self,
10010        _: &GoToDeclaration,
10011        window: &mut Window,
10012        cx: &mut Context<Self>,
10013    ) -> Task<Result<Navigated>> {
10014        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10015    }
10016
10017    pub fn go_to_implementation(
10018        &mut self,
10019        _: &GoToImplementation,
10020        window: &mut Window,
10021        cx: &mut Context<Self>,
10022    ) -> Task<Result<Navigated>> {
10023        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10024    }
10025
10026    pub fn go_to_implementation_split(
10027        &mut self,
10028        _: &GoToImplementationSplit,
10029        window: &mut Window,
10030        cx: &mut Context<Self>,
10031    ) -> Task<Result<Navigated>> {
10032        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10033    }
10034
10035    pub fn go_to_type_definition(
10036        &mut self,
10037        _: &GoToTypeDefinition,
10038        window: &mut Window,
10039        cx: &mut Context<Self>,
10040    ) -> Task<Result<Navigated>> {
10041        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10042    }
10043
10044    pub fn go_to_definition_split(
10045        &mut self,
10046        _: &GoToDefinitionSplit,
10047        window: &mut Window,
10048        cx: &mut Context<Self>,
10049    ) -> Task<Result<Navigated>> {
10050        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10051    }
10052
10053    pub fn go_to_type_definition_split(
10054        &mut self,
10055        _: &GoToTypeDefinitionSplit,
10056        window: &mut Window,
10057        cx: &mut Context<Self>,
10058    ) -> Task<Result<Navigated>> {
10059        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10060    }
10061
10062    fn go_to_definition_of_kind(
10063        &mut self,
10064        kind: GotoDefinitionKind,
10065        split: bool,
10066        window: &mut Window,
10067        cx: &mut Context<Self>,
10068    ) -> Task<Result<Navigated>> {
10069        let Some(provider) = self.semantics_provider.clone() else {
10070            return Task::ready(Ok(Navigated::No));
10071        };
10072        let head = self.selections.newest::<usize>(cx).head();
10073        let buffer = self.buffer.read(cx);
10074        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10075            text_anchor
10076        } else {
10077            return Task::ready(Ok(Navigated::No));
10078        };
10079
10080        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10081            return Task::ready(Ok(Navigated::No));
10082        };
10083
10084        cx.spawn_in(window, |editor, mut cx| async move {
10085            let definitions = definitions.await?;
10086            let navigated = editor
10087                .update_in(&mut cx, |editor, window, cx| {
10088                    editor.navigate_to_hover_links(
10089                        Some(kind),
10090                        definitions
10091                            .into_iter()
10092                            .filter(|location| {
10093                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10094                            })
10095                            .map(HoverLink::Text)
10096                            .collect::<Vec<_>>(),
10097                        split,
10098                        window,
10099                        cx,
10100                    )
10101                })?
10102                .await?;
10103            anyhow::Ok(navigated)
10104        })
10105    }
10106
10107    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10108        let selection = self.selections.newest_anchor();
10109        let head = selection.head();
10110        let tail = selection.tail();
10111
10112        let Some((buffer, start_position)) =
10113            self.buffer.read(cx).text_anchor_for_position(head, cx)
10114        else {
10115            return;
10116        };
10117
10118        let end_position = if head != tail {
10119            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10120                return;
10121            };
10122            Some(pos)
10123        } else {
10124            None
10125        };
10126
10127        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10128            let url = if let Some(end_pos) = end_position {
10129                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10130            } else {
10131                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10132            };
10133
10134            if let Some(url) = url {
10135                editor.update(&mut cx, |_, cx| {
10136                    cx.open_url(&url);
10137                })
10138            } else {
10139                Ok(())
10140            }
10141        });
10142
10143        url_finder.detach();
10144    }
10145
10146    pub fn open_selected_filename(
10147        &mut self,
10148        _: &OpenSelectedFilename,
10149        window: &mut Window,
10150        cx: &mut Context<Self>,
10151    ) {
10152        let Some(workspace) = self.workspace() else {
10153            return;
10154        };
10155
10156        let position = self.selections.newest_anchor().head();
10157
10158        let Some((buffer, buffer_position)) =
10159            self.buffer.read(cx).text_anchor_for_position(position, cx)
10160        else {
10161            return;
10162        };
10163
10164        let project = self.project.clone();
10165
10166        cx.spawn_in(window, |_, mut cx| async move {
10167            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10168
10169            if let Some((_, path)) = result {
10170                workspace
10171                    .update_in(&mut cx, |workspace, window, cx| {
10172                        workspace.open_resolved_path(path, window, cx)
10173                    })?
10174                    .await?;
10175            }
10176            anyhow::Ok(())
10177        })
10178        .detach();
10179    }
10180
10181    pub(crate) fn navigate_to_hover_links(
10182        &mut self,
10183        kind: Option<GotoDefinitionKind>,
10184        mut definitions: Vec<HoverLink>,
10185        split: bool,
10186        window: &mut Window,
10187        cx: &mut Context<Editor>,
10188    ) -> Task<Result<Navigated>> {
10189        // If there is one definition, just open it directly
10190        if definitions.len() == 1 {
10191            let definition = definitions.pop().unwrap();
10192
10193            enum TargetTaskResult {
10194                Location(Option<Location>),
10195                AlreadyNavigated,
10196            }
10197
10198            let target_task = match definition {
10199                HoverLink::Text(link) => {
10200                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10201                }
10202                HoverLink::InlayHint(lsp_location, server_id) => {
10203                    let computation =
10204                        self.compute_target_location(lsp_location, server_id, window, cx);
10205                    cx.background_executor().spawn(async move {
10206                        let location = computation.await?;
10207                        Ok(TargetTaskResult::Location(location))
10208                    })
10209                }
10210                HoverLink::Url(url) => {
10211                    cx.open_url(&url);
10212                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10213                }
10214                HoverLink::File(path) => {
10215                    if let Some(workspace) = self.workspace() {
10216                        cx.spawn_in(window, |_, mut cx| async move {
10217                            workspace
10218                                .update_in(&mut cx, |workspace, window, cx| {
10219                                    workspace.open_resolved_path(path, window, cx)
10220                                })?
10221                                .await
10222                                .map(|_| TargetTaskResult::AlreadyNavigated)
10223                        })
10224                    } else {
10225                        Task::ready(Ok(TargetTaskResult::Location(None)))
10226                    }
10227                }
10228            };
10229            cx.spawn_in(window, |editor, mut cx| async move {
10230                let target = match target_task.await.context("target resolution task")? {
10231                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10232                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10233                    TargetTaskResult::Location(Some(target)) => target,
10234                };
10235
10236                editor.update_in(&mut cx, |editor, window, cx| {
10237                    let Some(workspace) = editor.workspace() else {
10238                        return Navigated::No;
10239                    };
10240                    let pane = workspace.read(cx).active_pane().clone();
10241
10242                    let range = target.range.to_point(target.buffer.read(cx));
10243                    let range = editor.range_for_match(&range);
10244                    let range = collapse_multiline_range(range);
10245
10246                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10247                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10248                    } else {
10249                        window.defer(cx, move |window, cx| {
10250                            let target_editor: Entity<Self> =
10251                                workspace.update(cx, |workspace, cx| {
10252                                    let pane = if split {
10253                                        workspace.adjacent_pane(window, cx)
10254                                    } else {
10255                                        workspace.active_pane().clone()
10256                                    };
10257
10258                                    workspace.open_project_item(
10259                                        pane,
10260                                        target.buffer.clone(),
10261                                        true,
10262                                        true,
10263                                        window,
10264                                        cx,
10265                                    )
10266                                });
10267                            target_editor.update(cx, |target_editor, cx| {
10268                                // When selecting a definition in a different buffer, disable the nav history
10269                                // to avoid creating a history entry at the previous cursor location.
10270                                pane.update(cx, |pane, _| pane.disable_history());
10271                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10272                                pane.update(cx, |pane, _| pane.enable_history());
10273                            });
10274                        });
10275                    }
10276                    Navigated::Yes
10277                })
10278            })
10279        } else if !definitions.is_empty() {
10280            cx.spawn_in(window, |editor, mut cx| async move {
10281                let (title, location_tasks, workspace) = editor
10282                    .update_in(&mut cx, |editor, window, cx| {
10283                        let tab_kind = match kind {
10284                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10285                            _ => "Definitions",
10286                        };
10287                        let title = definitions
10288                            .iter()
10289                            .find_map(|definition| match definition {
10290                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10291                                    let buffer = origin.buffer.read(cx);
10292                                    format!(
10293                                        "{} for {}",
10294                                        tab_kind,
10295                                        buffer
10296                                            .text_for_range(origin.range.clone())
10297                                            .collect::<String>()
10298                                    )
10299                                }),
10300                                HoverLink::InlayHint(_, _) => None,
10301                                HoverLink::Url(_) => None,
10302                                HoverLink::File(_) => None,
10303                            })
10304                            .unwrap_or(tab_kind.to_string());
10305                        let location_tasks = definitions
10306                            .into_iter()
10307                            .map(|definition| match definition {
10308                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10309                                HoverLink::InlayHint(lsp_location, server_id) => editor
10310                                    .compute_target_location(lsp_location, server_id, window, cx),
10311                                HoverLink::Url(_) => Task::ready(Ok(None)),
10312                                HoverLink::File(_) => Task::ready(Ok(None)),
10313                            })
10314                            .collect::<Vec<_>>();
10315                        (title, location_tasks, editor.workspace().clone())
10316                    })
10317                    .context("location tasks preparation")?;
10318
10319                let locations = future::join_all(location_tasks)
10320                    .await
10321                    .into_iter()
10322                    .filter_map(|location| location.transpose())
10323                    .collect::<Result<_>>()
10324                    .context("location tasks")?;
10325
10326                let Some(workspace) = workspace else {
10327                    return Ok(Navigated::No);
10328                };
10329                let opened = workspace
10330                    .update_in(&mut cx, |workspace, window, cx| {
10331                        Self::open_locations_in_multibuffer(
10332                            workspace,
10333                            locations,
10334                            title,
10335                            split,
10336                            MultibufferSelectionMode::First,
10337                            window,
10338                            cx,
10339                        )
10340                    })
10341                    .ok();
10342
10343                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10344            })
10345        } else {
10346            Task::ready(Ok(Navigated::No))
10347        }
10348    }
10349
10350    fn compute_target_location(
10351        &self,
10352        lsp_location: lsp::Location,
10353        server_id: LanguageServerId,
10354        window: &mut Window,
10355        cx: &mut Context<Self>,
10356    ) -> Task<anyhow::Result<Option<Location>>> {
10357        let Some(project) = self.project.clone() else {
10358            return Task::ready(Ok(None));
10359        };
10360
10361        cx.spawn_in(window, move |editor, mut cx| async move {
10362            let location_task = editor.update(&mut cx, |_, cx| {
10363                project.update(cx, |project, cx| {
10364                    let language_server_name = project
10365                        .language_server_statuses(cx)
10366                        .find(|(id, _)| server_id == *id)
10367                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10368                    language_server_name.map(|language_server_name| {
10369                        project.open_local_buffer_via_lsp(
10370                            lsp_location.uri.clone(),
10371                            server_id,
10372                            language_server_name,
10373                            cx,
10374                        )
10375                    })
10376                })
10377            })?;
10378            let location = match location_task {
10379                Some(task) => Some({
10380                    let target_buffer_handle = task.await.context("open local buffer")?;
10381                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10382                        let target_start = target_buffer
10383                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10384                        let target_end = target_buffer
10385                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10386                        target_buffer.anchor_after(target_start)
10387                            ..target_buffer.anchor_before(target_end)
10388                    })?;
10389                    Location {
10390                        buffer: target_buffer_handle,
10391                        range,
10392                    }
10393                }),
10394                None => None,
10395            };
10396            Ok(location)
10397        })
10398    }
10399
10400    pub fn find_all_references(
10401        &mut self,
10402        _: &FindAllReferences,
10403        window: &mut Window,
10404        cx: &mut Context<Self>,
10405    ) -> Option<Task<Result<Navigated>>> {
10406        let selection = self.selections.newest::<usize>(cx);
10407        let multi_buffer = self.buffer.read(cx);
10408        let head = selection.head();
10409
10410        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10411        let head_anchor = multi_buffer_snapshot.anchor_at(
10412            head,
10413            if head < selection.tail() {
10414                Bias::Right
10415            } else {
10416                Bias::Left
10417            },
10418        );
10419
10420        match self
10421            .find_all_references_task_sources
10422            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10423        {
10424            Ok(_) => {
10425                log::info!(
10426                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10427                );
10428                return None;
10429            }
10430            Err(i) => {
10431                self.find_all_references_task_sources.insert(i, head_anchor);
10432            }
10433        }
10434
10435        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10436        let workspace = self.workspace()?;
10437        let project = workspace.read(cx).project().clone();
10438        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10439        Some(cx.spawn_in(window, |editor, mut cx| async move {
10440            let _cleanup = defer({
10441                let mut cx = cx.clone();
10442                move || {
10443                    let _ = editor.update(&mut cx, |editor, _| {
10444                        if let Ok(i) =
10445                            editor
10446                                .find_all_references_task_sources
10447                                .binary_search_by(|anchor| {
10448                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10449                                })
10450                        {
10451                            editor.find_all_references_task_sources.remove(i);
10452                        }
10453                    });
10454                }
10455            });
10456
10457            let locations = references.await?;
10458            if locations.is_empty() {
10459                return anyhow::Ok(Navigated::No);
10460            }
10461
10462            workspace.update_in(&mut cx, |workspace, window, cx| {
10463                let title = locations
10464                    .first()
10465                    .as_ref()
10466                    .map(|location| {
10467                        let buffer = location.buffer.read(cx);
10468                        format!(
10469                            "References to `{}`",
10470                            buffer
10471                                .text_for_range(location.range.clone())
10472                                .collect::<String>()
10473                        )
10474                    })
10475                    .unwrap();
10476                Self::open_locations_in_multibuffer(
10477                    workspace,
10478                    locations,
10479                    title,
10480                    false,
10481                    MultibufferSelectionMode::First,
10482                    window,
10483                    cx,
10484                );
10485                Navigated::Yes
10486            })
10487        }))
10488    }
10489
10490    /// Opens a multibuffer with the given project locations in it
10491    pub fn open_locations_in_multibuffer(
10492        workspace: &mut Workspace,
10493        mut locations: Vec<Location>,
10494        title: String,
10495        split: bool,
10496        multibuffer_selection_mode: MultibufferSelectionMode,
10497        window: &mut Window,
10498        cx: &mut Context<Workspace>,
10499    ) {
10500        // If there are multiple definitions, open them in a multibuffer
10501        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10502        let mut locations = locations.into_iter().peekable();
10503        let mut ranges = Vec::new();
10504        let capability = workspace.project().read(cx).capability();
10505
10506        let excerpt_buffer = cx.new(|cx| {
10507            let mut multibuffer = MultiBuffer::new(capability);
10508            while let Some(location) = locations.next() {
10509                let buffer = location.buffer.read(cx);
10510                let mut ranges_for_buffer = Vec::new();
10511                let range = location.range.to_offset(buffer);
10512                ranges_for_buffer.push(range.clone());
10513
10514                while let Some(next_location) = locations.peek() {
10515                    if next_location.buffer == location.buffer {
10516                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10517                        locations.next();
10518                    } else {
10519                        break;
10520                    }
10521                }
10522
10523                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10524                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10525                    location.buffer.clone(),
10526                    ranges_for_buffer,
10527                    DEFAULT_MULTIBUFFER_CONTEXT,
10528                    cx,
10529                ))
10530            }
10531
10532            multibuffer.with_title(title)
10533        });
10534
10535        let editor = cx.new(|cx| {
10536            Editor::for_multibuffer(
10537                excerpt_buffer,
10538                Some(workspace.project().clone()),
10539                true,
10540                window,
10541                cx,
10542            )
10543        });
10544        editor.update(cx, |editor, cx| {
10545            match multibuffer_selection_mode {
10546                MultibufferSelectionMode::First => {
10547                    if let Some(first_range) = ranges.first() {
10548                        editor.change_selections(None, window, cx, |selections| {
10549                            selections.clear_disjoint();
10550                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10551                        });
10552                    }
10553                    editor.highlight_background::<Self>(
10554                        &ranges,
10555                        |theme| theme.editor_highlighted_line_background,
10556                        cx,
10557                    );
10558                }
10559                MultibufferSelectionMode::All => {
10560                    editor.change_selections(None, window, cx, |selections| {
10561                        selections.clear_disjoint();
10562                        selections.select_anchor_ranges(ranges);
10563                    });
10564                }
10565            }
10566            editor.register_buffers_with_language_servers(cx);
10567        });
10568
10569        let item = Box::new(editor);
10570        let item_id = item.item_id();
10571
10572        if split {
10573            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10574        } else {
10575            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10576                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10577                    pane.close_current_preview_item(window, cx)
10578                } else {
10579                    None
10580                }
10581            });
10582            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10583        }
10584        workspace.active_pane().update(cx, |pane, cx| {
10585            pane.set_preview_item_id(Some(item_id), cx);
10586        });
10587    }
10588
10589    pub fn rename(
10590        &mut self,
10591        _: &Rename,
10592        window: &mut Window,
10593        cx: &mut Context<Self>,
10594    ) -> Option<Task<Result<()>>> {
10595        use language::ToOffset as _;
10596
10597        let provider = self.semantics_provider.clone()?;
10598        let selection = self.selections.newest_anchor().clone();
10599        let (cursor_buffer, cursor_buffer_position) = self
10600            .buffer
10601            .read(cx)
10602            .text_anchor_for_position(selection.head(), cx)?;
10603        let (tail_buffer, cursor_buffer_position_end) = self
10604            .buffer
10605            .read(cx)
10606            .text_anchor_for_position(selection.tail(), cx)?;
10607        if tail_buffer != cursor_buffer {
10608            return None;
10609        }
10610
10611        let snapshot = cursor_buffer.read(cx).snapshot();
10612        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10613        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10614        let prepare_rename = provider
10615            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10616            .unwrap_or_else(|| Task::ready(Ok(None)));
10617        drop(snapshot);
10618
10619        Some(cx.spawn_in(window, |this, mut cx| async move {
10620            let rename_range = if let Some(range) = prepare_rename.await? {
10621                Some(range)
10622            } else {
10623                this.update(&mut cx, |this, cx| {
10624                    let buffer = this.buffer.read(cx).snapshot(cx);
10625                    let mut buffer_highlights = this
10626                        .document_highlights_for_position(selection.head(), &buffer)
10627                        .filter(|highlight| {
10628                            highlight.start.excerpt_id == selection.head().excerpt_id
10629                                && highlight.end.excerpt_id == selection.head().excerpt_id
10630                        });
10631                    buffer_highlights
10632                        .next()
10633                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10634                })?
10635            };
10636            if let Some(rename_range) = rename_range {
10637                this.update_in(&mut cx, |this, window, cx| {
10638                    let snapshot = cursor_buffer.read(cx).snapshot();
10639                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10640                    let cursor_offset_in_rename_range =
10641                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10642                    let cursor_offset_in_rename_range_end =
10643                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10644
10645                    this.take_rename(false, window, cx);
10646                    let buffer = this.buffer.read(cx).read(cx);
10647                    let cursor_offset = selection.head().to_offset(&buffer);
10648                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10649                    let rename_end = rename_start + rename_buffer_range.len();
10650                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10651                    let mut old_highlight_id = None;
10652                    let old_name: Arc<str> = buffer
10653                        .chunks(rename_start..rename_end, true)
10654                        .map(|chunk| {
10655                            if old_highlight_id.is_none() {
10656                                old_highlight_id = chunk.syntax_highlight_id;
10657                            }
10658                            chunk.text
10659                        })
10660                        .collect::<String>()
10661                        .into();
10662
10663                    drop(buffer);
10664
10665                    // Position the selection in the rename editor so that it matches the current selection.
10666                    this.show_local_selections = false;
10667                    let rename_editor = cx.new(|cx| {
10668                        let mut editor = Editor::single_line(window, cx);
10669                        editor.buffer.update(cx, |buffer, cx| {
10670                            buffer.edit([(0..0, old_name.clone())], None, cx)
10671                        });
10672                        let rename_selection_range = match cursor_offset_in_rename_range
10673                            .cmp(&cursor_offset_in_rename_range_end)
10674                        {
10675                            Ordering::Equal => {
10676                                editor.select_all(&SelectAll, window, cx);
10677                                return editor;
10678                            }
10679                            Ordering::Less => {
10680                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10681                            }
10682                            Ordering::Greater => {
10683                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10684                            }
10685                        };
10686                        if rename_selection_range.end > old_name.len() {
10687                            editor.select_all(&SelectAll, window, cx);
10688                        } else {
10689                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10690                                s.select_ranges([rename_selection_range]);
10691                            });
10692                        }
10693                        editor
10694                    });
10695                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10696                        if e == &EditorEvent::Focused {
10697                            cx.emit(EditorEvent::FocusedIn)
10698                        }
10699                    })
10700                    .detach();
10701
10702                    let write_highlights =
10703                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10704                    let read_highlights =
10705                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10706                    let ranges = write_highlights
10707                        .iter()
10708                        .flat_map(|(_, ranges)| ranges.iter())
10709                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10710                        .cloned()
10711                        .collect();
10712
10713                    this.highlight_text::<Rename>(
10714                        ranges,
10715                        HighlightStyle {
10716                            fade_out: Some(0.6),
10717                            ..Default::default()
10718                        },
10719                        cx,
10720                    );
10721                    let rename_focus_handle = rename_editor.focus_handle(cx);
10722                    window.focus(&rename_focus_handle);
10723                    let block_id = this.insert_blocks(
10724                        [BlockProperties {
10725                            style: BlockStyle::Flex,
10726                            placement: BlockPlacement::Below(range.start),
10727                            height: 1,
10728                            render: Arc::new({
10729                                let rename_editor = rename_editor.clone();
10730                                move |cx: &mut BlockContext| {
10731                                    let mut text_style = cx.editor_style.text.clone();
10732                                    if let Some(highlight_style) = old_highlight_id
10733                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10734                                    {
10735                                        text_style = text_style.highlight(highlight_style);
10736                                    }
10737                                    div()
10738                                        .block_mouse_down()
10739                                        .pl(cx.anchor_x)
10740                                        .child(EditorElement::new(
10741                                            &rename_editor,
10742                                            EditorStyle {
10743                                                background: cx.theme().system().transparent,
10744                                                local_player: cx.editor_style.local_player,
10745                                                text: text_style,
10746                                                scrollbar_width: cx.editor_style.scrollbar_width,
10747                                                syntax: cx.editor_style.syntax.clone(),
10748                                                status: cx.editor_style.status.clone(),
10749                                                inlay_hints_style: HighlightStyle {
10750                                                    font_weight: Some(FontWeight::BOLD),
10751                                                    ..make_inlay_hints_style(cx.app)
10752                                                },
10753                                                inline_completion_styles: make_suggestion_styles(
10754                                                    cx.app,
10755                                                ),
10756                                                ..EditorStyle::default()
10757                                            },
10758                                        ))
10759                                        .into_any_element()
10760                                }
10761                            }),
10762                            priority: 0,
10763                        }],
10764                        Some(Autoscroll::fit()),
10765                        cx,
10766                    )[0];
10767                    this.pending_rename = Some(RenameState {
10768                        range,
10769                        old_name,
10770                        editor: rename_editor,
10771                        block_id,
10772                    });
10773                })?;
10774            }
10775
10776            Ok(())
10777        }))
10778    }
10779
10780    pub fn confirm_rename(
10781        &mut self,
10782        _: &ConfirmRename,
10783        window: &mut Window,
10784        cx: &mut Context<Self>,
10785    ) -> Option<Task<Result<()>>> {
10786        let rename = self.take_rename(false, window, cx)?;
10787        let workspace = self.workspace()?.downgrade();
10788        let (buffer, start) = self
10789            .buffer
10790            .read(cx)
10791            .text_anchor_for_position(rename.range.start, cx)?;
10792        let (end_buffer, _) = self
10793            .buffer
10794            .read(cx)
10795            .text_anchor_for_position(rename.range.end, cx)?;
10796        if buffer != end_buffer {
10797            return None;
10798        }
10799
10800        let old_name = rename.old_name;
10801        let new_name = rename.editor.read(cx).text(cx);
10802
10803        let rename = self.semantics_provider.as_ref()?.perform_rename(
10804            &buffer,
10805            start,
10806            new_name.clone(),
10807            cx,
10808        )?;
10809
10810        Some(cx.spawn_in(window, |editor, mut cx| async move {
10811            let project_transaction = rename.await?;
10812            Self::open_project_transaction(
10813                &editor,
10814                workspace,
10815                project_transaction,
10816                format!("Rename: {}{}", old_name, new_name),
10817                cx.clone(),
10818            )
10819            .await?;
10820
10821            editor.update(&mut cx, |editor, cx| {
10822                editor.refresh_document_highlights(cx);
10823            })?;
10824            Ok(())
10825        }))
10826    }
10827
10828    fn take_rename(
10829        &mut self,
10830        moving_cursor: bool,
10831        window: &mut Window,
10832        cx: &mut Context<Self>,
10833    ) -> Option<RenameState> {
10834        let rename = self.pending_rename.take()?;
10835        if rename.editor.focus_handle(cx).is_focused(window) {
10836            window.focus(&self.focus_handle);
10837        }
10838
10839        self.remove_blocks(
10840            [rename.block_id].into_iter().collect(),
10841            Some(Autoscroll::fit()),
10842            cx,
10843        );
10844        self.clear_highlights::<Rename>(cx);
10845        self.show_local_selections = true;
10846
10847        if moving_cursor {
10848            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10849                editor.selections.newest::<usize>(cx).head()
10850            });
10851
10852            // Update the selection to match the position of the selection inside
10853            // the rename editor.
10854            let snapshot = self.buffer.read(cx).read(cx);
10855            let rename_range = rename.range.to_offset(&snapshot);
10856            let cursor_in_editor = snapshot
10857                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10858                .min(rename_range.end);
10859            drop(snapshot);
10860
10861            self.change_selections(None, window, cx, |s| {
10862                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10863            });
10864        } else {
10865            self.refresh_document_highlights(cx);
10866        }
10867
10868        Some(rename)
10869    }
10870
10871    pub fn pending_rename(&self) -> Option<&RenameState> {
10872        self.pending_rename.as_ref()
10873    }
10874
10875    fn format(
10876        &mut self,
10877        _: &Format,
10878        window: &mut Window,
10879        cx: &mut Context<Self>,
10880    ) -> Option<Task<Result<()>>> {
10881        let project = match &self.project {
10882            Some(project) => project.clone(),
10883            None => return None,
10884        };
10885
10886        Some(self.perform_format(
10887            project,
10888            FormatTrigger::Manual,
10889            FormatTarget::Buffers,
10890            window,
10891            cx,
10892        ))
10893    }
10894
10895    fn format_selections(
10896        &mut self,
10897        _: &FormatSelections,
10898        window: &mut Window,
10899        cx: &mut Context<Self>,
10900    ) -> Option<Task<Result<()>>> {
10901        let project = match &self.project {
10902            Some(project) => project.clone(),
10903            None => return None,
10904        };
10905
10906        let ranges = self
10907            .selections
10908            .all_adjusted(cx)
10909            .into_iter()
10910            .map(|selection| selection.range())
10911            .collect_vec();
10912
10913        Some(self.perform_format(
10914            project,
10915            FormatTrigger::Manual,
10916            FormatTarget::Ranges(ranges),
10917            window,
10918            cx,
10919        ))
10920    }
10921
10922    fn perform_format(
10923        &mut self,
10924        project: Entity<Project>,
10925        trigger: FormatTrigger,
10926        target: FormatTarget,
10927        window: &mut Window,
10928        cx: &mut Context<Self>,
10929    ) -> Task<Result<()>> {
10930        let buffer = self.buffer.clone();
10931        let (buffers, target) = match target {
10932            FormatTarget::Buffers => {
10933                let mut buffers = buffer.read(cx).all_buffers();
10934                if trigger == FormatTrigger::Save {
10935                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10936                }
10937                (buffers, LspFormatTarget::Buffers)
10938            }
10939            FormatTarget::Ranges(selection_ranges) => {
10940                let multi_buffer = buffer.read(cx);
10941                let snapshot = multi_buffer.read(cx);
10942                let mut buffers = HashSet::default();
10943                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10944                    BTreeMap::new();
10945                for selection_range in selection_ranges {
10946                    for (buffer, buffer_range, _) in
10947                        snapshot.range_to_buffer_ranges(selection_range)
10948                    {
10949                        let buffer_id = buffer.remote_id();
10950                        let start = buffer.anchor_before(buffer_range.start);
10951                        let end = buffer.anchor_after(buffer_range.end);
10952                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10953                        buffer_id_to_ranges
10954                            .entry(buffer_id)
10955                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10956                            .or_insert_with(|| vec![start..end]);
10957                    }
10958                }
10959                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10960            }
10961        };
10962
10963        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10964        let format = project.update(cx, |project, cx| {
10965            project.format(buffers, target, true, trigger, cx)
10966        });
10967
10968        cx.spawn_in(window, |_, mut cx| async move {
10969            let transaction = futures::select_biased! {
10970                () = timeout => {
10971                    log::warn!("timed out waiting for formatting");
10972                    None
10973                }
10974                transaction = format.log_err().fuse() => transaction,
10975            };
10976
10977            buffer
10978                .update(&mut cx, |buffer, cx| {
10979                    if let Some(transaction) = transaction {
10980                        if !buffer.is_singleton() {
10981                            buffer.push_transaction(&transaction.0, cx);
10982                        }
10983                    }
10984
10985                    cx.notify();
10986                })
10987                .ok();
10988
10989            Ok(())
10990        })
10991    }
10992
10993    fn restart_language_server(
10994        &mut self,
10995        _: &RestartLanguageServer,
10996        _: &mut Window,
10997        cx: &mut Context<Self>,
10998    ) {
10999        if let Some(project) = self.project.clone() {
11000            self.buffer.update(cx, |multi_buffer, cx| {
11001                project.update(cx, |project, cx| {
11002                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11003                });
11004            })
11005        }
11006    }
11007
11008    fn cancel_language_server_work(
11009        &mut self,
11010        _: &actions::CancelLanguageServerWork,
11011        _: &mut Window,
11012        cx: &mut Context<Self>,
11013    ) {
11014        if let Some(project) = self.project.clone() {
11015            self.buffer.update(cx, |multi_buffer, cx| {
11016                project.update(cx, |project, cx| {
11017                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11018                });
11019            })
11020        }
11021    }
11022
11023    fn show_character_palette(
11024        &mut self,
11025        _: &ShowCharacterPalette,
11026        window: &mut Window,
11027        _: &mut Context<Self>,
11028    ) {
11029        window.show_character_palette();
11030    }
11031
11032    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11033        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11034            let buffer = self.buffer.read(cx).snapshot(cx);
11035            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11036            let is_valid = buffer
11037                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11038                .any(|entry| {
11039                    entry.diagnostic.is_primary
11040                        && !entry.range.is_empty()
11041                        && entry.range.start == primary_range_start
11042                        && entry.diagnostic.message == active_diagnostics.primary_message
11043                });
11044
11045            if is_valid != active_diagnostics.is_valid {
11046                active_diagnostics.is_valid = is_valid;
11047                let mut new_styles = HashMap::default();
11048                for (block_id, diagnostic) in &active_diagnostics.blocks {
11049                    new_styles.insert(
11050                        *block_id,
11051                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11052                    );
11053                }
11054                self.display_map.update(cx, |display_map, _cx| {
11055                    display_map.replace_blocks(new_styles)
11056                });
11057            }
11058        }
11059    }
11060
11061    fn activate_diagnostics(
11062        &mut self,
11063        buffer_id: BufferId,
11064        group_id: usize,
11065        window: &mut Window,
11066        cx: &mut Context<Self>,
11067    ) {
11068        self.dismiss_diagnostics(cx);
11069        let snapshot = self.snapshot(window, cx);
11070        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11071            let buffer = self.buffer.read(cx).snapshot(cx);
11072
11073            let mut primary_range = None;
11074            let mut primary_message = None;
11075            let diagnostic_group = buffer
11076                .diagnostic_group(buffer_id, group_id)
11077                .filter_map(|entry| {
11078                    let start = entry.range.start;
11079                    let end = entry.range.end;
11080                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11081                        && (start.row == end.row
11082                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11083                    {
11084                        return None;
11085                    }
11086                    if entry.diagnostic.is_primary {
11087                        primary_range = Some(entry.range.clone());
11088                        primary_message = Some(entry.diagnostic.message.clone());
11089                    }
11090                    Some(entry)
11091                })
11092                .collect::<Vec<_>>();
11093            let primary_range = primary_range?;
11094            let primary_message = primary_message?;
11095
11096            let blocks = display_map
11097                .insert_blocks(
11098                    diagnostic_group.iter().map(|entry| {
11099                        let diagnostic = entry.diagnostic.clone();
11100                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11101                        BlockProperties {
11102                            style: BlockStyle::Fixed,
11103                            placement: BlockPlacement::Below(
11104                                buffer.anchor_after(entry.range.start),
11105                            ),
11106                            height: message_height,
11107                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11108                            priority: 0,
11109                        }
11110                    }),
11111                    cx,
11112                )
11113                .into_iter()
11114                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11115                .collect();
11116
11117            Some(ActiveDiagnosticGroup {
11118                primary_range: buffer.anchor_before(primary_range.start)
11119                    ..buffer.anchor_after(primary_range.end),
11120                primary_message,
11121                group_id,
11122                blocks,
11123                is_valid: true,
11124            })
11125        });
11126    }
11127
11128    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11129        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11130            self.display_map.update(cx, |display_map, cx| {
11131                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11132            });
11133            cx.notify();
11134        }
11135    }
11136
11137    pub fn set_selections_from_remote(
11138        &mut self,
11139        selections: Vec<Selection<Anchor>>,
11140        pending_selection: Option<Selection<Anchor>>,
11141        window: &mut Window,
11142        cx: &mut Context<Self>,
11143    ) {
11144        let old_cursor_position = self.selections.newest_anchor().head();
11145        self.selections.change_with(cx, |s| {
11146            s.select_anchors(selections);
11147            if let Some(pending_selection) = pending_selection {
11148                s.set_pending(pending_selection, SelectMode::Character);
11149            } else {
11150                s.clear_pending();
11151            }
11152        });
11153        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11154    }
11155
11156    fn push_to_selection_history(&mut self) {
11157        self.selection_history.push(SelectionHistoryEntry {
11158            selections: self.selections.disjoint_anchors(),
11159            select_next_state: self.select_next_state.clone(),
11160            select_prev_state: self.select_prev_state.clone(),
11161            add_selections_state: self.add_selections_state.clone(),
11162        });
11163    }
11164
11165    pub fn transact(
11166        &mut self,
11167        window: &mut Window,
11168        cx: &mut Context<Self>,
11169        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11170    ) -> Option<TransactionId> {
11171        self.start_transaction_at(Instant::now(), window, cx);
11172        update(self, window, cx);
11173        self.end_transaction_at(Instant::now(), cx)
11174    }
11175
11176    pub fn start_transaction_at(
11177        &mut self,
11178        now: Instant,
11179        window: &mut Window,
11180        cx: &mut Context<Self>,
11181    ) {
11182        self.end_selection(window, cx);
11183        if let Some(tx_id) = self
11184            .buffer
11185            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11186        {
11187            self.selection_history
11188                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11189            cx.emit(EditorEvent::TransactionBegun {
11190                transaction_id: tx_id,
11191            })
11192        }
11193    }
11194
11195    pub fn end_transaction_at(
11196        &mut self,
11197        now: Instant,
11198        cx: &mut Context<Self>,
11199    ) -> Option<TransactionId> {
11200        if let Some(transaction_id) = self
11201            .buffer
11202            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11203        {
11204            if let Some((_, end_selections)) =
11205                self.selection_history.transaction_mut(transaction_id)
11206            {
11207                *end_selections = Some(self.selections.disjoint_anchors());
11208            } else {
11209                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11210            }
11211
11212            cx.emit(EditorEvent::Edited { transaction_id });
11213            Some(transaction_id)
11214        } else {
11215            None
11216        }
11217    }
11218
11219    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11220        if self.selection_mark_mode {
11221            self.change_selections(None, window, cx, |s| {
11222                s.move_with(|_, sel| {
11223                    sel.collapse_to(sel.head(), SelectionGoal::None);
11224                });
11225            })
11226        }
11227        self.selection_mark_mode = true;
11228        cx.notify();
11229    }
11230
11231    pub fn swap_selection_ends(
11232        &mut self,
11233        _: &actions::SwapSelectionEnds,
11234        window: &mut Window,
11235        cx: &mut Context<Self>,
11236    ) {
11237        self.change_selections(None, window, cx, |s| {
11238            s.move_with(|_, sel| {
11239                if sel.start != sel.end {
11240                    sel.reversed = !sel.reversed
11241                }
11242            });
11243        });
11244        self.request_autoscroll(Autoscroll::newest(), cx);
11245        cx.notify();
11246    }
11247
11248    pub fn toggle_fold(
11249        &mut self,
11250        _: &actions::ToggleFold,
11251        window: &mut Window,
11252        cx: &mut Context<Self>,
11253    ) {
11254        if self.is_singleton(cx) {
11255            let selection = self.selections.newest::<Point>(cx);
11256
11257            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11258            let range = if selection.is_empty() {
11259                let point = selection.head().to_display_point(&display_map);
11260                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11261                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11262                    .to_point(&display_map);
11263                start..end
11264            } else {
11265                selection.range()
11266            };
11267            if display_map.folds_in_range(range).next().is_some() {
11268                self.unfold_lines(&Default::default(), window, cx)
11269            } else {
11270                self.fold(&Default::default(), window, cx)
11271            }
11272        } else {
11273            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11274            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11275                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11276                .map(|(snapshot, _, _)| snapshot.remote_id())
11277                .collect();
11278
11279            for buffer_id in buffer_ids {
11280                if self.is_buffer_folded(buffer_id, cx) {
11281                    self.unfold_buffer(buffer_id, cx);
11282                } else {
11283                    self.fold_buffer(buffer_id, cx);
11284                }
11285            }
11286        }
11287    }
11288
11289    pub fn toggle_fold_recursive(
11290        &mut self,
11291        _: &actions::ToggleFoldRecursive,
11292        window: &mut Window,
11293        cx: &mut Context<Self>,
11294    ) {
11295        let selection = self.selections.newest::<Point>(cx);
11296
11297        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11298        let range = if selection.is_empty() {
11299            let point = selection.head().to_display_point(&display_map);
11300            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11301            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11302                .to_point(&display_map);
11303            start..end
11304        } else {
11305            selection.range()
11306        };
11307        if display_map.folds_in_range(range).next().is_some() {
11308            self.unfold_recursive(&Default::default(), window, cx)
11309        } else {
11310            self.fold_recursive(&Default::default(), window, cx)
11311        }
11312    }
11313
11314    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11315        if self.is_singleton(cx) {
11316            let mut to_fold = Vec::new();
11317            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11318            let selections = self.selections.all_adjusted(cx);
11319
11320            for selection in selections {
11321                let range = selection.range().sorted();
11322                let buffer_start_row = range.start.row;
11323
11324                if range.start.row != range.end.row {
11325                    let mut found = false;
11326                    let mut row = range.start.row;
11327                    while row <= range.end.row {
11328                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11329                        {
11330                            found = true;
11331                            row = crease.range().end.row + 1;
11332                            to_fold.push(crease);
11333                        } else {
11334                            row += 1
11335                        }
11336                    }
11337                    if found {
11338                        continue;
11339                    }
11340                }
11341
11342                for row in (0..=range.start.row).rev() {
11343                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11344                        if crease.range().end.row >= buffer_start_row {
11345                            to_fold.push(crease);
11346                            if row <= range.start.row {
11347                                break;
11348                            }
11349                        }
11350                    }
11351                }
11352            }
11353
11354            self.fold_creases(to_fold, true, window, cx);
11355        } else {
11356            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11357
11358            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11359                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11360                .map(|(snapshot, _, _)| snapshot.remote_id())
11361                .collect();
11362            for buffer_id in buffer_ids {
11363                self.fold_buffer(buffer_id, cx);
11364            }
11365        }
11366    }
11367
11368    fn fold_at_level(
11369        &mut self,
11370        fold_at: &FoldAtLevel,
11371        window: &mut Window,
11372        cx: &mut Context<Self>,
11373    ) {
11374        if !self.buffer.read(cx).is_singleton() {
11375            return;
11376        }
11377
11378        let fold_at_level = fold_at.level;
11379        let snapshot = self.buffer.read(cx).snapshot(cx);
11380        let mut to_fold = Vec::new();
11381        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11382
11383        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11384            while start_row < end_row {
11385                match self
11386                    .snapshot(window, cx)
11387                    .crease_for_buffer_row(MultiBufferRow(start_row))
11388                {
11389                    Some(crease) => {
11390                        let nested_start_row = crease.range().start.row + 1;
11391                        let nested_end_row = crease.range().end.row;
11392
11393                        if current_level < fold_at_level {
11394                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11395                        } else if current_level == fold_at_level {
11396                            to_fold.push(crease);
11397                        }
11398
11399                        start_row = nested_end_row + 1;
11400                    }
11401                    None => start_row += 1,
11402                }
11403            }
11404        }
11405
11406        self.fold_creases(to_fold, true, window, cx);
11407    }
11408
11409    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11410        if self.buffer.read(cx).is_singleton() {
11411            let mut fold_ranges = Vec::new();
11412            let snapshot = self.buffer.read(cx).snapshot(cx);
11413
11414            for row in 0..snapshot.max_row().0 {
11415                if let Some(foldable_range) = self
11416                    .snapshot(window, cx)
11417                    .crease_for_buffer_row(MultiBufferRow(row))
11418                {
11419                    fold_ranges.push(foldable_range);
11420                }
11421            }
11422
11423            self.fold_creases(fold_ranges, true, window, cx);
11424        } else {
11425            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11426                editor
11427                    .update_in(&mut cx, |editor, _, cx| {
11428                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11429                            editor.fold_buffer(buffer_id, cx);
11430                        }
11431                    })
11432                    .ok();
11433            });
11434        }
11435    }
11436
11437    pub fn fold_function_bodies(
11438        &mut self,
11439        _: &actions::FoldFunctionBodies,
11440        window: &mut Window,
11441        cx: &mut Context<Self>,
11442    ) {
11443        let snapshot = self.buffer.read(cx).snapshot(cx);
11444
11445        let ranges = snapshot
11446            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11447            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11448            .collect::<Vec<_>>();
11449
11450        let creases = ranges
11451            .into_iter()
11452            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11453            .collect();
11454
11455        self.fold_creases(creases, true, window, cx);
11456    }
11457
11458    pub fn fold_recursive(
11459        &mut self,
11460        _: &actions::FoldRecursive,
11461        window: &mut Window,
11462        cx: &mut Context<Self>,
11463    ) {
11464        let mut to_fold = Vec::new();
11465        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11466        let selections = self.selections.all_adjusted(cx);
11467
11468        for selection in selections {
11469            let range = selection.range().sorted();
11470            let buffer_start_row = range.start.row;
11471
11472            if range.start.row != range.end.row {
11473                let mut found = false;
11474                for row in range.start.row..=range.end.row {
11475                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11476                        found = true;
11477                        to_fold.push(crease);
11478                    }
11479                }
11480                if found {
11481                    continue;
11482                }
11483            }
11484
11485            for row in (0..=range.start.row).rev() {
11486                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11487                    if crease.range().end.row >= buffer_start_row {
11488                        to_fold.push(crease);
11489                    } else {
11490                        break;
11491                    }
11492                }
11493            }
11494        }
11495
11496        self.fold_creases(to_fold, true, window, cx);
11497    }
11498
11499    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11500        let buffer_row = fold_at.buffer_row;
11501        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11502
11503        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11504            let autoscroll = self
11505                .selections
11506                .all::<Point>(cx)
11507                .iter()
11508                .any(|selection| crease.range().overlaps(&selection.range()));
11509
11510            self.fold_creases(vec![crease], autoscroll, window, cx);
11511        }
11512    }
11513
11514    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11515        if self.is_singleton(cx) {
11516            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11517            let buffer = &display_map.buffer_snapshot;
11518            let selections = self.selections.all::<Point>(cx);
11519            let ranges = selections
11520                .iter()
11521                .map(|s| {
11522                    let range = s.display_range(&display_map).sorted();
11523                    let mut start = range.start.to_point(&display_map);
11524                    let mut end = range.end.to_point(&display_map);
11525                    start.column = 0;
11526                    end.column = buffer.line_len(MultiBufferRow(end.row));
11527                    start..end
11528                })
11529                .collect::<Vec<_>>();
11530
11531            self.unfold_ranges(&ranges, true, true, cx);
11532        } else {
11533            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11534            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11535                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11536                .map(|(snapshot, _, _)| snapshot.remote_id())
11537                .collect();
11538            for buffer_id in buffer_ids {
11539                self.unfold_buffer(buffer_id, cx);
11540            }
11541        }
11542    }
11543
11544    pub fn unfold_recursive(
11545        &mut self,
11546        _: &UnfoldRecursive,
11547        _window: &mut Window,
11548        cx: &mut Context<Self>,
11549    ) {
11550        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11551        let selections = self.selections.all::<Point>(cx);
11552        let ranges = selections
11553            .iter()
11554            .map(|s| {
11555                let mut range = s.display_range(&display_map).sorted();
11556                *range.start.column_mut() = 0;
11557                *range.end.column_mut() = display_map.line_len(range.end.row());
11558                let start = range.start.to_point(&display_map);
11559                let end = range.end.to_point(&display_map);
11560                start..end
11561            })
11562            .collect::<Vec<_>>();
11563
11564        self.unfold_ranges(&ranges, true, true, cx);
11565    }
11566
11567    pub fn unfold_at(
11568        &mut self,
11569        unfold_at: &UnfoldAt,
11570        _window: &mut Window,
11571        cx: &mut Context<Self>,
11572    ) {
11573        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11574
11575        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11576            ..Point::new(
11577                unfold_at.buffer_row.0,
11578                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11579            );
11580
11581        let autoscroll = self
11582            .selections
11583            .all::<Point>(cx)
11584            .iter()
11585            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11586
11587        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11588    }
11589
11590    pub fn unfold_all(
11591        &mut self,
11592        _: &actions::UnfoldAll,
11593        _window: &mut Window,
11594        cx: &mut Context<Self>,
11595    ) {
11596        if self.buffer.read(cx).is_singleton() {
11597            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11598            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11599        } else {
11600            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11601                editor
11602                    .update(&mut cx, |editor, cx| {
11603                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11604                            editor.unfold_buffer(buffer_id, cx);
11605                        }
11606                    })
11607                    .ok();
11608            });
11609        }
11610    }
11611
11612    pub fn fold_selected_ranges(
11613        &mut self,
11614        _: &FoldSelectedRanges,
11615        window: &mut Window,
11616        cx: &mut Context<Self>,
11617    ) {
11618        let selections = self.selections.all::<Point>(cx);
11619        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11620        let line_mode = self.selections.line_mode;
11621        let ranges = selections
11622            .into_iter()
11623            .map(|s| {
11624                if line_mode {
11625                    let start = Point::new(s.start.row, 0);
11626                    let end = Point::new(
11627                        s.end.row,
11628                        display_map
11629                            .buffer_snapshot
11630                            .line_len(MultiBufferRow(s.end.row)),
11631                    );
11632                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11633                } else {
11634                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11635                }
11636            })
11637            .collect::<Vec<_>>();
11638        self.fold_creases(ranges, true, window, cx);
11639    }
11640
11641    pub fn fold_ranges<T: ToOffset + Clone>(
11642        &mut self,
11643        ranges: Vec<Range<T>>,
11644        auto_scroll: bool,
11645        window: &mut Window,
11646        cx: &mut Context<Self>,
11647    ) {
11648        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11649        let ranges = ranges
11650            .into_iter()
11651            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11652            .collect::<Vec<_>>();
11653        self.fold_creases(ranges, auto_scroll, window, cx);
11654    }
11655
11656    pub fn fold_creases<T: ToOffset + Clone>(
11657        &mut self,
11658        creases: Vec<Crease<T>>,
11659        auto_scroll: bool,
11660        window: &mut Window,
11661        cx: &mut Context<Self>,
11662    ) {
11663        if creases.is_empty() {
11664            return;
11665        }
11666
11667        let mut buffers_affected = HashSet::default();
11668        let multi_buffer = self.buffer().read(cx);
11669        for crease in &creases {
11670            if let Some((_, buffer, _)) =
11671                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11672            {
11673                buffers_affected.insert(buffer.read(cx).remote_id());
11674            };
11675        }
11676
11677        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11678
11679        if auto_scroll {
11680            self.request_autoscroll(Autoscroll::fit(), cx);
11681        }
11682
11683        cx.notify();
11684
11685        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11686            // Clear diagnostics block when folding a range that contains it.
11687            let snapshot = self.snapshot(window, cx);
11688            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11689                drop(snapshot);
11690                self.active_diagnostics = Some(active_diagnostics);
11691                self.dismiss_diagnostics(cx);
11692            } else {
11693                self.active_diagnostics = Some(active_diagnostics);
11694            }
11695        }
11696
11697        self.scrollbar_marker_state.dirty = true;
11698    }
11699
11700    /// Removes any folds whose ranges intersect any of the given ranges.
11701    pub fn unfold_ranges<T: ToOffset + Clone>(
11702        &mut self,
11703        ranges: &[Range<T>],
11704        inclusive: bool,
11705        auto_scroll: bool,
11706        cx: &mut Context<Self>,
11707    ) {
11708        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11709            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11710        });
11711    }
11712
11713    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11714        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11715            return;
11716        }
11717        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11718            return;
11719        };
11720        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11721        self.display_map
11722            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11723        cx.emit(EditorEvent::BufferFoldToggled {
11724            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11725            folded: true,
11726        });
11727        cx.notify();
11728    }
11729
11730    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11731        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11732            return;
11733        }
11734        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11735            return;
11736        };
11737        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11738        self.display_map.update(cx, |display_map, cx| {
11739            display_map.unfold_buffer(buffer_id, cx);
11740        });
11741        cx.emit(EditorEvent::BufferFoldToggled {
11742            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11743            folded: false,
11744        });
11745        cx.notify();
11746    }
11747
11748    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11749        self.display_map.read(cx).is_buffer_folded(buffer)
11750    }
11751
11752    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
11753        self.display_map.read(cx).folded_buffers()
11754    }
11755
11756    /// Removes any folds with the given ranges.
11757    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11758        &mut self,
11759        ranges: &[Range<T>],
11760        type_id: TypeId,
11761        auto_scroll: bool,
11762        cx: &mut Context<Self>,
11763    ) {
11764        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11765            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11766        });
11767    }
11768
11769    fn remove_folds_with<T: ToOffset + Clone>(
11770        &mut self,
11771        ranges: &[Range<T>],
11772        auto_scroll: bool,
11773        cx: &mut Context<Self>,
11774        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
11775    ) {
11776        if ranges.is_empty() {
11777            return;
11778        }
11779
11780        let mut buffers_affected = HashSet::default();
11781        let multi_buffer = self.buffer().read(cx);
11782        for range in ranges {
11783            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11784                buffers_affected.insert(buffer.read(cx).remote_id());
11785            };
11786        }
11787
11788        self.display_map.update(cx, update);
11789
11790        if auto_scroll {
11791            self.request_autoscroll(Autoscroll::fit(), cx);
11792        }
11793
11794        cx.notify();
11795        self.scrollbar_marker_state.dirty = true;
11796        self.active_indent_guides_state.dirty = true;
11797    }
11798
11799    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
11800        self.display_map.read(cx).fold_placeholder.clone()
11801    }
11802
11803    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
11804        self.buffer.update(cx, |buffer, cx| {
11805            buffer.set_all_diff_hunks_expanded(cx);
11806        });
11807    }
11808
11809    pub fn expand_all_diff_hunks(
11810        &mut self,
11811        _: &ExpandAllHunkDiffs,
11812        _window: &mut Window,
11813        cx: &mut Context<Self>,
11814    ) {
11815        self.buffer.update(cx, |buffer, cx| {
11816            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11817        });
11818    }
11819
11820    pub fn toggle_selected_diff_hunks(
11821        &mut self,
11822        _: &ToggleSelectedDiffHunks,
11823        _window: &mut Window,
11824        cx: &mut Context<Self>,
11825    ) {
11826        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11827        self.toggle_diff_hunks_in_ranges(ranges, cx);
11828    }
11829
11830    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
11831        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11832        self.buffer
11833            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11834    }
11835
11836    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
11837        self.buffer.update(cx, |buffer, cx| {
11838            let ranges = vec![Anchor::min()..Anchor::max()];
11839            if !buffer.all_diff_hunks_expanded()
11840                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11841            {
11842                buffer.collapse_diff_hunks(ranges, cx);
11843                true
11844            } else {
11845                false
11846            }
11847        })
11848    }
11849
11850    fn toggle_diff_hunks_in_ranges(
11851        &mut self,
11852        ranges: Vec<Range<Anchor>>,
11853        cx: &mut Context<'_, Editor>,
11854    ) {
11855        self.buffer.update(cx, |buffer, cx| {
11856            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11857                buffer.collapse_diff_hunks(ranges, cx)
11858            } else {
11859                buffer.expand_diff_hunks(ranges, cx)
11860            }
11861        })
11862    }
11863
11864    pub(crate) fn apply_all_diff_hunks(
11865        &mut self,
11866        _: &ApplyAllDiffHunks,
11867        window: &mut Window,
11868        cx: &mut Context<Self>,
11869    ) {
11870        let buffers = self.buffer.read(cx).all_buffers();
11871        for branch_buffer in buffers {
11872            branch_buffer.update(cx, |branch_buffer, cx| {
11873                branch_buffer.merge_into_base(Vec::new(), cx);
11874            });
11875        }
11876
11877        if let Some(project) = self.project.clone() {
11878            self.save(true, project, window, cx).detach_and_log_err(cx);
11879        }
11880    }
11881
11882    pub(crate) fn apply_selected_diff_hunks(
11883        &mut self,
11884        _: &ApplyDiffHunk,
11885        window: &mut Window,
11886        cx: &mut Context<Self>,
11887    ) {
11888        let snapshot = self.snapshot(window, cx);
11889        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11890        let mut ranges_by_buffer = HashMap::default();
11891        self.transact(window, cx, |editor, _window, cx| {
11892            for hunk in hunks {
11893                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11894                    ranges_by_buffer
11895                        .entry(buffer.clone())
11896                        .or_insert_with(Vec::new)
11897                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11898                }
11899            }
11900
11901            for (buffer, ranges) in ranges_by_buffer {
11902                buffer.update(cx, |buffer, cx| {
11903                    buffer.merge_into_base(ranges, cx);
11904                });
11905            }
11906        });
11907
11908        if let Some(project) = self.project.clone() {
11909            self.save(true, project, window, cx).detach_and_log_err(cx);
11910        }
11911    }
11912
11913    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
11914        if hovered != self.gutter_hovered {
11915            self.gutter_hovered = hovered;
11916            cx.notify();
11917        }
11918    }
11919
11920    pub fn insert_blocks(
11921        &mut self,
11922        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11923        autoscroll: Option<Autoscroll>,
11924        cx: &mut Context<Self>,
11925    ) -> Vec<CustomBlockId> {
11926        let blocks = self
11927            .display_map
11928            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11929        if let Some(autoscroll) = autoscroll {
11930            self.request_autoscroll(autoscroll, cx);
11931        }
11932        cx.notify();
11933        blocks
11934    }
11935
11936    pub fn resize_blocks(
11937        &mut self,
11938        heights: HashMap<CustomBlockId, u32>,
11939        autoscroll: Option<Autoscroll>,
11940        cx: &mut Context<Self>,
11941    ) {
11942        self.display_map
11943            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11944        if let Some(autoscroll) = autoscroll {
11945            self.request_autoscroll(autoscroll, cx);
11946        }
11947        cx.notify();
11948    }
11949
11950    pub fn replace_blocks(
11951        &mut self,
11952        renderers: HashMap<CustomBlockId, RenderBlock>,
11953        autoscroll: Option<Autoscroll>,
11954        cx: &mut Context<Self>,
11955    ) {
11956        self.display_map
11957            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11958        if let Some(autoscroll) = autoscroll {
11959            self.request_autoscroll(autoscroll, cx);
11960        }
11961        cx.notify();
11962    }
11963
11964    pub fn remove_blocks(
11965        &mut self,
11966        block_ids: HashSet<CustomBlockId>,
11967        autoscroll: Option<Autoscroll>,
11968        cx: &mut Context<Self>,
11969    ) {
11970        self.display_map.update(cx, |display_map, cx| {
11971            display_map.remove_blocks(block_ids, cx)
11972        });
11973        if let Some(autoscroll) = autoscroll {
11974            self.request_autoscroll(autoscroll, cx);
11975        }
11976        cx.notify();
11977    }
11978
11979    pub fn row_for_block(
11980        &self,
11981        block_id: CustomBlockId,
11982        cx: &mut Context<Self>,
11983    ) -> Option<DisplayRow> {
11984        self.display_map
11985            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11986    }
11987
11988    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11989        self.focused_block = Some(focused_block);
11990    }
11991
11992    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11993        self.focused_block.take()
11994    }
11995
11996    pub fn insert_creases(
11997        &mut self,
11998        creases: impl IntoIterator<Item = Crease<Anchor>>,
11999        cx: &mut Context<Self>,
12000    ) -> Vec<CreaseId> {
12001        self.display_map
12002            .update(cx, |map, cx| map.insert_creases(creases, cx))
12003    }
12004
12005    pub fn remove_creases(
12006        &mut self,
12007        ids: impl IntoIterator<Item = CreaseId>,
12008        cx: &mut Context<Self>,
12009    ) {
12010        self.display_map
12011            .update(cx, |map, cx| map.remove_creases(ids, cx));
12012    }
12013
12014    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12015        self.display_map
12016            .update(cx, |map, cx| map.snapshot(cx))
12017            .longest_row()
12018    }
12019
12020    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12021        self.display_map
12022            .update(cx, |map, cx| map.snapshot(cx))
12023            .max_point()
12024    }
12025
12026    pub fn text(&self, cx: &App) -> String {
12027        self.buffer.read(cx).read(cx).text()
12028    }
12029
12030    pub fn text_option(&self, cx: &App) -> Option<String> {
12031        let text = self.text(cx);
12032        let text = text.trim();
12033
12034        if text.is_empty() {
12035            return None;
12036        }
12037
12038        Some(text.to_string())
12039    }
12040
12041    pub fn set_text(
12042        &mut self,
12043        text: impl Into<Arc<str>>,
12044        window: &mut Window,
12045        cx: &mut Context<Self>,
12046    ) {
12047        self.transact(window, cx, |this, _, cx| {
12048            this.buffer
12049                .read(cx)
12050                .as_singleton()
12051                .expect("you can only call set_text on editors for singleton buffers")
12052                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12053        });
12054    }
12055
12056    pub fn display_text(&self, cx: &mut App) -> String {
12057        self.display_map
12058            .update(cx, |map, cx| map.snapshot(cx))
12059            .text()
12060    }
12061
12062    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12063        let mut wrap_guides = smallvec::smallvec![];
12064
12065        if self.show_wrap_guides == Some(false) {
12066            return wrap_guides;
12067        }
12068
12069        let settings = self.buffer.read(cx).settings_at(0, cx);
12070        if settings.show_wrap_guides {
12071            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12072                wrap_guides.push((soft_wrap as usize, true));
12073            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12074                wrap_guides.push((soft_wrap as usize, true));
12075            }
12076            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12077        }
12078
12079        wrap_guides
12080    }
12081
12082    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12083        let settings = self.buffer.read(cx).settings_at(0, cx);
12084        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12085        match mode {
12086            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12087                SoftWrap::None
12088            }
12089            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12090            language_settings::SoftWrap::PreferredLineLength => {
12091                SoftWrap::Column(settings.preferred_line_length)
12092            }
12093            language_settings::SoftWrap::Bounded => {
12094                SoftWrap::Bounded(settings.preferred_line_length)
12095            }
12096        }
12097    }
12098
12099    pub fn set_soft_wrap_mode(
12100        &mut self,
12101        mode: language_settings::SoftWrap,
12102
12103        cx: &mut Context<Self>,
12104    ) {
12105        self.soft_wrap_mode_override = Some(mode);
12106        cx.notify();
12107    }
12108
12109    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12110        self.text_style_refinement = Some(style);
12111    }
12112
12113    /// called by the Element so we know what style we were most recently rendered with.
12114    pub(crate) fn set_style(
12115        &mut self,
12116        style: EditorStyle,
12117        window: &mut Window,
12118        cx: &mut Context<Self>,
12119    ) {
12120        let rem_size = window.rem_size();
12121        self.display_map.update(cx, |map, cx| {
12122            map.set_font(
12123                style.text.font(),
12124                style.text.font_size.to_pixels(rem_size),
12125                cx,
12126            )
12127        });
12128        self.style = Some(style);
12129    }
12130
12131    pub fn style(&self) -> Option<&EditorStyle> {
12132        self.style.as_ref()
12133    }
12134
12135    // Called by the element. This method is not designed to be called outside of the editor
12136    // element's layout code because it does not notify when rewrapping is computed synchronously.
12137    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12138        self.display_map
12139            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12140    }
12141
12142    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12143        if self.soft_wrap_mode_override.is_some() {
12144            self.soft_wrap_mode_override.take();
12145        } else {
12146            let soft_wrap = match self.soft_wrap_mode(cx) {
12147                SoftWrap::GitDiff => return,
12148                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12149                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12150                    language_settings::SoftWrap::None
12151                }
12152            };
12153            self.soft_wrap_mode_override = Some(soft_wrap);
12154        }
12155        cx.notify();
12156    }
12157
12158    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12159        let Some(workspace) = self.workspace() else {
12160            return;
12161        };
12162        let fs = workspace.read(cx).app_state().fs.clone();
12163        let current_show = TabBarSettings::get_global(cx).show;
12164        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12165            setting.show = Some(!current_show);
12166        });
12167    }
12168
12169    pub fn toggle_indent_guides(
12170        &mut self,
12171        _: &ToggleIndentGuides,
12172        _: &mut Window,
12173        cx: &mut Context<Self>,
12174    ) {
12175        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12176            self.buffer
12177                .read(cx)
12178                .settings_at(0, cx)
12179                .indent_guides
12180                .enabled
12181        });
12182        self.show_indent_guides = Some(!currently_enabled);
12183        cx.notify();
12184    }
12185
12186    fn should_show_indent_guides(&self) -> Option<bool> {
12187        self.show_indent_guides
12188    }
12189
12190    pub fn toggle_line_numbers(
12191        &mut self,
12192        _: &ToggleLineNumbers,
12193        _: &mut Window,
12194        cx: &mut Context<Self>,
12195    ) {
12196        let mut editor_settings = EditorSettings::get_global(cx).clone();
12197        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12198        EditorSettings::override_global(editor_settings, cx);
12199    }
12200
12201    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12202        self.use_relative_line_numbers
12203            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12204    }
12205
12206    pub fn toggle_relative_line_numbers(
12207        &mut self,
12208        _: &ToggleRelativeLineNumbers,
12209        _: &mut Window,
12210        cx: &mut Context<Self>,
12211    ) {
12212        let is_relative = self.should_use_relative_line_numbers(cx);
12213        self.set_relative_line_number(Some(!is_relative), cx)
12214    }
12215
12216    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12217        self.use_relative_line_numbers = is_relative;
12218        cx.notify();
12219    }
12220
12221    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12222        self.show_gutter = show_gutter;
12223        cx.notify();
12224    }
12225
12226    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12227        self.show_scrollbars = show_scrollbars;
12228        cx.notify();
12229    }
12230
12231    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12232        self.show_line_numbers = Some(show_line_numbers);
12233        cx.notify();
12234    }
12235
12236    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12237        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12238        cx.notify();
12239    }
12240
12241    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12242        self.show_code_actions = Some(show_code_actions);
12243        cx.notify();
12244    }
12245
12246    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12247        self.show_runnables = Some(show_runnables);
12248        cx.notify();
12249    }
12250
12251    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12252        if self.display_map.read(cx).masked != masked {
12253            self.display_map.update(cx, |map, _| map.masked = masked);
12254        }
12255        cx.notify()
12256    }
12257
12258    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12259        self.show_wrap_guides = Some(show_wrap_guides);
12260        cx.notify();
12261    }
12262
12263    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12264        self.show_indent_guides = Some(show_indent_guides);
12265        cx.notify();
12266    }
12267
12268    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12269        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12270            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12271                if let Some(dir) = file.abs_path(cx).parent() {
12272                    return Some(dir.to_owned());
12273                }
12274            }
12275
12276            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12277                return Some(project_path.path.to_path_buf());
12278            }
12279        }
12280
12281        None
12282    }
12283
12284    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12285        self.active_excerpt(cx)?
12286            .1
12287            .read(cx)
12288            .file()
12289            .and_then(|f| f.as_local())
12290    }
12291
12292    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12293        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12294            let project_path = buffer.read(cx).project_path(cx)?;
12295            let project = self.project.as_ref()?.read(cx);
12296            project.absolute_path(&project_path, cx)
12297        })
12298    }
12299
12300    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12301        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12302            let project_path = buffer.read(cx).project_path(cx)?;
12303            let project = self.project.as_ref()?.read(cx);
12304            let entry = project.entry_for_path(&project_path, cx)?;
12305            let path = entry.path.to_path_buf();
12306            Some(path)
12307        })
12308    }
12309
12310    pub fn reveal_in_finder(
12311        &mut self,
12312        _: &RevealInFileManager,
12313        _window: &mut Window,
12314        cx: &mut Context<Self>,
12315    ) {
12316        if let Some(target) = self.target_file(cx) {
12317            cx.reveal_path(&target.abs_path(cx));
12318        }
12319    }
12320
12321    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12322        if let Some(path) = self.target_file_abs_path(cx) {
12323            if let Some(path) = path.to_str() {
12324                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12325            }
12326        }
12327    }
12328
12329    pub fn copy_relative_path(
12330        &mut self,
12331        _: &CopyRelativePath,
12332        _window: &mut Window,
12333        cx: &mut Context<Self>,
12334    ) {
12335        if let Some(path) = self.target_file_path(cx) {
12336            if let Some(path) = path.to_str() {
12337                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12338            }
12339        }
12340    }
12341
12342    pub fn toggle_git_blame(
12343        &mut self,
12344        _: &ToggleGitBlame,
12345        window: &mut Window,
12346        cx: &mut Context<Self>,
12347    ) {
12348        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12349
12350        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12351            self.start_git_blame(true, window, cx);
12352        }
12353
12354        cx.notify();
12355    }
12356
12357    pub fn toggle_git_blame_inline(
12358        &mut self,
12359        _: &ToggleGitBlameInline,
12360        window: &mut Window,
12361        cx: &mut Context<Self>,
12362    ) {
12363        self.toggle_git_blame_inline_internal(true, window, cx);
12364        cx.notify();
12365    }
12366
12367    pub fn git_blame_inline_enabled(&self) -> bool {
12368        self.git_blame_inline_enabled
12369    }
12370
12371    pub fn toggle_selection_menu(
12372        &mut self,
12373        _: &ToggleSelectionMenu,
12374        _: &mut Window,
12375        cx: &mut Context<Self>,
12376    ) {
12377        self.show_selection_menu = self
12378            .show_selection_menu
12379            .map(|show_selections_menu| !show_selections_menu)
12380            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12381
12382        cx.notify();
12383    }
12384
12385    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12386        self.show_selection_menu
12387            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12388    }
12389
12390    fn start_git_blame(
12391        &mut self,
12392        user_triggered: bool,
12393        window: &mut Window,
12394        cx: &mut Context<Self>,
12395    ) {
12396        if let Some(project) = self.project.as_ref() {
12397            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12398                return;
12399            };
12400
12401            if buffer.read(cx).file().is_none() {
12402                return;
12403            }
12404
12405            let focused = self.focus_handle(cx).contains_focused(window, cx);
12406
12407            let project = project.clone();
12408            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12409            self.blame_subscription =
12410                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12411            self.blame = Some(blame);
12412        }
12413    }
12414
12415    fn toggle_git_blame_inline_internal(
12416        &mut self,
12417        user_triggered: bool,
12418        window: &mut Window,
12419        cx: &mut Context<Self>,
12420    ) {
12421        if self.git_blame_inline_enabled {
12422            self.git_blame_inline_enabled = false;
12423            self.show_git_blame_inline = false;
12424            self.show_git_blame_inline_delay_task.take();
12425        } else {
12426            self.git_blame_inline_enabled = true;
12427            self.start_git_blame_inline(user_triggered, window, cx);
12428        }
12429
12430        cx.notify();
12431    }
12432
12433    fn start_git_blame_inline(
12434        &mut self,
12435        user_triggered: bool,
12436        window: &mut Window,
12437        cx: &mut Context<Self>,
12438    ) {
12439        self.start_git_blame(user_triggered, window, cx);
12440
12441        if ProjectSettings::get_global(cx)
12442            .git
12443            .inline_blame_delay()
12444            .is_some()
12445        {
12446            self.start_inline_blame_timer(window, cx);
12447        } else {
12448            self.show_git_blame_inline = true
12449        }
12450    }
12451
12452    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12453        self.blame.as_ref()
12454    }
12455
12456    pub fn show_git_blame_gutter(&self) -> bool {
12457        self.show_git_blame_gutter
12458    }
12459
12460    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12461        self.show_git_blame_gutter && self.has_blame_entries(cx)
12462    }
12463
12464    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12465        self.show_git_blame_inline
12466            && self.focus_handle.is_focused(window)
12467            && !self.newest_selection_head_on_empty_line(cx)
12468            && self.has_blame_entries(cx)
12469    }
12470
12471    fn has_blame_entries(&self, cx: &App) -> bool {
12472        self.blame()
12473            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12474    }
12475
12476    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12477        let cursor_anchor = self.selections.newest_anchor().head();
12478
12479        let snapshot = self.buffer.read(cx).snapshot(cx);
12480        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12481
12482        snapshot.line_len(buffer_row) == 0
12483    }
12484
12485    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12486        let buffer_and_selection = maybe!({
12487            let selection = self.selections.newest::<Point>(cx);
12488            let selection_range = selection.range();
12489
12490            let multi_buffer = self.buffer().read(cx);
12491            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12492            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12493
12494            let (buffer, range, _) = if selection.reversed {
12495                buffer_ranges.first()
12496            } else {
12497                buffer_ranges.last()
12498            }?;
12499
12500            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12501                ..text::ToPoint::to_point(&range.end, &buffer).row;
12502            Some((
12503                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12504                selection,
12505            ))
12506        });
12507
12508        let Some((buffer, selection)) = buffer_and_selection else {
12509            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12510        };
12511
12512        let Some(project) = self.project.as_ref() else {
12513            return Task::ready(Err(anyhow!("editor does not have project")));
12514        };
12515
12516        project.update(cx, |project, cx| {
12517            project.get_permalink_to_line(&buffer, selection, cx)
12518        })
12519    }
12520
12521    pub fn copy_permalink_to_line(
12522        &mut self,
12523        _: &CopyPermalinkToLine,
12524        window: &mut Window,
12525        cx: &mut Context<Self>,
12526    ) {
12527        let permalink_task = self.get_permalink_to_line(cx);
12528        let workspace = self.workspace();
12529
12530        cx.spawn_in(window, |_, mut cx| async move {
12531            match permalink_task.await {
12532                Ok(permalink) => {
12533                    cx.update(|_, cx| {
12534                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12535                    })
12536                    .ok();
12537                }
12538                Err(err) => {
12539                    let message = format!("Failed to copy permalink: {err}");
12540
12541                    Err::<(), anyhow::Error>(err).log_err();
12542
12543                    if let Some(workspace) = workspace {
12544                        workspace
12545                            .update_in(&mut cx, |workspace, _, cx| {
12546                                struct CopyPermalinkToLine;
12547
12548                                workspace.show_toast(
12549                                    Toast::new(
12550                                        NotificationId::unique::<CopyPermalinkToLine>(),
12551                                        message,
12552                                    ),
12553                                    cx,
12554                                )
12555                            })
12556                            .ok();
12557                    }
12558                }
12559            }
12560        })
12561        .detach();
12562    }
12563
12564    pub fn copy_file_location(
12565        &mut self,
12566        _: &CopyFileLocation,
12567        _: &mut Window,
12568        cx: &mut Context<Self>,
12569    ) {
12570        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12571        if let Some(file) = self.target_file(cx) {
12572            if let Some(path) = file.path().to_str() {
12573                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12574            }
12575        }
12576    }
12577
12578    pub fn open_permalink_to_line(
12579        &mut self,
12580        _: &OpenPermalinkToLine,
12581        window: &mut Window,
12582        cx: &mut Context<Self>,
12583    ) {
12584        let permalink_task = self.get_permalink_to_line(cx);
12585        let workspace = self.workspace();
12586
12587        cx.spawn_in(window, |_, mut cx| async move {
12588            match permalink_task.await {
12589                Ok(permalink) => {
12590                    cx.update(|_, cx| {
12591                        cx.open_url(permalink.as_ref());
12592                    })
12593                    .ok();
12594                }
12595                Err(err) => {
12596                    let message = format!("Failed to open permalink: {err}");
12597
12598                    Err::<(), anyhow::Error>(err).log_err();
12599
12600                    if let Some(workspace) = workspace {
12601                        workspace
12602                            .update(&mut cx, |workspace, cx| {
12603                                struct OpenPermalinkToLine;
12604
12605                                workspace.show_toast(
12606                                    Toast::new(
12607                                        NotificationId::unique::<OpenPermalinkToLine>(),
12608                                        message,
12609                                    ),
12610                                    cx,
12611                                )
12612                            })
12613                            .ok();
12614                    }
12615                }
12616            }
12617        })
12618        .detach();
12619    }
12620
12621    pub fn insert_uuid_v4(
12622        &mut self,
12623        _: &InsertUuidV4,
12624        window: &mut Window,
12625        cx: &mut Context<Self>,
12626    ) {
12627        self.insert_uuid(UuidVersion::V4, window, cx);
12628    }
12629
12630    pub fn insert_uuid_v7(
12631        &mut self,
12632        _: &InsertUuidV7,
12633        window: &mut Window,
12634        cx: &mut Context<Self>,
12635    ) {
12636        self.insert_uuid(UuidVersion::V7, window, cx);
12637    }
12638
12639    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12640        self.transact(window, cx, |this, window, cx| {
12641            let edits = this
12642                .selections
12643                .all::<Point>(cx)
12644                .into_iter()
12645                .map(|selection| {
12646                    let uuid = match version {
12647                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12648                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12649                    };
12650
12651                    (selection.range(), uuid.to_string())
12652                });
12653            this.edit(edits, cx);
12654            this.refresh_inline_completion(true, false, window, cx);
12655        });
12656    }
12657
12658    pub fn open_selections_in_multibuffer(
12659        &mut self,
12660        _: &OpenSelectionsInMultibuffer,
12661        window: &mut Window,
12662        cx: &mut Context<Self>,
12663    ) {
12664        let multibuffer = self.buffer.read(cx);
12665
12666        let Some(buffer) = multibuffer.as_singleton() else {
12667            return;
12668        };
12669
12670        let Some(workspace) = self.workspace() else {
12671            return;
12672        };
12673
12674        let locations = self
12675            .selections
12676            .disjoint_anchors()
12677            .iter()
12678            .map(|range| Location {
12679                buffer: buffer.clone(),
12680                range: range.start.text_anchor..range.end.text_anchor,
12681            })
12682            .collect::<Vec<_>>();
12683
12684        let title = multibuffer.title(cx).to_string();
12685
12686        cx.spawn_in(window, |_, mut cx| async move {
12687            workspace.update_in(&mut cx, |workspace, window, cx| {
12688                Self::open_locations_in_multibuffer(
12689                    workspace,
12690                    locations,
12691                    format!("Selections for '{title}'"),
12692                    false,
12693                    MultibufferSelectionMode::All,
12694                    window,
12695                    cx,
12696                );
12697            })
12698        })
12699        .detach();
12700    }
12701
12702    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12703    /// last highlight added will be used.
12704    ///
12705    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12706    pub fn highlight_rows<T: 'static>(
12707        &mut self,
12708        range: Range<Anchor>,
12709        color: Hsla,
12710        should_autoscroll: bool,
12711        cx: &mut Context<Self>,
12712    ) {
12713        let snapshot = self.buffer().read(cx).snapshot(cx);
12714        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12715        let ix = row_highlights.binary_search_by(|highlight| {
12716            Ordering::Equal
12717                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12718                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12719        });
12720
12721        if let Err(mut ix) = ix {
12722            let index = post_inc(&mut self.highlight_order);
12723
12724            // If this range intersects with the preceding highlight, then merge it with
12725            // the preceding highlight. Otherwise insert a new highlight.
12726            let mut merged = false;
12727            if ix > 0 {
12728                let prev_highlight = &mut row_highlights[ix - 1];
12729                if prev_highlight
12730                    .range
12731                    .end
12732                    .cmp(&range.start, &snapshot)
12733                    .is_ge()
12734                {
12735                    ix -= 1;
12736                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12737                        prev_highlight.range.end = range.end;
12738                    }
12739                    merged = true;
12740                    prev_highlight.index = index;
12741                    prev_highlight.color = color;
12742                    prev_highlight.should_autoscroll = should_autoscroll;
12743                }
12744            }
12745
12746            if !merged {
12747                row_highlights.insert(
12748                    ix,
12749                    RowHighlight {
12750                        range: range.clone(),
12751                        index,
12752                        color,
12753                        should_autoscroll,
12754                    },
12755                );
12756            }
12757
12758            // If any of the following highlights intersect with this one, merge them.
12759            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12760                let highlight = &row_highlights[ix];
12761                if next_highlight
12762                    .range
12763                    .start
12764                    .cmp(&highlight.range.end, &snapshot)
12765                    .is_le()
12766                {
12767                    if next_highlight
12768                        .range
12769                        .end
12770                        .cmp(&highlight.range.end, &snapshot)
12771                        .is_gt()
12772                    {
12773                        row_highlights[ix].range.end = next_highlight.range.end;
12774                    }
12775                    row_highlights.remove(ix + 1);
12776                } else {
12777                    break;
12778                }
12779            }
12780        }
12781    }
12782
12783    /// Remove any highlighted row ranges of the given type that intersect the
12784    /// given ranges.
12785    pub fn remove_highlighted_rows<T: 'static>(
12786        &mut self,
12787        ranges_to_remove: Vec<Range<Anchor>>,
12788        cx: &mut Context<Self>,
12789    ) {
12790        let snapshot = self.buffer().read(cx).snapshot(cx);
12791        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12792        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12793        row_highlights.retain(|highlight| {
12794            while let Some(range_to_remove) = ranges_to_remove.peek() {
12795                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12796                    Ordering::Less | Ordering::Equal => {
12797                        ranges_to_remove.next();
12798                    }
12799                    Ordering::Greater => {
12800                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12801                            Ordering::Less | Ordering::Equal => {
12802                                return false;
12803                            }
12804                            Ordering::Greater => break,
12805                        }
12806                    }
12807                }
12808            }
12809
12810            true
12811        })
12812    }
12813
12814    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12815    pub fn clear_row_highlights<T: 'static>(&mut self) {
12816        self.highlighted_rows.remove(&TypeId::of::<T>());
12817    }
12818
12819    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12820    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12821        self.highlighted_rows
12822            .get(&TypeId::of::<T>())
12823            .map_or(&[] as &[_], |vec| vec.as_slice())
12824            .iter()
12825            .map(|highlight| (highlight.range.clone(), highlight.color))
12826    }
12827
12828    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12829    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12830    /// Allows to ignore certain kinds of highlights.
12831    pub fn highlighted_display_rows(
12832        &self,
12833        window: &mut Window,
12834        cx: &mut App,
12835    ) -> BTreeMap<DisplayRow, Hsla> {
12836        let snapshot = self.snapshot(window, cx);
12837        let mut used_highlight_orders = HashMap::default();
12838        self.highlighted_rows
12839            .iter()
12840            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12841            .fold(
12842                BTreeMap::<DisplayRow, Hsla>::new(),
12843                |mut unique_rows, highlight| {
12844                    let start = highlight.range.start.to_display_point(&snapshot);
12845                    let end = highlight.range.end.to_display_point(&snapshot);
12846                    let start_row = start.row().0;
12847                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12848                        && end.column() == 0
12849                    {
12850                        end.row().0.saturating_sub(1)
12851                    } else {
12852                        end.row().0
12853                    };
12854                    for row in start_row..=end_row {
12855                        let used_index =
12856                            used_highlight_orders.entry(row).or_insert(highlight.index);
12857                        if highlight.index >= *used_index {
12858                            *used_index = highlight.index;
12859                            unique_rows.insert(DisplayRow(row), highlight.color);
12860                        }
12861                    }
12862                    unique_rows
12863                },
12864            )
12865    }
12866
12867    pub fn highlighted_display_row_for_autoscroll(
12868        &self,
12869        snapshot: &DisplaySnapshot,
12870    ) -> Option<DisplayRow> {
12871        self.highlighted_rows
12872            .values()
12873            .flat_map(|highlighted_rows| highlighted_rows.iter())
12874            .filter_map(|highlight| {
12875                if highlight.should_autoscroll {
12876                    Some(highlight.range.start.to_display_point(snapshot).row())
12877                } else {
12878                    None
12879                }
12880            })
12881            .min()
12882    }
12883
12884    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
12885        self.highlight_background::<SearchWithinRange>(
12886            ranges,
12887            |colors| colors.editor_document_highlight_read_background,
12888            cx,
12889        )
12890    }
12891
12892    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12893        self.breadcrumb_header = Some(new_header);
12894    }
12895
12896    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
12897        self.clear_background_highlights::<SearchWithinRange>(cx);
12898    }
12899
12900    pub fn highlight_background<T: 'static>(
12901        &mut self,
12902        ranges: &[Range<Anchor>],
12903        color_fetcher: fn(&ThemeColors) -> Hsla,
12904        cx: &mut Context<Self>,
12905    ) {
12906        self.background_highlights
12907            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12908        self.scrollbar_marker_state.dirty = true;
12909        cx.notify();
12910    }
12911
12912    pub fn clear_background_highlights<T: 'static>(
12913        &mut self,
12914        cx: &mut Context<Self>,
12915    ) -> Option<BackgroundHighlight> {
12916        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12917        if !text_highlights.1.is_empty() {
12918            self.scrollbar_marker_state.dirty = true;
12919            cx.notify();
12920        }
12921        Some(text_highlights)
12922    }
12923
12924    pub fn highlight_gutter<T: 'static>(
12925        &mut self,
12926        ranges: &[Range<Anchor>],
12927        color_fetcher: fn(&App) -> Hsla,
12928        cx: &mut Context<Self>,
12929    ) {
12930        self.gutter_highlights
12931            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12932        cx.notify();
12933    }
12934
12935    pub fn clear_gutter_highlights<T: 'static>(
12936        &mut self,
12937        cx: &mut Context<Self>,
12938    ) -> Option<GutterHighlight> {
12939        cx.notify();
12940        self.gutter_highlights.remove(&TypeId::of::<T>())
12941    }
12942
12943    #[cfg(feature = "test-support")]
12944    pub fn all_text_background_highlights(
12945        &self,
12946        window: &mut Window,
12947        cx: &mut Context<Self>,
12948    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12949        let snapshot = self.snapshot(window, cx);
12950        let buffer = &snapshot.buffer_snapshot;
12951        let start = buffer.anchor_before(0);
12952        let end = buffer.anchor_after(buffer.len());
12953        let theme = cx.theme().colors();
12954        self.background_highlights_in_range(start..end, &snapshot, theme)
12955    }
12956
12957    #[cfg(feature = "test-support")]
12958    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
12959        let snapshot = self.buffer().read(cx).snapshot(cx);
12960
12961        let highlights = self
12962            .background_highlights
12963            .get(&TypeId::of::<items::BufferSearchHighlights>());
12964
12965        if let Some((_color, ranges)) = highlights {
12966            ranges
12967                .iter()
12968                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12969                .collect_vec()
12970        } else {
12971            vec![]
12972        }
12973    }
12974
12975    fn document_highlights_for_position<'a>(
12976        &'a self,
12977        position: Anchor,
12978        buffer: &'a MultiBufferSnapshot,
12979    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12980        let read_highlights = self
12981            .background_highlights
12982            .get(&TypeId::of::<DocumentHighlightRead>())
12983            .map(|h| &h.1);
12984        let write_highlights = self
12985            .background_highlights
12986            .get(&TypeId::of::<DocumentHighlightWrite>())
12987            .map(|h| &h.1);
12988        let left_position = position.bias_left(buffer);
12989        let right_position = position.bias_right(buffer);
12990        read_highlights
12991            .into_iter()
12992            .chain(write_highlights)
12993            .flat_map(move |ranges| {
12994                let start_ix = match ranges.binary_search_by(|probe| {
12995                    let cmp = probe.end.cmp(&left_position, buffer);
12996                    if cmp.is_ge() {
12997                        Ordering::Greater
12998                    } else {
12999                        Ordering::Less
13000                    }
13001                }) {
13002                    Ok(i) | Err(i) => i,
13003                };
13004
13005                ranges[start_ix..]
13006                    .iter()
13007                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13008            })
13009    }
13010
13011    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13012        self.background_highlights
13013            .get(&TypeId::of::<T>())
13014            .map_or(false, |(_, highlights)| !highlights.is_empty())
13015    }
13016
13017    pub fn background_highlights_in_range(
13018        &self,
13019        search_range: Range<Anchor>,
13020        display_snapshot: &DisplaySnapshot,
13021        theme: &ThemeColors,
13022    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13023        let mut results = Vec::new();
13024        for (color_fetcher, ranges) in self.background_highlights.values() {
13025            let color = color_fetcher(theme);
13026            let start_ix = match ranges.binary_search_by(|probe| {
13027                let cmp = probe
13028                    .end
13029                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13030                if cmp.is_gt() {
13031                    Ordering::Greater
13032                } else {
13033                    Ordering::Less
13034                }
13035            }) {
13036                Ok(i) | Err(i) => i,
13037            };
13038            for range in &ranges[start_ix..] {
13039                if range
13040                    .start
13041                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13042                    .is_ge()
13043                {
13044                    break;
13045                }
13046
13047                let start = range.start.to_display_point(display_snapshot);
13048                let end = range.end.to_display_point(display_snapshot);
13049                results.push((start..end, color))
13050            }
13051        }
13052        results
13053    }
13054
13055    pub fn background_highlight_row_ranges<T: 'static>(
13056        &self,
13057        search_range: Range<Anchor>,
13058        display_snapshot: &DisplaySnapshot,
13059        count: usize,
13060    ) -> Vec<RangeInclusive<DisplayPoint>> {
13061        let mut results = Vec::new();
13062        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13063            return vec![];
13064        };
13065
13066        let start_ix = match ranges.binary_search_by(|probe| {
13067            let cmp = probe
13068                .end
13069                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13070            if cmp.is_gt() {
13071                Ordering::Greater
13072            } else {
13073                Ordering::Less
13074            }
13075        }) {
13076            Ok(i) | Err(i) => i,
13077        };
13078        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13079            if let (Some(start_display), Some(end_display)) = (start, end) {
13080                results.push(
13081                    start_display.to_display_point(display_snapshot)
13082                        ..=end_display.to_display_point(display_snapshot),
13083                );
13084            }
13085        };
13086        let mut start_row: Option<Point> = None;
13087        let mut end_row: Option<Point> = None;
13088        if ranges.len() > count {
13089            return Vec::new();
13090        }
13091        for range in &ranges[start_ix..] {
13092            if range
13093                .start
13094                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13095                .is_ge()
13096            {
13097                break;
13098            }
13099            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13100            if let Some(current_row) = &end_row {
13101                if end.row == current_row.row {
13102                    continue;
13103                }
13104            }
13105            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13106            if start_row.is_none() {
13107                assert_eq!(end_row, None);
13108                start_row = Some(start);
13109                end_row = Some(end);
13110                continue;
13111            }
13112            if let Some(current_end) = end_row.as_mut() {
13113                if start.row > current_end.row + 1 {
13114                    push_region(start_row, end_row);
13115                    start_row = Some(start);
13116                    end_row = Some(end);
13117                } else {
13118                    // Merge two hunks.
13119                    *current_end = end;
13120                }
13121            } else {
13122                unreachable!();
13123            }
13124        }
13125        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13126        push_region(start_row, end_row);
13127        results
13128    }
13129
13130    pub fn gutter_highlights_in_range(
13131        &self,
13132        search_range: Range<Anchor>,
13133        display_snapshot: &DisplaySnapshot,
13134        cx: &App,
13135    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13136        let mut results = Vec::new();
13137        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13138            let color = color_fetcher(cx);
13139            let start_ix = match ranges.binary_search_by(|probe| {
13140                let cmp = probe
13141                    .end
13142                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13143                if cmp.is_gt() {
13144                    Ordering::Greater
13145                } else {
13146                    Ordering::Less
13147                }
13148            }) {
13149                Ok(i) | Err(i) => i,
13150            };
13151            for range in &ranges[start_ix..] {
13152                if range
13153                    .start
13154                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13155                    .is_ge()
13156                {
13157                    break;
13158                }
13159
13160                let start = range.start.to_display_point(display_snapshot);
13161                let end = range.end.to_display_point(display_snapshot);
13162                results.push((start..end, color))
13163            }
13164        }
13165        results
13166    }
13167
13168    /// Get the text ranges corresponding to the redaction query
13169    pub fn redacted_ranges(
13170        &self,
13171        search_range: Range<Anchor>,
13172        display_snapshot: &DisplaySnapshot,
13173        cx: &App,
13174    ) -> Vec<Range<DisplayPoint>> {
13175        display_snapshot
13176            .buffer_snapshot
13177            .redacted_ranges(search_range, |file| {
13178                if let Some(file) = file {
13179                    file.is_private()
13180                        && EditorSettings::get(
13181                            Some(SettingsLocation {
13182                                worktree_id: file.worktree_id(cx),
13183                                path: file.path().as_ref(),
13184                            }),
13185                            cx,
13186                        )
13187                        .redact_private_values
13188                } else {
13189                    false
13190                }
13191            })
13192            .map(|range| {
13193                range.start.to_display_point(display_snapshot)
13194                    ..range.end.to_display_point(display_snapshot)
13195            })
13196            .collect()
13197    }
13198
13199    pub fn highlight_text<T: 'static>(
13200        &mut self,
13201        ranges: Vec<Range<Anchor>>,
13202        style: HighlightStyle,
13203        cx: &mut Context<Self>,
13204    ) {
13205        self.display_map.update(cx, |map, _| {
13206            map.highlight_text(TypeId::of::<T>(), ranges, style)
13207        });
13208        cx.notify();
13209    }
13210
13211    pub(crate) fn highlight_inlays<T: 'static>(
13212        &mut self,
13213        highlights: Vec<InlayHighlight>,
13214        style: HighlightStyle,
13215        cx: &mut Context<Self>,
13216    ) {
13217        self.display_map.update(cx, |map, _| {
13218            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13219        });
13220        cx.notify();
13221    }
13222
13223    pub fn text_highlights<'a, T: 'static>(
13224        &'a self,
13225        cx: &'a App,
13226    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13227        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13228    }
13229
13230    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13231        let cleared = self
13232            .display_map
13233            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13234        if cleared {
13235            cx.notify();
13236        }
13237    }
13238
13239    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13240        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13241            && self.focus_handle.is_focused(window)
13242    }
13243
13244    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13245        self.show_cursor_when_unfocused = is_enabled;
13246        cx.notify();
13247    }
13248
13249    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13250        self.project
13251            .as_ref()
13252            .map(|project| project.read(cx).lsp_store())
13253    }
13254
13255    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13256        cx.notify();
13257    }
13258
13259    fn on_buffer_event(
13260        &mut self,
13261        multibuffer: &Entity<MultiBuffer>,
13262        event: &multi_buffer::Event,
13263        window: &mut Window,
13264        cx: &mut Context<Self>,
13265    ) {
13266        match event {
13267            multi_buffer::Event::Edited {
13268                singleton_buffer_edited,
13269                edited_buffer: buffer_edited,
13270            } => {
13271                self.scrollbar_marker_state.dirty = true;
13272                self.active_indent_guides_state.dirty = true;
13273                self.refresh_active_diagnostics(cx);
13274                self.refresh_code_actions(window, cx);
13275                if self.has_active_inline_completion() {
13276                    self.update_visible_inline_completion(window, cx);
13277                }
13278                if let Some(buffer) = buffer_edited {
13279                    let buffer_id = buffer.read(cx).remote_id();
13280                    if !self.registered_buffers.contains_key(&buffer_id) {
13281                        if let Some(lsp_store) = self.lsp_store(cx) {
13282                            lsp_store.update(cx, |lsp_store, cx| {
13283                                self.registered_buffers.insert(
13284                                    buffer_id,
13285                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13286                                );
13287                            })
13288                        }
13289                    }
13290                }
13291                cx.emit(EditorEvent::BufferEdited);
13292                cx.emit(SearchEvent::MatchesInvalidated);
13293                if *singleton_buffer_edited {
13294                    if let Some(project) = &self.project {
13295                        let project = project.read(cx);
13296                        #[allow(clippy::mutable_key_type)]
13297                        let languages_affected = multibuffer
13298                            .read(cx)
13299                            .all_buffers()
13300                            .into_iter()
13301                            .filter_map(|buffer| {
13302                                let buffer = buffer.read(cx);
13303                                let language = buffer.language()?;
13304                                if project.is_local()
13305                                    && project
13306                                        .language_servers_for_local_buffer(buffer, cx)
13307                                        .count()
13308                                        == 0
13309                                {
13310                                    None
13311                                } else {
13312                                    Some(language)
13313                                }
13314                            })
13315                            .cloned()
13316                            .collect::<HashSet<_>>();
13317                        if !languages_affected.is_empty() {
13318                            self.refresh_inlay_hints(
13319                                InlayHintRefreshReason::BufferEdited(languages_affected),
13320                                cx,
13321                            );
13322                        }
13323                    }
13324                }
13325
13326                let Some(project) = &self.project else { return };
13327                let (telemetry, is_via_ssh) = {
13328                    let project = project.read(cx);
13329                    let telemetry = project.client().telemetry().clone();
13330                    let is_via_ssh = project.is_via_ssh();
13331                    (telemetry, is_via_ssh)
13332                };
13333                refresh_linked_ranges(self, window, cx);
13334                telemetry.log_edit_event("editor", is_via_ssh);
13335            }
13336            multi_buffer::Event::ExcerptsAdded {
13337                buffer,
13338                predecessor,
13339                excerpts,
13340            } => {
13341                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13342                let buffer_id = buffer.read(cx).remote_id();
13343                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13344                    if let Some(project) = &self.project {
13345                        get_unstaged_changes_for_buffers(
13346                            project,
13347                            [buffer.clone()],
13348                            self.buffer.clone(),
13349                            cx,
13350                        );
13351                    }
13352                }
13353                cx.emit(EditorEvent::ExcerptsAdded {
13354                    buffer: buffer.clone(),
13355                    predecessor: *predecessor,
13356                    excerpts: excerpts.clone(),
13357                });
13358                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13359            }
13360            multi_buffer::Event::ExcerptsRemoved { ids } => {
13361                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13362                let buffer = self.buffer.read(cx);
13363                self.registered_buffers
13364                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13365                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13366            }
13367            multi_buffer::Event::ExcerptsEdited { ids } => {
13368                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13369            }
13370            multi_buffer::Event::ExcerptsExpanded { ids } => {
13371                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13372                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13373            }
13374            multi_buffer::Event::Reparsed(buffer_id) => {
13375                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13376
13377                cx.emit(EditorEvent::Reparsed(*buffer_id));
13378            }
13379            multi_buffer::Event::DiffHunksToggled => {
13380                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13381            }
13382            multi_buffer::Event::LanguageChanged(buffer_id) => {
13383                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13384                cx.emit(EditorEvent::Reparsed(*buffer_id));
13385                cx.notify();
13386            }
13387            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13388            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13389            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13390                cx.emit(EditorEvent::TitleChanged)
13391            }
13392            // multi_buffer::Event::DiffBaseChanged => {
13393            //     self.scrollbar_marker_state.dirty = true;
13394            //     cx.emit(EditorEvent::DiffBaseChanged);
13395            //     cx.notify();
13396            // }
13397            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13398            multi_buffer::Event::DiagnosticsUpdated => {
13399                self.refresh_active_diagnostics(cx);
13400                self.scrollbar_marker_state.dirty = true;
13401                cx.notify();
13402            }
13403            _ => {}
13404        };
13405    }
13406
13407    fn on_display_map_changed(
13408        &mut self,
13409        _: Entity<DisplayMap>,
13410        _: &mut Window,
13411        cx: &mut Context<Self>,
13412    ) {
13413        cx.notify();
13414    }
13415
13416    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13417        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13418        self.refresh_inline_completion(true, false, window, cx);
13419        self.refresh_inlay_hints(
13420            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13421                self.selections.newest_anchor().head(),
13422                &self.buffer.read(cx).snapshot(cx),
13423                cx,
13424            )),
13425            cx,
13426        );
13427
13428        let old_cursor_shape = self.cursor_shape;
13429
13430        {
13431            let editor_settings = EditorSettings::get_global(cx);
13432            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13433            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13434            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13435        }
13436
13437        if old_cursor_shape != self.cursor_shape {
13438            cx.emit(EditorEvent::CursorShapeChanged);
13439        }
13440
13441        let project_settings = ProjectSettings::get_global(cx);
13442        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13443
13444        if self.mode == EditorMode::Full {
13445            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13446            if self.git_blame_inline_enabled != inline_blame_enabled {
13447                self.toggle_git_blame_inline_internal(false, window, cx);
13448            }
13449        }
13450
13451        cx.notify();
13452    }
13453
13454    pub fn set_searchable(&mut self, searchable: bool) {
13455        self.searchable = searchable;
13456    }
13457
13458    pub fn searchable(&self) -> bool {
13459        self.searchable
13460    }
13461
13462    fn open_proposed_changes_editor(
13463        &mut self,
13464        _: &OpenProposedChangesEditor,
13465        window: &mut Window,
13466        cx: &mut Context<Self>,
13467    ) {
13468        let Some(workspace) = self.workspace() else {
13469            cx.propagate();
13470            return;
13471        };
13472
13473        let selections = self.selections.all::<usize>(cx);
13474        let multi_buffer = self.buffer.read(cx);
13475        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13476        let mut new_selections_by_buffer = HashMap::default();
13477        for selection in selections {
13478            for (buffer, range, _) in
13479                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13480            {
13481                let mut range = range.to_point(buffer);
13482                range.start.column = 0;
13483                range.end.column = buffer.line_len(range.end.row);
13484                new_selections_by_buffer
13485                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13486                    .or_insert(Vec::new())
13487                    .push(range)
13488            }
13489        }
13490
13491        let proposed_changes_buffers = new_selections_by_buffer
13492            .into_iter()
13493            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13494            .collect::<Vec<_>>();
13495        let proposed_changes_editor = cx.new(|cx| {
13496            ProposedChangesEditor::new(
13497                "Proposed changes",
13498                proposed_changes_buffers,
13499                self.project.clone(),
13500                window,
13501                cx,
13502            )
13503        });
13504
13505        window.defer(cx, move |window, cx| {
13506            workspace.update(cx, |workspace, cx| {
13507                workspace.active_pane().update(cx, |pane, cx| {
13508                    pane.add_item(
13509                        Box::new(proposed_changes_editor),
13510                        true,
13511                        true,
13512                        None,
13513                        window,
13514                        cx,
13515                    );
13516                });
13517            });
13518        });
13519    }
13520
13521    pub fn open_excerpts_in_split(
13522        &mut self,
13523        _: &OpenExcerptsSplit,
13524        window: &mut Window,
13525        cx: &mut Context<Self>,
13526    ) {
13527        self.open_excerpts_common(None, true, window, cx)
13528    }
13529
13530    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13531        self.open_excerpts_common(None, false, window, cx)
13532    }
13533
13534    fn open_excerpts_common(
13535        &mut self,
13536        jump_data: Option<JumpData>,
13537        split: bool,
13538        window: &mut Window,
13539        cx: &mut Context<Self>,
13540    ) {
13541        let Some(workspace) = self.workspace() else {
13542            cx.propagate();
13543            return;
13544        };
13545
13546        if self.buffer.read(cx).is_singleton() {
13547            cx.propagate();
13548            return;
13549        }
13550
13551        let mut new_selections_by_buffer = HashMap::default();
13552        match &jump_data {
13553            Some(JumpData::MultiBufferPoint {
13554                excerpt_id,
13555                position,
13556                anchor,
13557                line_offset_from_top,
13558            }) => {
13559                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13560                if let Some(buffer) = multi_buffer_snapshot
13561                    .buffer_id_for_excerpt(*excerpt_id)
13562                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13563                {
13564                    let buffer_snapshot = buffer.read(cx).snapshot();
13565                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13566                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13567                    } else {
13568                        buffer_snapshot.clip_point(*position, Bias::Left)
13569                    };
13570                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13571                    new_selections_by_buffer.insert(
13572                        buffer,
13573                        (
13574                            vec![jump_to_offset..jump_to_offset],
13575                            Some(*line_offset_from_top),
13576                        ),
13577                    );
13578                }
13579            }
13580            Some(JumpData::MultiBufferRow {
13581                row,
13582                line_offset_from_top,
13583            }) => {
13584                let point = MultiBufferPoint::new(row.0, 0);
13585                if let Some((buffer, buffer_point, _)) =
13586                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13587                {
13588                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13589                    new_selections_by_buffer
13590                        .entry(buffer)
13591                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13592                        .0
13593                        .push(buffer_offset..buffer_offset)
13594                }
13595            }
13596            None => {
13597                let selections = self.selections.all::<usize>(cx);
13598                let multi_buffer = self.buffer.read(cx);
13599                for selection in selections {
13600                    for (buffer, mut range, _) in multi_buffer
13601                        .snapshot(cx)
13602                        .range_to_buffer_ranges(selection.range())
13603                    {
13604                        // When editing branch buffers, jump to the corresponding location
13605                        // in their base buffer.
13606                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13607                        let buffer = buffer_handle.read(cx);
13608                        if let Some(base_buffer) = buffer.base_buffer() {
13609                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13610                            buffer_handle = base_buffer;
13611                        }
13612
13613                        if selection.reversed {
13614                            mem::swap(&mut range.start, &mut range.end);
13615                        }
13616                        new_selections_by_buffer
13617                            .entry(buffer_handle)
13618                            .or_insert((Vec::new(), None))
13619                            .0
13620                            .push(range)
13621                    }
13622                }
13623            }
13624        }
13625
13626        if new_selections_by_buffer.is_empty() {
13627            return;
13628        }
13629
13630        // We defer the pane interaction because we ourselves are a workspace item
13631        // and activating a new item causes the pane to call a method on us reentrantly,
13632        // which panics if we're on the stack.
13633        window.defer(cx, move |window, cx| {
13634            workspace.update(cx, |workspace, cx| {
13635                let pane = if split {
13636                    workspace.adjacent_pane(window, cx)
13637                } else {
13638                    workspace.active_pane().clone()
13639                };
13640
13641                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13642                    let editor = buffer
13643                        .read(cx)
13644                        .file()
13645                        .is_none()
13646                        .then(|| {
13647                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13648                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13649                            // Instead, we try to activate the existing editor in the pane first.
13650                            let (editor, pane_item_index) =
13651                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13652                                    let editor = item.downcast::<Editor>()?;
13653                                    let singleton_buffer =
13654                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13655                                    if singleton_buffer == buffer {
13656                                        Some((editor, i))
13657                                    } else {
13658                                        None
13659                                    }
13660                                })?;
13661                            pane.update(cx, |pane, cx| {
13662                                pane.activate_item(pane_item_index, true, true, window, cx)
13663                            });
13664                            Some(editor)
13665                        })
13666                        .flatten()
13667                        .unwrap_or_else(|| {
13668                            workspace.open_project_item::<Self>(
13669                                pane.clone(),
13670                                buffer,
13671                                true,
13672                                true,
13673                                window,
13674                                cx,
13675                            )
13676                        });
13677
13678                    editor.update(cx, |editor, cx| {
13679                        let autoscroll = match scroll_offset {
13680                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13681                            None => Autoscroll::newest(),
13682                        };
13683                        let nav_history = editor.nav_history.take();
13684                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13685                            s.select_ranges(ranges);
13686                        });
13687                        editor.nav_history = nav_history;
13688                    });
13689                }
13690            })
13691        });
13692    }
13693
13694    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13695        let snapshot = self.buffer.read(cx).read(cx);
13696        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13697        Some(
13698            ranges
13699                .iter()
13700                .map(move |range| {
13701                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13702                })
13703                .collect(),
13704        )
13705    }
13706
13707    fn selection_replacement_ranges(
13708        &self,
13709        range: Range<OffsetUtf16>,
13710        cx: &mut App,
13711    ) -> Vec<Range<OffsetUtf16>> {
13712        let selections = self.selections.all::<OffsetUtf16>(cx);
13713        let newest_selection = selections
13714            .iter()
13715            .max_by_key(|selection| selection.id)
13716            .unwrap();
13717        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13718        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13719        let snapshot = self.buffer.read(cx).read(cx);
13720        selections
13721            .into_iter()
13722            .map(|mut selection| {
13723                selection.start.0 =
13724                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
13725                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13726                snapshot.clip_offset_utf16(selection.start, Bias::Left)
13727                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13728            })
13729            .collect()
13730    }
13731
13732    fn report_editor_event(
13733        &self,
13734        event_type: &'static str,
13735        file_extension: Option<String>,
13736        cx: &App,
13737    ) {
13738        if cfg!(any(test, feature = "test-support")) {
13739            return;
13740        }
13741
13742        let Some(project) = &self.project else { return };
13743
13744        // If None, we are in a file without an extension
13745        let file = self
13746            .buffer
13747            .read(cx)
13748            .as_singleton()
13749            .and_then(|b| b.read(cx).file());
13750        let file_extension = file_extension.or(file
13751            .as_ref()
13752            .and_then(|file| Path::new(file.file_name(cx)).extension())
13753            .and_then(|e| e.to_str())
13754            .map(|a| a.to_string()));
13755
13756        let vim_mode = cx
13757            .global::<SettingsStore>()
13758            .raw_user_settings()
13759            .get("vim_mode")
13760            == Some(&serde_json::Value::Bool(true));
13761
13762        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13763            == language::language_settings::InlineCompletionProvider::Copilot;
13764        let copilot_enabled_for_language = self
13765            .buffer
13766            .read(cx)
13767            .settings_at(0, cx)
13768            .show_inline_completions;
13769
13770        let project = project.read(cx);
13771        telemetry::event!(
13772            event_type,
13773            file_extension,
13774            vim_mode,
13775            copilot_enabled,
13776            copilot_enabled_for_language,
13777            is_via_ssh = project.is_via_ssh(),
13778        );
13779    }
13780
13781    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13782    /// with each line being an array of {text, highlight} objects.
13783    fn copy_highlight_json(
13784        &mut self,
13785        _: &CopyHighlightJson,
13786        window: &mut Window,
13787        cx: &mut Context<Self>,
13788    ) {
13789        #[derive(Serialize)]
13790        struct Chunk<'a> {
13791            text: String,
13792            highlight: Option<&'a str>,
13793        }
13794
13795        let snapshot = self.buffer.read(cx).snapshot(cx);
13796        let range = self
13797            .selected_text_range(false, window, cx)
13798            .and_then(|selection| {
13799                if selection.range.is_empty() {
13800                    None
13801                } else {
13802                    Some(selection.range)
13803                }
13804            })
13805            .unwrap_or_else(|| 0..snapshot.len());
13806
13807        let chunks = snapshot.chunks(range, true);
13808        let mut lines = Vec::new();
13809        let mut line: VecDeque<Chunk> = VecDeque::new();
13810
13811        let Some(style) = self.style.as_ref() else {
13812            return;
13813        };
13814
13815        for chunk in chunks {
13816            let highlight = chunk
13817                .syntax_highlight_id
13818                .and_then(|id| id.name(&style.syntax));
13819            let mut chunk_lines = chunk.text.split('\n').peekable();
13820            while let Some(text) = chunk_lines.next() {
13821                let mut merged_with_last_token = false;
13822                if let Some(last_token) = line.back_mut() {
13823                    if last_token.highlight == highlight {
13824                        last_token.text.push_str(text);
13825                        merged_with_last_token = true;
13826                    }
13827                }
13828
13829                if !merged_with_last_token {
13830                    line.push_back(Chunk {
13831                        text: text.into(),
13832                        highlight,
13833                    });
13834                }
13835
13836                if chunk_lines.peek().is_some() {
13837                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13838                        line.pop_front();
13839                    }
13840                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13841                        line.pop_back();
13842                    }
13843
13844                    lines.push(mem::take(&mut line));
13845                }
13846            }
13847        }
13848
13849        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13850            return;
13851        };
13852        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13853    }
13854
13855    pub fn open_context_menu(
13856        &mut self,
13857        _: &OpenContextMenu,
13858        window: &mut Window,
13859        cx: &mut Context<Self>,
13860    ) {
13861        self.request_autoscroll(Autoscroll::newest(), cx);
13862        let position = self.selections.newest_display(cx).start;
13863        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
13864    }
13865
13866    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13867        &self.inlay_hint_cache
13868    }
13869
13870    pub fn replay_insert_event(
13871        &mut self,
13872        text: &str,
13873        relative_utf16_range: Option<Range<isize>>,
13874        window: &mut Window,
13875        cx: &mut Context<Self>,
13876    ) {
13877        if !self.input_enabled {
13878            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13879            return;
13880        }
13881        if let Some(relative_utf16_range) = relative_utf16_range {
13882            let selections = self.selections.all::<OffsetUtf16>(cx);
13883            self.change_selections(None, window, cx, |s| {
13884                let new_ranges = selections.into_iter().map(|range| {
13885                    let start = OffsetUtf16(
13886                        range
13887                            .head()
13888                            .0
13889                            .saturating_add_signed(relative_utf16_range.start),
13890                    );
13891                    let end = OffsetUtf16(
13892                        range
13893                            .head()
13894                            .0
13895                            .saturating_add_signed(relative_utf16_range.end),
13896                    );
13897                    start..end
13898                });
13899                s.select_ranges(new_ranges);
13900            });
13901        }
13902
13903        self.handle_input(text, window, cx);
13904    }
13905
13906    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
13907        let Some(provider) = self.semantics_provider.as_ref() else {
13908            return false;
13909        };
13910
13911        let mut supports = false;
13912        self.buffer().read(cx).for_each_buffer(|buffer| {
13913            supports |= provider.supports_inlay_hints(buffer, cx);
13914        });
13915        supports
13916    }
13917    pub fn is_focused(&self, window: &mut Window) -> bool {
13918        self.focus_handle.is_focused(window)
13919    }
13920
13921    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13922        cx.emit(EditorEvent::Focused);
13923
13924        if let Some(descendant) = self
13925            .last_focused_descendant
13926            .take()
13927            .and_then(|descendant| descendant.upgrade())
13928        {
13929            window.focus(&descendant);
13930        } else {
13931            if let Some(blame) = self.blame.as_ref() {
13932                blame.update(cx, GitBlame::focus)
13933            }
13934
13935            self.blink_manager.update(cx, BlinkManager::enable);
13936            self.show_cursor_names(window, cx);
13937            self.buffer.update(cx, |buffer, cx| {
13938                buffer.finalize_last_transaction(cx);
13939                if self.leader_peer_id.is_none() {
13940                    buffer.set_active_selections(
13941                        &self.selections.disjoint_anchors(),
13942                        self.selections.line_mode,
13943                        self.cursor_shape,
13944                        cx,
13945                    );
13946                }
13947            });
13948        }
13949    }
13950
13951    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
13952        cx.emit(EditorEvent::FocusedIn)
13953    }
13954
13955    fn handle_focus_out(
13956        &mut self,
13957        event: FocusOutEvent,
13958        _window: &mut Window,
13959        _cx: &mut Context<Self>,
13960    ) {
13961        if event.blurred != self.focus_handle {
13962            self.last_focused_descendant = Some(event.blurred);
13963        }
13964    }
13965
13966    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13967        self.blink_manager.update(cx, BlinkManager::disable);
13968        self.buffer
13969            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13970
13971        if let Some(blame) = self.blame.as_ref() {
13972            blame.update(cx, GitBlame::blur)
13973        }
13974        if !self.hover_state.focused(window, cx) {
13975            hide_hover(self, cx);
13976        }
13977
13978        self.hide_context_menu(window, cx);
13979        cx.emit(EditorEvent::Blurred);
13980        cx.notify();
13981    }
13982
13983    pub fn register_action<A: Action>(
13984        &mut self,
13985        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
13986    ) -> Subscription {
13987        let id = self.next_editor_action_id.post_inc();
13988        let listener = Arc::new(listener);
13989        self.editor_actions.borrow_mut().insert(
13990            id,
13991            Box::new(move |window, _| {
13992                let listener = listener.clone();
13993                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
13994                    let action = action.downcast_ref().unwrap();
13995                    if phase == DispatchPhase::Bubble {
13996                        listener(action, window, cx)
13997                    }
13998                })
13999            }),
14000        );
14001
14002        let editor_actions = self.editor_actions.clone();
14003        Subscription::new(move || {
14004            editor_actions.borrow_mut().remove(&id);
14005        })
14006    }
14007
14008    pub fn file_header_size(&self) -> u32 {
14009        FILE_HEADER_HEIGHT
14010    }
14011
14012    pub fn revert(
14013        &mut self,
14014        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14015        window: &mut Window,
14016        cx: &mut Context<Self>,
14017    ) {
14018        self.buffer().update(cx, |multi_buffer, cx| {
14019            for (buffer_id, changes) in revert_changes {
14020                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14021                    buffer.update(cx, |buffer, cx| {
14022                        buffer.edit(
14023                            changes.into_iter().map(|(range, text)| {
14024                                (range, text.to_string().map(Arc::<str>::from))
14025                            }),
14026                            None,
14027                            cx,
14028                        );
14029                    });
14030                }
14031            }
14032        });
14033        self.change_selections(None, window, cx, |selections| selections.refresh());
14034    }
14035
14036    pub fn to_pixel_point(
14037        &self,
14038        source: multi_buffer::Anchor,
14039        editor_snapshot: &EditorSnapshot,
14040        window: &mut Window,
14041    ) -> Option<gpui::Point<Pixels>> {
14042        let source_point = source.to_display_point(editor_snapshot);
14043        self.display_to_pixel_point(source_point, editor_snapshot, window)
14044    }
14045
14046    pub fn display_to_pixel_point(
14047        &self,
14048        source: DisplayPoint,
14049        editor_snapshot: &EditorSnapshot,
14050        window: &mut Window,
14051    ) -> Option<gpui::Point<Pixels>> {
14052        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14053        let text_layout_details = self.text_layout_details(window);
14054        let scroll_top = text_layout_details
14055            .scroll_anchor
14056            .scroll_position(editor_snapshot)
14057            .y;
14058
14059        if source.row().as_f32() < scroll_top.floor() {
14060            return None;
14061        }
14062        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14063        let source_y = line_height * (source.row().as_f32() - scroll_top);
14064        Some(gpui::Point::new(source_x, source_y))
14065    }
14066
14067    pub fn has_active_completions_menu(&self) -> bool {
14068        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14069            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14070        })
14071    }
14072
14073    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14074        self.addons
14075            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14076    }
14077
14078    pub fn unregister_addon<T: Addon>(&mut self) {
14079        self.addons.remove(&std::any::TypeId::of::<T>());
14080    }
14081
14082    pub fn addon<T: Addon>(&self) -> Option<&T> {
14083        let type_id = std::any::TypeId::of::<T>();
14084        self.addons
14085            .get(&type_id)
14086            .and_then(|item| item.to_any().downcast_ref::<T>())
14087    }
14088
14089    fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14090        let text_layout_details = self.text_layout_details(window);
14091        let style = &text_layout_details.editor_style;
14092        let font_id = window.text_system().resolve_font(&style.text.font());
14093        let font_size = style.text.font_size.to_pixels(window.rem_size());
14094        let line_height = style.text.line_height_in_pixels(window.rem_size());
14095
14096        let em_width = window
14097            .text_system()
14098            .typographic_bounds(font_id, font_size, 'm')
14099            .unwrap()
14100            .size
14101            .width;
14102
14103        gpui::Point::new(em_width, line_height)
14104    }
14105}
14106
14107fn get_unstaged_changes_for_buffers(
14108    project: &Entity<Project>,
14109    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14110    buffer: Entity<MultiBuffer>,
14111    cx: &mut App,
14112) {
14113    let mut tasks = Vec::new();
14114    project.update(cx, |project, cx| {
14115        for buffer in buffers {
14116            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14117        }
14118    });
14119    cx.spawn(|mut cx| async move {
14120        let change_sets = futures::future::join_all(tasks).await;
14121        buffer
14122            .update(&mut cx, |buffer, cx| {
14123                for change_set in change_sets {
14124                    if let Some(change_set) = change_set.log_err() {
14125                        buffer.add_change_set(change_set, cx);
14126                    }
14127                }
14128            })
14129            .ok();
14130    })
14131    .detach();
14132}
14133
14134fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14135    let tab_size = tab_size.get() as usize;
14136    let mut width = offset;
14137
14138    for ch in text.chars() {
14139        width += if ch == '\t' {
14140            tab_size - (width % tab_size)
14141        } else {
14142            1
14143        };
14144    }
14145
14146    width - offset
14147}
14148
14149#[cfg(test)]
14150mod tests {
14151    use super::*;
14152
14153    #[test]
14154    fn test_string_size_with_expanded_tabs() {
14155        let nz = |val| NonZeroU32::new(val).unwrap();
14156        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14157        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14158        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14159        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14160        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14161        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14162        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14163        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14164    }
14165}
14166
14167/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14168struct WordBreakingTokenizer<'a> {
14169    input: &'a str,
14170}
14171
14172impl<'a> WordBreakingTokenizer<'a> {
14173    fn new(input: &'a str) -> Self {
14174        Self { input }
14175    }
14176}
14177
14178fn is_char_ideographic(ch: char) -> bool {
14179    use unicode_script::Script::*;
14180    use unicode_script::UnicodeScript;
14181    matches!(ch.script(), Han | Tangut | Yi)
14182}
14183
14184fn is_grapheme_ideographic(text: &str) -> bool {
14185    text.chars().any(is_char_ideographic)
14186}
14187
14188fn is_grapheme_whitespace(text: &str) -> bool {
14189    text.chars().any(|x| x.is_whitespace())
14190}
14191
14192fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14193    text.chars().next().map_or(false, |ch| {
14194        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14195    })
14196}
14197
14198#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14199struct WordBreakToken<'a> {
14200    token: &'a str,
14201    grapheme_len: usize,
14202    is_whitespace: bool,
14203}
14204
14205impl<'a> Iterator for WordBreakingTokenizer<'a> {
14206    /// Yields a span, the count of graphemes in the token, and whether it was
14207    /// whitespace. Note that it also breaks at word boundaries.
14208    type Item = WordBreakToken<'a>;
14209
14210    fn next(&mut self) -> Option<Self::Item> {
14211        use unicode_segmentation::UnicodeSegmentation;
14212        if self.input.is_empty() {
14213            return None;
14214        }
14215
14216        let mut iter = self.input.graphemes(true).peekable();
14217        let mut offset = 0;
14218        let mut graphemes = 0;
14219        if let Some(first_grapheme) = iter.next() {
14220            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14221            offset += first_grapheme.len();
14222            graphemes += 1;
14223            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14224                if let Some(grapheme) = iter.peek().copied() {
14225                    if should_stay_with_preceding_ideograph(grapheme) {
14226                        offset += grapheme.len();
14227                        graphemes += 1;
14228                    }
14229                }
14230            } else {
14231                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14232                let mut next_word_bound = words.peek().copied();
14233                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14234                    next_word_bound = words.next();
14235                }
14236                while let Some(grapheme) = iter.peek().copied() {
14237                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14238                        break;
14239                    };
14240                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14241                        break;
14242                    };
14243                    offset += grapheme.len();
14244                    graphemes += 1;
14245                    iter.next();
14246                }
14247            }
14248            let token = &self.input[..offset];
14249            self.input = &self.input[offset..];
14250            if is_whitespace {
14251                Some(WordBreakToken {
14252                    token: " ",
14253                    grapheme_len: 1,
14254                    is_whitespace: true,
14255                })
14256            } else {
14257                Some(WordBreakToken {
14258                    token,
14259                    grapheme_len: graphemes,
14260                    is_whitespace: false,
14261                })
14262            }
14263        } else {
14264            None
14265        }
14266    }
14267}
14268
14269#[test]
14270fn test_word_breaking_tokenizer() {
14271    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14272        ("", &[]),
14273        ("  ", &[(" ", 1, true)]),
14274        ("Ʒ", &[("Ʒ", 1, false)]),
14275        ("Ǽ", &[("Ǽ", 1, false)]),
14276        ("", &[("", 1, false)]),
14277        ("⋑⋑", &[("⋑⋑", 2, false)]),
14278        (
14279            "原理,进而",
14280            &[
14281                ("", 1, false),
14282                ("理,", 2, false),
14283                ("", 1, false),
14284                ("", 1, false),
14285            ],
14286        ),
14287        (
14288            "hello world",
14289            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14290        ),
14291        (
14292            "hello, world",
14293            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14294        ),
14295        (
14296            "  hello world",
14297            &[
14298                (" ", 1, true),
14299                ("hello", 5, false),
14300                (" ", 1, true),
14301                ("world", 5, false),
14302            ],
14303        ),
14304        (
14305            "这是什么 \n 钢笔",
14306            &[
14307                ("", 1, false),
14308                ("", 1, false),
14309                ("", 1, false),
14310                ("", 1, false),
14311                (" ", 1, true),
14312                ("", 1, false),
14313                ("", 1, false),
14314            ],
14315        ),
14316        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14317    ];
14318
14319    for (input, result) in tests {
14320        assert_eq!(
14321            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14322            result
14323                .iter()
14324                .copied()
14325                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14326                    token,
14327                    grapheme_len,
14328                    is_whitespace,
14329                })
14330                .collect::<Vec<_>>()
14331        );
14332    }
14333}
14334
14335fn wrap_with_prefix(
14336    line_prefix: String,
14337    unwrapped_text: String,
14338    wrap_column: usize,
14339    tab_size: NonZeroU32,
14340) -> String {
14341    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14342    let mut wrapped_text = String::new();
14343    let mut current_line = line_prefix.clone();
14344
14345    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14346    let mut current_line_len = line_prefix_len;
14347    for WordBreakToken {
14348        token,
14349        grapheme_len,
14350        is_whitespace,
14351    } in tokenizer
14352    {
14353        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14354            wrapped_text.push_str(current_line.trim_end());
14355            wrapped_text.push('\n');
14356            current_line.truncate(line_prefix.len());
14357            current_line_len = line_prefix_len;
14358            if !is_whitespace {
14359                current_line.push_str(token);
14360                current_line_len += grapheme_len;
14361            }
14362        } else if !is_whitespace {
14363            current_line.push_str(token);
14364            current_line_len += grapheme_len;
14365        } else if current_line_len != line_prefix_len {
14366            current_line.push(' ');
14367            current_line_len += 1;
14368        }
14369    }
14370
14371    if !current_line.is_empty() {
14372        wrapped_text.push_str(&current_line);
14373    }
14374    wrapped_text
14375}
14376
14377#[test]
14378fn test_wrap_with_prefix() {
14379    assert_eq!(
14380        wrap_with_prefix(
14381            "# ".to_string(),
14382            "abcdefg".to_string(),
14383            4,
14384            NonZeroU32::new(4).unwrap()
14385        ),
14386        "# abcdefg"
14387    );
14388    assert_eq!(
14389        wrap_with_prefix(
14390            "".to_string(),
14391            "\thello world".to_string(),
14392            8,
14393            NonZeroU32::new(4).unwrap()
14394        ),
14395        "hello\nworld"
14396    );
14397    assert_eq!(
14398        wrap_with_prefix(
14399            "// ".to_string(),
14400            "xx \nyy zz aa bb cc".to_string(),
14401            12,
14402            NonZeroU32::new(4).unwrap()
14403        ),
14404        "// xx yy zz\n// aa bb cc"
14405    );
14406    assert_eq!(
14407        wrap_with_prefix(
14408            String::new(),
14409            "这是什么 \n 钢笔".to_string(),
14410            3,
14411            NonZeroU32::new(4).unwrap()
14412        ),
14413        "这是什\n么 钢\n"
14414    );
14415}
14416
14417pub trait CollaborationHub {
14418    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14419    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14420    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14421}
14422
14423impl CollaborationHub for Entity<Project> {
14424    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14425        self.read(cx).collaborators()
14426    }
14427
14428    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14429        self.read(cx).user_store().read(cx).participant_indices()
14430    }
14431
14432    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14433        let this = self.read(cx);
14434        let user_ids = this.collaborators().values().map(|c| c.user_id);
14435        this.user_store().read_with(cx, |user_store, cx| {
14436            user_store.participant_names(user_ids, cx)
14437        })
14438    }
14439}
14440
14441pub trait SemanticsProvider {
14442    fn hover(
14443        &self,
14444        buffer: &Entity<Buffer>,
14445        position: text::Anchor,
14446        cx: &mut App,
14447    ) -> Option<Task<Vec<project::Hover>>>;
14448
14449    fn inlay_hints(
14450        &self,
14451        buffer_handle: Entity<Buffer>,
14452        range: Range<text::Anchor>,
14453        cx: &mut App,
14454    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14455
14456    fn resolve_inlay_hint(
14457        &self,
14458        hint: InlayHint,
14459        buffer_handle: Entity<Buffer>,
14460        server_id: LanguageServerId,
14461        cx: &mut App,
14462    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14463
14464    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14465
14466    fn document_highlights(
14467        &self,
14468        buffer: &Entity<Buffer>,
14469        position: text::Anchor,
14470        cx: &mut App,
14471    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14472
14473    fn definitions(
14474        &self,
14475        buffer: &Entity<Buffer>,
14476        position: text::Anchor,
14477        kind: GotoDefinitionKind,
14478        cx: &mut App,
14479    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14480
14481    fn range_for_rename(
14482        &self,
14483        buffer: &Entity<Buffer>,
14484        position: text::Anchor,
14485        cx: &mut App,
14486    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14487
14488    fn perform_rename(
14489        &self,
14490        buffer: &Entity<Buffer>,
14491        position: text::Anchor,
14492        new_name: String,
14493        cx: &mut App,
14494    ) -> Option<Task<Result<ProjectTransaction>>>;
14495}
14496
14497pub trait CompletionProvider {
14498    fn completions(
14499        &self,
14500        buffer: &Entity<Buffer>,
14501        buffer_position: text::Anchor,
14502        trigger: CompletionContext,
14503        window: &mut Window,
14504        cx: &mut Context<Editor>,
14505    ) -> Task<Result<Vec<Completion>>>;
14506
14507    fn resolve_completions(
14508        &self,
14509        buffer: Entity<Buffer>,
14510        completion_indices: Vec<usize>,
14511        completions: Rc<RefCell<Box<[Completion]>>>,
14512        cx: &mut Context<Editor>,
14513    ) -> Task<Result<bool>>;
14514
14515    fn apply_additional_edits_for_completion(
14516        &self,
14517        _buffer: Entity<Buffer>,
14518        _completions: Rc<RefCell<Box<[Completion]>>>,
14519        _completion_index: usize,
14520        _push_to_history: bool,
14521        _cx: &mut Context<Editor>,
14522    ) -> Task<Result<Option<language::Transaction>>> {
14523        Task::ready(Ok(None))
14524    }
14525
14526    fn is_completion_trigger(
14527        &self,
14528        buffer: &Entity<Buffer>,
14529        position: language::Anchor,
14530        text: &str,
14531        trigger_in_words: bool,
14532        cx: &mut Context<Editor>,
14533    ) -> bool;
14534
14535    fn sort_completions(&self) -> bool {
14536        true
14537    }
14538}
14539
14540pub trait CodeActionProvider {
14541    fn id(&self) -> Arc<str>;
14542
14543    fn code_actions(
14544        &self,
14545        buffer: &Entity<Buffer>,
14546        range: Range<text::Anchor>,
14547        window: &mut Window,
14548        cx: &mut App,
14549    ) -> Task<Result<Vec<CodeAction>>>;
14550
14551    fn apply_code_action(
14552        &self,
14553        buffer_handle: Entity<Buffer>,
14554        action: CodeAction,
14555        excerpt_id: ExcerptId,
14556        push_to_history: bool,
14557        window: &mut Window,
14558        cx: &mut App,
14559    ) -> Task<Result<ProjectTransaction>>;
14560}
14561
14562impl CodeActionProvider for Entity<Project> {
14563    fn id(&self) -> Arc<str> {
14564        "project".into()
14565    }
14566
14567    fn code_actions(
14568        &self,
14569        buffer: &Entity<Buffer>,
14570        range: Range<text::Anchor>,
14571        _window: &mut Window,
14572        cx: &mut App,
14573    ) -> Task<Result<Vec<CodeAction>>> {
14574        self.update(cx, |project, cx| {
14575            project.code_actions(buffer, range, None, cx)
14576        })
14577    }
14578
14579    fn apply_code_action(
14580        &self,
14581        buffer_handle: Entity<Buffer>,
14582        action: CodeAction,
14583        _excerpt_id: ExcerptId,
14584        push_to_history: bool,
14585        _window: &mut Window,
14586        cx: &mut App,
14587    ) -> Task<Result<ProjectTransaction>> {
14588        self.update(cx, |project, cx| {
14589            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14590        })
14591    }
14592}
14593
14594fn snippet_completions(
14595    project: &Project,
14596    buffer: &Entity<Buffer>,
14597    buffer_position: text::Anchor,
14598    cx: &mut App,
14599) -> Task<Result<Vec<Completion>>> {
14600    let language = buffer.read(cx).language_at(buffer_position);
14601    let language_name = language.as_ref().map(|language| language.lsp_id());
14602    let snippet_store = project.snippets().read(cx);
14603    let snippets = snippet_store.snippets_for(language_name, cx);
14604
14605    if snippets.is_empty() {
14606        return Task::ready(Ok(vec![]));
14607    }
14608    let snapshot = buffer.read(cx).text_snapshot();
14609    let chars: String = snapshot
14610        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14611        .collect();
14612
14613    let scope = language.map(|language| language.default_scope());
14614    let executor = cx.background_executor().clone();
14615
14616    cx.background_executor().spawn(async move {
14617        let classifier = CharClassifier::new(scope).for_completion(true);
14618        let mut last_word = chars
14619            .chars()
14620            .take_while(|c| classifier.is_word(*c))
14621            .collect::<String>();
14622        last_word = last_word.chars().rev().collect();
14623
14624        if last_word.is_empty() {
14625            return Ok(vec![]);
14626        }
14627
14628        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14629        let to_lsp = |point: &text::Anchor| {
14630            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14631            point_to_lsp(end)
14632        };
14633        let lsp_end = to_lsp(&buffer_position);
14634
14635        let candidates = snippets
14636            .iter()
14637            .enumerate()
14638            .flat_map(|(ix, snippet)| {
14639                snippet
14640                    .prefix
14641                    .iter()
14642                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14643            })
14644            .collect::<Vec<StringMatchCandidate>>();
14645
14646        let mut matches = fuzzy::match_strings(
14647            &candidates,
14648            &last_word,
14649            last_word.chars().any(|c| c.is_uppercase()),
14650            100,
14651            &Default::default(),
14652            executor,
14653        )
14654        .await;
14655
14656        // Remove all candidates where the query's start does not match the start of any word in the candidate
14657        if let Some(query_start) = last_word.chars().next() {
14658            matches.retain(|string_match| {
14659                split_words(&string_match.string).any(|word| {
14660                    // Check that the first codepoint of the word as lowercase matches the first
14661                    // codepoint of the query as lowercase
14662                    word.chars()
14663                        .flat_map(|codepoint| codepoint.to_lowercase())
14664                        .zip(query_start.to_lowercase())
14665                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14666                })
14667            });
14668        }
14669
14670        let matched_strings = matches
14671            .into_iter()
14672            .map(|m| m.string)
14673            .collect::<HashSet<_>>();
14674
14675        let result: Vec<Completion> = snippets
14676            .into_iter()
14677            .filter_map(|snippet| {
14678                let matching_prefix = snippet
14679                    .prefix
14680                    .iter()
14681                    .find(|prefix| matched_strings.contains(*prefix))?;
14682                let start = as_offset - last_word.len();
14683                let start = snapshot.anchor_before(start);
14684                let range = start..buffer_position;
14685                let lsp_start = to_lsp(&start);
14686                let lsp_range = lsp::Range {
14687                    start: lsp_start,
14688                    end: lsp_end,
14689                };
14690                Some(Completion {
14691                    old_range: range,
14692                    new_text: snippet.body.clone(),
14693                    resolved: false,
14694                    label: CodeLabel {
14695                        text: matching_prefix.clone(),
14696                        runs: vec![],
14697                        filter_range: 0..matching_prefix.len(),
14698                    },
14699                    server_id: LanguageServerId(usize::MAX),
14700                    documentation: snippet.description.clone().map(Documentation::SingleLine),
14701                    lsp_completion: lsp::CompletionItem {
14702                        label: snippet.prefix.first().unwrap().clone(),
14703                        kind: Some(CompletionItemKind::SNIPPET),
14704                        label_details: snippet.description.as_ref().map(|description| {
14705                            lsp::CompletionItemLabelDetails {
14706                                detail: Some(description.clone()),
14707                                description: None,
14708                            }
14709                        }),
14710                        insert_text_format: Some(InsertTextFormat::SNIPPET),
14711                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14712                            lsp::InsertReplaceEdit {
14713                                new_text: snippet.body.clone(),
14714                                insert: lsp_range,
14715                                replace: lsp_range,
14716                            },
14717                        )),
14718                        filter_text: Some(snippet.body.clone()),
14719                        sort_text: Some(char::MAX.to_string()),
14720                        ..Default::default()
14721                    },
14722                    confirm: None,
14723                })
14724            })
14725            .collect();
14726
14727        Ok(result)
14728    })
14729}
14730
14731impl CompletionProvider for Entity<Project> {
14732    fn completions(
14733        &self,
14734        buffer: &Entity<Buffer>,
14735        buffer_position: text::Anchor,
14736        options: CompletionContext,
14737        _window: &mut Window,
14738        cx: &mut Context<Editor>,
14739    ) -> Task<Result<Vec<Completion>>> {
14740        self.update(cx, |project, cx| {
14741            let snippets = snippet_completions(project, buffer, buffer_position, cx);
14742            let project_completions = project.completions(buffer, buffer_position, options, cx);
14743            cx.background_executor().spawn(async move {
14744                let mut completions = project_completions.await?;
14745                let snippets_completions = snippets.await?;
14746                completions.extend(snippets_completions);
14747                Ok(completions)
14748            })
14749        })
14750    }
14751
14752    fn resolve_completions(
14753        &self,
14754        buffer: Entity<Buffer>,
14755        completion_indices: Vec<usize>,
14756        completions: Rc<RefCell<Box<[Completion]>>>,
14757        cx: &mut Context<Editor>,
14758    ) -> Task<Result<bool>> {
14759        self.update(cx, |project, cx| {
14760            project.lsp_store().update(cx, |lsp_store, cx| {
14761                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
14762            })
14763        })
14764    }
14765
14766    fn apply_additional_edits_for_completion(
14767        &self,
14768        buffer: Entity<Buffer>,
14769        completions: Rc<RefCell<Box<[Completion]>>>,
14770        completion_index: usize,
14771        push_to_history: bool,
14772        cx: &mut Context<Editor>,
14773    ) -> Task<Result<Option<language::Transaction>>> {
14774        self.update(cx, |project, cx| {
14775            project.lsp_store().update(cx, |lsp_store, cx| {
14776                lsp_store.apply_additional_edits_for_completion(
14777                    buffer,
14778                    completions,
14779                    completion_index,
14780                    push_to_history,
14781                    cx,
14782                )
14783            })
14784        })
14785    }
14786
14787    fn is_completion_trigger(
14788        &self,
14789        buffer: &Entity<Buffer>,
14790        position: language::Anchor,
14791        text: &str,
14792        trigger_in_words: bool,
14793        cx: &mut Context<Editor>,
14794    ) -> bool {
14795        let mut chars = text.chars();
14796        let char = if let Some(char) = chars.next() {
14797            char
14798        } else {
14799            return false;
14800        };
14801        if chars.next().is_some() {
14802            return false;
14803        }
14804
14805        let buffer = buffer.read(cx);
14806        let snapshot = buffer.snapshot();
14807        if !snapshot.settings_at(position, cx).show_completions_on_input {
14808            return false;
14809        }
14810        let classifier = snapshot.char_classifier_at(position).for_completion(true);
14811        if trigger_in_words && classifier.is_word(char) {
14812            return true;
14813        }
14814
14815        buffer.completion_triggers().contains(text)
14816    }
14817}
14818
14819impl SemanticsProvider for Entity<Project> {
14820    fn hover(
14821        &self,
14822        buffer: &Entity<Buffer>,
14823        position: text::Anchor,
14824        cx: &mut App,
14825    ) -> Option<Task<Vec<project::Hover>>> {
14826        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14827    }
14828
14829    fn document_highlights(
14830        &self,
14831        buffer: &Entity<Buffer>,
14832        position: text::Anchor,
14833        cx: &mut App,
14834    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14835        Some(self.update(cx, |project, cx| {
14836            project.document_highlights(buffer, position, cx)
14837        }))
14838    }
14839
14840    fn definitions(
14841        &self,
14842        buffer: &Entity<Buffer>,
14843        position: text::Anchor,
14844        kind: GotoDefinitionKind,
14845        cx: &mut App,
14846    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14847        Some(self.update(cx, |project, cx| match kind {
14848            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14849            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14850            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14851            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14852        }))
14853    }
14854
14855    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
14856        // TODO: make this work for remote projects
14857        self.read(cx)
14858            .language_servers_for_local_buffer(buffer.read(cx), cx)
14859            .any(
14860                |(_, server)| match server.capabilities().inlay_hint_provider {
14861                    Some(lsp::OneOf::Left(enabled)) => enabled,
14862                    Some(lsp::OneOf::Right(_)) => true,
14863                    None => false,
14864                },
14865            )
14866    }
14867
14868    fn inlay_hints(
14869        &self,
14870        buffer_handle: Entity<Buffer>,
14871        range: Range<text::Anchor>,
14872        cx: &mut App,
14873    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14874        Some(self.update(cx, |project, cx| {
14875            project.inlay_hints(buffer_handle, range, cx)
14876        }))
14877    }
14878
14879    fn resolve_inlay_hint(
14880        &self,
14881        hint: InlayHint,
14882        buffer_handle: Entity<Buffer>,
14883        server_id: LanguageServerId,
14884        cx: &mut App,
14885    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14886        Some(self.update(cx, |project, cx| {
14887            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14888        }))
14889    }
14890
14891    fn range_for_rename(
14892        &self,
14893        buffer: &Entity<Buffer>,
14894        position: text::Anchor,
14895        cx: &mut App,
14896    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14897        Some(self.update(cx, |project, cx| {
14898            let buffer = buffer.clone();
14899            let task = project.prepare_rename(buffer.clone(), position, cx);
14900            cx.spawn(|_, mut cx| async move {
14901                Ok(match task.await? {
14902                    PrepareRenameResponse::Success(range) => Some(range),
14903                    PrepareRenameResponse::InvalidPosition => None,
14904                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14905                        // Fallback on using TreeSitter info to determine identifier range
14906                        buffer.update(&mut cx, |buffer, _| {
14907                            let snapshot = buffer.snapshot();
14908                            let (range, kind) = snapshot.surrounding_word(position);
14909                            if kind != Some(CharKind::Word) {
14910                                return None;
14911                            }
14912                            Some(
14913                                snapshot.anchor_before(range.start)
14914                                    ..snapshot.anchor_after(range.end),
14915                            )
14916                        })?
14917                    }
14918                })
14919            })
14920        }))
14921    }
14922
14923    fn perform_rename(
14924        &self,
14925        buffer: &Entity<Buffer>,
14926        position: text::Anchor,
14927        new_name: String,
14928        cx: &mut App,
14929    ) -> Option<Task<Result<ProjectTransaction>>> {
14930        Some(self.update(cx, |project, cx| {
14931            project.perform_rename(buffer.clone(), position, new_name, cx)
14932        }))
14933    }
14934}
14935
14936fn inlay_hint_settings(
14937    location: Anchor,
14938    snapshot: &MultiBufferSnapshot,
14939    cx: &mut Context<Editor>,
14940) -> InlayHintSettings {
14941    let file = snapshot.file_at(location);
14942    let language = snapshot.language_at(location).map(|l| l.name());
14943    language_settings(language, file, cx).inlay_hints
14944}
14945
14946fn consume_contiguous_rows(
14947    contiguous_row_selections: &mut Vec<Selection<Point>>,
14948    selection: &Selection<Point>,
14949    display_map: &DisplaySnapshot,
14950    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14951) -> (MultiBufferRow, MultiBufferRow) {
14952    contiguous_row_selections.push(selection.clone());
14953    let start_row = MultiBufferRow(selection.start.row);
14954    let mut end_row = ending_row(selection, display_map);
14955
14956    while let Some(next_selection) = selections.peek() {
14957        if next_selection.start.row <= end_row.0 {
14958            end_row = ending_row(next_selection, display_map);
14959            contiguous_row_selections.push(selections.next().unwrap().clone());
14960        } else {
14961            break;
14962        }
14963    }
14964    (start_row, end_row)
14965}
14966
14967fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14968    if next_selection.end.column > 0 || next_selection.is_empty() {
14969        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14970    } else {
14971        MultiBufferRow(next_selection.end.row)
14972    }
14973}
14974
14975impl EditorSnapshot {
14976    pub fn remote_selections_in_range<'a>(
14977        &'a self,
14978        range: &'a Range<Anchor>,
14979        collaboration_hub: &dyn CollaborationHub,
14980        cx: &'a App,
14981    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14982        let participant_names = collaboration_hub.user_names(cx);
14983        let participant_indices = collaboration_hub.user_participant_indices(cx);
14984        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14985        let collaborators_by_replica_id = collaborators_by_peer_id
14986            .iter()
14987            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14988            .collect::<HashMap<_, _>>();
14989        self.buffer_snapshot
14990            .selections_in_range(range, false)
14991            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14992                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14993                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14994                let user_name = participant_names.get(&collaborator.user_id).cloned();
14995                Some(RemoteSelection {
14996                    replica_id,
14997                    selection,
14998                    cursor_shape,
14999                    line_mode,
15000                    participant_index,
15001                    peer_id: collaborator.peer_id,
15002                    user_name,
15003                })
15004            })
15005    }
15006
15007    pub fn hunks_for_ranges(
15008        &self,
15009        ranges: impl Iterator<Item = Range<Point>>,
15010    ) -> Vec<MultiBufferDiffHunk> {
15011        let mut hunks = Vec::new();
15012        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15013            HashMap::default();
15014        for query_range in ranges {
15015            let query_rows =
15016                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15017            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15018                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15019            ) {
15020                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15021                // when the caret is just above or just below the deleted hunk.
15022                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15023                let related_to_selection = if allow_adjacent {
15024                    hunk.row_range.overlaps(&query_rows)
15025                        || hunk.row_range.start == query_rows.end
15026                        || hunk.row_range.end == query_rows.start
15027                } else {
15028                    hunk.row_range.overlaps(&query_rows)
15029                };
15030                if related_to_selection {
15031                    if !processed_buffer_rows
15032                        .entry(hunk.buffer_id)
15033                        .or_default()
15034                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15035                    {
15036                        continue;
15037                    }
15038                    hunks.push(hunk);
15039                }
15040            }
15041        }
15042
15043        hunks
15044    }
15045
15046    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15047        self.display_snapshot.buffer_snapshot.language_at(position)
15048    }
15049
15050    pub fn is_focused(&self) -> bool {
15051        self.is_focused
15052    }
15053
15054    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15055        self.placeholder_text.as_ref()
15056    }
15057
15058    pub fn scroll_position(&self) -> gpui::Point<f32> {
15059        self.scroll_anchor.scroll_position(&self.display_snapshot)
15060    }
15061
15062    fn gutter_dimensions(
15063        &self,
15064        font_id: FontId,
15065        font_size: Pixels,
15066        em_width: Pixels,
15067        em_advance: Pixels,
15068        max_line_number_width: Pixels,
15069        cx: &App,
15070    ) -> GutterDimensions {
15071        if !self.show_gutter {
15072            return GutterDimensions::default();
15073        }
15074        let descent = cx.text_system().descent(font_id, font_size);
15075
15076        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15077            matches!(
15078                ProjectSettings::get_global(cx).git.git_gutter,
15079                Some(GitGutterSetting::TrackedFiles)
15080            )
15081        });
15082        let gutter_settings = EditorSettings::get_global(cx).gutter;
15083        let show_line_numbers = self
15084            .show_line_numbers
15085            .unwrap_or(gutter_settings.line_numbers);
15086        let line_gutter_width = if show_line_numbers {
15087            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15088            let min_width_for_number_on_gutter = em_advance * 4.0;
15089            max_line_number_width.max(min_width_for_number_on_gutter)
15090        } else {
15091            0.0.into()
15092        };
15093
15094        let show_code_actions = self
15095            .show_code_actions
15096            .unwrap_or(gutter_settings.code_actions);
15097
15098        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15099
15100        let git_blame_entries_width =
15101            self.git_blame_gutter_max_author_length
15102                .map(|max_author_length| {
15103                    // Length of the author name, but also space for the commit hash,
15104                    // the spacing and the timestamp.
15105                    let max_char_count = max_author_length
15106                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15107                        + 7 // length of commit sha
15108                        + 14 // length of max relative timestamp ("60 minutes ago")
15109                        + 4; // gaps and margins
15110
15111                    em_advance * max_char_count
15112                });
15113
15114        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15115        left_padding += if show_code_actions || show_runnables {
15116            em_width * 3.0
15117        } else if show_git_gutter && show_line_numbers {
15118            em_width * 2.0
15119        } else if show_git_gutter || show_line_numbers {
15120            em_width
15121        } else {
15122            px(0.)
15123        };
15124
15125        let right_padding = if gutter_settings.folds && show_line_numbers {
15126            em_width * 4.0
15127        } else if gutter_settings.folds {
15128            em_width * 3.0
15129        } else if show_line_numbers {
15130            em_width
15131        } else {
15132            px(0.)
15133        };
15134
15135        GutterDimensions {
15136            left_padding,
15137            right_padding,
15138            width: line_gutter_width + left_padding + right_padding,
15139            margin: -descent,
15140            git_blame_entries_width,
15141        }
15142    }
15143
15144    pub fn render_crease_toggle(
15145        &self,
15146        buffer_row: MultiBufferRow,
15147        row_contains_cursor: bool,
15148        editor: Entity<Editor>,
15149        window: &mut Window,
15150        cx: &mut App,
15151    ) -> Option<AnyElement> {
15152        let folded = self.is_line_folded(buffer_row);
15153        let mut is_foldable = false;
15154
15155        if let Some(crease) = self
15156            .crease_snapshot
15157            .query_row(buffer_row, &self.buffer_snapshot)
15158        {
15159            is_foldable = true;
15160            match crease {
15161                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15162                    if let Some(render_toggle) = render_toggle {
15163                        let toggle_callback =
15164                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15165                                if folded {
15166                                    editor.update(cx, |editor, cx| {
15167                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15168                                    });
15169                                } else {
15170                                    editor.update(cx, |editor, cx| {
15171                                        editor.unfold_at(
15172                                            &crate::UnfoldAt { buffer_row },
15173                                            window,
15174                                            cx,
15175                                        )
15176                                    });
15177                                }
15178                            });
15179                        return Some((render_toggle)(
15180                            buffer_row,
15181                            folded,
15182                            toggle_callback,
15183                            window,
15184                            cx,
15185                        ));
15186                    }
15187                }
15188            }
15189        }
15190
15191        is_foldable |= self.starts_indent(buffer_row);
15192
15193        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15194            Some(
15195                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15196                    .toggle_state(folded)
15197                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15198                        if folded {
15199                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15200                        } else {
15201                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15202                        }
15203                    }))
15204                    .into_any_element(),
15205            )
15206        } else {
15207            None
15208        }
15209    }
15210
15211    pub fn render_crease_trailer(
15212        &self,
15213        buffer_row: MultiBufferRow,
15214        window: &mut Window,
15215        cx: &mut App,
15216    ) -> Option<AnyElement> {
15217        let folded = self.is_line_folded(buffer_row);
15218        if let Crease::Inline { render_trailer, .. } = self
15219            .crease_snapshot
15220            .query_row(buffer_row, &self.buffer_snapshot)?
15221        {
15222            let render_trailer = render_trailer.as_ref()?;
15223            Some(render_trailer(buffer_row, folded, window, cx))
15224        } else {
15225            None
15226        }
15227    }
15228}
15229
15230impl Deref for EditorSnapshot {
15231    type Target = DisplaySnapshot;
15232
15233    fn deref(&self) -> &Self::Target {
15234        &self.display_snapshot
15235    }
15236}
15237
15238#[derive(Clone, Debug, PartialEq, Eq)]
15239pub enum EditorEvent {
15240    InputIgnored {
15241        text: Arc<str>,
15242    },
15243    InputHandled {
15244        utf16_range_to_replace: Option<Range<isize>>,
15245        text: Arc<str>,
15246    },
15247    ExcerptsAdded {
15248        buffer: Entity<Buffer>,
15249        predecessor: ExcerptId,
15250        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15251    },
15252    ExcerptsRemoved {
15253        ids: Vec<ExcerptId>,
15254    },
15255    BufferFoldToggled {
15256        ids: Vec<ExcerptId>,
15257        folded: bool,
15258    },
15259    ExcerptsEdited {
15260        ids: Vec<ExcerptId>,
15261    },
15262    ExcerptsExpanded {
15263        ids: Vec<ExcerptId>,
15264    },
15265    BufferEdited,
15266    Edited {
15267        transaction_id: clock::Lamport,
15268    },
15269    Reparsed(BufferId),
15270    Focused,
15271    FocusedIn,
15272    Blurred,
15273    DirtyChanged,
15274    Saved,
15275    TitleChanged,
15276    DiffBaseChanged,
15277    SelectionsChanged {
15278        local: bool,
15279    },
15280    ScrollPositionChanged {
15281        local: bool,
15282        autoscroll: bool,
15283    },
15284    Closed,
15285    TransactionUndone {
15286        transaction_id: clock::Lamport,
15287    },
15288    TransactionBegun {
15289        transaction_id: clock::Lamport,
15290    },
15291    Reloaded,
15292    CursorShapeChanged,
15293}
15294
15295impl EventEmitter<EditorEvent> for Editor {}
15296
15297impl Focusable for Editor {
15298    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15299        self.focus_handle.clone()
15300    }
15301}
15302
15303impl Render for Editor {
15304    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15305        let settings = ThemeSettings::get_global(cx);
15306
15307        let mut text_style = match self.mode {
15308            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15309                color: cx.theme().colors().editor_foreground,
15310                font_family: settings.ui_font.family.clone(),
15311                font_features: settings.ui_font.features.clone(),
15312                font_fallbacks: settings.ui_font.fallbacks.clone(),
15313                font_size: rems(0.875).into(),
15314                font_weight: settings.ui_font.weight,
15315                line_height: relative(settings.buffer_line_height.value()),
15316                ..Default::default()
15317            },
15318            EditorMode::Full => TextStyle {
15319                color: cx.theme().colors().editor_foreground,
15320                font_family: settings.buffer_font.family.clone(),
15321                font_features: settings.buffer_font.features.clone(),
15322                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15323                font_size: settings.buffer_font_size().into(),
15324                font_weight: settings.buffer_font.weight,
15325                line_height: relative(settings.buffer_line_height.value()),
15326                ..Default::default()
15327            },
15328        };
15329        if let Some(text_style_refinement) = &self.text_style_refinement {
15330            text_style.refine(text_style_refinement)
15331        }
15332
15333        let background = match self.mode {
15334            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15335            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15336            EditorMode::Full => cx.theme().colors().editor_background,
15337        };
15338
15339        EditorElement::new(
15340            &cx.entity(),
15341            EditorStyle {
15342                background,
15343                local_player: cx.theme().players().local(),
15344                text: text_style,
15345                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15346                syntax: cx.theme().syntax().clone(),
15347                status: cx.theme().status().clone(),
15348                inlay_hints_style: make_inlay_hints_style(cx),
15349                inline_completion_styles: make_suggestion_styles(cx),
15350                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15351            },
15352        )
15353    }
15354}
15355
15356impl EntityInputHandler for Editor {
15357    fn text_for_range(
15358        &mut self,
15359        range_utf16: Range<usize>,
15360        adjusted_range: &mut Option<Range<usize>>,
15361        _: &mut Window,
15362        cx: &mut Context<Self>,
15363    ) -> Option<String> {
15364        let snapshot = self.buffer.read(cx).read(cx);
15365        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15366        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15367        if (start.0..end.0) != range_utf16 {
15368            adjusted_range.replace(start.0..end.0);
15369        }
15370        Some(snapshot.text_for_range(start..end).collect())
15371    }
15372
15373    fn selected_text_range(
15374        &mut self,
15375        ignore_disabled_input: bool,
15376        _: &mut Window,
15377        cx: &mut Context<Self>,
15378    ) -> Option<UTF16Selection> {
15379        // Prevent the IME menu from appearing when holding down an alphabetic key
15380        // while input is disabled.
15381        if !ignore_disabled_input && !self.input_enabled {
15382            return None;
15383        }
15384
15385        let selection = self.selections.newest::<OffsetUtf16>(cx);
15386        let range = selection.range();
15387
15388        Some(UTF16Selection {
15389            range: range.start.0..range.end.0,
15390            reversed: selection.reversed,
15391        })
15392    }
15393
15394    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15395        let snapshot = self.buffer.read(cx).read(cx);
15396        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15397        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15398    }
15399
15400    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15401        self.clear_highlights::<InputComposition>(cx);
15402        self.ime_transaction.take();
15403    }
15404
15405    fn replace_text_in_range(
15406        &mut self,
15407        range_utf16: Option<Range<usize>>,
15408        text: &str,
15409        window: &mut Window,
15410        cx: &mut Context<Self>,
15411    ) {
15412        if !self.input_enabled {
15413            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15414            return;
15415        }
15416
15417        self.transact(window, cx, |this, window, cx| {
15418            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15419                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15420                Some(this.selection_replacement_ranges(range_utf16, cx))
15421            } else {
15422                this.marked_text_ranges(cx)
15423            };
15424
15425            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15426                let newest_selection_id = this.selections.newest_anchor().id;
15427                this.selections
15428                    .all::<OffsetUtf16>(cx)
15429                    .iter()
15430                    .zip(ranges_to_replace.iter())
15431                    .find_map(|(selection, range)| {
15432                        if selection.id == newest_selection_id {
15433                            Some(
15434                                (range.start.0 as isize - selection.head().0 as isize)
15435                                    ..(range.end.0 as isize - selection.head().0 as isize),
15436                            )
15437                        } else {
15438                            None
15439                        }
15440                    })
15441            });
15442
15443            cx.emit(EditorEvent::InputHandled {
15444                utf16_range_to_replace: range_to_replace,
15445                text: text.into(),
15446            });
15447
15448            if let Some(new_selected_ranges) = new_selected_ranges {
15449                this.change_selections(None, window, cx, |selections| {
15450                    selections.select_ranges(new_selected_ranges)
15451                });
15452                this.backspace(&Default::default(), window, cx);
15453            }
15454
15455            this.handle_input(text, window, cx);
15456        });
15457
15458        if let Some(transaction) = self.ime_transaction {
15459            self.buffer.update(cx, |buffer, cx| {
15460                buffer.group_until_transaction(transaction, cx);
15461            });
15462        }
15463
15464        self.unmark_text(window, cx);
15465    }
15466
15467    fn replace_and_mark_text_in_range(
15468        &mut self,
15469        range_utf16: Option<Range<usize>>,
15470        text: &str,
15471        new_selected_range_utf16: Option<Range<usize>>,
15472        window: &mut Window,
15473        cx: &mut Context<Self>,
15474    ) {
15475        if !self.input_enabled {
15476            return;
15477        }
15478
15479        let transaction = self.transact(window, cx, |this, window, cx| {
15480            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15481                let snapshot = this.buffer.read(cx).read(cx);
15482                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15483                    for marked_range in &mut marked_ranges {
15484                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15485                        marked_range.start.0 += relative_range_utf16.start;
15486                        marked_range.start =
15487                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15488                        marked_range.end =
15489                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15490                    }
15491                }
15492                Some(marked_ranges)
15493            } else if let Some(range_utf16) = range_utf16 {
15494                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15495                Some(this.selection_replacement_ranges(range_utf16, cx))
15496            } else {
15497                None
15498            };
15499
15500            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15501                let newest_selection_id = this.selections.newest_anchor().id;
15502                this.selections
15503                    .all::<OffsetUtf16>(cx)
15504                    .iter()
15505                    .zip(ranges_to_replace.iter())
15506                    .find_map(|(selection, range)| {
15507                        if selection.id == newest_selection_id {
15508                            Some(
15509                                (range.start.0 as isize - selection.head().0 as isize)
15510                                    ..(range.end.0 as isize - selection.head().0 as isize),
15511                            )
15512                        } else {
15513                            None
15514                        }
15515                    })
15516            });
15517
15518            cx.emit(EditorEvent::InputHandled {
15519                utf16_range_to_replace: range_to_replace,
15520                text: text.into(),
15521            });
15522
15523            if let Some(ranges) = ranges_to_replace {
15524                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15525            }
15526
15527            let marked_ranges = {
15528                let snapshot = this.buffer.read(cx).read(cx);
15529                this.selections
15530                    .disjoint_anchors()
15531                    .iter()
15532                    .map(|selection| {
15533                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15534                    })
15535                    .collect::<Vec<_>>()
15536            };
15537
15538            if text.is_empty() {
15539                this.unmark_text(window, cx);
15540            } else {
15541                this.highlight_text::<InputComposition>(
15542                    marked_ranges.clone(),
15543                    HighlightStyle {
15544                        underline: Some(UnderlineStyle {
15545                            thickness: px(1.),
15546                            color: None,
15547                            wavy: false,
15548                        }),
15549                        ..Default::default()
15550                    },
15551                    cx,
15552                );
15553            }
15554
15555            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15556            let use_autoclose = this.use_autoclose;
15557            let use_auto_surround = this.use_auto_surround;
15558            this.set_use_autoclose(false);
15559            this.set_use_auto_surround(false);
15560            this.handle_input(text, window, cx);
15561            this.set_use_autoclose(use_autoclose);
15562            this.set_use_auto_surround(use_auto_surround);
15563
15564            if let Some(new_selected_range) = new_selected_range_utf16 {
15565                let snapshot = this.buffer.read(cx).read(cx);
15566                let new_selected_ranges = marked_ranges
15567                    .into_iter()
15568                    .map(|marked_range| {
15569                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15570                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15571                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15572                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15573                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15574                    })
15575                    .collect::<Vec<_>>();
15576
15577                drop(snapshot);
15578                this.change_selections(None, window, cx, |selections| {
15579                    selections.select_ranges(new_selected_ranges)
15580                });
15581            }
15582        });
15583
15584        self.ime_transaction = self.ime_transaction.or(transaction);
15585        if let Some(transaction) = self.ime_transaction {
15586            self.buffer.update(cx, |buffer, cx| {
15587                buffer.group_until_transaction(transaction, cx);
15588            });
15589        }
15590
15591        if self.text_highlights::<InputComposition>(cx).is_none() {
15592            self.ime_transaction.take();
15593        }
15594    }
15595
15596    fn bounds_for_range(
15597        &mut self,
15598        range_utf16: Range<usize>,
15599        element_bounds: gpui::Bounds<Pixels>,
15600        window: &mut Window,
15601        cx: &mut Context<Self>,
15602    ) -> Option<gpui::Bounds<Pixels>> {
15603        let text_layout_details = self.text_layout_details(window);
15604        let gpui::Point {
15605            x: em_width,
15606            y: line_height,
15607        } = self.character_size(window);
15608
15609        let snapshot = self.snapshot(window, cx);
15610        let scroll_position = snapshot.scroll_position();
15611        let scroll_left = scroll_position.x * em_width;
15612
15613        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15614        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15615            + self.gutter_dimensions.width
15616            + self.gutter_dimensions.margin;
15617        let y = line_height * (start.row().as_f32() - scroll_position.y);
15618
15619        Some(Bounds {
15620            origin: element_bounds.origin + point(x, y),
15621            size: size(em_width, line_height),
15622        })
15623    }
15624}
15625
15626trait SelectionExt {
15627    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15628    fn spanned_rows(
15629        &self,
15630        include_end_if_at_line_start: bool,
15631        map: &DisplaySnapshot,
15632    ) -> Range<MultiBufferRow>;
15633}
15634
15635impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15636    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15637        let start = self
15638            .start
15639            .to_point(&map.buffer_snapshot)
15640            .to_display_point(map);
15641        let end = self
15642            .end
15643            .to_point(&map.buffer_snapshot)
15644            .to_display_point(map);
15645        if self.reversed {
15646            end..start
15647        } else {
15648            start..end
15649        }
15650    }
15651
15652    fn spanned_rows(
15653        &self,
15654        include_end_if_at_line_start: bool,
15655        map: &DisplaySnapshot,
15656    ) -> Range<MultiBufferRow> {
15657        let start = self.start.to_point(&map.buffer_snapshot);
15658        let mut end = self.end.to_point(&map.buffer_snapshot);
15659        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15660            end.row -= 1;
15661        }
15662
15663        let buffer_start = map.prev_line_boundary(start).0;
15664        let buffer_end = map.next_line_boundary(end).0;
15665        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15666    }
15667}
15668
15669impl<T: InvalidationRegion> InvalidationStack<T> {
15670    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15671    where
15672        S: Clone + ToOffset,
15673    {
15674        while let Some(region) = self.last() {
15675            let all_selections_inside_invalidation_ranges =
15676                if selections.len() == region.ranges().len() {
15677                    selections
15678                        .iter()
15679                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15680                        .all(|(selection, invalidation_range)| {
15681                            let head = selection.head().to_offset(buffer);
15682                            invalidation_range.start <= head && invalidation_range.end >= head
15683                        })
15684                } else {
15685                    false
15686                };
15687
15688            if all_selections_inside_invalidation_ranges {
15689                break;
15690            } else {
15691                self.pop();
15692            }
15693        }
15694    }
15695}
15696
15697impl<T> Default for InvalidationStack<T> {
15698    fn default() -> Self {
15699        Self(Default::default())
15700    }
15701}
15702
15703impl<T> Deref for InvalidationStack<T> {
15704    type Target = Vec<T>;
15705
15706    fn deref(&self) -> &Self::Target {
15707        &self.0
15708    }
15709}
15710
15711impl<T> DerefMut for InvalidationStack<T> {
15712    fn deref_mut(&mut self) -> &mut Self::Target {
15713        &mut self.0
15714    }
15715}
15716
15717impl InvalidationRegion for SnippetState {
15718    fn ranges(&self) -> &[Range<Anchor>] {
15719        &self.ranges[self.active_index]
15720    }
15721}
15722
15723pub fn diagnostic_block_renderer(
15724    diagnostic: Diagnostic,
15725    max_message_rows: Option<u8>,
15726    allow_closing: bool,
15727    _is_valid: bool,
15728) -> RenderBlock {
15729    let (text_without_backticks, code_ranges) =
15730        highlight_diagnostic_message(&diagnostic, max_message_rows);
15731
15732    Arc::new(move |cx: &mut BlockContext| {
15733        let group_id: SharedString = cx.block_id.to_string().into();
15734
15735        let mut text_style = cx.window.text_style().clone();
15736        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15737        let theme_settings = ThemeSettings::get_global(cx);
15738        text_style.font_family = theme_settings.buffer_font.family.clone();
15739        text_style.font_style = theme_settings.buffer_font.style;
15740        text_style.font_features = theme_settings.buffer_font.features.clone();
15741        text_style.font_weight = theme_settings.buffer_font.weight;
15742
15743        let multi_line_diagnostic = diagnostic.message.contains('\n');
15744
15745        let buttons = |diagnostic: &Diagnostic| {
15746            if multi_line_diagnostic {
15747                v_flex()
15748            } else {
15749                h_flex()
15750            }
15751            .when(allow_closing, |div| {
15752                div.children(diagnostic.is_primary.then(|| {
15753                    IconButton::new("close-block", IconName::XCircle)
15754                        .icon_color(Color::Muted)
15755                        .size(ButtonSize::Compact)
15756                        .style(ButtonStyle::Transparent)
15757                        .visible_on_hover(group_id.clone())
15758                        .on_click(move |_click, window, cx| {
15759                            window.dispatch_action(Box::new(Cancel), cx)
15760                        })
15761                        .tooltip(|window, cx| {
15762                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
15763                        })
15764                }))
15765            })
15766            .child(
15767                IconButton::new("copy-block", IconName::Copy)
15768                    .icon_color(Color::Muted)
15769                    .size(ButtonSize::Compact)
15770                    .style(ButtonStyle::Transparent)
15771                    .visible_on_hover(group_id.clone())
15772                    .on_click({
15773                        let message = diagnostic.message.clone();
15774                        move |_click, _, cx| {
15775                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15776                        }
15777                    })
15778                    .tooltip(Tooltip::text("Copy diagnostic message")),
15779            )
15780        };
15781
15782        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
15783            AvailableSpace::min_size(),
15784            cx.window,
15785            cx.app,
15786        );
15787
15788        h_flex()
15789            .id(cx.block_id)
15790            .group(group_id.clone())
15791            .relative()
15792            .size_full()
15793            .block_mouse_down()
15794            .pl(cx.gutter_dimensions.width)
15795            .w(cx.max_width - cx.gutter_dimensions.full_width())
15796            .child(
15797                div()
15798                    .flex()
15799                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15800                    .flex_shrink(),
15801            )
15802            .child(buttons(&diagnostic))
15803            .child(div().flex().flex_shrink_0().child(
15804                StyledText::new(text_without_backticks.clone()).with_highlights(
15805                    &text_style,
15806                    code_ranges.iter().map(|range| {
15807                        (
15808                            range.clone(),
15809                            HighlightStyle {
15810                                font_weight: Some(FontWeight::BOLD),
15811                                ..Default::default()
15812                            },
15813                        )
15814                    }),
15815                ),
15816            ))
15817            .into_any_element()
15818    })
15819}
15820
15821fn inline_completion_edit_text(
15822    editor_snapshot: &EditorSnapshot,
15823    edits: &Vec<(Range<Anchor>, String)>,
15824    include_deletions: bool,
15825    cx: &App,
15826) -> InlineCompletionText {
15827    let edit_start = edits
15828        .first()
15829        .unwrap()
15830        .0
15831        .start
15832        .to_display_point(editor_snapshot);
15833
15834    let mut text = String::new();
15835    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
15836    let mut highlights = Vec::new();
15837    for (old_range, new_text) in edits {
15838        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
15839        text.extend(
15840            editor_snapshot
15841                .buffer_snapshot
15842                .chunks(offset..old_offset_range.start, false)
15843                .map(|chunk| chunk.text),
15844        );
15845        offset = old_offset_range.end;
15846
15847        let start = text.len();
15848        let color = if include_deletions && new_text.is_empty() {
15849            text.extend(
15850                editor_snapshot
15851                    .buffer_snapshot
15852                    .chunks(old_offset_range.start..offset, false)
15853                    .map(|chunk| chunk.text),
15854            );
15855            cx.theme().status().deleted_background
15856        } else {
15857            text.push_str(new_text);
15858            cx.theme().status().created_background
15859        };
15860        let end = text.len();
15861
15862        highlights.push((
15863            start..end,
15864            HighlightStyle {
15865                background_color: Some(color),
15866                ..Default::default()
15867            },
15868        ));
15869    }
15870
15871    let edit_end = edits
15872        .last()
15873        .unwrap()
15874        .0
15875        .end
15876        .to_display_point(editor_snapshot);
15877    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
15878        .to_offset(editor_snapshot, Bias::Right);
15879    text.extend(
15880        editor_snapshot
15881            .buffer_snapshot
15882            .chunks(offset..end_of_line, false)
15883            .map(|chunk| chunk.text),
15884    );
15885
15886    InlineCompletionText::Edit {
15887        text: text.into(),
15888        highlights,
15889    }
15890}
15891
15892pub fn highlight_diagnostic_message(
15893    diagnostic: &Diagnostic,
15894    mut max_message_rows: Option<u8>,
15895) -> (SharedString, Vec<Range<usize>>) {
15896    let mut text_without_backticks = String::new();
15897    let mut code_ranges = Vec::new();
15898
15899    if let Some(source) = &diagnostic.source {
15900        text_without_backticks.push_str(source);
15901        code_ranges.push(0..source.len());
15902        text_without_backticks.push_str(": ");
15903    }
15904
15905    let mut prev_offset = 0;
15906    let mut in_code_block = false;
15907    let has_row_limit = max_message_rows.is_some();
15908    let mut newline_indices = diagnostic
15909        .message
15910        .match_indices('\n')
15911        .filter(|_| has_row_limit)
15912        .map(|(ix, _)| ix)
15913        .fuse()
15914        .peekable();
15915
15916    for (quote_ix, _) in diagnostic
15917        .message
15918        .match_indices('`')
15919        .chain([(diagnostic.message.len(), "")])
15920    {
15921        let mut first_newline_ix = None;
15922        let mut last_newline_ix = None;
15923        while let Some(newline_ix) = newline_indices.peek() {
15924            if *newline_ix < quote_ix {
15925                if first_newline_ix.is_none() {
15926                    first_newline_ix = Some(*newline_ix);
15927                }
15928                last_newline_ix = Some(*newline_ix);
15929
15930                if let Some(rows_left) = &mut max_message_rows {
15931                    if *rows_left == 0 {
15932                        break;
15933                    } else {
15934                        *rows_left -= 1;
15935                    }
15936                }
15937                let _ = newline_indices.next();
15938            } else {
15939                break;
15940            }
15941        }
15942        let prev_len = text_without_backticks.len();
15943        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15944        text_without_backticks.push_str(new_text);
15945        if in_code_block {
15946            code_ranges.push(prev_len..text_without_backticks.len());
15947        }
15948        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15949        in_code_block = !in_code_block;
15950        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15951            text_without_backticks.push_str("...");
15952            break;
15953        }
15954    }
15955
15956    (text_without_backticks.into(), code_ranges)
15957}
15958
15959fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15960    match severity {
15961        DiagnosticSeverity::ERROR => colors.error,
15962        DiagnosticSeverity::WARNING => colors.warning,
15963        DiagnosticSeverity::INFORMATION => colors.info,
15964        DiagnosticSeverity::HINT => colors.info,
15965        _ => colors.ignored,
15966    }
15967}
15968
15969pub fn styled_runs_for_code_label<'a>(
15970    label: &'a CodeLabel,
15971    syntax_theme: &'a theme::SyntaxTheme,
15972) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15973    let fade_out = HighlightStyle {
15974        fade_out: Some(0.35),
15975        ..Default::default()
15976    };
15977
15978    let mut prev_end = label.filter_range.end;
15979    label
15980        .runs
15981        .iter()
15982        .enumerate()
15983        .flat_map(move |(ix, (range, highlight_id))| {
15984            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15985                style
15986            } else {
15987                return Default::default();
15988            };
15989            let mut muted_style = style;
15990            muted_style.highlight(fade_out);
15991
15992            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15993            if range.start >= label.filter_range.end {
15994                if range.start > prev_end {
15995                    runs.push((prev_end..range.start, fade_out));
15996                }
15997                runs.push((range.clone(), muted_style));
15998            } else if range.end <= label.filter_range.end {
15999                runs.push((range.clone(), style));
16000            } else {
16001                runs.push((range.start..label.filter_range.end, style));
16002                runs.push((label.filter_range.end..range.end, muted_style));
16003            }
16004            prev_end = cmp::max(prev_end, range.end);
16005
16006            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16007                runs.push((prev_end..label.text.len(), fade_out));
16008            }
16009
16010            runs
16011        })
16012}
16013
16014pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16015    let mut prev_index = 0;
16016    let mut prev_codepoint: Option<char> = None;
16017    text.char_indices()
16018        .chain([(text.len(), '\0')])
16019        .filter_map(move |(index, codepoint)| {
16020            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16021            let is_boundary = index == text.len()
16022                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16023                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16024            if is_boundary {
16025                let chunk = &text[prev_index..index];
16026                prev_index = index;
16027                Some(chunk)
16028            } else {
16029                None
16030            }
16031        })
16032}
16033
16034pub trait RangeToAnchorExt: Sized {
16035    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16036
16037    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16038        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16039        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16040    }
16041}
16042
16043impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16044    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16045        let start_offset = self.start.to_offset(snapshot);
16046        let end_offset = self.end.to_offset(snapshot);
16047        if start_offset == end_offset {
16048            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16049        } else {
16050            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16051        }
16052    }
16053}
16054
16055pub trait RowExt {
16056    fn as_f32(&self) -> f32;
16057
16058    fn next_row(&self) -> Self;
16059
16060    fn previous_row(&self) -> Self;
16061
16062    fn minus(&self, other: Self) -> u32;
16063}
16064
16065impl RowExt for DisplayRow {
16066    fn as_f32(&self) -> f32 {
16067        self.0 as f32
16068    }
16069
16070    fn next_row(&self) -> Self {
16071        Self(self.0 + 1)
16072    }
16073
16074    fn previous_row(&self) -> Self {
16075        Self(self.0.saturating_sub(1))
16076    }
16077
16078    fn minus(&self, other: Self) -> u32 {
16079        self.0 - other.0
16080    }
16081}
16082
16083impl RowExt for MultiBufferRow {
16084    fn as_f32(&self) -> f32 {
16085        self.0 as f32
16086    }
16087
16088    fn next_row(&self) -> Self {
16089        Self(self.0 + 1)
16090    }
16091
16092    fn previous_row(&self) -> Self {
16093        Self(self.0.saturating_sub(1))
16094    }
16095
16096    fn minus(&self, other: Self) -> u32 {
16097        self.0 - other.0
16098    }
16099}
16100
16101trait RowRangeExt {
16102    type Row;
16103
16104    fn len(&self) -> usize;
16105
16106    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16107}
16108
16109impl RowRangeExt for Range<MultiBufferRow> {
16110    type Row = MultiBufferRow;
16111
16112    fn len(&self) -> usize {
16113        (self.end.0 - self.start.0) as usize
16114    }
16115
16116    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16117        (self.start.0..self.end.0).map(MultiBufferRow)
16118    }
16119}
16120
16121impl RowRangeExt for Range<DisplayRow> {
16122    type Row = DisplayRow;
16123
16124    fn len(&self) -> usize {
16125        (self.end.0 - self.start.0) as usize
16126    }
16127
16128    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16129        (self.start.0..self.end.0).map(DisplayRow)
16130    }
16131}
16132
16133/// If select range has more than one line, we
16134/// just point the cursor to range.start.
16135fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16136    if range.start.row == range.end.row {
16137        range
16138    } else {
16139        range.start..range.start
16140    }
16141}
16142pub struct KillRing(ClipboardItem);
16143impl Global for KillRing {}
16144
16145const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16146
16147fn all_edits_insertions_or_deletions(
16148    edits: &Vec<(Range<Anchor>, String)>,
16149    snapshot: &MultiBufferSnapshot,
16150) -> bool {
16151    let mut all_insertions = true;
16152    let mut all_deletions = true;
16153
16154    for (range, new_text) in edits.iter() {
16155        let range_is_empty = range.to_offset(&snapshot).is_empty();
16156        let text_is_empty = new_text.is_empty();
16157
16158        if range_is_empty != text_is_empty {
16159            if range_is_empty {
16160                all_deletions = false;
16161            } else {
16162                all_insertions = false;
16163            }
16164        } else {
16165            return false;
16166        }
16167
16168        if !all_insertions && !all_deletions {
16169            return false;
16170        }
16171    }
16172    all_insertions || all_deletions
16173}