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