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::*;
   66pub use element::{
   67    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   68};
   69use element::{LineWithInvisibles, PositionMap};
   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    last_position_map: Option<Rc<PositionMap>>,
  727    expect_bounds_change: Option<Bounds<Pixels>>,
  728    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  729    tasks_update_task: Option<Task<()>>,
  730    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  731    breadcrumb_header: Option<String>,
  732    focused_block: Option<FocusedBlock>,
  733    next_scroll_position: NextScrollCursorCenterTopBottom,
  734    addons: HashMap<TypeId, Box<dyn Addon>>,
  735    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  736    selection_mark_mode: bool,
  737    toggle_fold_multiple_buffers: Task<()>,
  738    _scroll_cursor_center_top_bottom_task: Task<()>,
  739}
  740
  741#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  742enum NextScrollCursorCenterTopBottom {
  743    #[default]
  744    Center,
  745    Top,
  746    Bottom,
  747}
  748
  749impl NextScrollCursorCenterTopBottom {
  750    fn next(&self) -> Self {
  751        match self {
  752            Self::Center => Self::Top,
  753            Self::Top => Self::Bottom,
  754            Self::Bottom => Self::Center,
  755        }
  756    }
  757}
  758
  759#[derive(Clone)]
  760pub struct EditorSnapshot {
  761    pub mode: EditorMode,
  762    show_gutter: bool,
  763    show_line_numbers: Option<bool>,
  764    show_git_diff_gutter: Option<bool>,
  765    show_code_actions: Option<bool>,
  766    show_runnables: Option<bool>,
  767    git_blame_gutter_max_author_length: Option<usize>,
  768    pub display_snapshot: DisplaySnapshot,
  769    pub placeholder_text: Option<Arc<str>>,
  770    is_focused: bool,
  771    scroll_anchor: ScrollAnchor,
  772    ongoing_scroll: OngoingScroll,
  773    current_line_highlight: CurrentLineHighlight,
  774    gutter_hovered: bool,
  775}
  776
  777const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  778
  779#[derive(Default, Debug, Clone, Copy)]
  780pub struct GutterDimensions {
  781    pub left_padding: Pixels,
  782    pub right_padding: Pixels,
  783    pub width: Pixels,
  784    pub margin: Pixels,
  785    pub git_blame_entries_width: Option<Pixels>,
  786}
  787
  788impl GutterDimensions {
  789    /// The full width of the space taken up by the gutter.
  790    pub fn full_width(&self) -> Pixels {
  791        self.margin + self.width
  792    }
  793
  794    /// The width of the space reserved for the fold indicators,
  795    /// use alongside 'justify_end' and `gutter_width` to
  796    /// right align content with the line numbers
  797    pub fn fold_area_width(&self) -> Pixels {
  798        self.margin + self.right_padding
  799    }
  800}
  801
  802#[derive(Debug)]
  803pub struct RemoteSelection {
  804    pub replica_id: ReplicaId,
  805    pub selection: Selection<Anchor>,
  806    pub cursor_shape: CursorShape,
  807    pub peer_id: PeerId,
  808    pub line_mode: bool,
  809    pub participant_index: Option<ParticipantIndex>,
  810    pub user_name: Option<SharedString>,
  811}
  812
  813#[derive(Clone, Debug)]
  814struct SelectionHistoryEntry {
  815    selections: Arc<[Selection<Anchor>]>,
  816    select_next_state: Option<SelectNextState>,
  817    select_prev_state: Option<SelectNextState>,
  818    add_selections_state: Option<AddSelectionsState>,
  819}
  820
  821enum SelectionHistoryMode {
  822    Normal,
  823    Undoing,
  824    Redoing,
  825}
  826
  827#[derive(Clone, PartialEq, Eq, Hash)]
  828struct HoveredCursor {
  829    replica_id: u16,
  830    selection_id: usize,
  831}
  832
  833impl Default for SelectionHistoryMode {
  834    fn default() -> Self {
  835        Self::Normal
  836    }
  837}
  838
  839#[derive(Default)]
  840struct SelectionHistory {
  841    #[allow(clippy::type_complexity)]
  842    selections_by_transaction:
  843        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  844    mode: SelectionHistoryMode,
  845    undo_stack: VecDeque<SelectionHistoryEntry>,
  846    redo_stack: VecDeque<SelectionHistoryEntry>,
  847}
  848
  849impl SelectionHistory {
  850    fn insert_transaction(
  851        &mut self,
  852        transaction_id: TransactionId,
  853        selections: Arc<[Selection<Anchor>]>,
  854    ) {
  855        self.selections_by_transaction
  856            .insert(transaction_id, (selections, None));
  857    }
  858
  859    #[allow(clippy::type_complexity)]
  860    fn transaction(
  861        &self,
  862        transaction_id: TransactionId,
  863    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  864        self.selections_by_transaction.get(&transaction_id)
  865    }
  866
  867    #[allow(clippy::type_complexity)]
  868    fn transaction_mut(
  869        &mut self,
  870        transaction_id: TransactionId,
  871    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  872        self.selections_by_transaction.get_mut(&transaction_id)
  873    }
  874
  875    fn push(&mut self, entry: SelectionHistoryEntry) {
  876        if !entry.selections.is_empty() {
  877            match self.mode {
  878                SelectionHistoryMode::Normal => {
  879                    self.push_undo(entry);
  880                    self.redo_stack.clear();
  881                }
  882                SelectionHistoryMode::Undoing => self.push_redo(entry),
  883                SelectionHistoryMode::Redoing => self.push_undo(entry),
  884            }
  885        }
  886    }
  887
  888    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  889        if self
  890            .undo_stack
  891            .back()
  892            .map_or(true, |e| e.selections != entry.selections)
  893        {
  894            self.undo_stack.push_back(entry);
  895            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  896                self.undo_stack.pop_front();
  897            }
  898        }
  899    }
  900
  901    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  902        if self
  903            .redo_stack
  904            .back()
  905            .map_or(true, |e| e.selections != entry.selections)
  906        {
  907            self.redo_stack.push_back(entry);
  908            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  909                self.redo_stack.pop_front();
  910            }
  911        }
  912    }
  913}
  914
  915struct RowHighlight {
  916    index: usize,
  917    range: Range<Anchor>,
  918    color: Hsla,
  919    should_autoscroll: bool,
  920}
  921
  922#[derive(Clone, Debug)]
  923struct AddSelectionsState {
  924    above: bool,
  925    stack: Vec<usize>,
  926}
  927
  928#[derive(Clone)]
  929struct SelectNextState {
  930    query: AhoCorasick,
  931    wordwise: bool,
  932    done: bool,
  933}
  934
  935impl std::fmt::Debug for SelectNextState {
  936    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  937        f.debug_struct(std::any::type_name::<Self>())
  938            .field("wordwise", &self.wordwise)
  939            .field("done", &self.done)
  940            .finish()
  941    }
  942}
  943
  944#[derive(Debug)]
  945struct AutocloseRegion {
  946    selection_id: usize,
  947    range: Range<Anchor>,
  948    pair: BracketPair,
  949}
  950
  951#[derive(Debug)]
  952struct SnippetState {
  953    ranges: Vec<Vec<Range<Anchor>>>,
  954    active_index: usize,
  955    choices: Vec<Option<Vec<String>>>,
  956}
  957
  958#[doc(hidden)]
  959pub struct RenameState {
  960    pub range: Range<Anchor>,
  961    pub old_name: Arc<str>,
  962    pub editor: Entity<Editor>,
  963    block_id: CustomBlockId,
  964}
  965
  966struct InvalidationStack<T>(Vec<T>);
  967
  968struct RegisteredInlineCompletionProvider {
  969    provider: Arc<dyn InlineCompletionProviderHandle>,
  970    _subscription: Subscription,
  971}
  972
  973#[derive(Debug)]
  974struct ActiveDiagnosticGroup {
  975    primary_range: Range<Anchor>,
  976    primary_message: String,
  977    group_id: usize,
  978    blocks: HashMap<CustomBlockId, Diagnostic>,
  979    is_valid: bool,
  980}
  981
  982#[derive(Serialize, Deserialize, Clone, Debug)]
  983pub struct ClipboardSelection {
  984    pub len: usize,
  985    pub is_entire_line: bool,
  986    pub first_line_indent: u32,
  987}
  988
  989#[derive(Debug)]
  990pub(crate) struct NavigationData {
  991    cursor_anchor: Anchor,
  992    cursor_position: Point,
  993    scroll_anchor: ScrollAnchor,
  994    scroll_top_row: u32,
  995}
  996
  997#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  998pub enum GotoDefinitionKind {
  999    Symbol,
 1000    Declaration,
 1001    Type,
 1002    Implementation,
 1003}
 1004
 1005#[derive(Debug, Clone)]
 1006enum InlayHintRefreshReason {
 1007    Toggle(bool),
 1008    SettingsChange(InlayHintSettings),
 1009    NewLinesShown,
 1010    BufferEdited(HashSet<Arc<Language>>),
 1011    RefreshRequested,
 1012    ExcerptsRemoved(Vec<ExcerptId>),
 1013}
 1014
 1015impl InlayHintRefreshReason {
 1016    fn description(&self) -> &'static str {
 1017        match self {
 1018            Self::Toggle(_) => "toggle",
 1019            Self::SettingsChange(_) => "settings change",
 1020            Self::NewLinesShown => "new lines shown",
 1021            Self::BufferEdited(_) => "buffer edited",
 1022            Self::RefreshRequested => "refresh requested",
 1023            Self::ExcerptsRemoved(_) => "excerpts removed",
 1024        }
 1025    }
 1026}
 1027
 1028pub enum FormatTarget {
 1029    Buffers,
 1030    Ranges(Vec<Range<MultiBufferPoint>>),
 1031}
 1032
 1033pub(crate) struct FocusedBlock {
 1034    id: BlockId,
 1035    focus_handle: WeakFocusHandle,
 1036}
 1037
 1038#[derive(Clone)]
 1039enum JumpData {
 1040    MultiBufferRow {
 1041        row: MultiBufferRow,
 1042        line_offset_from_top: u32,
 1043    },
 1044    MultiBufferPoint {
 1045        excerpt_id: ExcerptId,
 1046        position: Point,
 1047        anchor: text::Anchor,
 1048        line_offset_from_top: u32,
 1049    },
 1050}
 1051
 1052pub enum MultibufferSelectionMode {
 1053    First,
 1054    All,
 1055}
 1056
 1057impl Editor {
 1058    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1059        let buffer = cx.new(|cx| Buffer::local("", cx));
 1060        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1061        Self::new(
 1062            EditorMode::SingleLine { auto_width: false },
 1063            buffer,
 1064            None,
 1065            false,
 1066            window,
 1067            cx,
 1068        )
 1069    }
 1070
 1071    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1072        let buffer = cx.new(|cx| Buffer::local("", cx));
 1073        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1074        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1075    }
 1076
 1077    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1078        let buffer = cx.new(|cx| Buffer::local("", cx));
 1079        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1080        Self::new(
 1081            EditorMode::SingleLine { auto_width: true },
 1082            buffer,
 1083            None,
 1084            false,
 1085            window,
 1086            cx,
 1087        )
 1088    }
 1089
 1090    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1091        let buffer = cx.new(|cx| Buffer::local("", cx));
 1092        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1093        Self::new(
 1094            EditorMode::AutoHeight { max_lines },
 1095            buffer,
 1096            None,
 1097            false,
 1098            window,
 1099            cx,
 1100        )
 1101    }
 1102
 1103    pub fn for_buffer(
 1104        buffer: Entity<Buffer>,
 1105        project: Option<Entity<Project>>,
 1106        window: &mut Window,
 1107        cx: &mut Context<Self>,
 1108    ) -> Self {
 1109        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1110        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1111    }
 1112
 1113    pub fn for_multibuffer(
 1114        buffer: Entity<MultiBuffer>,
 1115        project: Option<Entity<Project>>,
 1116        show_excerpt_controls: bool,
 1117        window: &mut Window,
 1118        cx: &mut Context<Self>,
 1119    ) -> Self {
 1120        Self::new(
 1121            EditorMode::Full,
 1122            buffer,
 1123            project,
 1124            show_excerpt_controls,
 1125            window,
 1126            cx,
 1127        )
 1128    }
 1129
 1130    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1131        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1132        let mut clone = Self::new(
 1133            self.mode,
 1134            self.buffer.clone(),
 1135            self.project.clone(),
 1136            show_excerpt_controls,
 1137            window,
 1138            cx,
 1139        );
 1140        self.display_map.update(cx, |display_map, cx| {
 1141            let snapshot = display_map.snapshot(cx);
 1142            clone.display_map.update(cx, |display_map, cx| {
 1143                display_map.set_state(&snapshot, cx);
 1144            });
 1145        });
 1146        clone.selections.clone_state(&self.selections);
 1147        clone.scroll_manager.clone_state(&self.scroll_manager);
 1148        clone.searchable = self.searchable;
 1149        clone
 1150    }
 1151
 1152    pub fn new(
 1153        mode: EditorMode,
 1154        buffer: Entity<MultiBuffer>,
 1155        project: Option<Entity<Project>>,
 1156        show_excerpt_controls: bool,
 1157        window: &mut Window,
 1158        cx: &mut Context<Self>,
 1159    ) -> Self {
 1160        let style = window.text_style();
 1161        let font_size = style.font_size.to_pixels(window.rem_size());
 1162        let editor = cx.entity().downgrade();
 1163        let fold_placeholder = FoldPlaceholder {
 1164            constrain_width: true,
 1165            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1166                let editor = editor.clone();
 1167                div()
 1168                    .id(fold_id)
 1169                    .bg(cx.theme().colors().ghost_element_background)
 1170                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1171                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1172                    .rounded_sm()
 1173                    .size_full()
 1174                    .cursor_pointer()
 1175                    .child("")
 1176                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1177                    .on_click(move |_, _window, cx| {
 1178                        editor
 1179                            .update(cx, |editor, cx| {
 1180                                editor.unfold_ranges(
 1181                                    &[fold_range.start..fold_range.end],
 1182                                    true,
 1183                                    false,
 1184                                    cx,
 1185                                );
 1186                                cx.stop_propagation();
 1187                            })
 1188                            .ok();
 1189                    })
 1190                    .into_any()
 1191            }),
 1192            merge_adjacent: true,
 1193            ..Default::default()
 1194        };
 1195        let display_map = cx.new(|cx| {
 1196            DisplayMap::new(
 1197                buffer.clone(),
 1198                style.font(),
 1199                font_size,
 1200                None,
 1201                show_excerpt_controls,
 1202                FILE_HEADER_HEIGHT,
 1203                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1204                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1205                fold_placeholder,
 1206                cx,
 1207            )
 1208        });
 1209
 1210        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1211
 1212        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1213
 1214        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1215            .then(|| language_settings::SoftWrap::None);
 1216
 1217        let mut project_subscriptions = Vec::new();
 1218        if mode == EditorMode::Full {
 1219            if let Some(project) = project.as_ref() {
 1220                if buffer.read(cx).is_singleton() {
 1221                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1222                        cx.emit(EditorEvent::TitleChanged);
 1223                    }));
 1224                }
 1225                project_subscriptions.push(cx.subscribe_in(
 1226                    project,
 1227                    window,
 1228                    |editor, _, event, window, cx| {
 1229                        if let project::Event::RefreshInlayHints = event {
 1230                            editor
 1231                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1232                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1233                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1234                                let focus_handle = editor.focus_handle(cx);
 1235                                if focus_handle.is_focused(window) {
 1236                                    let snapshot = buffer.read(cx).snapshot();
 1237                                    for (range, snippet) in snippet_edits {
 1238                                        let editor_range =
 1239                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1240                                        editor
 1241                                            .insert_snippet(
 1242                                                &[editor_range],
 1243                                                snippet.clone(),
 1244                                                window,
 1245                                                cx,
 1246                                            )
 1247                                            .ok();
 1248                                    }
 1249                                }
 1250                            }
 1251                        }
 1252                    },
 1253                ));
 1254                if let Some(task_inventory) = project
 1255                    .read(cx)
 1256                    .task_store()
 1257                    .read(cx)
 1258                    .task_inventory()
 1259                    .cloned()
 1260                {
 1261                    project_subscriptions.push(cx.observe_in(
 1262                        &task_inventory,
 1263                        window,
 1264                        |editor, _, window, cx| {
 1265                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1266                        },
 1267                    ));
 1268                }
 1269            }
 1270        }
 1271
 1272        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1273
 1274        let inlay_hint_settings =
 1275            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1276        let focus_handle = cx.focus_handle();
 1277        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1278            .detach();
 1279        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1280            .detach();
 1281        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1282            .detach();
 1283        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1284            .detach();
 1285
 1286        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1287            Some(false)
 1288        } else {
 1289            None
 1290        };
 1291
 1292        let mut code_action_providers = Vec::new();
 1293        if let Some(project) = project.clone() {
 1294            get_unstaged_changes_for_buffers(
 1295                &project,
 1296                buffer.read(cx).all_buffers(),
 1297                buffer.clone(),
 1298                cx,
 1299            );
 1300            code_action_providers.push(Rc::new(project) as Rc<_>);
 1301        }
 1302
 1303        let mut this = Self {
 1304            focus_handle,
 1305            show_cursor_when_unfocused: false,
 1306            last_focused_descendant: None,
 1307            buffer: buffer.clone(),
 1308            display_map: display_map.clone(),
 1309            selections,
 1310            scroll_manager: ScrollManager::new(cx),
 1311            columnar_selection_tail: None,
 1312            add_selections_state: None,
 1313            select_next_state: None,
 1314            select_prev_state: None,
 1315            selection_history: Default::default(),
 1316            autoclose_regions: Default::default(),
 1317            snippet_stack: Default::default(),
 1318            select_larger_syntax_node_stack: Vec::new(),
 1319            ime_transaction: Default::default(),
 1320            active_diagnostics: None,
 1321            soft_wrap_mode_override,
 1322            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1323            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1324            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1325            project,
 1326            blink_manager: blink_manager.clone(),
 1327            show_local_selections: true,
 1328            show_scrollbars: true,
 1329            mode,
 1330            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1331            show_gutter: mode == EditorMode::Full,
 1332            show_line_numbers: None,
 1333            use_relative_line_numbers: None,
 1334            show_git_diff_gutter: None,
 1335            show_code_actions: None,
 1336            show_runnables: None,
 1337            show_wrap_guides: None,
 1338            show_indent_guides,
 1339            placeholder_text: None,
 1340            highlight_order: 0,
 1341            highlighted_rows: HashMap::default(),
 1342            background_highlights: Default::default(),
 1343            gutter_highlights: TreeMap::default(),
 1344            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1345            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1346            nav_history: None,
 1347            context_menu: RefCell::new(None),
 1348            mouse_context_menu: None,
 1349            completion_tasks: Default::default(),
 1350            signature_help_state: SignatureHelpState::default(),
 1351            auto_signature_help: None,
 1352            find_all_references_task_sources: Vec::new(),
 1353            next_completion_id: 0,
 1354            next_inlay_id: 0,
 1355            code_action_providers,
 1356            available_code_actions: Default::default(),
 1357            code_actions_task: Default::default(),
 1358            document_highlights_task: Default::default(),
 1359            linked_editing_range_task: Default::default(),
 1360            pending_rename: Default::default(),
 1361            searchable: true,
 1362            cursor_shape: EditorSettings::get_global(cx)
 1363                .cursor_shape
 1364                .unwrap_or_default(),
 1365            current_line_highlight: None,
 1366            autoindent_mode: Some(AutoindentMode::EachLine),
 1367            collapse_matches: false,
 1368            workspace: None,
 1369            input_enabled: true,
 1370            use_modal_editing: mode == EditorMode::Full,
 1371            read_only: false,
 1372            use_autoclose: true,
 1373            use_auto_surround: true,
 1374            auto_replace_emoji_shortcode: false,
 1375            leader_peer_id: None,
 1376            remote_id: None,
 1377            hover_state: Default::default(),
 1378            hovered_link_state: Default::default(),
 1379            inline_completion_provider: None,
 1380            active_inline_completion: None,
 1381            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1382
 1383            gutter_hovered: false,
 1384            pixel_position_of_newest_cursor: None,
 1385            last_bounds: None,
 1386            last_position_map: None,
 1387            expect_bounds_change: None,
 1388            gutter_dimensions: GutterDimensions::default(),
 1389            style: None,
 1390            show_cursor_names: false,
 1391            hovered_cursors: Default::default(),
 1392            next_editor_action_id: EditorActionId::default(),
 1393            editor_actions: Rc::default(),
 1394            show_inline_completions_override: None,
 1395            enable_inline_completions: true,
 1396            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1397            custom_context_menu: None,
 1398            show_git_blame_gutter: false,
 1399            show_git_blame_inline: false,
 1400            show_selection_menu: None,
 1401            show_git_blame_inline_delay_task: None,
 1402            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1403            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1404                .session
 1405                .restore_unsaved_buffers,
 1406            blame: None,
 1407            blame_subscription: None,
 1408            tasks: Default::default(),
 1409            _subscriptions: vec![
 1410                cx.observe(&buffer, Self::on_buffer_changed),
 1411                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1412                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1413                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1414                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1415                cx.observe_window_activation(window, |editor, window, cx| {
 1416                    let active = window.is_window_active();
 1417                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1418                        if active {
 1419                            blink_manager.enable(cx);
 1420                        } else {
 1421                            blink_manager.disable(cx);
 1422                        }
 1423                    });
 1424                }),
 1425            ],
 1426            tasks_update_task: None,
 1427            linked_edit_ranges: Default::default(),
 1428            previous_search_ranges: None,
 1429            breadcrumb_header: None,
 1430            focused_block: None,
 1431            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1432            addons: HashMap::default(),
 1433            registered_buffers: HashMap::default(),
 1434            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1435            selection_mark_mode: false,
 1436            toggle_fold_multiple_buffers: Task::ready(()),
 1437            text_style_refinement: None,
 1438        };
 1439        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1440        this._subscriptions.extend(project_subscriptions);
 1441
 1442        this.end_selection(window, cx);
 1443        this.scroll_manager.show_scrollbar(window, cx);
 1444
 1445        if mode == EditorMode::Full {
 1446            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1447            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1448
 1449            if this.git_blame_inline_enabled {
 1450                this.git_blame_inline_enabled = true;
 1451                this.start_git_blame_inline(false, window, cx);
 1452            }
 1453
 1454            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1455                if let Some(project) = this.project.as_ref() {
 1456                    let lsp_store = project.read(cx).lsp_store();
 1457                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1458                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1459                    });
 1460                    this.registered_buffers
 1461                        .insert(buffer.read(cx).remote_id(), handle);
 1462                }
 1463            }
 1464        }
 1465
 1466        this.report_editor_event("Editor Opened", None, cx);
 1467        this
 1468    }
 1469
 1470    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1471        self.mouse_context_menu
 1472            .as_ref()
 1473            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1474    }
 1475
 1476    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1477        let mut key_context = KeyContext::new_with_defaults();
 1478        key_context.add("Editor");
 1479        let mode = match self.mode {
 1480            EditorMode::SingleLine { .. } => "single_line",
 1481            EditorMode::AutoHeight { .. } => "auto_height",
 1482            EditorMode::Full => "full",
 1483        };
 1484
 1485        if EditorSettings::jupyter_enabled(cx) {
 1486            key_context.add("jupyter");
 1487        }
 1488
 1489        key_context.set("mode", mode);
 1490        if self.pending_rename.is_some() {
 1491            key_context.add("renaming");
 1492        }
 1493        match self.context_menu.borrow().as_ref() {
 1494            Some(CodeContextMenu::Completions(_)) => {
 1495                key_context.add("menu");
 1496                key_context.add("showing_completions")
 1497            }
 1498            Some(CodeContextMenu::CodeActions(_)) => {
 1499                key_context.add("menu");
 1500                key_context.add("showing_code_actions")
 1501            }
 1502            None => {}
 1503        }
 1504
 1505        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1506        if !self.focus_handle(cx).contains_focused(window, cx)
 1507            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1508        {
 1509            for addon in self.addons.values() {
 1510                addon.extend_key_context(&mut key_context, cx)
 1511            }
 1512        }
 1513
 1514        if let Some(extension) = self
 1515            .buffer
 1516            .read(cx)
 1517            .as_singleton()
 1518            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1519        {
 1520            key_context.set("extension", extension.to_string());
 1521        }
 1522
 1523        if self.has_active_inline_completion() {
 1524            key_context.add("copilot_suggestion");
 1525            key_context.add("inline_completion");
 1526        }
 1527
 1528        if self.selection_mark_mode {
 1529            key_context.add("selection_mode");
 1530        }
 1531
 1532        key_context
 1533    }
 1534
 1535    pub fn new_file(
 1536        workspace: &mut Workspace,
 1537        _: &workspace::NewFile,
 1538        window: &mut Window,
 1539        cx: &mut Context<Workspace>,
 1540    ) {
 1541        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1542            "Failed to create buffer",
 1543            window,
 1544            cx,
 1545            |e, _, _| match e.error_code() {
 1546                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1547                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1548                e.error_tag("required").unwrap_or("the latest version")
 1549            )),
 1550                _ => None,
 1551            },
 1552        );
 1553    }
 1554
 1555    pub fn new_in_workspace(
 1556        workspace: &mut Workspace,
 1557        window: &mut Window,
 1558        cx: &mut Context<Workspace>,
 1559    ) -> Task<Result<Entity<Editor>>> {
 1560        let project = workspace.project().clone();
 1561        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1562
 1563        cx.spawn_in(window, |workspace, mut cx| async move {
 1564            let buffer = create.await?;
 1565            workspace.update_in(&mut cx, |workspace, window, cx| {
 1566                let editor =
 1567                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1568                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1569                editor
 1570            })
 1571        })
 1572    }
 1573
 1574    fn new_file_vertical(
 1575        workspace: &mut Workspace,
 1576        _: &workspace::NewFileSplitVertical,
 1577        window: &mut Window,
 1578        cx: &mut Context<Workspace>,
 1579    ) {
 1580        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1581    }
 1582
 1583    fn new_file_horizontal(
 1584        workspace: &mut Workspace,
 1585        _: &workspace::NewFileSplitHorizontal,
 1586        window: &mut Window,
 1587        cx: &mut Context<Workspace>,
 1588    ) {
 1589        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1590    }
 1591
 1592    fn new_file_in_direction(
 1593        workspace: &mut Workspace,
 1594        direction: SplitDirection,
 1595        window: &mut Window,
 1596        cx: &mut Context<Workspace>,
 1597    ) {
 1598        let project = workspace.project().clone();
 1599        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1600
 1601        cx.spawn_in(window, |workspace, mut cx| async move {
 1602            let buffer = create.await?;
 1603            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1604                workspace.split_item(
 1605                    direction,
 1606                    Box::new(
 1607                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1608                    ),
 1609                    window,
 1610                    cx,
 1611                )
 1612            })?;
 1613            anyhow::Ok(())
 1614        })
 1615        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1616            match e.error_code() {
 1617                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1618                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1619                e.error_tag("required").unwrap_or("the latest version")
 1620            )),
 1621                _ => None,
 1622            }
 1623        });
 1624    }
 1625
 1626    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1627        self.leader_peer_id
 1628    }
 1629
 1630    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1631        &self.buffer
 1632    }
 1633
 1634    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1635        self.workspace.as_ref()?.0.upgrade()
 1636    }
 1637
 1638    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1639        self.buffer().read(cx).title(cx)
 1640    }
 1641
 1642    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1643        let git_blame_gutter_max_author_length = self
 1644            .render_git_blame_gutter(cx)
 1645            .then(|| {
 1646                if let Some(blame) = self.blame.as_ref() {
 1647                    let max_author_length =
 1648                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1649                    Some(max_author_length)
 1650                } else {
 1651                    None
 1652                }
 1653            })
 1654            .flatten();
 1655
 1656        EditorSnapshot {
 1657            mode: self.mode,
 1658            show_gutter: self.show_gutter,
 1659            show_line_numbers: self.show_line_numbers,
 1660            show_git_diff_gutter: self.show_git_diff_gutter,
 1661            show_code_actions: self.show_code_actions,
 1662            show_runnables: self.show_runnables,
 1663            git_blame_gutter_max_author_length,
 1664            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1665            scroll_anchor: self.scroll_manager.anchor(),
 1666            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1667            placeholder_text: self.placeholder_text.clone(),
 1668            is_focused: self.focus_handle.is_focused(window),
 1669            current_line_highlight: self
 1670                .current_line_highlight
 1671                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1672            gutter_hovered: self.gutter_hovered,
 1673        }
 1674    }
 1675
 1676    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1677        self.buffer.read(cx).language_at(point, cx)
 1678    }
 1679
 1680    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1681        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1682    }
 1683
 1684    pub fn active_excerpt(
 1685        &self,
 1686        cx: &App,
 1687    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1688        self.buffer
 1689            .read(cx)
 1690            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1691    }
 1692
 1693    pub fn mode(&self) -> EditorMode {
 1694        self.mode
 1695    }
 1696
 1697    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1698        self.collaboration_hub.as_deref()
 1699    }
 1700
 1701    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1702        self.collaboration_hub = Some(hub);
 1703    }
 1704
 1705    pub fn set_custom_context_menu(
 1706        &mut self,
 1707        f: impl 'static
 1708            + Fn(
 1709                &mut Self,
 1710                DisplayPoint,
 1711                &mut Window,
 1712                &mut Context<Self>,
 1713            ) -> Option<Entity<ui::ContextMenu>>,
 1714    ) {
 1715        self.custom_context_menu = Some(Box::new(f))
 1716    }
 1717
 1718    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1719        self.completion_provider = provider;
 1720    }
 1721
 1722    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1723        self.semantics_provider.clone()
 1724    }
 1725
 1726    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1727        self.semantics_provider = provider;
 1728    }
 1729
 1730    pub fn set_inline_completion_provider<T>(
 1731        &mut self,
 1732        provider: Option<Entity<T>>,
 1733        window: &mut Window,
 1734        cx: &mut Context<Self>,
 1735    ) where
 1736        T: InlineCompletionProvider,
 1737    {
 1738        self.inline_completion_provider =
 1739            provider.map(|provider| RegisteredInlineCompletionProvider {
 1740                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1741                    if this.focus_handle.is_focused(window) {
 1742                        this.update_visible_inline_completion(window, cx);
 1743                    }
 1744                }),
 1745                provider: Arc::new(provider),
 1746            });
 1747        self.refresh_inline_completion(false, false, window, cx);
 1748    }
 1749
 1750    pub fn placeholder_text(&self) -> Option<&str> {
 1751        self.placeholder_text.as_deref()
 1752    }
 1753
 1754    pub fn set_placeholder_text(
 1755        &mut self,
 1756        placeholder_text: impl Into<Arc<str>>,
 1757        cx: &mut Context<Self>,
 1758    ) {
 1759        let placeholder_text = Some(placeholder_text.into());
 1760        if self.placeholder_text != placeholder_text {
 1761            self.placeholder_text = placeholder_text;
 1762            cx.notify();
 1763        }
 1764    }
 1765
 1766    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1767        self.cursor_shape = cursor_shape;
 1768
 1769        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1770        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1771
 1772        cx.notify();
 1773    }
 1774
 1775    pub fn set_current_line_highlight(
 1776        &mut self,
 1777        current_line_highlight: Option<CurrentLineHighlight>,
 1778    ) {
 1779        self.current_line_highlight = current_line_highlight;
 1780    }
 1781
 1782    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1783        self.collapse_matches = collapse_matches;
 1784    }
 1785
 1786    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1787        let buffers = self.buffer.read(cx).all_buffers();
 1788        let Some(lsp_store) = self.lsp_store(cx) else {
 1789            return;
 1790        };
 1791        lsp_store.update(cx, |lsp_store, cx| {
 1792            for buffer in buffers {
 1793                self.registered_buffers
 1794                    .entry(buffer.read(cx).remote_id())
 1795                    .or_insert_with(|| {
 1796                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1797                    });
 1798            }
 1799        })
 1800    }
 1801
 1802    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1803        if self.collapse_matches {
 1804            return range.start..range.start;
 1805        }
 1806        range.clone()
 1807    }
 1808
 1809    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1810        if self.display_map.read(cx).clip_at_line_ends != clip {
 1811            self.display_map
 1812                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1813        }
 1814    }
 1815
 1816    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1817        self.input_enabled = input_enabled;
 1818    }
 1819
 1820    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1821        self.enable_inline_completions = enabled;
 1822        if !self.enable_inline_completions {
 1823            self.take_active_inline_completion(cx);
 1824            cx.notify();
 1825        }
 1826    }
 1827
 1828    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1829        self.menu_inline_completions_policy = value;
 1830    }
 1831
 1832    pub fn set_autoindent(&mut self, autoindent: bool) {
 1833        if autoindent {
 1834            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1835        } else {
 1836            self.autoindent_mode = None;
 1837        }
 1838    }
 1839
 1840    pub fn read_only(&self, cx: &App) -> bool {
 1841        self.read_only || self.buffer.read(cx).read_only()
 1842    }
 1843
 1844    pub fn set_read_only(&mut self, read_only: bool) {
 1845        self.read_only = read_only;
 1846    }
 1847
 1848    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1849        self.use_autoclose = autoclose;
 1850    }
 1851
 1852    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1853        self.use_auto_surround = auto_surround;
 1854    }
 1855
 1856    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1857        self.auto_replace_emoji_shortcode = auto_replace;
 1858    }
 1859
 1860    pub fn toggle_inline_completions(
 1861        &mut self,
 1862        _: &ToggleInlineCompletions,
 1863        window: &mut Window,
 1864        cx: &mut Context<Self>,
 1865    ) {
 1866        if self.show_inline_completions_override.is_some() {
 1867            self.set_show_inline_completions(None, window, cx);
 1868        } else {
 1869            let cursor = self.selections.newest_anchor().head();
 1870            if let Some((buffer, cursor_buffer_position)) =
 1871                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1872            {
 1873                let show_inline_completions =
 1874                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1875                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1876            }
 1877        }
 1878    }
 1879
 1880    pub fn set_show_inline_completions(
 1881        &mut self,
 1882        show_inline_completions: Option<bool>,
 1883        window: &mut Window,
 1884        cx: &mut Context<Self>,
 1885    ) {
 1886        self.show_inline_completions_override = show_inline_completions;
 1887        self.refresh_inline_completion(false, true, window, cx);
 1888    }
 1889
 1890    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1891        let cursor = self.selections.newest_anchor().head();
 1892        if let Some((buffer, buffer_position)) =
 1893            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1894        {
 1895            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1896        } else {
 1897            false
 1898        }
 1899    }
 1900
 1901    fn should_show_inline_completions(
 1902        &self,
 1903        buffer: &Entity<Buffer>,
 1904        buffer_position: language::Anchor,
 1905        cx: &App,
 1906    ) -> bool {
 1907        if !self.snippet_stack.is_empty() {
 1908            return false;
 1909        }
 1910
 1911        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1912            return false;
 1913        }
 1914
 1915        if let Some(provider) = self.inline_completion_provider() {
 1916            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1917                show_inline_completions
 1918            } else {
 1919                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1920            }
 1921        } else {
 1922            false
 1923        }
 1924    }
 1925
 1926    fn inline_completions_disabled_in_scope(
 1927        &self,
 1928        buffer: &Entity<Buffer>,
 1929        buffer_position: language::Anchor,
 1930        cx: &App,
 1931    ) -> bool {
 1932        let snapshot = buffer.read(cx).snapshot();
 1933        let settings = snapshot.settings_at(buffer_position, cx);
 1934
 1935        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1936            return false;
 1937        };
 1938
 1939        scope.override_name().map_or(false, |scope_name| {
 1940            settings
 1941                .inline_completions_disabled_in
 1942                .iter()
 1943                .any(|s| s == scope_name)
 1944        })
 1945    }
 1946
 1947    pub fn set_use_modal_editing(&mut self, to: bool) {
 1948        self.use_modal_editing = to;
 1949    }
 1950
 1951    pub fn use_modal_editing(&self) -> bool {
 1952        self.use_modal_editing
 1953    }
 1954
 1955    fn selections_did_change(
 1956        &mut self,
 1957        local: bool,
 1958        old_cursor_position: &Anchor,
 1959        show_completions: bool,
 1960        window: &mut Window,
 1961        cx: &mut Context<Self>,
 1962    ) {
 1963        window.invalidate_character_coordinates();
 1964
 1965        // Copy selections to primary selection buffer
 1966        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1967        if local {
 1968            let selections = self.selections.all::<usize>(cx);
 1969            let buffer_handle = self.buffer.read(cx).read(cx);
 1970
 1971            let mut text = String::new();
 1972            for (index, selection) in selections.iter().enumerate() {
 1973                let text_for_selection = buffer_handle
 1974                    .text_for_range(selection.start..selection.end)
 1975                    .collect::<String>();
 1976
 1977                text.push_str(&text_for_selection);
 1978                if index != selections.len() - 1 {
 1979                    text.push('\n');
 1980                }
 1981            }
 1982
 1983            if !text.is_empty() {
 1984                cx.write_to_primary(ClipboardItem::new_string(text));
 1985            }
 1986        }
 1987
 1988        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1989            self.buffer.update(cx, |buffer, cx| {
 1990                buffer.set_active_selections(
 1991                    &self.selections.disjoint_anchors(),
 1992                    self.selections.line_mode,
 1993                    self.cursor_shape,
 1994                    cx,
 1995                )
 1996            });
 1997        }
 1998        let display_map = self
 1999            .display_map
 2000            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2001        let buffer = &display_map.buffer_snapshot;
 2002        self.add_selections_state = None;
 2003        self.select_next_state = None;
 2004        self.select_prev_state = None;
 2005        self.select_larger_syntax_node_stack.clear();
 2006        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2007        self.snippet_stack
 2008            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2009        self.take_rename(false, window, cx);
 2010
 2011        let new_cursor_position = self.selections.newest_anchor().head();
 2012
 2013        self.push_to_nav_history(
 2014            *old_cursor_position,
 2015            Some(new_cursor_position.to_point(buffer)),
 2016            cx,
 2017        );
 2018
 2019        if local {
 2020            let new_cursor_position = self.selections.newest_anchor().head();
 2021            let mut context_menu = self.context_menu.borrow_mut();
 2022            let completion_menu = match context_menu.as_ref() {
 2023                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2024                _ => {
 2025                    *context_menu = None;
 2026                    None
 2027                }
 2028            };
 2029
 2030            if let Some(completion_menu) = completion_menu {
 2031                let cursor_position = new_cursor_position.to_offset(buffer);
 2032                let (word_range, kind) =
 2033                    buffer.surrounding_word(completion_menu.initial_position, true);
 2034                if kind == Some(CharKind::Word)
 2035                    && word_range.to_inclusive().contains(&cursor_position)
 2036                {
 2037                    let mut completion_menu = completion_menu.clone();
 2038                    drop(context_menu);
 2039
 2040                    let query = Self::completion_query(buffer, cursor_position);
 2041                    cx.spawn(move |this, mut cx| async move {
 2042                        completion_menu
 2043                            .filter(query.as_deref(), cx.background_executor().clone())
 2044                            .await;
 2045
 2046                        this.update(&mut cx, |this, cx| {
 2047                            let mut context_menu = this.context_menu.borrow_mut();
 2048                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2049                            else {
 2050                                return;
 2051                            };
 2052
 2053                            if menu.id > completion_menu.id {
 2054                                return;
 2055                            }
 2056
 2057                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2058                            drop(context_menu);
 2059                            cx.notify();
 2060                        })
 2061                    })
 2062                    .detach();
 2063
 2064                    if show_completions {
 2065                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2066                    }
 2067                } else {
 2068                    drop(context_menu);
 2069                    self.hide_context_menu(window, cx);
 2070                }
 2071            } else {
 2072                drop(context_menu);
 2073            }
 2074
 2075            hide_hover(self, cx);
 2076
 2077            if old_cursor_position.to_display_point(&display_map).row()
 2078                != new_cursor_position.to_display_point(&display_map).row()
 2079            {
 2080                self.available_code_actions.take();
 2081            }
 2082            self.refresh_code_actions(window, cx);
 2083            self.refresh_document_highlights(cx);
 2084            refresh_matching_bracket_highlights(self, window, cx);
 2085            self.update_visible_inline_completion(window, cx);
 2086            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2087            if self.git_blame_inline_enabled {
 2088                self.start_inline_blame_timer(window, cx);
 2089            }
 2090        }
 2091
 2092        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2093        cx.emit(EditorEvent::SelectionsChanged { local });
 2094
 2095        if self.selections.disjoint_anchors().len() == 1 {
 2096            cx.emit(SearchEvent::ActiveMatchChanged)
 2097        }
 2098        cx.notify();
 2099    }
 2100
 2101    pub fn change_selections<R>(
 2102        &mut self,
 2103        autoscroll: Option<Autoscroll>,
 2104        window: &mut Window,
 2105        cx: &mut Context<Self>,
 2106        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2107    ) -> R {
 2108        self.change_selections_inner(autoscroll, true, window, cx, change)
 2109    }
 2110
 2111    pub fn change_selections_inner<R>(
 2112        &mut self,
 2113        autoscroll: Option<Autoscroll>,
 2114        request_completions: bool,
 2115        window: &mut Window,
 2116        cx: &mut Context<Self>,
 2117        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2118    ) -> R {
 2119        let old_cursor_position = self.selections.newest_anchor().head();
 2120        self.push_to_selection_history();
 2121
 2122        let (changed, result) = self.selections.change_with(cx, change);
 2123
 2124        if changed {
 2125            if let Some(autoscroll) = autoscroll {
 2126                self.request_autoscroll(autoscroll, cx);
 2127            }
 2128            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2129
 2130            if self.should_open_signature_help_automatically(
 2131                &old_cursor_position,
 2132                self.signature_help_state.backspace_pressed(),
 2133                cx,
 2134            ) {
 2135                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2136            }
 2137            self.signature_help_state.set_backspace_pressed(false);
 2138        }
 2139
 2140        result
 2141    }
 2142
 2143    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2144    where
 2145        I: IntoIterator<Item = (Range<S>, T)>,
 2146        S: ToOffset,
 2147        T: Into<Arc<str>>,
 2148    {
 2149        if self.read_only(cx) {
 2150            return;
 2151        }
 2152
 2153        self.buffer
 2154            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2155    }
 2156
 2157    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2158    where
 2159        I: IntoIterator<Item = (Range<S>, T)>,
 2160        S: ToOffset,
 2161        T: Into<Arc<str>>,
 2162    {
 2163        if self.read_only(cx) {
 2164            return;
 2165        }
 2166
 2167        self.buffer.update(cx, |buffer, cx| {
 2168            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2169        });
 2170    }
 2171
 2172    pub fn edit_with_block_indent<I, S, T>(
 2173        &mut self,
 2174        edits: I,
 2175        original_indent_columns: Vec<u32>,
 2176        cx: &mut Context<Self>,
 2177    ) where
 2178        I: IntoIterator<Item = (Range<S>, T)>,
 2179        S: ToOffset,
 2180        T: Into<Arc<str>>,
 2181    {
 2182        if self.read_only(cx) {
 2183            return;
 2184        }
 2185
 2186        self.buffer.update(cx, |buffer, cx| {
 2187            buffer.edit(
 2188                edits,
 2189                Some(AutoindentMode::Block {
 2190                    original_indent_columns,
 2191                }),
 2192                cx,
 2193            )
 2194        });
 2195    }
 2196
 2197    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2198        self.hide_context_menu(window, cx);
 2199
 2200        match phase {
 2201            SelectPhase::Begin {
 2202                position,
 2203                add,
 2204                click_count,
 2205            } => self.begin_selection(position, add, click_count, window, cx),
 2206            SelectPhase::BeginColumnar {
 2207                position,
 2208                goal_column,
 2209                reset,
 2210            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2211            SelectPhase::Extend {
 2212                position,
 2213                click_count,
 2214            } => self.extend_selection(position, click_count, window, cx),
 2215            SelectPhase::Update {
 2216                position,
 2217                goal_column,
 2218                scroll_delta,
 2219            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2220            SelectPhase::End => self.end_selection(window, cx),
 2221        }
 2222    }
 2223
 2224    fn extend_selection(
 2225        &mut self,
 2226        position: DisplayPoint,
 2227        click_count: usize,
 2228        window: &mut Window,
 2229        cx: &mut Context<Self>,
 2230    ) {
 2231        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2232        let tail = self.selections.newest::<usize>(cx).tail();
 2233        self.begin_selection(position, false, click_count, window, cx);
 2234
 2235        let position = position.to_offset(&display_map, Bias::Left);
 2236        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2237
 2238        let mut pending_selection = self
 2239            .selections
 2240            .pending_anchor()
 2241            .expect("extend_selection not called with pending selection");
 2242        if position >= tail {
 2243            pending_selection.start = tail_anchor;
 2244        } else {
 2245            pending_selection.end = tail_anchor;
 2246            pending_selection.reversed = true;
 2247        }
 2248
 2249        let mut pending_mode = self.selections.pending_mode().unwrap();
 2250        match &mut pending_mode {
 2251            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2252            _ => {}
 2253        }
 2254
 2255        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2256            s.set_pending(pending_selection, pending_mode)
 2257        });
 2258    }
 2259
 2260    fn begin_selection(
 2261        &mut self,
 2262        position: DisplayPoint,
 2263        add: bool,
 2264        click_count: usize,
 2265        window: &mut Window,
 2266        cx: &mut Context<Self>,
 2267    ) {
 2268        if !self.focus_handle.is_focused(window) {
 2269            self.last_focused_descendant = None;
 2270            window.focus(&self.focus_handle);
 2271        }
 2272
 2273        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2274        let buffer = &display_map.buffer_snapshot;
 2275        let newest_selection = self.selections.newest_anchor().clone();
 2276        let position = display_map.clip_point(position, Bias::Left);
 2277
 2278        let start;
 2279        let end;
 2280        let mode;
 2281        let mut auto_scroll;
 2282        match click_count {
 2283            1 => {
 2284                start = buffer.anchor_before(position.to_point(&display_map));
 2285                end = start;
 2286                mode = SelectMode::Character;
 2287                auto_scroll = true;
 2288            }
 2289            2 => {
 2290                let range = movement::surrounding_word(&display_map, position);
 2291                start = buffer.anchor_before(range.start.to_point(&display_map));
 2292                end = buffer.anchor_before(range.end.to_point(&display_map));
 2293                mode = SelectMode::Word(start..end);
 2294                auto_scroll = true;
 2295            }
 2296            3 => {
 2297                let position = display_map
 2298                    .clip_point(position, Bias::Left)
 2299                    .to_point(&display_map);
 2300                let line_start = display_map.prev_line_boundary(position).0;
 2301                let next_line_start = buffer.clip_point(
 2302                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2303                    Bias::Left,
 2304                );
 2305                start = buffer.anchor_before(line_start);
 2306                end = buffer.anchor_before(next_line_start);
 2307                mode = SelectMode::Line(start..end);
 2308                auto_scroll = true;
 2309            }
 2310            _ => {
 2311                start = buffer.anchor_before(0);
 2312                end = buffer.anchor_before(buffer.len());
 2313                mode = SelectMode::All;
 2314                auto_scroll = false;
 2315            }
 2316        }
 2317        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2318
 2319        let point_to_delete: Option<usize> = {
 2320            let selected_points: Vec<Selection<Point>> =
 2321                self.selections.disjoint_in_range(start..end, cx);
 2322
 2323            if !add || click_count > 1 {
 2324                None
 2325            } else if !selected_points.is_empty() {
 2326                Some(selected_points[0].id)
 2327            } else {
 2328                let clicked_point_already_selected =
 2329                    self.selections.disjoint.iter().find(|selection| {
 2330                        selection.start.to_point(buffer) == start.to_point(buffer)
 2331                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2332                    });
 2333
 2334                clicked_point_already_selected.map(|selection| selection.id)
 2335            }
 2336        };
 2337
 2338        let selections_count = self.selections.count();
 2339
 2340        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2341            if let Some(point_to_delete) = point_to_delete {
 2342                s.delete(point_to_delete);
 2343
 2344                if selections_count == 1 {
 2345                    s.set_pending_anchor_range(start..end, mode);
 2346                }
 2347            } else {
 2348                if !add {
 2349                    s.clear_disjoint();
 2350                } else if click_count > 1 {
 2351                    s.delete(newest_selection.id)
 2352                }
 2353
 2354                s.set_pending_anchor_range(start..end, mode);
 2355            }
 2356        });
 2357    }
 2358
 2359    fn begin_columnar_selection(
 2360        &mut self,
 2361        position: DisplayPoint,
 2362        goal_column: u32,
 2363        reset: bool,
 2364        window: &mut Window,
 2365        cx: &mut Context<Self>,
 2366    ) {
 2367        if !self.focus_handle.is_focused(window) {
 2368            self.last_focused_descendant = None;
 2369            window.focus(&self.focus_handle);
 2370        }
 2371
 2372        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2373
 2374        if reset {
 2375            let pointer_position = display_map
 2376                .buffer_snapshot
 2377                .anchor_before(position.to_point(&display_map));
 2378
 2379            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2380                s.clear_disjoint();
 2381                s.set_pending_anchor_range(
 2382                    pointer_position..pointer_position,
 2383                    SelectMode::Character,
 2384                );
 2385            });
 2386        }
 2387
 2388        let tail = self.selections.newest::<Point>(cx).tail();
 2389        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2390
 2391        if !reset {
 2392            self.select_columns(
 2393                tail.to_display_point(&display_map),
 2394                position,
 2395                goal_column,
 2396                &display_map,
 2397                window,
 2398                cx,
 2399            );
 2400        }
 2401    }
 2402
 2403    fn update_selection(
 2404        &mut self,
 2405        position: DisplayPoint,
 2406        goal_column: u32,
 2407        scroll_delta: gpui::Point<f32>,
 2408        window: &mut Window,
 2409        cx: &mut Context<Self>,
 2410    ) {
 2411        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2412
 2413        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2414            let tail = tail.to_display_point(&display_map);
 2415            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2416        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2417            let buffer = self.buffer.read(cx).snapshot(cx);
 2418            let head;
 2419            let tail;
 2420            let mode = self.selections.pending_mode().unwrap();
 2421            match &mode {
 2422                SelectMode::Character => {
 2423                    head = position.to_point(&display_map);
 2424                    tail = pending.tail().to_point(&buffer);
 2425                }
 2426                SelectMode::Word(original_range) => {
 2427                    let original_display_range = original_range.start.to_display_point(&display_map)
 2428                        ..original_range.end.to_display_point(&display_map);
 2429                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2430                        ..original_display_range.end.to_point(&display_map);
 2431                    if movement::is_inside_word(&display_map, position)
 2432                        || original_display_range.contains(&position)
 2433                    {
 2434                        let word_range = movement::surrounding_word(&display_map, position);
 2435                        if word_range.start < original_display_range.start {
 2436                            head = word_range.start.to_point(&display_map);
 2437                        } else {
 2438                            head = word_range.end.to_point(&display_map);
 2439                        }
 2440                    } else {
 2441                        head = position.to_point(&display_map);
 2442                    }
 2443
 2444                    if head <= original_buffer_range.start {
 2445                        tail = original_buffer_range.end;
 2446                    } else {
 2447                        tail = original_buffer_range.start;
 2448                    }
 2449                }
 2450                SelectMode::Line(original_range) => {
 2451                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2452
 2453                    let position = display_map
 2454                        .clip_point(position, Bias::Left)
 2455                        .to_point(&display_map);
 2456                    let line_start = display_map.prev_line_boundary(position).0;
 2457                    let next_line_start = buffer.clip_point(
 2458                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2459                        Bias::Left,
 2460                    );
 2461
 2462                    if line_start < original_range.start {
 2463                        head = line_start
 2464                    } else {
 2465                        head = next_line_start
 2466                    }
 2467
 2468                    if head <= original_range.start {
 2469                        tail = original_range.end;
 2470                    } else {
 2471                        tail = original_range.start;
 2472                    }
 2473                }
 2474                SelectMode::All => {
 2475                    return;
 2476                }
 2477            };
 2478
 2479            if head < tail {
 2480                pending.start = buffer.anchor_before(head);
 2481                pending.end = buffer.anchor_before(tail);
 2482                pending.reversed = true;
 2483            } else {
 2484                pending.start = buffer.anchor_before(tail);
 2485                pending.end = buffer.anchor_before(head);
 2486                pending.reversed = false;
 2487            }
 2488
 2489            self.change_selections(None, window, cx, |s| {
 2490                s.set_pending(pending, mode);
 2491            });
 2492        } else {
 2493            log::error!("update_selection dispatched with no pending selection");
 2494            return;
 2495        }
 2496
 2497        self.apply_scroll_delta(scroll_delta, window, cx);
 2498        cx.notify();
 2499    }
 2500
 2501    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2502        self.columnar_selection_tail.take();
 2503        if self.selections.pending_anchor().is_some() {
 2504            let selections = self.selections.all::<usize>(cx);
 2505            self.change_selections(None, window, cx, |s| {
 2506                s.select(selections);
 2507                s.clear_pending();
 2508            });
 2509        }
 2510    }
 2511
 2512    fn select_columns(
 2513        &mut self,
 2514        tail: DisplayPoint,
 2515        head: DisplayPoint,
 2516        goal_column: u32,
 2517        display_map: &DisplaySnapshot,
 2518        window: &mut Window,
 2519        cx: &mut Context<Self>,
 2520    ) {
 2521        let start_row = cmp::min(tail.row(), head.row());
 2522        let end_row = cmp::max(tail.row(), head.row());
 2523        let start_column = cmp::min(tail.column(), goal_column);
 2524        let end_column = cmp::max(tail.column(), goal_column);
 2525        let reversed = start_column < tail.column();
 2526
 2527        let selection_ranges = (start_row.0..=end_row.0)
 2528            .map(DisplayRow)
 2529            .filter_map(|row| {
 2530                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2531                    let start = display_map
 2532                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2533                        .to_point(display_map);
 2534                    let end = display_map
 2535                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2536                        .to_point(display_map);
 2537                    if reversed {
 2538                        Some(end..start)
 2539                    } else {
 2540                        Some(start..end)
 2541                    }
 2542                } else {
 2543                    None
 2544                }
 2545            })
 2546            .collect::<Vec<_>>();
 2547
 2548        self.change_selections(None, window, cx, |s| {
 2549            s.select_ranges(selection_ranges);
 2550        });
 2551        cx.notify();
 2552    }
 2553
 2554    pub fn has_pending_nonempty_selection(&self) -> bool {
 2555        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2556            Some(Selection { start, end, .. }) => start != end,
 2557            None => false,
 2558        };
 2559
 2560        pending_nonempty_selection
 2561            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2562    }
 2563
 2564    pub fn has_pending_selection(&self) -> bool {
 2565        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2566    }
 2567
 2568    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2569        self.selection_mark_mode = false;
 2570
 2571        if self.clear_expanded_diff_hunks(cx) {
 2572            cx.notify();
 2573            return;
 2574        }
 2575        if self.dismiss_menus_and_popups(true, window, cx) {
 2576            return;
 2577        }
 2578
 2579        if self.mode == EditorMode::Full
 2580            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2581        {
 2582            return;
 2583        }
 2584
 2585        cx.propagate();
 2586    }
 2587
 2588    pub fn dismiss_menus_and_popups(
 2589        &mut self,
 2590        should_report_inline_completion_event: bool,
 2591        window: &mut Window,
 2592        cx: &mut Context<Self>,
 2593    ) -> bool {
 2594        if self.take_rename(false, window, cx).is_some() {
 2595            return true;
 2596        }
 2597
 2598        if hide_hover(self, cx) {
 2599            return true;
 2600        }
 2601
 2602        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2603            return true;
 2604        }
 2605
 2606        if self.hide_context_menu(window, cx).is_some() {
 2607            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2608                self.update_visible_inline_completion(window, cx);
 2609            }
 2610            return true;
 2611        }
 2612
 2613        if self.mouse_context_menu.take().is_some() {
 2614            return true;
 2615        }
 2616
 2617        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2618            return true;
 2619        }
 2620
 2621        if self.snippet_stack.pop().is_some() {
 2622            return true;
 2623        }
 2624
 2625        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2626            self.dismiss_diagnostics(cx);
 2627            return true;
 2628        }
 2629
 2630        false
 2631    }
 2632
 2633    fn linked_editing_ranges_for(
 2634        &self,
 2635        selection: Range<text::Anchor>,
 2636        cx: &App,
 2637    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2638        if self.linked_edit_ranges.is_empty() {
 2639            return None;
 2640        }
 2641        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2642            selection.end.buffer_id.and_then(|end_buffer_id| {
 2643                if selection.start.buffer_id != Some(end_buffer_id) {
 2644                    return None;
 2645                }
 2646                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2647                let snapshot = buffer.read(cx).snapshot();
 2648                self.linked_edit_ranges
 2649                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2650                    .map(|ranges| (ranges, snapshot, buffer))
 2651            })?;
 2652        use text::ToOffset as TO;
 2653        // find offset from the start of current range to current cursor position
 2654        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2655
 2656        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2657        let start_difference = start_offset - start_byte_offset;
 2658        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2659        let end_difference = end_offset - start_byte_offset;
 2660        // Current range has associated linked ranges.
 2661        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2662        for range in linked_ranges.iter() {
 2663            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2664            let end_offset = start_offset + end_difference;
 2665            let start_offset = start_offset + start_difference;
 2666            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2667                continue;
 2668            }
 2669            if self.selections.disjoint_anchor_ranges().any(|s| {
 2670                if s.start.buffer_id != selection.start.buffer_id
 2671                    || s.end.buffer_id != selection.end.buffer_id
 2672                {
 2673                    return false;
 2674                }
 2675                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2676                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2677            }) {
 2678                continue;
 2679            }
 2680            let start = buffer_snapshot.anchor_after(start_offset);
 2681            let end = buffer_snapshot.anchor_after(end_offset);
 2682            linked_edits
 2683                .entry(buffer.clone())
 2684                .or_default()
 2685                .push(start..end);
 2686        }
 2687        Some(linked_edits)
 2688    }
 2689
 2690    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2691        let text: Arc<str> = text.into();
 2692
 2693        if self.read_only(cx) {
 2694            return;
 2695        }
 2696
 2697        let selections = self.selections.all_adjusted(cx);
 2698        let mut bracket_inserted = false;
 2699        let mut edits = Vec::new();
 2700        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2701        let mut new_selections = Vec::with_capacity(selections.len());
 2702        let mut new_autoclose_regions = Vec::new();
 2703        let snapshot = self.buffer.read(cx).read(cx);
 2704
 2705        for (selection, autoclose_region) in
 2706            self.selections_with_autoclose_regions(selections, &snapshot)
 2707        {
 2708            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2709                // Determine if the inserted text matches the opening or closing
 2710                // bracket of any of this language's bracket pairs.
 2711                let mut bracket_pair = None;
 2712                let mut is_bracket_pair_start = false;
 2713                let mut is_bracket_pair_end = false;
 2714                if !text.is_empty() {
 2715                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2716                    //  and they are removing the character that triggered IME popup.
 2717                    for (pair, enabled) in scope.brackets() {
 2718                        if !pair.close && !pair.surround {
 2719                            continue;
 2720                        }
 2721
 2722                        if enabled && pair.start.ends_with(text.as_ref()) {
 2723                            let prefix_len = pair.start.len() - text.len();
 2724                            let preceding_text_matches_prefix = prefix_len == 0
 2725                                || (selection.start.column >= (prefix_len as u32)
 2726                                    && snapshot.contains_str_at(
 2727                                        Point::new(
 2728                                            selection.start.row,
 2729                                            selection.start.column - (prefix_len as u32),
 2730                                        ),
 2731                                        &pair.start[..prefix_len],
 2732                                    ));
 2733                            if preceding_text_matches_prefix {
 2734                                bracket_pair = Some(pair.clone());
 2735                                is_bracket_pair_start = true;
 2736                                break;
 2737                            }
 2738                        }
 2739                        if pair.end.as_str() == text.as_ref() {
 2740                            bracket_pair = Some(pair.clone());
 2741                            is_bracket_pair_end = true;
 2742                            break;
 2743                        }
 2744                    }
 2745                }
 2746
 2747                if let Some(bracket_pair) = bracket_pair {
 2748                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2749                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2750                    let auto_surround =
 2751                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2752                    if selection.is_empty() {
 2753                        if is_bracket_pair_start {
 2754                            // If the inserted text is a suffix of an opening bracket and the
 2755                            // selection is preceded by the rest of the opening bracket, then
 2756                            // insert the closing bracket.
 2757                            let following_text_allows_autoclose = snapshot
 2758                                .chars_at(selection.start)
 2759                                .next()
 2760                                .map_or(true, |c| scope.should_autoclose_before(c));
 2761
 2762                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2763                                && bracket_pair.start.len() == 1
 2764                            {
 2765                                let target = bracket_pair.start.chars().next().unwrap();
 2766                                let current_line_count = snapshot
 2767                                    .reversed_chars_at(selection.start)
 2768                                    .take_while(|&c| c != '\n')
 2769                                    .filter(|&c| c == target)
 2770                                    .count();
 2771                                current_line_count % 2 == 1
 2772                            } else {
 2773                                false
 2774                            };
 2775
 2776                            if autoclose
 2777                                && bracket_pair.close
 2778                                && following_text_allows_autoclose
 2779                                && !is_closing_quote
 2780                            {
 2781                                let anchor = snapshot.anchor_before(selection.end);
 2782                                new_selections.push((selection.map(|_| anchor), text.len()));
 2783                                new_autoclose_regions.push((
 2784                                    anchor,
 2785                                    text.len(),
 2786                                    selection.id,
 2787                                    bracket_pair.clone(),
 2788                                ));
 2789                                edits.push((
 2790                                    selection.range(),
 2791                                    format!("{}{}", text, bracket_pair.end).into(),
 2792                                ));
 2793                                bracket_inserted = true;
 2794                                continue;
 2795                            }
 2796                        }
 2797
 2798                        if let Some(region) = autoclose_region {
 2799                            // If the selection is followed by an auto-inserted closing bracket,
 2800                            // then don't insert that closing bracket again; just move the selection
 2801                            // past the closing bracket.
 2802                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2803                                && text.as_ref() == region.pair.end.as_str();
 2804                            if should_skip {
 2805                                let anchor = snapshot.anchor_after(selection.end);
 2806                                new_selections
 2807                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2808                                continue;
 2809                            }
 2810                        }
 2811
 2812                        let always_treat_brackets_as_autoclosed = snapshot
 2813                            .settings_at(selection.start, cx)
 2814                            .always_treat_brackets_as_autoclosed;
 2815                        if always_treat_brackets_as_autoclosed
 2816                            && is_bracket_pair_end
 2817                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2818                        {
 2819                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2820                            // and the inserted text is a closing bracket and the selection is followed
 2821                            // by the closing bracket then move the selection past the closing bracket.
 2822                            let anchor = snapshot.anchor_after(selection.end);
 2823                            new_selections.push((selection.map(|_| anchor), text.len()));
 2824                            continue;
 2825                        }
 2826                    }
 2827                    // If an opening bracket is 1 character long and is typed while
 2828                    // text is selected, then surround that text with the bracket pair.
 2829                    else if auto_surround
 2830                        && bracket_pair.surround
 2831                        && is_bracket_pair_start
 2832                        && bracket_pair.start.chars().count() == 1
 2833                    {
 2834                        edits.push((selection.start..selection.start, text.clone()));
 2835                        edits.push((
 2836                            selection.end..selection.end,
 2837                            bracket_pair.end.as_str().into(),
 2838                        ));
 2839                        bracket_inserted = true;
 2840                        new_selections.push((
 2841                            Selection {
 2842                                id: selection.id,
 2843                                start: snapshot.anchor_after(selection.start),
 2844                                end: snapshot.anchor_before(selection.end),
 2845                                reversed: selection.reversed,
 2846                                goal: selection.goal,
 2847                            },
 2848                            0,
 2849                        ));
 2850                        continue;
 2851                    }
 2852                }
 2853            }
 2854
 2855            if self.auto_replace_emoji_shortcode
 2856                && selection.is_empty()
 2857                && text.as_ref().ends_with(':')
 2858            {
 2859                if let Some(possible_emoji_short_code) =
 2860                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2861                {
 2862                    if !possible_emoji_short_code.is_empty() {
 2863                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2864                            let emoji_shortcode_start = Point::new(
 2865                                selection.start.row,
 2866                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2867                            );
 2868
 2869                            // Remove shortcode from buffer
 2870                            edits.push((
 2871                                emoji_shortcode_start..selection.start,
 2872                                "".to_string().into(),
 2873                            ));
 2874                            new_selections.push((
 2875                                Selection {
 2876                                    id: selection.id,
 2877                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2878                                    end: snapshot.anchor_before(selection.start),
 2879                                    reversed: selection.reversed,
 2880                                    goal: selection.goal,
 2881                                },
 2882                                0,
 2883                            ));
 2884
 2885                            // Insert emoji
 2886                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2887                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2888                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2889
 2890                            continue;
 2891                        }
 2892                    }
 2893                }
 2894            }
 2895
 2896            // If not handling any auto-close operation, then just replace the selected
 2897            // text with the given input and move the selection to the end of the
 2898            // newly inserted text.
 2899            let anchor = snapshot.anchor_after(selection.end);
 2900            if !self.linked_edit_ranges.is_empty() {
 2901                let start_anchor = snapshot.anchor_before(selection.start);
 2902
 2903                let is_word_char = text.chars().next().map_or(true, |char| {
 2904                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2905                    classifier.is_word(char)
 2906                });
 2907
 2908                if is_word_char {
 2909                    if let Some(ranges) = self
 2910                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2911                    {
 2912                        for (buffer, edits) in ranges {
 2913                            linked_edits
 2914                                .entry(buffer.clone())
 2915                                .or_default()
 2916                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2917                        }
 2918                    }
 2919                }
 2920            }
 2921
 2922            new_selections.push((selection.map(|_| anchor), 0));
 2923            edits.push((selection.start..selection.end, text.clone()));
 2924        }
 2925
 2926        drop(snapshot);
 2927
 2928        self.transact(window, cx, |this, window, cx| {
 2929            this.buffer.update(cx, |buffer, cx| {
 2930                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2931            });
 2932            for (buffer, edits) in linked_edits {
 2933                buffer.update(cx, |buffer, cx| {
 2934                    let snapshot = buffer.snapshot();
 2935                    let edits = edits
 2936                        .into_iter()
 2937                        .map(|(range, text)| {
 2938                            use text::ToPoint as TP;
 2939                            let end_point = TP::to_point(&range.end, &snapshot);
 2940                            let start_point = TP::to_point(&range.start, &snapshot);
 2941                            (start_point..end_point, text)
 2942                        })
 2943                        .sorted_by_key(|(range, _)| range.start)
 2944                        .collect::<Vec<_>>();
 2945                    buffer.edit(edits, None, cx);
 2946                })
 2947            }
 2948            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2949            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2950            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2951            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2952                .zip(new_selection_deltas)
 2953                .map(|(selection, delta)| Selection {
 2954                    id: selection.id,
 2955                    start: selection.start + delta,
 2956                    end: selection.end + delta,
 2957                    reversed: selection.reversed,
 2958                    goal: SelectionGoal::None,
 2959                })
 2960                .collect::<Vec<_>>();
 2961
 2962            let mut i = 0;
 2963            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2964                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2965                let start = map.buffer_snapshot.anchor_before(position);
 2966                let end = map.buffer_snapshot.anchor_after(position);
 2967                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2968                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2969                        Ordering::Less => i += 1,
 2970                        Ordering::Greater => break,
 2971                        Ordering::Equal => {
 2972                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2973                                Ordering::Less => i += 1,
 2974                                Ordering::Equal => break,
 2975                                Ordering::Greater => break,
 2976                            }
 2977                        }
 2978                    }
 2979                }
 2980                this.autoclose_regions.insert(
 2981                    i,
 2982                    AutocloseRegion {
 2983                        selection_id,
 2984                        range: start..end,
 2985                        pair,
 2986                    },
 2987                );
 2988            }
 2989
 2990            let had_active_inline_completion = this.has_active_inline_completion();
 2991            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2992                s.select(new_selections)
 2993            });
 2994
 2995            if !bracket_inserted {
 2996                if let Some(on_type_format_task) =
 2997                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2998                {
 2999                    on_type_format_task.detach_and_log_err(cx);
 3000                }
 3001            }
 3002
 3003            let editor_settings = EditorSettings::get_global(cx);
 3004            if bracket_inserted
 3005                && (editor_settings.auto_signature_help
 3006                    || editor_settings.show_signature_help_after_edits)
 3007            {
 3008                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3009            }
 3010
 3011            let trigger_in_words =
 3012                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3013            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3014            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3015            this.refresh_inline_completion(true, false, window, cx);
 3016        });
 3017    }
 3018
 3019    fn find_possible_emoji_shortcode_at_position(
 3020        snapshot: &MultiBufferSnapshot,
 3021        position: Point,
 3022    ) -> Option<String> {
 3023        let mut chars = Vec::new();
 3024        let mut found_colon = false;
 3025        for char in snapshot.reversed_chars_at(position).take(100) {
 3026            // Found a possible emoji shortcode in the middle of the buffer
 3027            if found_colon {
 3028                if char.is_whitespace() {
 3029                    chars.reverse();
 3030                    return Some(chars.iter().collect());
 3031                }
 3032                // If the previous character is not a whitespace, we are in the middle of a word
 3033                // and we only want to complete the shortcode if the word is made up of other emojis
 3034                let mut containing_word = String::new();
 3035                for ch in snapshot
 3036                    .reversed_chars_at(position)
 3037                    .skip(chars.len() + 1)
 3038                    .take(100)
 3039                {
 3040                    if ch.is_whitespace() {
 3041                        break;
 3042                    }
 3043                    containing_word.push(ch);
 3044                }
 3045                let containing_word = containing_word.chars().rev().collect::<String>();
 3046                if util::word_consists_of_emojis(containing_word.as_str()) {
 3047                    chars.reverse();
 3048                    return Some(chars.iter().collect());
 3049                }
 3050            }
 3051
 3052            if char.is_whitespace() || !char.is_ascii() {
 3053                return None;
 3054            }
 3055            if char == ':' {
 3056                found_colon = true;
 3057            } else {
 3058                chars.push(char);
 3059            }
 3060        }
 3061        // Found a possible emoji shortcode at the beginning of the buffer
 3062        chars.reverse();
 3063        Some(chars.iter().collect())
 3064    }
 3065
 3066    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3067        self.transact(window, cx, |this, window, cx| {
 3068            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3069                let selections = this.selections.all::<usize>(cx);
 3070                let multi_buffer = this.buffer.read(cx);
 3071                let buffer = multi_buffer.snapshot(cx);
 3072                selections
 3073                    .iter()
 3074                    .map(|selection| {
 3075                        let start_point = selection.start.to_point(&buffer);
 3076                        let mut indent =
 3077                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3078                        indent.len = cmp::min(indent.len, start_point.column);
 3079                        let start = selection.start;
 3080                        let end = selection.end;
 3081                        let selection_is_empty = start == end;
 3082                        let language_scope = buffer.language_scope_at(start);
 3083                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3084                            &language_scope
 3085                        {
 3086                            let leading_whitespace_len = buffer
 3087                                .reversed_chars_at(start)
 3088                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3089                                .map(|c| c.len_utf8())
 3090                                .sum::<usize>();
 3091
 3092                            let trailing_whitespace_len = buffer
 3093                                .chars_at(end)
 3094                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3095                                .map(|c| c.len_utf8())
 3096                                .sum::<usize>();
 3097
 3098                            let insert_extra_newline =
 3099                                language.brackets().any(|(pair, enabled)| {
 3100                                    let pair_start = pair.start.trim_end();
 3101                                    let pair_end = pair.end.trim_start();
 3102
 3103                                    enabled
 3104                                        && pair.newline
 3105                                        && buffer.contains_str_at(
 3106                                            end + trailing_whitespace_len,
 3107                                            pair_end,
 3108                                        )
 3109                                        && buffer.contains_str_at(
 3110                                            (start - leading_whitespace_len)
 3111                                                .saturating_sub(pair_start.len()),
 3112                                            pair_start,
 3113                                        )
 3114                                });
 3115
 3116                            // Comment extension on newline is allowed only for cursor selections
 3117                            let comment_delimiter = maybe!({
 3118                                if !selection_is_empty {
 3119                                    return None;
 3120                                }
 3121
 3122                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3123                                    return None;
 3124                                }
 3125
 3126                                let delimiters = language.line_comment_prefixes();
 3127                                let max_len_of_delimiter =
 3128                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3129                                let (snapshot, range) =
 3130                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3131
 3132                                let mut index_of_first_non_whitespace = 0;
 3133                                let comment_candidate = snapshot
 3134                                    .chars_for_range(range)
 3135                                    .skip_while(|c| {
 3136                                        let should_skip = c.is_whitespace();
 3137                                        if should_skip {
 3138                                            index_of_first_non_whitespace += 1;
 3139                                        }
 3140                                        should_skip
 3141                                    })
 3142                                    .take(max_len_of_delimiter)
 3143                                    .collect::<String>();
 3144                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3145                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3146                                })?;
 3147                                let cursor_is_placed_after_comment_marker =
 3148                                    index_of_first_non_whitespace + comment_prefix.len()
 3149                                        <= start_point.column as usize;
 3150                                if cursor_is_placed_after_comment_marker {
 3151                                    Some(comment_prefix.clone())
 3152                                } else {
 3153                                    None
 3154                                }
 3155                            });
 3156                            (comment_delimiter, insert_extra_newline)
 3157                        } else {
 3158                            (None, false)
 3159                        };
 3160
 3161                        let capacity_for_delimiter = comment_delimiter
 3162                            .as_deref()
 3163                            .map(str::len)
 3164                            .unwrap_or_default();
 3165                        let mut new_text =
 3166                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3167                        new_text.push('\n');
 3168                        new_text.extend(indent.chars());
 3169                        if let Some(delimiter) = &comment_delimiter {
 3170                            new_text.push_str(delimiter);
 3171                        }
 3172                        if insert_extra_newline {
 3173                            new_text = new_text.repeat(2);
 3174                        }
 3175
 3176                        let anchor = buffer.anchor_after(end);
 3177                        let new_selection = selection.map(|_| anchor);
 3178                        (
 3179                            (start..end, new_text),
 3180                            (insert_extra_newline, new_selection),
 3181                        )
 3182                    })
 3183                    .unzip()
 3184            };
 3185
 3186            this.edit_with_autoindent(edits, cx);
 3187            let buffer = this.buffer.read(cx).snapshot(cx);
 3188            let new_selections = selection_fixup_info
 3189                .into_iter()
 3190                .map(|(extra_newline_inserted, new_selection)| {
 3191                    let mut cursor = new_selection.end.to_point(&buffer);
 3192                    if extra_newline_inserted {
 3193                        cursor.row -= 1;
 3194                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3195                    }
 3196                    new_selection.map(|_| cursor)
 3197                })
 3198                .collect();
 3199
 3200            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3201                s.select(new_selections)
 3202            });
 3203            this.refresh_inline_completion(true, false, window, cx);
 3204        });
 3205    }
 3206
 3207    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3208        let buffer = self.buffer.read(cx);
 3209        let snapshot = buffer.snapshot(cx);
 3210
 3211        let mut edits = Vec::new();
 3212        let mut rows = Vec::new();
 3213
 3214        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3215            let cursor = selection.head();
 3216            let row = cursor.row;
 3217
 3218            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3219
 3220            let newline = "\n".to_string();
 3221            edits.push((start_of_line..start_of_line, newline));
 3222
 3223            rows.push(row + rows_inserted as u32);
 3224        }
 3225
 3226        self.transact(window, cx, |editor, window, cx| {
 3227            editor.edit(edits, cx);
 3228
 3229            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3230                let mut index = 0;
 3231                s.move_cursors_with(|map, _, _| {
 3232                    let row = rows[index];
 3233                    index += 1;
 3234
 3235                    let point = Point::new(row, 0);
 3236                    let boundary = map.next_line_boundary(point).1;
 3237                    let clipped = map.clip_point(boundary, Bias::Left);
 3238
 3239                    (clipped, SelectionGoal::None)
 3240                });
 3241            });
 3242
 3243            let mut indent_edits = Vec::new();
 3244            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3245            for row in rows {
 3246                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3247                for (row, indent) in indents {
 3248                    if indent.len == 0 {
 3249                        continue;
 3250                    }
 3251
 3252                    let text = match indent.kind {
 3253                        IndentKind::Space => " ".repeat(indent.len as usize),
 3254                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3255                    };
 3256                    let point = Point::new(row.0, 0);
 3257                    indent_edits.push((point..point, text));
 3258                }
 3259            }
 3260            editor.edit(indent_edits, cx);
 3261        });
 3262    }
 3263
 3264    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3265        let buffer = self.buffer.read(cx);
 3266        let snapshot = buffer.snapshot(cx);
 3267
 3268        let mut edits = Vec::new();
 3269        let mut rows = Vec::new();
 3270        let mut rows_inserted = 0;
 3271
 3272        for selection in self.selections.all_adjusted(cx) {
 3273            let cursor = selection.head();
 3274            let row = cursor.row;
 3275
 3276            let point = Point::new(row + 1, 0);
 3277            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3278
 3279            let newline = "\n".to_string();
 3280            edits.push((start_of_line..start_of_line, newline));
 3281
 3282            rows_inserted += 1;
 3283            rows.push(row + rows_inserted);
 3284        }
 3285
 3286        self.transact(window, cx, |editor, window, cx| {
 3287            editor.edit(edits, cx);
 3288
 3289            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3290                let mut index = 0;
 3291                s.move_cursors_with(|map, _, _| {
 3292                    let row = rows[index];
 3293                    index += 1;
 3294
 3295                    let point = Point::new(row, 0);
 3296                    let boundary = map.next_line_boundary(point).1;
 3297                    let clipped = map.clip_point(boundary, Bias::Left);
 3298
 3299                    (clipped, SelectionGoal::None)
 3300                });
 3301            });
 3302
 3303            let mut indent_edits = Vec::new();
 3304            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3305            for row in rows {
 3306                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3307                for (row, indent) in indents {
 3308                    if indent.len == 0 {
 3309                        continue;
 3310                    }
 3311
 3312                    let text = match indent.kind {
 3313                        IndentKind::Space => " ".repeat(indent.len as usize),
 3314                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3315                    };
 3316                    let point = Point::new(row.0, 0);
 3317                    indent_edits.push((point..point, text));
 3318                }
 3319            }
 3320            editor.edit(indent_edits, cx);
 3321        });
 3322    }
 3323
 3324    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3325        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3326            original_indent_columns: Vec::new(),
 3327        });
 3328        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3329    }
 3330
 3331    fn insert_with_autoindent_mode(
 3332        &mut self,
 3333        text: &str,
 3334        autoindent_mode: Option<AutoindentMode>,
 3335        window: &mut Window,
 3336        cx: &mut Context<Self>,
 3337    ) {
 3338        if self.read_only(cx) {
 3339            return;
 3340        }
 3341
 3342        let text: Arc<str> = text.into();
 3343        self.transact(window, cx, |this, window, cx| {
 3344            let old_selections = this.selections.all_adjusted(cx);
 3345            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3346                let anchors = {
 3347                    let snapshot = buffer.read(cx);
 3348                    old_selections
 3349                        .iter()
 3350                        .map(|s| {
 3351                            let anchor = snapshot.anchor_after(s.head());
 3352                            s.map(|_| anchor)
 3353                        })
 3354                        .collect::<Vec<_>>()
 3355                };
 3356                buffer.edit(
 3357                    old_selections
 3358                        .iter()
 3359                        .map(|s| (s.start..s.end, text.clone())),
 3360                    autoindent_mode,
 3361                    cx,
 3362                );
 3363                anchors
 3364            });
 3365
 3366            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3367                s.select_anchors(selection_anchors);
 3368            });
 3369
 3370            cx.notify();
 3371        });
 3372    }
 3373
 3374    fn trigger_completion_on_input(
 3375        &mut self,
 3376        text: &str,
 3377        trigger_in_words: bool,
 3378        window: &mut Window,
 3379        cx: &mut Context<Self>,
 3380    ) {
 3381        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3382            self.show_completions(
 3383                &ShowCompletions {
 3384                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3385                },
 3386                window,
 3387                cx,
 3388            );
 3389        } else {
 3390            self.hide_context_menu(window, cx);
 3391        }
 3392    }
 3393
 3394    fn is_completion_trigger(
 3395        &self,
 3396        text: &str,
 3397        trigger_in_words: bool,
 3398        cx: &mut Context<Self>,
 3399    ) -> bool {
 3400        let position = self.selections.newest_anchor().head();
 3401        let multibuffer = self.buffer.read(cx);
 3402        let Some(buffer) = position
 3403            .buffer_id
 3404            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3405        else {
 3406            return false;
 3407        };
 3408
 3409        if let Some(completion_provider) = &self.completion_provider {
 3410            completion_provider.is_completion_trigger(
 3411                &buffer,
 3412                position.text_anchor,
 3413                text,
 3414                trigger_in_words,
 3415                cx,
 3416            )
 3417        } else {
 3418            false
 3419        }
 3420    }
 3421
 3422    /// If any empty selections is touching the start of its innermost containing autoclose
 3423    /// region, expand it to select the brackets.
 3424    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3425        let selections = self.selections.all::<usize>(cx);
 3426        let buffer = self.buffer.read(cx).read(cx);
 3427        let new_selections = self
 3428            .selections_with_autoclose_regions(selections, &buffer)
 3429            .map(|(mut selection, region)| {
 3430                if !selection.is_empty() {
 3431                    return selection;
 3432                }
 3433
 3434                if let Some(region) = region {
 3435                    let mut range = region.range.to_offset(&buffer);
 3436                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3437                        range.start -= region.pair.start.len();
 3438                        if buffer.contains_str_at(range.start, &region.pair.start)
 3439                            && buffer.contains_str_at(range.end, &region.pair.end)
 3440                        {
 3441                            range.end += region.pair.end.len();
 3442                            selection.start = range.start;
 3443                            selection.end = range.end;
 3444
 3445                            return selection;
 3446                        }
 3447                    }
 3448                }
 3449
 3450                let always_treat_brackets_as_autoclosed = buffer
 3451                    .settings_at(selection.start, cx)
 3452                    .always_treat_brackets_as_autoclosed;
 3453
 3454                if !always_treat_brackets_as_autoclosed {
 3455                    return selection;
 3456                }
 3457
 3458                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3459                    for (pair, enabled) in scope.brackets() {
 3460                        if !enabled || !pair.close {
 3461                            continue;
 3462                        }
 3463
 3464                        if buffer.contains_str_at(selection.start, &pair.end) {
 3465                            let pair_start_len = pair.start.len();
 3466                            if buffer.contains_str_at(
 3467                                selection.start.saturating_sub(pair_start_len),
 3468                                &pair.start,
 3469                            ) {
 3470                                selection.start -= pair_start_len;
 3471                                selection.end += pair.end.len();
 3472
 3473                                return selection;
 3474                            }
 3475                        }
 3476                    }
 3477                }
 3478
 3479                selection
 3480            })
 3481            .collect();
 3482
 3483        drop(buffer);
 3484        self.change_selections(None, window, cx, |selections| {
 3485            selections.select(new_selections)
 3486        });
 3487    }
 3488
 3489    /// Iterate the given selections, and for each one, find the smallest surrounding
 3490    /// autoclose region. This uses the ordering of the selections and the autoclose
 3491    /// regions to avoid repeated comparisons.
 3492    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3493        &'a self,
 3494        selections: impl IntoIterator<Item = Selection<D>>,
 3495        buffer: &'a MultiBufferSnapshot,
 3496    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3497        let mut i = 0;
 3498        let mut regions = self.autoclose_regions.as_slice();
 3499        selections.into_iter().map(move |selection| {
 3500            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3501
 3502            let mut enclosing = None;
 3503            while let Some(pair_state) = regions.get(i) {
 3504                if pair_state.range.end.to_offset(buffer) < range.start {
 3505                    regions = &regions[i + 1..];
 3506                    i = 0;
 3507                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3508                    break;
 3509                } else {
 3510                    if pair_state.selection_id == selection.id {
 3511                        enclosing = Some(pair_state);
 3512                    }
 3513                    i += 1;
 3514                }
 3515            }
 3516
 3517            (selection, enclosing)
 3518        })
 3519    }
 3520
 3521    /// Remove any autoclose regions that no longer contain their selection.
 3522    fn invalidate_autoclose_regions(
 3523        &mut self,
 3524        mut selections: &[Selection<Anchor>],
 3525        buffer: &MultiBufferSnapshot,
 3526    ) {
 3527        self.autoclose_regions.retain(|state| {
 3528            let mut i = 0;
 3529            while let Some(selection) = selections.get(i) {
 3530                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3531                    selections = &selections[1..];
 3532                    continue;
 3533                }
 3534                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3535                    break;
 3536                }
 3537                if selection.id == state.selection_id {
 3538                    return true;
 3539                } else {
 3540                    i += 1;
 3541                }
 3542            }
 3543            false
 3544        });
 3545    }
 3546
 3547    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3548        let offset = position.to_offset(buffer);
 3549        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3550        if offset > word_range.start && kind == Some(CharKind::Word) {
 3551            Some(
 3552                buffer
 3553                    .text_for_range(word_range.start..offset)
 3554                    .collect::<String>(),
 3555            )
 3556        } else {
 3557            None
 3558        }
 3559    }
 3560
 3561    pub fn toggle_inlay_hints(
 3562        &mut self,
 3563        _: &ToggleInlayHints,
 3564        _: &mut Window,
 3565        cx: &mut Context<Self>,
 3566    ) {
 3567        self.refresh_inlay_hints(
 3568            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3569            cx,
 3570        );
 3571    }
 3572
 3573    pub fn inlay_hints_enabled(&self) -> bool {
 3574        self.inlay_hint_cache.enabled
 3575    }
 3576
 3577    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3578        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3579            return;
 3580        }
 3581
 3582        let reason_description = reason.description();
 3583        let ignore_debounce = matches!(
 3584            reason,
 3585            InlayHintRefreshReason::SettingsChange(_)
 3586                | InlayHintRefreshReason::Toggle(_)
 3587                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3588        );
 3589        let (invalidate_cache, required_languages) = match reason {
 3590            InlayHintRefreshReason::Toggle(enabled) => {
 3591                self.inlay_hint_cache.enabled = enabled;
 3592                if enabled {
 3593                    (InvalidationStrategy::RefreshRequested, None)
 3594                } else {
 3595                    self.inlay_hint_cache.clear();
 3596                    self.splice_inlays(
 3597                        self.visible_inlay_hints(cx)
 3598                            .iter()
 3599                            .map(|inlay| inlay.id)
 3600                            .collect(),
 3601                        Vec::new(),
 3602                        cx,
 3603                    );
 3604                    return;
 3605                }
 3606            }
 3607            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3608                match self.inlay_hint_cache.update_settings(
 3609                    &self.buffer,
 3610                    new_settings,
 3611                    self.visible_inlay_hints(cx),
 3612                    cx,
 3613                ) {
 3614                    ControlFlow::Break(Some(InlaySplice {
 3615                        to_remove,
 3616                        to_insert,
 3617                    })) => {
 3618                        self.splice_inlays(to_remove, to_insert, cx);
 3619                        return;
 3620                    }
 3621                    ControlFlow::Break(None) => return,
 3622                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3623                }
 3624            }
 3625            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3626                if let Some(InlaySplice {
 3627                    to_remove,
 3628                    to_insert,
 3629                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3630                {
 3631                    self.splice_inlays(to_remove, to_insert, cx);
 3632                }
 3633                return;
 3634            }
 3635            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3636            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3637                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3638            }
 3639            InlayHintRefreshReason::RefreshRequested => {
 3640                (InvalidationStrategy::RefreshRequested, None)
 3641            }
 3642        };
 3643
 3644        if let Some(InlaySplice {
 3645            to_remove,
 3646            to_insert,
 3647        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3648            reason_description,
 3649            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3650            invalidate_cache,
 3651            ignore_debounce,
 3652            cx,
 3653        ) {
 3654            self.splice_inlays(to_remove, to_insert, cx);
 3655        }
 3656    }
 3657
 3658    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3659        self.display_map
 3660            .read(cx)
 3661            .current_inlays()
 3662            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3663            .cloned()
 3664            .collect()
 3665    }
 3666
 3667    pub fn excerpts_for_inlay_hints_query(
 3668        &self,
 3669        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3670        cx: &mut Context<Editor>,
 3671    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3672        let Some(project) = self.project.as_ref() else {
 3673            return HashMap::default();
 3674        };
 3675        let project = project.read(cx);
 3676        let multi_buffer = self.buffer().read(cx);
 3677        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3678        let multi_buffer_visible_start = self
 3679            .scroll_manager
 3680            .anchor()
 3681            .anchor
 3682            .to_point(&multi_buffer_snapshot);
 3683        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3684            multi_buffer_visible_start
 3685                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3686            Bias::Left,
 3687        );
 3688        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3689        multi_buffer_snapshot
 3690            .range_to_buffer_ranges(multi_buffer_visible_range)
 3691            .into_iter()
 3692            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3693            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3694                let buffer_file = project::File::from_dyn(buffer.file())?;
 3695                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3696                let worktree_entry = buffer_worktree
 3697                    .read(cx)
 3698                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3699                if worktree_entry.is_ignored {
 3700                    return None;
 3701                }
 3702
 3703                let language = buffer.language()?;
 3704                if let Some(restrict_to_languages) = restrict_to_languages {
 3705                    if !restrict_to_languages.contains(language) {
 3706                        return None;
 3707                    }
 3708                }
 3709                Some((
 3710                    excerpt_id,
 3711                    (
 3712                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3713                        buffer.version().clone(),
 3714                        excerpt_visible_range,
 3715                    ),
 3716                ))
 3717            })
 3718            .collect()
 3719    }
 3720
 3721    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3722        TextLayoutDetails {
 3723            text_system: window.text_system().clone(),
 3724            editor_style: self.style.clone().unwrap(),
 3725            rem_size: window.rem_size(),
 3726            scroll_anchor: self.scroll_manager.anchor(),
 3727            visible_rows: self.visible_line_count(),
 3728            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3729        }
 3730    }
 3731
 3732    pub fn splice_inlays(
 3733        &self,
 3734        to_remove: Vec<InlayId>,
 3735        to_insert: Vec<Inlay>,
 3736        cx: &mut Context<Self>,
 3737    ) {
 3738        self.display_map.update(cx, |display_map, cx| {
 3739            display_map.splice_inlays(to_remove, to_insert, cx)
 3740        });
 3741        cx.notify();
 3742    }
 3743
 3744    fn trigger_on_type_formatting(
 3745        &self,
 3746        input: String,
 3747        window: &mut Window,
 3748        cx: &mut Context<Self>,
 3749    ) -> Option<Task<Result<()>>> {
 3750        if input.len() != 1 {
 3751            return None;
 3752        }
 3753
 3754        let project = self.project.as_ref()?;
 3755        let position = self.selections.newest_anchor().head();
 3756        let (buffer, buffer_position) = self
 3757            .buffer
 3758            .read(cx)
 3759            .text_anchor_for_position(position, cx)?;
 3760
 3761        let settings = language_settings::language_settings(
 3762            buffer
 3763                .read(cx)
 3764                .language_at(buffer_position)
 3765                .map(|l| l.name()),
 3766            buffer.read(cx).file(),
 3767            cx,
 3768        );
 3769        if !settings.use_on_type_format {
 3770            return None;
 3771        }
 3772
 3773        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3774        // hence we do LSP request & edit on host side only — add formats to host's history.
 3775        let push_to_lsp_host_history = true;
 3776        // If this is not the host, append its history with new edits.
 3777        let push_to_client_history = project.read(cx).is_via_collab();
 3778
 3779        let on_type_formatting = project.update(cx, |project, cx| {
 3780            project.on_type_format(
 3781                buffer.clone(),
 3782                buffer_position,
 3783                input,
 3784                push_to_lsp_host_history,
 3785                cx,
 3786            )
 3787        });
 3788        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3789            if let Some(transaction) = on_type_formatting.await? {
 3790                if push_to_client_history {
 3791                    buffer
 3792                        .update(&mut cx, |buffer, _| {
 3793                            buffer.push_transaction(transaction, Instant::now());
 3794                        })
 3795                        .ok();
 3796                }
 3797                editor.update(&mut cx, |editor, cx| {
 3798                    editor.refresh_document_highlights(cx);
 3799                })?;
 3800            }
 3801            Ok(())
 3802        }))
 3803    }
 3804
 3805    pub fn show_completions(
 3806        &mut self,
 3807        options: &ShowCompletions,
 3808        window: &mut Window,
 3809        cx: &mut Context<Self>,
 3810    ) {
 3811        if self.pending_rename.is_some() {
 3812            return;
 3813        }
 3814
 3815        let Some(provider) = self.completion_provider.as_ref() else {
 3816            return;
 3817        };
 3818
 3819        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3820            return;
 3821        }
 3822
 3823        let position = self.selections.newest_anchor().head();
 3824        if position.diff_base_anchor.is_some() {
 3825            return;
 3826        }
 3827        let (buffer, buffer_position) =
 3828            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3829                output
 3830            } else {
 3831                return;
 3832            };
 3833        let show_completion_documentation = buffer
 3834            .read(cx)
 3835            .snapshot()
 3836            .settings_at(buffer_position, cx)
 3837            .show_completion_documentation;
 3838
 3839        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3840
 3841        let trigger_kind = match &options.trigger {
 3842            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3843                CompletionTriggerKind::TRIGGER_CHARACTER
 3844            }
 3845            _ => CompletionTriggerKind::INVOKED,
 3846        };
 3847        let completion_context = CompletionContext {
 3848            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3849                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3850                    Some(String::from(trigger))
 3851                } else {
 3852                    None
 3853                }
 3854            }),
 3855            trigger_kind,
 3856        };
 3857        let completions =
 3858            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3859        let sort_completions = provider.sort_completions();
 3860
 3861        let id = post_inc(&mut self.next_completion_id);
 3862        let task = cx.spawn_in(window, |editor, mut cx| {
 3863            async move {
 3864                editor.update(&mut cx, |this, _| {
 3865                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3866                })?;
 3867                let completions = completions.await.log_err();
 3868                let menu = if let Some(completions) = completions {
 3869                    let mut menu = CompletionsMenu::new(
 3870                        id,
 3871                        sort_completions,
 3872                        show_completion_documentation,
 3873                        position,
 3874                        buffer.clone(),
 3875                        completions.into(),
 3876                    );
 3877
 3878                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3879                        .await;
 3880
 3881                    menu.visible().then_some(menu)
 3882                } else {
 3883                    None
 3884                };
 3885
 3886                editor.update_in(&mut cx, |editor, window, cx| {
 3887                    match editor.context_menu.borrow().as_ref() {
 3888                        None => {}
 3889                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3890                            if prev_menu.id > id {
 3891                                return;
 3892                            }
 3893                        }
 3894                        _ => return,
 3895                    }
 3896
 3897                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3898                        let mut menu = menu.unwrap();
 3899                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3900
 3901                        if editor.show_inline_completions_in_menu(cx) {
 3902                            if let Some(hint) = editor.inline_completion_menu_hint(window, cx) {
 3903                                menu.show_inline_completion_hint(hint);
 3904                            }
 3905                        } else {
 3906                            editor.discard_inline_completion(false, cx);
 3907                        }
 3908
 3909                        *editor.context_menu.borrow_mut() =
 3910                            Some(CodeContextMenu::Completions(menu));
 3911
 3912                        cx.notify();
 3913                    } else if editor.completion_tasks.len() <= 1 {
 3914                        // If there are no more completion tasks and the last menu was
 3915                        // empty, we should hide it.
 3916                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3917                        // If it was already hidden and we don't show inline
 3918                        // completions in the menu, we should also show the
 3919                        // inline-completion when available.
 3920                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3921                            editor.update_visible_inline_completion(window, cx);
 3922                        }
 3923                    }
 3924                })?;
 3925
 3926                Ok::<_, anyhow::Error>(())
 3927            }
 3928            .log_err()
 3929        });
 3930
 3931        self.completion_tasks.push((id, task));
 3932    }
 3933
 3934    pub fn confirm_completion(
 3935        &mut self,
 3936        action: &ConfirmCompletion,
 3937        window: &mut Window,
 3938        cx: &mut Context<Self>,
 3939    ) -> Option<Task<Result<()>>> {
 3940        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3941    }
 3942
 3943    pub fn compose_completion(
 3944        &mut self,
 3945        action: &ComposeCompletion,
 3946        window: &mut Window,
 3947        cx: &mut Context<Self>,
 3948    ) -> Option<Task<Result<()>>> {
 3949        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3950    }
 3951
 3952    fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3953        let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
 3954            return;
 3955        };
 3956
 3957        let project = project.read(cx);
 3958
 3959        ZedPredictModal::toggle(
 3960            workspace,
 3961            project.user_store().clone(),
 3962            project.client().clone(),
 3963            project.fs().clone(),
 3964            window,
 3965            cx,
 3966        );
 3967    }
 3968
 3969    fn do_completion(
 3970        &mut self,
 3971        item_ix: Option<usize>,
 3972        intent: CompletionIntent,
 3973        window: &mut Window,
 3974        cx: &mut Context<Editor>,
 3975    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3976        use language::ToOffset as _;
 3977
 3978        {
 3979            let context_menu = self.context_menu.borrow();
 3980            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3981                let entries = menu.entries.borrow();
 3982                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3983                match entry {
 3984                    Some(CompletionEntry::InlineCompletionHint(
 3985                        InlineCompletionMenuHint::Loading,
 3986                    )) => return Some(Task::ready(Ok(()))),
 3987                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3988                        drop(entries);
 3989                        drop(context_menu);
 3990                        self.context_menu_next(&Default::default(), window, cx);
 3991                        return Some(Task::ready(Ok(())));
 3992                    }
 3993                    Some(CompletionEntry::InlineCompletionHint(
 3994                        InlineCompletionMenuHint::PendingTermsAcceptance,
 3995                    )) => {
 3996                        drop(entries);
 3997                        drop(context_menu);
 3998                        self.toggle_zed_predict_onboarding(window, cx);
 3999                        return Some(Task::ready(Ok(())));
 4000                    }
 4001                    _ => {}
 4002                }
 4003            }
 4004        }
 4005
 4006        let completions_menu =
 4007            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4008                menu
 4009            } else {
 4010                return None;
 4011            };
 4012
 4013        let entries = completions_menu.entries.borrow();
 4014        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4015        let mat = match mat {
 4016            CompletionEntry::InlineCompletionHint(_) => {
 4017                self.accept_inline_completion(&AcceptInlineCompletion, window, cx);
 4018                cx.stop_propagation();
 4019                return Some(Task::ready(Ok(())));
 4020            }
 4021            CompletionEntry::Match(mat) => {
 4022                if self.show_inline_completions_in_menu(cx) {
 4023                    self.discard_inline_completion(true, cx);
 4024                }
 4025                mat
 4026            }
 4027        };
 4028        let candidate_id = mat.candidate_id;
 4029        drop(entries);
 4030
 4031        let buffer_handle = completions_menu.buffer;
 4032        let completion = completions_menu
 4033            .completions
 4034            .borrow()
 4035            .get(candidate_id)?
 4036            .clone();
 4037        cx.stop_propagation();
 4038
 4039        let snippet;
 4040        let text;
 4041
 4042        if completion.is_snippet() {
 4043            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4044            text = snippet.as_ref().unwrap().text.clone();
 4045        } else {
 4046            snippet = None;
 4047            text = completion.new_text.clone();
 4048        };
 4049        let selections = self.selections.all::<usize>(cx);
 4050        let buffer = buffer_handle.read(cx);
 4051        let old_range = completion.old_range.to_offset(buffer);
 4052        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4053
 4054        let newest_selection = self.selections.newest_anchor();
 4055        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4056            return None;
 4057        }
 4058
 4059        let lookbehind = newest_selection
 4060            .start
 4061            .text_anchor
 4062            .to_offset(buffer)
 4063            .saturating_sub(old_range.start);
 4064        let lookahead = old_range
 4065            .end
 4066            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4067        let mut common_prefix_len = old_text
 4068            .bytes()
 4069            .zip(text.bytes())
 4070            .take_while(|(a, b)| a == b)
 4071            .count();
 4072
 4073        let snapshot = self.buffer.read(cx).snapshot(cx);
 4074        let mut range_to_replace: Option<Range<isize>> = None;
 4075        let mut ranges = Vec::new();
 4076        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4077        for selection in &selections {
 4078            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4079                let start = selection.start.saturating_sub(lookbehind);
 4080                let end = selection.end + lookahead;
 4081                if selection.id == newest_selection.id {
 4082                    range_to_replace = Some(
 4083                        ((start + common_prefix_len) as isize - selection.start as isize)
 4084                            ..(end as isize - selection.start as isize),
 4085                    );
 4086                }
 4087                ranges.push(start + common_prefix_len..end);
 4088            } else {
 4089                common_prefix_len = 0;
 4090                ranges.clear();
 4091                ranges.extend(selections.iter().map(|s| {
 4092                    if s.id == newest_selection.id {
 4093                        range_to_replace = Some(
 4094                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4095                                - selection.start as isize
 4096                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4097                                    - selection.start as isize,
 4098                        );
 4099                        old_range.clone()
 4100                    } else {
 4101                        s.start..s.end
 4102                    }
 4103                }));
 4104                break;
 4105            }
 4106            if !self.linked_edit_ranges.is_empty() {
 4107                let start_anchor = snapshot.anchor_before(selection.head());
 4108                let end_anchor = snapshot.anchor_after(selection.tail());
 4109                if let Some(ranges) = self
 4110                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4111                {
 4112                    for (buffer, edits) in ranges {
 4113                        linked_edits.entry(buffer.clone()).or_default().extend(
 4114                            edits
 4115                                .into_iter()
 4116                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4117                        );
 4118                    }
 4119                }
 4120            }
 4121        }
 4122        let text = &text[common_prefix_len..];
 4123
 4124        cx.emit(EditorEvent::InputHandled {
 4125            utf16_range_to_replace: range_to_replace,
 4126            text: text.into(),
 4127        });
 4128
 4129        self.transact(window, cx, |this, window, cx| {
 4130            if let Some(mut snippet) = snippet {
 4131                snippet.text = text.to_string();
 4132                for tabstop in snippet
 4133                    .tabstops
 4134                    .iter_mut()
 4135                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4136                {
 4137                    tabstop.start -= common_prefix_len as isize;
 4138                    tabstop.end -= common_prefix_len as isize;
 4139                }
 4140
 4141                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4142            } else {
 4143                this.buffer.update(cx, |buffer, cx| {
 4144                    buffer.edit(
 4145                        ranges.iter().map(|range| (range.clone(), text)),
 4146                        this.autoindent_mode.clone(),
 4147                        cx,
 4148                    );
 4149                });
 4150            }
 4151            for (buffer, edits) in linked_edits {
 4152                buffer.update(cx, |buffer, cx| {
 4153                    let snapshot = buffer.snapshot();
 4154                    let edits = edits
 4155                        .into_iter()
 4156                        .map(|(range, text)| {
 4157                            use text::ToPoint as TP;
 4158                            let end_point = TP::to_point(&range.end, &snapshot);
 4159                            let start_point = TP::to_point(&range.start, &snapshot);
 4160                            (start_point..end_point, text)
 4161                        })
 4162                        .sorted_by_key(|(range, _)| range.start)
 4163                        .collect::<Vec<_>>();
 4164                    buffer.edit(edits, None, cx);
 4165                })
 4166            }
 4167
 4168            this.refresh_inline_completion(true, false, window, cx);
 4169        });
 4170
 4171        let show_new_completions_on_confirm = completion
 4172            .confirm
 4173            .as_ref()
 4174            .map_or(false, |confirm| confirm(intent, window, cx));
 4175        if show_new_completions_on_confirm {
 4176            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4177        }
 4178
 4179        let provider = self.completion_provider.as_ref()?;
 4180        drop(completion);
 4181        let apply_edits = provider.apply_additional_edits_for_completion(
 4182            buffer_handle,
 4183            completions_menu.completions.clone(),
 4184            candidate_id,
 4185            true,
 4186            cx,
 4187        );
 4188
 4189        let editor_settings = EditorSettings::get_global(cx);
 4190        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4191            // After the code completion is finished, users often want to know what signatures are needed.
 4192            // so we should automatically call signature_help
 4193            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4194        }
 4195
 4196        Some(cx.foreground_executor().spawn(async move {
 4197            apply_edits.await?;
 4198            Ok(())
 4199        }))
 4200    }
 4201
 4202    pub fn toggle_code_actions(
 4203        &mut self,
 4204        action: &ToggleCodeActions,
 4205        window: &mut Window,
 4206        cx: &mut Context<Self>,
 4207    ) {
 4208        let mut context_menu = self.context_menu.borrow_mut();
 4209        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4210            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4211                // Toggle if we're selecting the same one
 4212                *context_menu = None;
 4213                cx.notify();
 4214                return;
 4215            } else {
 4216                // Otherwise, clear it and start a new one
 4217                *context_menu = None;
 4218                cx.notify();
 4219            }
 4220        }
 4221        drop(context_menu);
 4222        let snapshot = self.snapshot(window, cx);
 4223        let deployed_from_indicator = action.deployed_from_indicator;
 4224        let mut task = self.code_actions_task.take();
 4225        let action = action.clone();
 4226        cx.spawn_in(window, |editor, mut cx| async move {
 4227            while let Some(prev_task) = task {
 4228                prev_task.await.log_err();
 4229                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4230            }
 4231
 4232            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4233                if editor.focus_handle.is_focused(window) {
 4234                    let multibuffer_point = action
 4235                        .deployed_from_indicator
 4236                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4237                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4238                    let (buffer, buffer_row) = snapshot
 4239                        .buffer_snapshot
 4240                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4241                        .and_then(|(buffer_snapshot, range)| {
 4242                            editor
 4243                                .buffer
 4244                                .read(cx)
 4245                                .buffer(buffer_snapshot.remote_id())
 4246                                .map(|buffer| (buffer, range.start.row))
 4247                        })?;
 4248                    let (_, code_actions) = editor
 4249                        .available_code_actions
 4250                        .clone()
 4251                        .and_then(|(location, code_actions)| {
 4252                            let snapshot = location.buffer.read(cx).snapshot();
 4253                            let point_range = location.range.to_point(&snapshot);
 4254                            let point_range = point_range.start.row..=point_range.end.row;
 4255                            if point_range.contains(&buffer_row) {
 4256                                Some((location, code_actions))
 4257                            } else {
 4258                                None
 4259                            }
 4260                        })
 4261                        .unzip();
 4262                    let buffer_id = buffer.read(cx).remote_id();
 4263                    let tasks = editor
 4264                        .tasks
 4265                        .get(&(buffer_id, buffer_row))
 4266                        .map(|t| Arc::new(t.to_owned()));
 4267                    if tasks.is_none() && code_actions.is_none() {
 4268                        return None;
 4269                    }
 4270
 4271                    editor.completion_tasks.clear();
 4272                    editor.discard_inline_completion(false, cx);
 4273                    let task_context =
 4274                        tasks
 4275                            .as_ref()
 4276                            .zip(editor.project.clone())
 4277                            .map(|(tasks, project)| {
 4278                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4279                            });
 4280
 4281                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4282                        let task_context = match task_context {
 4283                            Some(task_context) => task_context.await,
 4284                            None => None,
 4285                        };
 4286                        let resolved_tasks =
 4287                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4288                                Rc::new(ResolvedTasks {
 4289                                    templates: tasks.resolve(&task_context).collect(),
 4290                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4291                                        multibuffer_point.row,
 4292                                        tasks.column,
 4293                                    )),
 4294                                })
 4295                            });
 4296                        let spawn_straight_away = resolved_tasks
 4297                            .as_ref()
 4298                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4299                            && code_actions
 4300                                .as_ref()
 4301                                .map_or(true, |actions| actions.is_empty());
 4302                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4303                            *editor.context_menu.borrow_mut() =
 4304                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4305                                    buffer,
 4306                                    actions: CodeActionContents {
 4307                                        tasks: resolved_tasks,
 4308                                        actions: code_actions,
 4309                                    },
 4310                                    selected_item: Default::default(),
 4311                                    scroll_handle: UniformListScrollHandle::default(),
 4312                                    deployed_from_indicator,
 4313                                }));
 4314                            if spawn_straight_away {
 4315                                if let Some(task) = editor.confirm_code_action(
 4316                                    &ConfirmCodeAction { item_ix: Some(0) },
 4317                                    window,
 4318                                    cx,
 4319                                ) {
 4320                                    cx.notify();
 4321                                    return task;
 4322                                }
 4323                            }
 4324                            cx.notify();
 4325                            Task::ready(Ok(()))
 4326                        }) {
 4327                            task.await
 4328                        } else {
 4329                            Ok(())
 4330                        }
 4331                    }))
 4332                } else {
 4333                    Some(Task::ready(Ok(())))
 4334                }
 4335            })?;
 4336            if let Some(task) = spawned_test_task {
 4337                task.await?;
 4338            }
 4339
 4340            Ok::<_, anyhow::Error>(())
 4341        })
 4342        .detach_and_log_err(cx);
 4343    }
 4344
 4345    pub fn confirm_code_action(
 4346        &mut self,
 4347        action: &ConfirmCodeAction,
 4348        window: &mut Window,
 4349        cx: &mut Context<Self>,
 4350    ) -> Option<Task<Result<()>>> {
 4351        let actions_menu =
 4352            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4353                menu
 4354            } else {
 4355                return None;
 4356            };
 4357        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4358        let action = actions_menu.actions.get(action_ix)?;
 4359        let title = action.label();
 4360        let buffer = actions_menu.buffer;
 4361        let workspace = self.workspace()?;
 4362
 4363        match action {
 4364            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4365                workspace.update(cx, |workspace, cx| {
 4366                    workspace::tasks::schedule_resolved_task(
 4367                        workspace,
 4368                        task_source_kind,
 4369                        resolved_task,
 4370                        false,
 4371                        cx,
 4372                    );
 4373
 4374                    Some(Task::ready(Ok(())))
 4375                })
 4376            }
 4377            CodeActionsItem::CodeAction {
 4378                excerpt_id,
 4379                action,
 4380                provider,
 4381            } => {
 4382                let apply_code_action =
 4383                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4384                let workspace = workspace.downgrade();
 4385                Some(cx.spawn_in(window, |editor, cx| async move {
 4386                    let project_transaction = apply_code_action.await?;
 4387                    Self::open_project_transaction(
 4388                        &editor,
 4389                        workspace,
 4390                        project_transaction,
 4391                        title,
 4392                        cx,
 4393                    )
 4394                    .await
 4395                }))
 4396            }
 4397        }
 4398    }
 4399
 4400    pub async fn open_project_transaction(
 4401        this: &WeakEntity<Editor>,
 4402        workspace: WeakEntity<Workspace>,
 4403        transaction: ProjectTransaction,
 4404        title: String,
 4405        mut cx: AsyncWindowContext,
 4406    ) -> Result<()> {
 4407        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4408        cx.update(|_, cx| {
 4409            entries.sort_unstable_by_key(|(buffer, _)| {
 4410                buffer.read(cx).file().map(|f| f.path().clone())
 4411            });
 4412        })?;
 4413
 4414        // If the project transaction's edits are all contained within this editor, then
 4415        // avoid opening a new editor to display them.
 4416
 4417        if let Some((buffer, transaction)) = entries.first() {
 4418            if entries.len() == 1 {
 4419                let excerpt = this.update(&mut cx, |editor, cx| {
 4420                    editor
 4421                        .buffer()
 4422                        .read(cx)
 4423                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4424                })?;
 4425                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4426                    if excerpted_buffer == *buffer {
 4427                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4428                            let excerpt_range = excerpt_range.to_offset(buffer);
 4429                            buffer
 4430                                .edited_ranges_for_transaction::<usize>(transaction)
 4431                                .all(|range| {
 4432                                    excerpt_range.start <= range.start
 4433                                        && excerpt_range.end >= range.end
 4434                                })
 4435                        })?;
 4436
 4437                        if all_edits_within_excerpt {
 4438                            return Ok(());
 4439                        }
 4440                    }
 4441                }
 4442            }
 4443        } else {
 4444            return Ok(());
 4445        }
 4446
 4447        let mut ranges_to_highlight = Vec::new();
 4448        let excerpt_buffer = cx.new(|cx| {
 4449            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4450            for (buffer_handle, transaction) in &entries {
 4451                let buffer = buffer_handle.read(cx);
 4452                ranges_to_highlight.extend(
 4453                    multibuffer.push_excerpts_with_context_lines(
 4454                        buffer_handle.clone(),
 4455                        buffer
 4456                            .edited_ranges_for_transaction::<usize>(transaction)
 4457                            .collect(),
 4458                        DEFAULT_MULTIBUFFER_CONTEXT,
 4459                        cx,
 4460                    ),
 4461                );
 4462            }
 4463            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4464            multibuffer
 4465        })?;
 4466
 4467        workspace.update_in(&mut cx, |workspace, window, cx| {
 4468            let project = workspace.project().clone();
 4469            let editor = cx
 4470                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4471            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4472            editor.update(cx, |editor, cx| {
 4473                editor.highlight_background::<Self>(
 4474                    &ranges_to_highlight,
 4475                    |theme| theme.editor_highlighted_line_background,
 4476                    cx,
 4477                );
 4478            });
 4479        })?;
 4480
 4481        Ok(())
 4482    }
 4483
 4484    pub fn clear_code_action_providers(&mut self) {
 4485        self.code_action_providers.clear();
 4486        self.available_code_actions.take();
 4487    }
 4488
 4489    pub fn add_code_action_provider(
 4490        &mut self,
 4491        provider: Rc<dyn CodeActionProvider>,
 4492        window: &mut Window,
 4493        cx: &mut Context<Self>,
 4494    ) {
 4495        if self
 4496            .code_action_providers
 4497            .iter()
 4498            .any(|existing_provider| existing_provider.id() == provider.id())
 4499        {
 4500            return;
 4501        }
 4502
 4503        self.code_action_providers.push(provider);
 4504        self.refresh_code_actions(window, cx);
 4505    }
 4506
 4507    pub fn remove_code_action_provider(
 4508        &mut self,
 4509        id: Arc<str>,
 4510        window: &mut Window,
 4511        cx: &mut Context<Self>,
 4512    ) {
 4513        self.code_action_providers
 4514            .retain(|provider| provider.id() != id);
 4515        self.refresh_code_actions(window, cx);
 4516    }
 4517
 4518    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4519        let buffer = self.buffer.read(cx);
 4520        let newest_selection = self.selections.newest_anchor().clone();
 4521        if newest_selection.head().diff_base_anchor.is_some() {
 4522            return None;
 4523        }
 4524        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4525        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4526        if start_buffer != end_buffer {
 4527            return None;
 4528        }
 4529
 4530        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4531            cx.background_executor()
 4532                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4533                .await;
 4534
 4535            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4536                let providers = this.code_action_providers.clone();
 4537                let tasks = this
 4538                    .code_action_providers
 4539                    .iter()
 4540                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4541                    .collect::<Vec<_>>();
 4542                (providers, tasks)
 4543            })?;
 4544
 4545            let mut actions = Vec::new();
 4546            for (provider, provider_actions) in
 4547                providers.into_iter().zip(future::join_all(tasks).await)
 4548            {
 4549                if let Some(provider_actions) = provider_actions.log_err() {
 4550                    actions.extend(provider_actions.into_iter().map(|action| {
 4551                        AvailableCodeAction {
 4552                            excerpt_id: newest_selection.start.excerpt_id,
 4553                            action,
 4554                            provider: provider.clone(),
 4555                        }
 4556                    }));
 4557                }
 4558            }
 4559
 4560            this.update(&mut cx, |this, cx| {
 4561                this.available_code_actions = if actions.is_empty() {
 4562                    None
 4563                } else {
 4564                    Some((
 4565                        Location {
 4566                            buffer: start_buffer,
 4567                            range: start..end,
 4568                        },
 4569                        actions.into(),
 4570                    ))
 4571                };
 4572                cx.notify();
 4573            })
 4574        }));
 4575        None
 4576    }
 4577
 4578    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4579        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4580            self.show_git_blame_inline = false;
 4581
 4582            self.show_git_blame_inline_delay_task =
 4583                Some(cx.spawn_in(window, |this, mut cx| async move {
 4584                    cx.background_executor().timer(delay).await;
 4585
 4586                    this.update(&mut cx, |this, cx| {
 4587                        this.show_git_blame_inline = true;
 4588                        cx.notify();
 4589                    })
 4590                    .log_err();
 4591                }));
 4592        }
 4593    }
 4594
 4595    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4596        if self.pending_rename.is_some() {
 4597            return None;
 4598        }
 4599
 4600        let provider = self.semantics_provider.clone()?;
 4601        let buffer = self.buffer.read(cx);
 4602        let newest_selection = self.selections.newest_anchor().clone();
 4603        let cursor_position = newest_selection.head();
 4604        let (cursor_buffer, cursor_buffer_position) =
 4605            buffer.text_anchor_for_position(cursor_position, cx)?;
 4606        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4607        if cursor_buffer != tail_buffer {
 4608            return None;
 4609        }
 4610        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4611        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4612            cx.background_executor()
 4613                .timer(Duration::from_millis(debounce))
 4614                .await;
 4615
 4616            let highlights = if let Some(highlights) = cx
 4617                .update(|cx| {
 4618                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4619                })
 4620                .ok()
 4621                .flatten()
 4622            {
 4623                highlights.await.log_err()
 4624            } else {
 4625                None
 4626            };
 4627
 4628            if let Some(highlights) = highlights {
 4629                this.update(&mut cx, |this, cx| {
 4630                    if this.pending_rename.is_some() {
 4631                        return;
 4632                    }
 4633
 4634                    let buffer_id = cursor_position.buffer_id;
 4635                    let buffer = this.buffer.read(cx);
 4636                    if !buffer
 4637                        .text_anchor_for_position(cursor_position, cx)
 4638                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4639                    {
 4640                        return;
 4641                    }
 4642
 4643                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4644                    let mut write_ranges = Vec::new();
 4645                    let mut read_ranges = Vec::new();
 4646                    for highlight in highlights {
 4647                        for (excerpt_id, excerpt_range) in
 4648                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4649                        {
 4650                            let start = highlight
 4651                                .range
 4652                                .start
 4653                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4654                            let end = highlight
 4655                                .range
 4656                                .end
 4657                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4658                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4659                                continue;
 4660                            }
 4661
 4662                            let range = Anchor {
 4663                                buffer_id,
 4664                                excerpt_id,
 4665                                text_anchor: start,
 4666                                diff_base_anchor: None,
 4667                            }..Anchor {
 4668                                buffer_id,
 4669                                excerpt_id,
 4670                                text_anchor: end,
 4671                                diff_base_anchor: None,
 4672                            };
 4673                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4674                                write_ranges.push(range);
 4675                            } else {
 4676                                read_ranges.push(range);
 4677                            }
 4678                        }
 4679                    }
 4680
 4681                    this.highlight_background::<DocumentHighlightRead>(
 4682                        &read_ranges,
 4683                        |theme| theme.editor_document_highlight_read_background,
 4684                        cx,
 4685                    );
 4686                    this.highlight_background::<DocumentHighlightWrite>(
 4687                        &write_ranges,
 4688                        |theme| theme.editor_document_highlight_write_background,
 4689                        cx,
 4690                    );
 4691                    cx.notify();
 4692                })
 4693                .log_err();
 4694            }
 4695        }));
 4696        None
 4697    }
 4698
 4699    pub fn refresh_inline_completion(
 4700        &mut self,
 4701        debounce: bool,
 4702        user_requested: bool,
 4703        window: &mut Window,
 4704        cx: &mut Context<Self>,
 4705    ) -> Option<()> {
 4706        let provider = self.inline_completion_provider()?;
 4707        let cursor = self.selections.newest_anchor().head();
 4708        let (buffer, cursor_buffer_position) =
 4709            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4710
 4711        if !user_requested
 4712            && (!self.enable_inline_completions
 4713                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4714                || !self.is_focused(window)
 4715                || buffer.read(cx).is_empty())
 4716        {
 4717            self.discard_inline_completion(false, cx);
 4718            return None;
 4719        }
 4720
 4721        self.update_visible_inline_completion(window, cx);
 4722        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4723        Some(())
 4724    }
 4725
 4726    fn cycle_inline_completion(
 4727        &mut self,
 4728        direction: Direction,
 4729        window: &mut Window,
 4730        cx: &mut Context<Self>,
 4731    ) -> Option<()> {
 4732        let provider = self.inline_completion_provider()?;
 4733        let cursor = self.selections.newest_anchor().head();
 4734        let (buffer, cursor_buffer_position) =
 4735            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4736        if !self.enable_inline_completions
 4737            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4738        {
 4739            return None;
 4740        }
 4741
 4742        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4743        self.update_visible_inline_completion(window, cx);
 4744
 4745        Some(())
 4746    }
 4747
 4748    pub fn show_inline_completion(
 4749        &mut self,
 4750        _: &ShowInlineCompletion,
 4751        window: &mut Window,
 4752        cx: &mut Context<Self>,
 4753    ) {
 4754        if !self.has_active_inline_completion() {
 4755            self.refresh_inline_completion(false, true, window, cx);
 4756            return;
 4757        }
 4758
 4759        self.update_visible_inline_completion(window, cx);
 4760    }
 4761
 4762    pub fn display_cursor_names(
 4763        &mut self,
 4764        _: &DisplayCursorNames,
 4765        window: &mut Window,
 4766        cx: &mut Context<Self>,
 4767    ) {
 4768        self.show_cursor_names(window, cx);
 4769    }
 4770
 4771    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4772        self.show_cursor_names = true;
 4773        cx.notify();
 4774        cx.spawn_in(window, |this, mut cx| async move {
 4775            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4776            this.update(&mut cx, |this, cx| {
 4777                this.show_cursor_names = false;
 4778                cx.notify()
 4779            })
 4780            .ok()
 4781        })
 4782        .detach();
 4783    }
 4784
 4785    pub fn next_inline_completion(
 4786        &mut self,
 4787        _: &NextInlineCompletion,
 4788        window: &mut Window,
 4789        cx: &mut Context<Self>,
 4790    ) {
 4791        if self.has_active_inline_completion() {
 4792            self.cycle_inline_completion(Direction::Next, window, cx);
 4793        } else {
 4794            let is_copilot_disabled = self
 4795                .refresh_inline_completion(false, true, window, cx)
 4796                .is_none();
 4797            if is_copilot_disabled {
 4798                cx.propagate();
 4799            }
 4800        }
 4801    }
 4802
 4803    pub fn previous_inline_completion(
 4804        &mut self,
 4805        _: &PreviousInlineCompletion,
 4806        window: &mut Window,
 4807        cx: &mut Context<Self>,
 4808    ) {
 4809        if self.has_active_inline_completion() {
 4810            self.cycle_inline_completion(Direction::Prev, window, cx);
 4811        } else {
 4812            let is_copilot_disabled = self
 4813                .refresh_inline_completion(false, true, window, cx)
 4814                .is_none();
 4815            if is_copilot_disabled {
 4816                cx.propagate();
 4817            }
 4818        }
 4819    }
 4820
 4821    pub fn accept_inline_completion(
 4822        &mut self,
 4823        _: &AcceptInlineCompletion,
 4824        window: &mut Window,
 4825        cx: &mut Context<Self>,
 4826    ) {
 4827        let buffer = self.buffer.read(cx);
 4828        let snapshot = buffer.snapshot(cx);
 4829        let selection = self.selections.newest_adjusted(cx);
 4830        let cursor = selection.head();
 4831        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4832        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4833        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4834        {
 4835            if cursor.column < suggested_indent.len
 4836                && cursor.column <= current_indent.len
 4837                && current_indent.len <= suggested_indent.len
 4838            {
 4839                self.tab(&Default::default(), window, cx);
 4840                return;
 4841            }
 4842        }
 4843
 4844        if self.show_inline_completions_in_menu(cx) {
 4845            self.hide_context_menu(window, cx);
 4846        }
 4847
 4848        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4849            return;
 4850        };
 4851
 4852        self.report_inline_completion_event(true, cx);
 4853
 4854        match &active_inline_completion.completion {
 4855            InlineCompletion::Move(position) => {
 4856                let position = *position;
 4857                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4858                    selections.select_anchor_ranges([position..position]);
 4859                });
 4860            }
 4861            InlineCompletion::Edit {
 4862                edits,
 4863                display_mode: _,
 4864            } => {
 4865                if let Some(provider) = self.inline_completion_provider() {
 4866                    provider.accept(cx);
 4867                }
 4868
 4869                let snapshot = self.buffer.read(cx).snapshot(cx);
 4870                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4871
 4872                self.buffer.update(cx, |buffer, cx| {
 4873                    buffer.edit(edits.iter().cloned(), None, cx)
 4874                });
 4875
 4876                self.change_selections(None, window, cx, |s| {
 4877                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4878                });
 4879
 4880                self.update_visible_inline_completion(window, cx);
 4881                if self.active_inline_completion.is_none() {
 4882                    self.refresh_inline_completion(true, true, window, cx);
 4883                }
 4884
 4885                cx.notify();
 4886            }
 4887        }
 4888    }
 4889
 4890    pub fn accept_partial_inline_completion(
 4891        &mut self,
 4892        _: &AcceptPartialInlineCompletion,
 4893        window: &mut Window,
 4894        cx: &mut Context<Self>,
 4895    ) {
 4896        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4897            return;
 4898        };
 4899        if self.selections.count() != 1 {
 4900            return;
 4901        }
 4902
 4903        self.report_inline_completion_event(true, cx);
 4904
 4905        match &active_inline_completion.completion {
 4906            InlineCompletion::Move(position) => {
 4907                let position = *position;
 4908                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4909                    selections.select_anchor_ranges([position..position]);
 4910                });
 4911            }
 4912            InlineCompletion::Edit {
 4913                edits,
 4914                display_mode: _,
 4915            } => {
 4916                // Find an insertion that starts at the cursor position.
 4917                let snapshot = self.buffer.read(cx).snapshot(cx);
 4918                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4919                let insertion = edits.iter().find_map(|(range, text)| {
 4920                    let range = range.to_offset(&snapshot);
 4921                    if range.is_empty() && range.start == cursor_offset {
 4922                        Some(text)
 4923                    } else {
 4924                        None
 4925                    }
 4926                });
 4927
 4928                if let Some(text) = insertion {
 4929                    let mut partial_completion = text
 4930                        .chars()
 4931                        .by_ref()
 4932                        .take_while(|c| c.is_alphabetic())
 4933                        .collect::<String>();
 4934                    if partial_completion.is_empty() {
 4935                        partial_completion = text
 4936                            .chars()
 4937                            .by_ref()
 4938                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4939                            .collect::<String>();
 4940                    }
 4941
 4942                    cx.emit(EditorEvent::InputHandled {
 4943                        utf16_range_to_replace: None,
 4944                        text: partial_completion.clone().into(),
 4945                    });
 4946
 4947                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4948
 4949                    self.refresh_inline_completion(true, true, window, cx);
 4950                    cx.notify();
 4951                } else {
 4952                    self.accept_inline_completion(&Default::default(), window, cx);
 4953                }
 4954            }
 4955        }
 4956    }
 4957
 4958    fn discard_inline_completion(
 4959        &mut self,
 4960        should_report_inline_completion_event: bool,
 4961        cx: &mut Context<Self>,
 4962    ) -> bool {
 4963        if should_report_inline_completion_event {
 4964            self.report_inline_completion_event(false, cx);
 4965        }
 4966
 4967        if let Some(provider) = self.inline_completion_provider() {
 4968            provider.discard(cx);
 4969        }
 4970
 4971        self.take_active_inline_completion(cx).is_some()
 4972    }
 4973
 4974    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4975        let Some(provider) = self.inline_completion_provider() else {
 4976            return;
 4977        };
 4978
 4979        let Some((_, buffer, _)) = self
 4980            .buffer
 4981            .read(cx)
 4982            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4983        else {
 4984            return;
 4985        };
 4986
 4987        let extension = buffer
 4988            .read(cx)
 4989            .file()
 4990            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4991
 4992        let event_type = match accepted {
 4993            true => "Inline Completion Accepted",
 4994            false => "Inline Completion Discarded",
 4995        };
 4996        telemetry::event!(
 4997            event_type,
 4998            provider = provider.name(),
 4999            suggestion_accepted = accepted,
 5000            file_extension = extension,
 5001        );
 5002    }
 5003
 5004    pub fn has_active_inline_completion(&self) -> bool {
 5005        self.active_inline_completion.is_some()
 5006    }
 5007
 5008    fn take_active_inline_completion(
 5009        &mut self,
 5010        cx: &mut Context<Self>,
 5011    ) -> Option<InlineCompletion> {
 5012        let active_inline_completion = self.active_inline_completion.take()?;
 5013        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 5014        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5015        Some(active_inline_completion.completion)
 5016    }
 5017
 5018    fn update_visible_inline_completion(
 5019        &mut self,
 5020        window: &mut Window,
 5021        cx: &mut Context<Self>,
 5022    ) -> Option<()> {
 5023        let selection = self.selections.newest_anchor();
 5024        let cursor = selection.head();
 5025        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5026        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5027        let excerpt_id = cursor.excerpt_id;
 5028
 5029        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 5030            && (self.context_menu.borrow().is_some()
 5031                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5032        if completions_menu_has_precedence
 5033            || !offset_selection.is_empty()
 5034            || !self.enable_inline_completions
 5035            || self
 5036                .active_inline_completion
 5037                .as_ref()
 5038                .map_or(false, |completion| {
 5039                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5040                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5041                    !invalidation_range.contains(&offset_selection.head())
 5042                })
 5043        {
 5044            self.discard_inline_completion(false, cx);
 5045            return None;
 5046        }
 5047
 5048        self.take_active_inline_completion(cx);
 5049        let provider = self.inline_completion_provider()?;
 5050
 5051        let (buffer, cursor_buffer_position) =
 5052            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5053
 5054        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5055        let edits = completion
 5056            .edits
 5057            .into_iter()
 5058            .flat_map(|(range, new_text)| {
 5059                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5060                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5061                Some((start..end, new_text))
 5062            })
 5063            .collect::<Vec<_>>();
 5064        if edits.is_empty() {
 5065            return None;
 5066        }
 5067
 5068        let first_edit_start = edits.first().unwrap().0.start;
 5069        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5070        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5071
 5072        let last_edit_end = edits.last().unwrap().0.end;
 5073        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5074        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5075
 5076        let cursor_row = cursor.to_point(&multibuffer).row;
 5077
 5078        let mut inlay_ids = Vec::new();
 5079        let invalidation_row_range;
 5080        let completion;
 5081        if cursor_row < edit_start_row {
 5082            invalidation_row_range = cursor_row..edit_end_row;
 5083            completion = InlineCompletion::Move(first_edit_start);
 5084        } else if cursor_row > edit_end_row {
 5085            invalidation_row_range = edit_start_row..cursor_row;
 5086            completion = InlineCompletion::Move(first_edit_start);
 5087        } else {
 5088            if edits
 5089                .iter()
 5090                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5091            {
 5092                let mut inlays = Vec::new();
 5093                for (range, new_text) in &edits {
 5094                    let inlay = Inlay::inline_completion(
 5095                        post_inc(&mut self.next_inlay_id),
 5096                        range.start,
 5097                        new_text.as_str(),
 5098                    );
 5099                    inlay_ids.push(inlay.id);
 5100                    inlays.push(inlay);
 5101                }
 5102
 5103                self.splice_inlays(vec![], inlays, cx);
 5104            } else {
 5105                let background_color = cx.theme().status().deleted_background;
 5106                self.highlight_text::<InlineCompletionHighlight>(
 5107                    edits.iter().map(|(range, _)| range.clone()).collect(),
 5108                    HighlightStyle {
 5109                        background_color: Some(background_color),
 5110                        ..Default::default()
 5111                    },
 5112                    cx,
 5113                );
 5114            }
 5115
 5116            invalidation_row_range = edit_start_row..edit_end_row;
 5117
 5118            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5119                if provider.show_tab_accept_marker()
 5120                    && first_edit_start_point.row == last_edit_end_point.row
 5121                    && !edits.iter().any(|(_, edit)| edit.contains('\n'))
 5122                {
 5123                    EditDisplayMode::TabAccept
 5124                } else {
 5125                    EditDisplayMode::Inline
 5126                }
 5127            } else {
 5128                EditDisplayMode::DiffPopover
 5129            };
 5130
 5131            completion = InlineCompletion::Edit {
 5132                edits,
 5133                display_mode,
 5134            };
 5135        };
 5136
 5137        let invalidation_range = multibuffer
 5138            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5139            ..multibuffer.anchor_after(Point::new(
 5140                invalidation_row_range.end,
 5141                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5142            ));
 5143
 5144        self.active_inline_completion = Some(InlineCompletionState {
 5145            inlay_ids,
 5146            completion,
 5147            invalidation_range,
 5148        });
 5149
 5150        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 5151            if let Some(hint) = self.inline_completion_menu_hint(window, cx) {
 5152                match self.context_menu.borrow_mut().as_mut() {
 5153                    Some(CodeContextMenu::Completions(menu)) => {
 5154                        menu.show_inline_completion_hint(hint);
 5155                    }
 5156                    _ => {}
 5157                }
 5158            }
 5159        }
 5160
 5161        cx.notify();
 5162
 5163        Some(())
 5164    }
 5165
 5166    fn inline_completion_menu_hint(
 5167        &self,
 5168        window: &mut Window,
 5169        cx: &mut Context<Self>,
 5170    ) -> Option<InlineCompletionMenuHint> {
 5171        let provider = self.inline_completion_provider()?;
 5172        if self.has_active_inline_completion() {
 5173            let editor_snapshot = self.snapshot(window, cx);
 5174
 5175            let text = match &self.active_inline_completion.as_ref()?.completion {
 5176                InlineCompletion::Edit {
 5177                    edits,
 5178                    display_mode: _,
 5179                } => inline_completion_edit_text(&editor_snapshot, edits, true, cx),
 5180                InlineCompletion::Move(target) => {
 5181                    let target_point =
 5182                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 5183                    let target_line = target_point.row + 1;
 5184                    InlineCompletionText::Move(
 5185                        format!("Jump to edit in line {}", target_line).into(),
 5186                    )
 5187                }
 5188            };
 5189
 5190            Some(InlineCompletionMenuHint::Loaded { text })
 5191        } else if provider.is_refreshing(cx) {
 5192            Some(InlineCompletionMenuHint::Loading)
 5193        } else if provider.needs_terms_acceptance(cx) {
 5194            Some(InlineCompletionMenuHint::PendingTermsAcceptance)
 5195        } else {
 5196            Some(InlineCompletionMenuHint::None)
 5197        }
 5198    }
 5199
 5200    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5201        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5202    }
 5203
 5204    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5205        let by_provider = matches!(
 5206            self.menu_inline_completions_policy,
 5207            MenuInlineCompletionsPolicy::ByProvider
 5208        );
 5209
 5210        by_provider
 5211            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5212            && self
 5213                .inline_completion_provider()
 5214                .map_or(false, |provider| provider.show_completions_in_menu())
 5215    }
 5216
 5217    fn render_code_actions_indicator(
 5218        &self,
 5219        _style: &EditorStyle,
 5220        row: DisplayRow,
 5221        is_active: bool,
 5222        cx: &mut Context<Self>,
 5223    ) -> Option<IconButton> {
 5224        if self.available_code_actions.is_some() {
 5225            Some(
 5226                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5227                    .shape(ui::IconButtonShape::Square)
 5228                    .icon_size(IconSize::XSmall)
 5229                    .icon_color(Color::Muted)
 5230                    .toggle_state(is_active)
 5231                    .tooltip({
 5232                        let focus_handle = self.focus_handle.clone();
 5233                        move |window, cx| {
 5234                            Tooltip::for_action_in(
 5235                                "Toggle Code Actions",
 5236                                &ToggleCodeActions {
 5237                                    deployed_from_indicator: None,
 5238                                },
 5239                                &focus_handle,
 5240                                window,
 5241                                cx,
 5242                            )
 5243                        }
 5244                    })
 5245                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5246                        window.focus(&editor.focus_handle(cx));
 5247                        editor.toggle_code_actions(
 5248                            &ToggleCodeActions {
 5249                                deployed_from_indicator: Some(row),
 5250                            },
 5251                            window,
 5252                            cx,
 5253                        );
 5254                    })),
 5255            )
 5256        } else {
 5257            None
 5258        }
 5259    }
 5260
 5261    fn clear_tasks(&mut self) {
 5262        self.tasks.clear()
 5263    }
 5264
 5265    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5266        if self.tasks.insert(key, value).is_some() {
 5267            // This case should hopefully be rare, but just in case...
 5268            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5269        }
 5270    }
 5271
 5272    fn build_tasks_context(
 5273        project: &Entity<Project>,
 5274        buffer: &Entity<Buffer>,
 5275        buffer_row: u32,
 5276        tasks: &Arc<RunnableTasks>,
 5277        cx: &mut Context<Self>,
 5278    ) -> Task<Option<task::TaskContext>> {
 5279        let position = Point::new(buffer_row, tasks.column);
 5280        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5281        let location = Location {
 5282            buffer: buffer.clone(),
 5283            range: range_start..range_start,
 5284        };
 5285        // Fill in the environmental variables from the tree-sitter captures
 5286        let mut captured_task_variables = TaskVariables::default();
 5287        for (capture_name, value) in tasks.extra_variables.clone() {
 5288            captured_task_variables.insert(
 5289                task::VariableName::Custom(capture_name.into()),
 5290                value.clone(),
 5291            );
 5292        }
 5293        project.update(cx, |project, cx| {
 5294            project.task_store().update(cx, |task_store, cx| {
 5295                task_store.task_context_for_location(captured_task_variables, location, cx)
 5296            })
 5297        })
 5298    }
 5299
 5300    pub fn spawn_nearest_task(
 5301        &mut self,
 5302        action: &SpawnNearestTask,
 5303        window: &mut Window,
 5304        cx: &mut Context<Self>,
 5305    ) {
 5306        let Some((workspace, _)) = self.workspace.clone() else {
 5307            return;
 5308        };
 5309        let Some(project) = self.project.clone() else {
 5310            return;
 5311        };
 5312
 5313        // Try to find a closest, enclosing node using tree-sitter that has a
 5314        // task
 5315        let Some((buffer, buffer_row, tasks)) = self
 5316            .find_enclosing_node_task(cx)
 5317            // Or find the task that's closest in row-distance.
 5318            .or_else(|| self.find_closest_task(cx))
 5319        else {
 5320            return;
 5321        };
 5322
 5323        let reveal_strategy = action.reveal;
 5324        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5325        cx.spawn_in(window, |_, mut cx| async move {
 5326            let context = task_context.await?;
 5327            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5328
 5329            let resolved = resolved_task.resolved.as_mut()?;
 5330            resolved.reveal = reveal_strategy;
 5331
 5332            workspace
 5333                .update(&mut cx, |workspace, cx| {
 5334                    workspace::tasks::schedule_resolved_task(
 5335                        workspace,
 5336                        task_source_kind,
 5337                        resolved_task,
 5338                        false,
 5339                        cx,
 5340                    );
 5341                })
 5342                .ok()
 5343        })
 5344        .detach();
 5345    }
 5346
 5347    fn find_closest_task(
 5348        &mut self,
 5349        cx: &mut Context<Self>,
 5350    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5351        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5352
 5353        let ((buffer_id, row), tasks) = self
 5354            .tasks
 5355            .iter()
 5356            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5357
 5358        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5359        let tasks = Arc::new(tasks.to_owned());
 5360        Some((buffer, *row, tasks))
 5361    }
 5362
 5363    fn find_enclosing_node_task(
 5364        &mut self,
 5365        cx: &mut Context<Self>,
 5366    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5367        let snapshot = self.buffer.read(cx).snapshot(cx);
 5368        let offset = self.selections.newest::<usize>(cx).head();
 5369        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5370        let buffer_id = excerpt.buffer().remote_id();
 5371
 5372        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5373        let mut cursor = layer.node().walk();
 5374
 5375        while cursor.goto_first_child_for_byte(offset).is_some() {
 5376            if cursor.node().end_byte() == offset {
 5377                cursor.goto_next_sibling();
 5378            }
 5379        }
 5380
 5381        // Ascend to the smallest ancestor that contains the range and has a task.
 5382        loop {
 5383            let node = cursor.node();
 5384            let node_range = node.byte_range();
 5385            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5386
 5387            // Check if this node contains our offset
 5388            if node_range.start <= offset && node_range.end >= offset {
 5389                // If it contains offset, check for task
 5390                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5391                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5392                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5393                }
 5394            }
 5395
 5396            if !cursor.goto_parent() {
 5397                break;
 5398            }
 5399        }
 5400        None
 5401    }
 5402
 5403    fn render_run_indicator(
 5404        &self,
 5405        _style: &EditorStyle,
 5406        is_active: bool,
 5407        row: DisplayRow,
 5408        cx: &mut Context<Self>,
 5409    ) -> IconButton {
 5410        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5411            .shape(ui::IconButtonShape::Square)
 5412            .icon_size(IconSize::XSmall)
 5413            .icon_color(Color::Muted)
 5414            .toggle_state(is_active)
 5415            .on_click(cx.listener(move |editor, _e, window, cx| {
 5416                window.focus(&editor.focus_handle(cx));
 5417                editor.toggle_code_actions(
 5418                    &ToggleCodeActions {
 5419                        deployed_from_indicator: Some(row),
 5420                    },
 5421                    window,
 5422                    cx,
 5423                );
 5424            }))
 5425    }
 5426
 5427    #[cfg(any(test, feature = "test-support"))]
 5428    pub fn context_menu_visible(&self) -> bool {
 5429        self.context_menu
 5430            .borrow()
 5431            .as_ref()
 5432            .map_or(false, |menu| menu.visible())
 5433    }
 5434
 5435    #[cfg(feature = "test-support")]
 5436    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5437        self.context_menu
 5438            .borrow()
 5439            .as_ref()
 5440            .map_or(false, |menu| match menu {
 5441                CodeContextMenu::Completions(menu) => {
 5442                    menu.entries.borrow().first().map_or(false, |entry| {
 5443                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5444                    })
 5445                }
 5446                CodeContextMenu::CodeActions(_) => false,
 5447            })
 5448    }
 5449
 5450    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5451        self.context_menu
 5452            .borrow()
 5453            .as_ref()
 5454            .map(|menu| menu.origin(cursor_position))
 5455    }
 5456
 5457    fn render_context_menu(
 5458        &self,
 5459        style: &EditorStyle,
 5460        max_height_in_lines: u32,
 5461        y_flipped: bool,
 5462        window: &mut Window,
 5463        cx: &mut Context<Editor>,
 5464    ) -> Option<AnyElement> {
 5465        self.context_menu.borrow().as_ref().and_then(|menu| {
 5466            if menu.visible() {
 5467                Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5468            } else {
 5469                None
 5470            }
 5471        })
 5472    }
 5473
 5474    fn render_context_menu_aside(
 5475        &self,
 5476        style: &EditorStyle,
 5477        max_size: Size<Pixels>,
 5478        cx: &mut Context<Editor>,
 5479    ) -> Option<AnyElement> {
 5480        self.context_menu.borrow().as_ref().and_then(|menu| {
 5481            if menu.visible() {
 5482                menu.render_aside(
 5483                    style,
 5484                    max_size,
 5485                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5486                    cx,
 5487                )
 5488            } else {
 5489                None
 5490            }
 5491        })
 5492    }
 5493
 5494    fn hide_context_menu(
 5495        &mut self,
 5496        window: &mut Window,
 5497        cx: &mut Context<Self>,
 5498    ) -> Option<CodeContextMenu> {
 5499        cx.notify();
 5500        self.completion_tasks.clear();
 5501        let context_menu = self.context_menu.borrow_mut().take();
 5502        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5503            self.update_visible_inline_completion(window, cx);
 5504        }
 5505        context_menu
 5506    }
 5507
 5508    fn show_snippet_choices(
 5509        &mut self,
 5510        choices: &Vec<String>,
 5511        selection: Range<Anchor>,
 5512        cx: &mut Context<Self>,
 5513    ) {
 5514        if selection.start.buffer_id.is_none() {
 5515            return;
 5516        }
 5517        let buffer_id = selection.start.buffer_id.unwrap();
 5518        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5519        let id = post_inc(&mut self.next_completion_id);
 5520
 5521        if let Some(buffer) = buffer {
 5522            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5523                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5524            ));
 5525        }
 5526    }
 5527
 5528    pub fn insert_snippet(
 5529        &mut self,
 5530        insertion_ranges: &[Range<usize>],
 5531        snippet: Snippet,
 5532        window: &mut Window,
 5533        cx: &mut Context<Self>,
 5534    ) -> Result<()> {
 5535        struct Tabstop<T> {
 5536            is_end_tabstop: bool,
 5537            ranges: Vec<Range<T>>,
 5538            choices: Option<Vec<String>>,
 5539        }
 5540
 5541        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5542            let snippet_text: Arc<str> = snippet.text.clone().into();
 5543            buffer.edit(
 5544                insertion_ranges
 5545                    .iter()
 5546                    .cloned()
 5547                    .map(|range| (range, snippet_text.clone())),
 5548                Some(AutoindentMode::EachLine),
 5549                cx,
 5550            );
 5551
 5552            let snapshot = &*buffer.read(cx);
 5553            let snippet = &snippet;
 5554            snippet
 5555                .tabstops
 5556                .iter()
 5557                .map(|tabstop| {
 5558                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5559                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5560                    });
 5561                    let mut tabstop_ranges = tabstop
 5562                        .ranges
 5563                        .iter()
 5564                        .flat_map(|tabstop_range| {
 5565                            let mut delta = 0_isize;
 5566                            insertion_ranges.iter().map(move |insertion_range| {
 5567                                let insertion_start = insertion_range.start as isize + delta;
 5568                                delta +=
 5569                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5570
 5571                                let start = ((insertion_start + tabstop_range.start) as usize)
 5572                                    .min(snapshot.len());
 5573                                let end = ((insertion_start + tabstop_range.end) as usize)
 5574                                    .min(snapshot.len());
 5575                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5576                            })
 5577                        })
 5578                        .collect::<Vec<_>>();
 5579                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5580
 5581                    Tabstop {
 5582                        is_end_tabstop,
 5583                        ranges: tabstop_ranges,
 5584                        choices: tabstop.choices.clone(),
 5585                    }
 5586                })
 5587                .collect::<Vec<_>>()
 5588        });
 5589        if let Some(tabstop) = tabstops.first() {
 5590            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5591                s.select_ranges(tabstop.ranges.iter().cloned());
 5592            });
 5593
 5594            if let Some(choices) = &tabstop.choices {
 5595                if let Some(selection) = tabstop.ranges.first() {
 5596                    self.show_snippet_choices(choices, selection.clone(), cx)
 5597                }
 5598            }
 5599
 5600            // If we're already at the last tabstop and it's at the end of the snippet,
 5601            // we're done, we don't need to keep the state around.
 5602            if !tabstop.is_end_tabstop {
 5603                let choices = tabstops
 5604                    .iter()
 5605                    .map(|tabstop| tabstop.choices.clone())
 5606                    .collect();
 5607
 5608                let ranges = tabstops
 5609                    .into_iter()
 5610                    .map(|tabstop| tabstop.ranges)
 5611                    .collect::<Vec<_>>();
 5612
 5613                self.snippet_stack.push(SnippetState {
 5614                    active_index: 0,
 5615                    ranges,
 5616                    choices,
 5617                });
 5618            }
 5619
 5620            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5621            if self.autoclose_regions.is_empty() {
 5622                let snapshot = self.buffer.read(cx).snapshot(cx);
 5623                for selection in &mut self.selections.all::<Point>(cx) {
 5624                    let selection_head = selection.head();
 5625                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5626                        continue;
 5627                    };
 5628
 5629                    let mut bracket_pair = None;
 5630                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5631                    let prev_chars = snapshot
 5632                        .reversed_chars_at(selection_head)
 5633                        .collect::<String>();
 5634                    for (pair, enabled) in scope.brackets() {
 5635                        if enabled
 5636                            && pair.close
 5637                            && prev_chars.starts_with(pair.start.as_str())
 5638                            && next_chars.starts_with(pair.end.as_str())
 5639                        {
 5640                            bracket_pair = Some(pair.clone());
 5641                            break;
 5642                        }
 5643                    }
 5644                    if let Some(pair) = bracket_pair {
 5645                        let start = snapshot.anchor_after(selection_head);
 5646                        let end = snapshot.anchor_after(selection_head);
 5647                        self.autoclose_regions.push(AutocloseRegion {
 5648                            selection_id: selection.id,
 5649                            range: start..end,
 5650                            pair,
 5651                        });
 5652                    }
 5653                }
 5654            }
 5655        }
 5656        Ok(())
 5657    }
 5658
 5659    pub fn move_to_next_snippet_tabstop(
 5660        &mut self,
 5661        window: &mut Window,
 5662        cx: &mut Context<Self>,
 5663    ) -> bool {
 5664        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5665    }
 5666
 5667    pub fn move_to_prev_snippet_tabstop(
 5668        &mut self,
 5669        window: &mut Window,
 5670        cx: &mut Context<Self>,
 5671    ) -> bool {
 5672        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5673    }
 5674
 5675    pub fn move_to_snippet_tabstop(
 5676        &mut self,
 5677        bias: Bias,
 5678        window: &mut Window,
 5679        cx: &mut Context<Self>,
 5680    ) -> bool {
 5681        if let Some(mut snippet) = self.snippet_stack.pop() {
 5682            match bias {
 5683                Bias::Left => {
 5684                    if snippet.active_index > 0 {
 5685                        snippet.active_index -= 1;
 5686                    } else {
 5687                        self.snippet_stack.push(snippet);
 5688                        return false;
 5689                    }
 5690                }
 5691                Bias::Right => {
 5692                    if snippet.active_index + 1 < snippet.ranges.len() {
 5693                        snippet.active_index += 1;
 5694                    } else {
 5695                        self.snippet_stack.push(snippet);
 5696                        return false;
 5697                    }
 5698                }
 5699            }
 5700            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5701                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5702                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5703                });
 5704
 5705                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5706                    if let Some(selection) = current_ranges.first() {
 5707                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5708                    }
 5709                }
 5710
 5711                // If snippet state is not at the last tabstop, push it back on the stack
 5712                if snippet.active_index + 1 < snippet.ranges.len() {
 5713                    self.snippet_stack.push(snippet);
 5714                }
 5715                return true;
 5716            }
 5717        }
 5718
 5719        false
 5720    }
 5721
 5722    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5723        self.transact(window, cx, |this, window, cx| {
 5724            this.select_all(&SelectAll, window, cx);
 5725            this.insert("", window, cx);
 5726        });
 5727    }
 5728
 5729    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 5730        self.transact(window, cx, |this, window, cx| {
 5731            this.select_autoclose_pair(window, cx);
 5732            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5733            if !this.linked_edit_ranges.is_empty() {
 5734                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5735                let snapshot = this.buffer.read(cx).snapshot(cx);
 5736
 5737                for selection in selections.iter() {
 5738                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5739                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5740                    if selection_start.buffer_id != selection_end.buffer_id {
 5741                        continue;
 5742                    }
 5743                    if let Some(ranges) =
 5744                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5745                    {
 5746                        for (buffer, entries) in ranges {
 5747                            linked_ranges.entry(buffer).or_default().extend(entries);
 5748                        }
 5749                    }
 5750                }
 5751            }
 5752
 5753            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5754            if !this.selections.line_mode {
 5755                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5756                for selection in &mut selections {
 5757                    if selection.is_empty() {
 5758                        let old_head = selection.head();
 5759                        let mut new_head =
 5760                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5761                                .to_point(&display_map);
 5762                        if let Some((buffer, line_buffer_range)) = display_map
 5763                            .buffer_snapshot
 5764                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5765                        {
 5766                            let indent_size =
 5767                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5768                            let indent_len = match indent_size.kind {
 5769                                IndentKind::Space => {
 5770                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5771                                }
 5772                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5773                            };
 5774                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5775                                let indent_len = indent_len.get();
 5776                                new_head = cmp::min(
 5777                                    new_head,
 5778                                    MultiBufferPoint::new(
 5779                                        old_head.row,
 5780                                        ((old_head.column - 1) / indent_len) * indent_len,
 5781                                    ),
 5782                                );
 5783                            }
 5784                        }
 5785
 5786                        selection.set_head(new_head, SelectionGoal::None);
 5787                    }
 5788                }
 5789            }
 5790
 5791            this.signature_help_state.set_backspace_pressed(true);
 5792            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5793                s.select(selections)
 5794            });
 5795            this.insert("", window, cx);
 5796            let empty_str: Arc<str> = Arc::from("");
 5797            for (buffer, edits) in linked_ranges {
 5798                let snapshot = buffer.read(cx).snapshot();
 5799                use text::ToPoint as TP;
 5800
 5801                let edits = edits
 5802                    .into_iter()
 5803                    .map(|range| {
 5804                        let end_point = TP::to_point(&range.end, &snapshot);
 5805                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5806
 5807                        if end_point == start_point {
 5808                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5809                                .saturating_sub(1);
 5810                            start_point =
 5811                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5812                        };
 5813
 5814                        (start_point..end_point, empty_str.clone())
 5815                    })
 5816                    .sorted_by_key(|(range, _)| range.start)
 5817                    .collect::<Vec<_>>();
 5818                buffer.update(cx, |this, cx| {
 5819                    this.edit(edits, None, cx);
 5820                })
 5821            }
 5822            this.refresh_inline_completion(true, false, window, cx);
 5823            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 5824        });
 5825    }
 5826
 5827    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 5828        self.transact(window, cx, |this, window, cx| {
 5829            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5830                let line_mode = s.line_mode;
 5831                s.move_with(|map, selection| {
 5832                    if selection.is_empty() && !line_mode {
 5833                        let cursor = movement::right(map, selection.head());
 5834                        selection.end = cursor;
 5835                        selection.reversed = true;
 5836                        selection.goal = SelectionGoal::None;
 5837                    }
 5838                })
 5839            });
 5840            this.insert("", window, cx);
 5841            this.refresh_inline_completion(true, false, window, cx);
 5842        });
 5843    }
 5844
 5845    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 5846        if self.move_to_prev_snippet_tabstop(window, cx) {
 5847            return;
 5848        }
 5849
 5850        self.outdent(&Outdent, window, cx);
 5851    }
 5852
 5853    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 5854        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 5855            return;
 5856        }
 5857
 5858        let mut selections = self.selections.all_adjusted(cx);
 5859        let buffer = self.buffer.read(cx);
 5860        let snapshot = buffer.snapshot(cx);
 5861        let rows_iter = selections.iter().map(|s| s.head().row);
 5862        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5863
 5864        let mut edits = Vec::new();
 5865        let mut prev_edited_row = 0;
 5866        let mut row_delta = 0;
 5867        for selection in &mut selections {
 5868            if selection.start.row != prev_edited_row {
 5869                row_delta = 0;
 5870            }
 5871            prev_edited_row = selection.end.row;
 5872
 5873            // If the selection is non-empty, then increase the indentation of the selected lines.
 5874            if !selection.is_empty() {
 5875                row_delta =
 5876                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5877                continue;
 5878            }
 5879
 5880            // If the selection is empty and the cursor is in the leading whitespace before the
 5881            // suggested indentation, then auto-indent the line.
 5882            let cursor = selection.head();
 5883            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5884            if let Some(suggested_indent) =
 5885                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5886            {
 5887                if cursor.column < suggested_indent.len
 5888                    && cursor.column <= current_indent.len
 5889                    && current_indent.len <= suggested_indent.len
 5890                {
 5891                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5892                    selection.end = selection.start;
 5893                    if row_delta == 0 {
 5894                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5895                            cursor.row,
 5896                            current_indent,
 5897                            suggested_indent,
 5898                        ));
 5899                        row_delta = suggested_indent.len - current_indent.len;
 5900                    }
 5901                    continue;
 5902                }
 5903            }
 5904
 5905            // Otherwise, insert a hard or soft tab.
 5906            let settings = buffer.settings_at(cursor, cx);
 5907            let tab_size = if settings.hard_tabs {
 5908                IndentSize::tab()
 5909            } else {
 5910                let tab_size = settings.tab_size.get();
 5911                let char_column = snapshot
 5912                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5913                    .flat_map(str::chars)
 5914                    .count()
 5915                    + row_delta as usize;
 5916                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5917                IndentSize::spaces(chars_to_next_tab_stop)
 5918            };
 5919            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5920            selection.end = selection.start;
 5921            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5922            row_delta += tab_size.len;
 5923        }
 5924
 5925        self.transact(window, cx, |this, window, cx| {
 5926            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5927            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5928                s.select(selections)
 5929            });
 5930            this.refresh_inline_completion(true, false, window, cx);
 5931        });
 5932    }
 5933
 5934    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 5935        if self.read_only(cx) {
 5936            return;
 5937        }
 5938        let mut selections = self.selections.all::<Point>(cx);
 5939        let mut prev_edited_row = 0;
 5940        let mut row_delta = 0;
 5941        let mut edits = Vec::new();
 5942        let buffer = self.buffer.read(cx);
 5943        let snapshot = buffer.snapshot(cx);
 5944        for selection in &mut selections {
 5945            if selection.start.row != prev_edited_row {
 5946                row_delta = 0;
 5947            }
 5948            prev_edited_row = selection.end.row;
 5949
 5950            row_delta =
 5951                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5952        }
 5953
 5954        self.transact(window, cx, |this, window, cx| {
 5955            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5956            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5957                s.select(selections)
 5958            });
 5959        });
 5960    }
 5961
 5962    fn indent_selection(
 5963        buffer: &MultiBuffer,
 5964        snapshot: &MultiBufferSnapshot,
 5965        selection: &mut Selection<Point>,
 5966        edits: &mut Vec<(Range<Point>, String)>,
 5967        delta_for_start_row: u32,
 5968        cx: &App,
 5969    ) -> u32 {
 5970        let settings = buffer.settings_at(selection.start, cx);
 5971        let tab_size = settings.tab_size.get();
 5972        let indent_kind = if settings.hard_tabs {
 5973            IndentKind::Tab
 5974        } else {
 5975            IndentKind::Space
 5976        };
 5977        let mut start_row = selection.start.row;
 5978        let mut end_row = selection.end.row + 1;
 5979
 5980        // If a selection ends at the beginning of a line, don't indent
 5981        // that last line.
 5982        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5983            end_row -= 1;
 5984        }
 5985
 5986        // Avoid re-indenting a row that has already been indented by a
 5987        // previous selection, but still update this selection's column
 5988        // to reflect that indentation.
 5989        if delta_for_start_row > 0 {
 5990            start_row += 1;
 5991            selection.start.column += delta_for_start_row;
 5992            if selection.end.row == selection.start.row {
 5993                selection.end.column += delta_for_start_row;
 5994            }
 5995        }
 5996
 5997        let mut delta_for_end_row = 0;
 5998        let has_multiple_rows = start_row + 1 != end_row;
 5999        for row in start_row..end_row {
 6000            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6001            let indent_delta = match (current_indent.kind, indent_kind) {
 6002                (IndentKind::Space, IndentKind::Space) => {
 6003                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6004                    IndentSize::spaces(columns_to_next_tab_stop)
 6005                }
 6006                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6007                (_, IndentKind::Tab) => IndentSize::tab(),
 6008            };
 6009
 6010            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6011                0
 6012            } else {
 6013                selection.start.column
 6014            };
 6015            let row_start = Point::new(row, start);
 6016            edits.push((
 6017                row_start..row_start,
 6018                indent_delta.chars().collect::<String>(),
 6019            ));
 6020
 6021            // Update this selection's endpoints to reflect the indentation.
 6022            if row == selection.start.row {
 6023                selection.start.column += indent_delta.len;
 6024            }
 6025            if row == selection.end.row {
 6026                selection.end.column += indent_delta.len;
 6027                delta_for_end_row = indent_delta.len;
 6028            }
 6029        }
 6030
 6031        if selection.start.row == selection.end.row {
 6032            delta_for_start_row + delta_for_end_row
 6033        } else {
 6034            delta_for_end_row
 6035        }
 6036    }
 6037
 6038    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6039        if self.read_only(cx) {
 6040            return;
 6041        }
 6042        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6043        let selections = self.selections.all::<Point>(cx);
 6044        let mut deletion_ranges = Vec::new();
 6045        let mut last_outdent = None;
 6046        {
 6047            let buffer = self.buffer.read(cx);
 6048            let snapshot = buffer.snapshot(cx);
 6049            for selection in &selections {
 6050                let settings = buffer.settings_at(selection.start, cx);
 6051                let tab_size = settings.tab_size.get();
 6052                let mut rows = selection.spanned_rows(false, &display_map);
 6053
 6054                // Avoid re-outdenting a row that has already been outdented by a
 6055                // previous selection.
 6056                if let Some(last_row) = last_outdent {
 6057                    if last_row == rows.start {
 6058                        rows.start = rows.start.next_row();
 6059                    }
 6060                }
 6061                let has_multiple_rows = rows.len() > 1;
 6062                for row in rows.iter_rows() {
 6063                    let indent_size = snapshot.indent_size_for_line(row);
 6064                    if indent_size.len > 0 {
 6065                        let deletion_len = match indent_size.kind {
 6066                            IndentKind::Space => {
 6067                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6068                                if columns_to_prev_tab_stop == 0 {
 6069                                    tab_size
 6070                                } else {
 6071                                    columns_to_prev_tab_stop
 6072                                }
 6073                            }
 6074                            IndentKind::Tab => 1,
 6075                        };
 6076                        let start = if has_multiple_rows
 6077                            || deletion_len > selection.start.column
 6078                            || indent_size.len < selection.start.column
 6079                        {
 6080                            0
 6081                        } else {
 6082                            selection.start.column - deletion_len
 6083                        };
 6084                        deletion_ranges.push(
 6085                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6086                        );
 6087                        last_outdent = Some(row);
 6088                    }
 6089                }
 6090            }
 6091        }
 6092
 6093        self.transact(window, cx, |this, window, cx| {
 6094            this.buffer.update(cx, |buffer, cx| {
 6095                let empty_str: Arc<str> = Arc::default();
 6096                buffer.edit(
 6097                    deletion_ranges
 6098                        .into_iter()
 6099                        .map(|range| (range, empty_str.clone())),
 6100                    None,
 6101                    cx,
 6102                );
 6103            });
 6104            let selections = this.selections.all::<usize>(cx);
 6105            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6106                s.select(selections)
 6107            });
 6108        });
 6109    }
 6110
 6111    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6112        if self.read_only(cx) {
 6113            return;
 6114        }
 6115        let selections = self
 6116            .selections
 6117            .all::<usize>(cx)
 6118            .into_iter()
 6119            .map(|s| s.range());
 6120
 6121        self.transact(window, cx, |this, window, cx| {
 6122            this.buffer.update(cx, |buffer, cx| {
 6123                buffer.autoindent_ranges(selections, cx);
 6124            });
 6125            let selections = this.selections.all::<usize>(cx);
 6126            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6127                s.select(selections)
 6128            });
 6129        });
 6130    }
 6131
 6132    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6133        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6134        let selections = self.selections.all::<Point>(cx);
 6135
 6136        let mut new_cursors = Vec::new();
 6137        let mut edit_ranges = Vec::new();
 6138        let mut selections = selections.iter().peekable();
 6139        while let Some(selection) = selections.next() {
 6140            let mut rows = selection.spanned_rows(false, &display_map);
 6141            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6142
 6143            // Accumulate contiguous regions of rows that we want to delete.
 6144            while let Some(next_selection) = selections.peek() {
 6145                let next_rows = next_selection.spanned_rows(false, &display_map);
 6146                if next_rows.start <= rows.end {
 6147                    rows.end = next_rows.end;
 6148                    selections.next().unwrap();
 6149                } else {
 6150                    break;
 6151                }
 6152            }
 6153
 6154            let buffer = &display_map.buffer_snapshot;
 6155            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6156            let edit_end;
 6157            let cursor_buffer_row;
 6158            if buffer.max_point().row >= rows.end.0 {
 6159                // If there's a line after the range, delete the \n from the end of the row range
 6160                // and position the cursor on the next line.
 6161                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6162                cursor_buffer_row = rows.end;
 6163            } else {
 6164                // If there isn't a line after the range, delete the \n from the line before the
 6165                // start of the row range and position the cursor there.
 6166                edit_start = edit_start.saturating_sub(1);
 6167                edit_end = buffer.len();
 6168                cursor_buffer_row = rows.start.previous_row();
 6169            }
 6170
 6171            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6172            *cursor.column_mut() =
 6173                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6174
 6175            new_cursors.push((
 6176                selection.id,
 6177                buffer.anchor_after(cursor.to_point(&display_map)),
 6178            ));
 6179            edit_ranges.push(edit_start..edit_end);
 6180        }
 6181
 6182        self.transact(window, cx, |this, window, cx| {
 6183            let buffer = this.buffer.update(cx, |buffer, cx| {
 6184                let empty_str: Arc<str> = Arc::default();
 6185                buffer.edit(
 6186                    edit_ranges
 6187                        .into_iter()
 6188                        .map(|range| (range, empty_str.clone())),
 6189                    None,
 6190                    cx,
 6191                );
 6192                buffer.snapshot(cx)
 6193            });
 6194            let new_selections = new_cursors
 6195                .into_iter()
 6196                .map(|(id, cursor)| {
 6197                    let cursor = cursor.to_point(&buffer);
 6198                    Selection {
 6199                        id,
 6200                        start: cursor,
 6201                        end: cursor,
 6202                        reversed: false,
 6203                        goal: SelectionGoal::None,
 6204                    }
 6205                })
 6206                .collect();
 6207
 6208            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6209                s.select(new_selections);
 6210            });
 6211        });
 6212    }
 6213
 6214    pub fn join_lines_impl(
 6215        &mut self,
 6216        insert_whitespace: bool,
 6217        window: &mut Window,
 6218        cx: &mut Context<Self>,
 6219    ) {
 6220        if self.read_only(cx) {
 6221            return;
 6222        }
 6223        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6224        for selection in self.selections.all::<Point>(cx) {
 6225            let start = MultiBufferRow(selection.start.row);
 6226            // Treat single line selections as if they include the next line. Otherwise this action
 6227            // would do nothing for single line selections individual cursors.
 6228            let end = if selection.start.row == selection.end.row {
 6229                MultiBufferRow(selection.start.row + 1)
 6230            } else {
 6231                MultiBufferRow(selection.end.row)
 6232            };
 6233
 6234            if let Some(last_row_range) = row_ranges.last_mut() {
 6235                if start <= last_row_range.end {
 6236                    last_row_range.end = end;
 6237                    continue;
 6238                }
 6239            }
 6240            row_ranges.push(start..end);
 6241        }
 6242
 6243        let snapshot = self.buffer.read(cx).snapshot(cx);
 6244        let mut cursor_positions = Vec::new();
 6245        for row_range in &row_ranges {
 6246            let anchor = snapshot.anchor_before(Point::new(
 6247                row_range.end.previous_row().0,
 6248                snapshot.line_len(row_range.end.previous_row()),
 6249            ));
 6250            cursor_positions.push(anchor..anchor);
 6251        }
 6252
 6253        self.transact(window, cx, |this, window, cx| {
 6254            for row_range in row_ranges.into_iter().rev() {
 6255                for row in row_range.iter_rows().rev() {
 6256                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6257                    let next_line_row = row.next_row();
 6258                    let indent = snapshot.indent_size_for_line(next_line_row);
 6259                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6260
 6261                    let replace =
 6262                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6263                            " "
 6264                        } else {
 6265                            ""
 6266                        };
 6267
 6268                    this.buffer.update(cx, |buffer, cx| {
 6269                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6270                    });
 6271                }
 6272            }
 6273
 6274            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6275                s.select_anchor_ranges(cursor_positions)
 6276            });
 6277        });
 6278    }
 6279
 6280    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6281        self.join_lines_impl(true, window, cx);
 6282    }
 6283
 6284    pub fn sort_lines_case_sensitive(
 6285        &mut self,
 6286        _: &SortLinesCaseSensitive,
 6287        window: &mut Window,
 6288        cx: &mut Context<Self>,
 6289    ) {
 6290        self.manipulate_lines(window, cx, |lines| lines.sort())
 6291    }
 6292
 6293    pub fn sort_lines_case_insensitive(
 6294        &mut self,
 6295        _: &SortLinesCaseInsensitive,
 6296        window: &mut Window,
 6297        cx: &mut Context<Self>,
 6298    ) {
 6299        self.manipulate_lines(window, cx, |lines| {
 6300            lines.sort_by_key(|line| line.to_lowercase())
 6301        })
 6302    }
 6303
 6304    pub fn unique_lines_case_insensitive(
 6305        &mut self,
 6306        _: &UniqueLinesCaseInsensitive,
 6307        window: &mut Window,
 6308        cx: &mut Context<Self>,
 6309    ) {
 6310        self.manipulate_lines(window, cx, |lines| {
 6311            let mut seen = HashSet::default();
 6312            lines.retain(|line| seen.insert(line.to_lowercase()));
 6313        })
 6314    }
 6315
 6316    pub fn unique_lines_case_sensitive(
 6317        &mut self,
 6318        _: &UniqueLinesCaseSensitive,
 6319        window: &mut Window,
 6320        cx: &mut Context<Self>,
 6321    ) {
 6322        self.manipulate_lines(window, cx, |lines| {
 6323            let mut seen = HashSet::default();
 6324            lines.retain(|line| seen.insert(*line));
 6325        })
 6326    }
 6327
 6328    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6329        let mut revert_changes = HashMap::default();
 6330        let snapshot = self.snapshot(window, cx);
 6331        for hunk in snapshot
 6332            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6333        {
 6334            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6335        }
 6336        if !revert_changes.is_empty() {
 6337            self.transact(window, cx, |editor, window, cx| {
 6338                editor.revert(revert_changes, window, cx);
 6339            });
 6340        }
 6341    }
 6342
 6343    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6344        let Some(project) = self.project.clone() else {
 6345            return;
 6346        };
 6347        self.reload(project, window, cx)
 6348            .detach_and_notify_err(window, cx);
 6349    }
 6350
 6351    pub fn revert_selected_hunks(
 6352        &mut self,
 6353        _: &RevertSelectedHunks,
 6354        window: &mut Window,
 6355        cx: &mut Context<Self>,
 6356    ) {
 6357        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6358        self.revert_hunks_in_ranges(selections, window, cx);
 6359    }
 6360
 6361    fn revert_hunks_in_ranges(
 6362        &mut self,
 6363        ranges: impl Iterator<Item = Range<Point>>,
 6364        window: &mut Window,
 6365        cx: &mut Context<Editor>,
 6366    ) {
 6367        let mut revert_changes = HashMap::default();
 6368        let snapshot = self.snapshot(window, cx);
 6369        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6370            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6371        }
 6372        if !revert_changes.is_empty() {
 6373            self.transact(window, cx, |editor, window, cx| {
 6374                editor.revert(revert_changes, window, cx);
 6375            });
 6376        }
 6377    }
 6378
 6379    pub fn open_active_item_in_terminal(
 6380        &mut self,
 6381        _: &OpenInTerminal,
 6382        window: &mut Window,
 6383        cx: &mut Context<Self>,
 6384    ) {
 6385        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6386            let project_path = buffer.read(cx).project_path(cx)?;
 6387            let project = self.project.as_ref()?.read(cx);
 6388            let entry = project.entry_for_path(&project_path, cx)?;
 6389            let parent = match &entry.canonical_path {
 6390                Some(canonical_path) => canonical_path.to_path_buf(),
 6391                None => project.absolute_path(&project_path, cx)?,
 6392            }
 6393            .parent()?
 6394            .to_path_buf();
 6395            Some(parent)
 6396        }) {
 6397            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6398        }
 6399    }
 6400
 6401    pub fn prepare_revert_change(
 6402        &self,
 6403        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6404        hunk: &MultiBufferDiffHunk,
 6405        cx: &mut App,
 6406    ) -> Option<()> {
 6407        let buffer = self.buffer.read(cx);
 6408        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6409        let buffer = buffer.buffer(hunk.buffer_id)?;
 6410        let buffer = buffer.read(cx);
 6411        let original_text = change_set
 6412            .read(cx)
 6413            .base_text
 6414            .as_ref()?
 6415            .as_rope()
 6416            .slice(hunk.diff_base_byte_range.clone());
 6417        let buffer_snapshot = buffer.snapshot();
 6418        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6419        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6420            probe
 6421                .0
 6422                .start
 6423                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6424                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6425        }) {
 6426            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6427            Some(())
 6428        } else {
 6429            None
 6430        }
 6431    }
 6432
 6433    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6434        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6435    }
 6436
 6437    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6438        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6439    }
 6440
 6441    fn manipulate_lines<Fn>(
 6442        &mut self,
 6443        window: &mut Window,
 6444        cx: &mut Context<Self>,
 6445        mut callback: Fn,
 6446    ) where
 6447        Fn: FnMut(&mut Vec<&str>),
 6448    {
 6449        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6450        let buffer = self.buffer.read(cx).snapshot(cx);
 6451
 6452        let mut edits = Vec::new();
 6453
 6454        let selections = self.selections.all::<Point>(cx);
 6455        let mut selections = selections.iter().peekable();
 6456        let mut contiguous_row_selections = Vec::new();
 6457        let mut new_selections = Vec::new();
 6458        let mut added_lines = 0;
 6459        let mut removed_lines = 0;
 6460
 6461        while let Some(selection) = selections.next() {
 6462            let (start_row, end_row) = consume_contiguous_rows(
 6463                &mut contiguous_row_selections,
 6464                selection,
 6465                &display_map,
 6466                &mut selections,
 6467            );
 6468
 6469            let start_point = Point::new(start_row.0, 0);
 6470            let end_point = Point::new(
 6471                end_row.previous_row().0,
 6472                buffer.line_len(end_row.previous_row()),
 6473            );
 6474            let text = buffer
 6475                .text_for_range(start_point..end_point)
 6476                .collect::<String>();
 6477
 6478            let mut lines = text.split('\n').collect_vec();
 6479
 6480            let lines_before = lines.len();
 6481            callback(&mut lines);
 6482            let lines_after = lines.len();
 6483
 6484            edits.push((start_point..end_point, lines.join("\n")));
 6485
 6486            // Selections must change based on added and removed line count
 6487            let start_row =
 6488                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6489            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6490            new_selections.push(Selection {
 6491                id: selection.id,
 6492                start: start_row,
 6493                end: end_row,
 6494                goal: SelectionGoal::None,
 6495                reversed: selection.reversed,
 6496            });
 6497
 6498            if lines_after > lines_before {
 6499                added_lines += lines_after - lines_before;
 6500            } else if lines_before > lines_after {
 6501                removed_lines += lines_before - lines_after;
 6502            }
 6503        }
 6504
 6505        self.transact(window, cx, |this, window, cx| {
 6506            let buffer = this.buffer.update(cx, |buffer, cx| {
 6507                buffer.edit(edits, None, cx);
 6508                buffer.snapshot(cx)
 6509            });
 6510
 6511            // Recalculate offsets on newly edited buffer
 6512            let new_selections = new_selections
 6513                .iter()
 6514                .map(|s| {
 6515                    let start_point = Point::new(s.start.0, 0);
 6516                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6517                    Selection {
 6518                        id: s.id,
 6519                        start: buffer.point_to_offset(start_point),
 6520                        end: buffer.point_to_offset(end_point),
 6521                        goal: s.goal,
 6522                        reversed: s.reversed,
 6523                    }
 6524                })
 6525                .collect();
 6526
 6527            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6528                s.select(new_selections);
 6529            });
 6530
 6531            this.request_autoscroll(Autoscroll::fit(), cx);
 6532        });
 6533    }
 6534
 6535    pub fn convert_to_upper_case(
 6536        &mut self,
 6537        _: &ConvertToUpperCase,
 6538        window: &mut Window,
 6539        cx: &mut Context<Self>,
 6540    ) {
 6541        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6542    }
 6543
 6544    pub fn convert_to_lower_case(
 6545        &mut self,
 6546        _: &ConvertToLowerCase,
 6547        window: &mut Window,
 6548        cx: &mut Context<Self>,
 6549    ) {
 6550        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6551    }
 6552
 6553    pub fn convert_to_title_case(
 6554        &mut self,
 6555        _: &ConvertToTitleCase,
 6556        window: &mut Window,
 6557        cx: &mut Context<Self>,
 6558    ) {
 6559        self.manipulate_text(window, cx, |text| {
 6560            text.split('\n')
 6561                .map(|line| line.to_case(Case::Title))
 6562                .join("\n")
 6563        })
 6564    }
 6565
 6566    pub fn convert_to_snake_case(
 6567        &mut self,
 6568        _: &ConvertToSnakeCase,
 6569        window: &mut Window,
 6570        cx: &mut Context<Self>,
 6571    ) {
 6572        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6573    }
 6574
 6575    pub fn convert_to_kebab_case(
 6576        &mut self,
 6577        _: &ConvertToKebabCase,
 6578        window: &mut Window,
 6579        cx: &mut Context<Self>,
 6580    ) {
 6581        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6582    }
 6583
 6584    pub fn convert_to_upper_camel_case(
 6585        &mut self,
 6586        _: &ConvertToUpperCamelCase,
 6587        window: &mut Window,
 6588        cx: &mut Context<Self>,
 6589    ) {
 6590        self.manipulate_text(window, cx, |text| {
 6591            text.split('\n')
 6592                .map(|line| line.to_case(Case::UpperCamel))
 6593                .join("\n")
 6594        })
 6595    }
 6596
 6597    pub fn convert_to_lower_camel_case(
 6598        &mut self,
 6599        _: &ConvertToLowerCamelCase,
 6600        window: &mut Window,
 6601        cx: &mut Context<Self>,
 6602    ) {
 6603        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6604    }
 6605
 6606    pub fn convert_to_opposite_case(
 6607        &mut self,
 6608        _: &ConvertToOppositeCase,
 6609        window: &mut Window,
 6610        cx: &mut Context<Self>,
 6611    ) {
 6612        self.manipulate_text(window, cx, |text| {
 6613            text.chars()
 6614                .fold(String::with_capacity(text.len()), |mut t, c| {
 6615                    if c.is_uppercase() {
 6616                        t.extend(c.to_lowercase());
 6617                    } else {
 6618                        t.extend(c.to_uppercase());
 6619                    }
 6620                    t
 6621                })
 6622        })
 6623    }
 6624
 6625    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6626    where
 6627        Fn: FnMut(&str) -> String,
 6628    {
 6629        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6630        let buffer = self.buffer.read(cx).snapshot(cx);
 6631
 6632        let mut new_selections = Vec::new();
 6633        let mut edits = Vec::new();
 6634        let mut selection_adjustment = 0i32;
 6635
 6636        for selection in self.selections.all::<usize>(cx) {
 6637            let selection_is_empty = selection.is_empty();
 6638
 6639            let (start, end) = if selection_is_empty {
 6640                let word_range = movement::surrounding_word(
 6641                    &display_map,
 6642                    selection.start.to_display_point(&display_map),
 6643                );
 6644                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6645                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6646                (start, end)
 6647            } else {
 6648                (selection.start, selection.end)
 6649            };
 6650
 6651            let text = buffer.text_for_range(start..end).collect::<String>();
 6652            let old_length = text.len() as i32;
 6653            let text = callback(&text);
 6654
 6655            new_selections.push(Selection {
 6656                start: (start as i32 - selection_adjustment) as usize,
 6657                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6658                goal: SelectionGoal::None,
 6659                ..selection
 6660            });
 6661
 6662            selection_adjustment += old_length - text.len() as i32;
 6663
 6664            edits.push((start..end, text));
 6665        }
 6666
 6667        self.transact(window, cx, |this, window, cx| {
 6668            this.buffer.update(cx, |buffer, cx| {
 6669                buffer.edit(edits, None, cx);
 6670            });
 6671
 6672            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6673                s.select(new_selections);
 6674            });
 6675
 6676            this.request_autoscroll(Autoscroll::fit(), cx);
 6677        });
 6678    }
 6679
 6680    pub fn duplicate(
 6681        &mut self,
 6682        upwards: bool,
 6683        whole_lines: bool,
 6684        window: &mut Window,
 6685        cx: &mut Context<Self>,
 6686    ) {
 6687        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6688        let buffer = &display_map.buffer_snapshot;
 6689        let selections = self.selections.all::<Point>(cx);
 6690
 6691        let mut edits = Vec::new();
 6692        let mut selections_iter = selections.iter().peekable();
 6693        while let Some(selection) = selections_iter.next() {
 6694            let mut rows = selection.spanned_rows(false, &display_map);
 6695            // duplicate line-wise
 6696            if whole_lines || selection.start == selection.end {
 6697                // Avoid duplicating the same lines twice.
 6698                while let Some(next_selection) = selections_iter.peek() {
 6699                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6700                    if next_rows.start < rows.end {
 6701                        rows.end = next_rows.end;
 6702                        selections_iter.next().unwrap();
 6703                    } else {
 6704                        break;
 6705                    }
 6706                }
 6707
 6708                // Copy the text from the selected row region and splice it either at the start
 6709                // or end of the region.
 6710                let start = Point::new(rows.start.0, 0);
 6711                let end = Point::new(
 6712                    rows.end.previous_row().0,
 6713                    buffer.line_len(rows.end.previous_row()),
 6714                );
 6715                let text = buffer
 6716                    .text_for_range(start..end)
 6717                    .chain(Some("\n"))
 6718                    .collect::<String>();
 6719                let insert_location = if upwards {
 6720                    Point::new(rows.end.0, 0)
 6721                } else {
 6722                    start
 6723                };
 6724                edits.push((insert_location..insert_location, text));
 6725            } else {
 6726                // duplicate character-wise
 6727                let start = selection.start;
 6728                let end = selection.end;
 6729                let text = buffer.text_for_range(start..end).collect::<String>();
 6730                edits.push((selection.end..selection.end, text));
 6731            }
 6732        }
 6733
 6734        self.transact(window, cx, |this, _, cx| {
 6735            this.buffer.update(cx, |buffer, cx| {
 6736                buffer.edit(edits, None, cx);
 6737            });
 6738
 6739            this.request_autoscroll(Autoscroll::fit(), cx);
 6740        });
 6741    }
 6742
 6743    pub fn duplicate_line_up(
 6744        &mut self,
 6745        _: &DuplicateLineUp,
 6746        window: &mut Window,
 6747        cx: &mut Context<Self>,
 6748    ) {
 6749        self.duplicate(true, true, window, cx);
 6750    }
 6751
 6752    pub fn duplicate_line_down(
 6753        &mut self,
 6754        _: &DuplicateLineDown,
 6755        window: &mut Window,
 6756        cx: &mut Context<Self>,
 6757    ) {
 6758        self.duplicate(false, true, window, cx);
 6759    }
 6760
 6761    pub fn duplicate_selection(
 6762        &mut self,
 6763        _: &DuplicateSelection,
 6764        window: &mut Window,
 6765        cx: &mut Context<Self>,
 6766    ) {
 6767        self.duplicate(false, false, window, cx);
 6768    }
 6769
 6770    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 6771        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6772        let buffer = self.buffer.read(cx).snapshot(cx);
 6773
 6774        let mut edits = Vec::new();
 6775        let mut unfold_ranges = Vec::new();
 6776        let mut refold_creases = Vec::new();
 6777
 6778        let selections = self.selections.all::<Point>(cx);
 6779        let mut selections = selections.iter().peekable();
 6780        let mut contiguous_row_selections = Vec::new();
 6781        let mut new_selections = Vec::new();
 6782
 6783        while let Some(selection) = selections.next() {
 6784            // Find all the selections that span a contiguous row range
 6785            let (start_row, end_row) = consume_contiguous_rows(
 6786                &mut contiguous_row_selections,
 6787                selection,
 6788                &display_map,
 6789                &mut selections,
 6790            );
 6791
 6792            // Move the text spanned by the row range to be before the line preceding the row range
 6793            if start_row.0 > 0 {
 6794                let range_to_move = Point::new(
 6795                    start_row.previous_row().0,
 6796                    buffer.line_len(start_row.previous_row()),
 6797                )
 6798                    ..Point::new(
 6799                        end_row.previous_row().0,
 6800                        buffer.line_len(end_row.previous_row()),
 6801                    );
 6802                let insertion_point = display_map
 6803                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6804                    .0;
 6805
 6806                // Don't move lines across excerpts
 6807                if buffer
 6808                    .excerpt_containing(insertion_point..range_to_move.end)
 6809                    .is_some()
 6810                {
 6811                    let text = buffer
 6812                        .text_for_range(range_to_move.clone())
 6813                        .flat_map(|s| s.chars())
 6814                        .skip(1)
 6815                        .chain(['\n'])
 6816                        .collect::<String>();
 6817
 6818                    edits.push((
 6819                        buffer.anchor_after(range_to_move.start)
 6820                            ..buffer.anchor_before(range_to_move.end),
 6821                        String::new(),
 6822                    ));
 6823                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6824                    edits.push((insertion_anchor..insertion_anchor, text));
 6825
 6826                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6827
 6828                    // Move selections up
 6829                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6830                        |mut selection| {
 6831                            selection.start.row -= row_delta;
 6832                            selection.end.row -= row_delta;
 6833                            selection
 6834                        },
 6835                    ));
 6836
 6837                    // Move folds up
 6838                    unfold_ranges.push(range_to_move.clone());
 6839                    for fold in display_map.folds_in_range(
 6840                        buffer.anchor_before(range_to_move.start)
 6841                            ..buffer.anchor_after(range_to_move.end),
 6842                    ) {
 6843                        let mut start = fold.range.start.to_point(&buffer);
 6844                        let mut end = fold.range.end.to_point(&buffer);
 6845                        start.row -= row_delta;
 6846                        end.row -= row_delta;
 6847                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6848                    }
 6849                }
 6850            }
 6851
 6852            // If we didn't move line(s), preserve the existing selections
 6853            new_selections.append(&mut contiguous_row_selections);
 6854        }
 6855
 6856        self.transact(window, cx, |this, window, cx| {
 6857            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6858            this.buffer.update(cx, |buffer, cx| {
 6859                for (range, text) in edits {
 6860                    buffer.edit([(range, text)], None, cx);
 6861                }
 6862            });
 6863            this.fold_creases(refold_creases, true, window, cx);
 6864            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6865                s.select(new_selections);
 6866            })
 6867        });
 6868    }
 6869
 6870    pub fn move_line_down(
 6871        &mut self,
 6872        _: &MoveLineDown,
 6873        window: &mut Window,
 6874        cx: &mut Context<Self>,
 6875    ) {
 6876        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6877        let buffer = self.buffer.read(cx).snapshot(cx);
 6878
 6879        let mut edits = Vec::new();
 6880        let mut unfold_ranges = Vec::new();
 6881        let mut refold_creases = Vec::new();
 6882
 6883        let selections = self.selections.all::<Point>(cx);
 6884        let mut selections = selections.iter().peekable();
 6885        let mut contiguous_row_selections = Vec::new();
 6886        let mut new_selections = Vec::new();
 6887
 6888        while let Some(selection) = selections.next() {
 6889            // Find all the selections that span a contiguous row range
 6890            let (start_row, end_row) = consume_contiguous_rows(
 6891                &mut contiguous_row_selections,
 6892                selection,
 6893                &display_map,
 6894                &mut selections,
 6895            );
 6896
 6897            // Move the text spanned by the row range to be after the last line of the row range
 6898            if end_row.0 <= buffer.max_point().row {
 6899                let range_to_move =
 6900                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6901                let insertion_point = display_map
 6902                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6903                    .0;
 6904
 6905                // Don't move lines across excerpt boundaries
 6906                if buffer
 6907                    .excerpt_containing(range_to_move.start..insertion_point)
 6908                    .is_some()
 6909                {
 6910                    let mut text = String::from("\n");
 6911                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6912                    text.pop(); // Drop trailing newline
 6913                    edits.push((
 6914                        buffer.anchor_after(range_to_move.start)
 6915                            ..buffer.anchor_before(range_to_move.end),
 6916                        String::new(),
 6917                    ));
 6918                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6919                    edits.push((insertion_anchor..insertion_anchor, text));
 6920
 6921                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6922
 6923                    // Move selections down
 6924                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6925                        |mut selection| {
 6926                            selection.start.row += row_delta;
 6927                            selection.end.row += row_delta;
 6928                            selection
 6929                        },
 6930                    ));
 6931
 6932                    // Move folds down
 6933                    unfold_ranges.push(range_to_move.clone());
 6934                    for fold in display_map.folds_in_range(
 6935                        buffer.anchor_before(range_to_move.start)
 6936                            ..buffer.anchor_after(range_to_move.end),
 6937                    ) {
 6938                        let mut start = fold.range.start.to_point(&buffer);
 6939                        let mut end = fold.range.end.to_point(&buffer);
 6940                        start.row += row_delta;
 6941                        end.row += row_delta;
 6942                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6943                    }
 6944                }
 6945            }
 6946
 6947            // If we didn't move line(s), preserve the existing selections
 6948            new_selections.append(&mut contiguous_row_selections);
 6949        }
 6950
 6951        self.transact(window, cx, |this, window, cx| {
 6952            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6953            this.buffer.update(cx, |buffer, cx| {
 6954                for (range, text) in edits {
 6955                    buffer.edit([(range, text)], None, cx);
 6956                }
 6957            });
 6958            this.fold_creases(refold_creases, true, window, cx);
 6959            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6960                s.select(new_selections)
 6961            });
 6962        });
 6963    }
 6964
 6965    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 6966        let text_layout_details = &self.text_layout_details(window);
 6967        self.transact(window, cx, |this, window, cx| {
 6968            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6969                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6970                let line_mode = s.line_mode;
 6971                s.move_with(|display_map, selection| {
 6972                    if !selection.is_empty() || line_mode {
 6973                        return;
 6974                    }
 6975
 6976                    let mut head = selection.head();
 6977                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6978                    if head.column() == display_map.line_len(head.row()) {
 6979                        transpose_offset = display_map
 6980                            .buffer_snapshot
 6981                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6982                    }
 6983
 6984                    if transpose_offset == 0 {
 6985                        return;
 6986                    }
 6987
 6988                    *head.column_mut() += 1;
 6989                    head = display_map.clip_point(head, Bias::Right);
 6990                    let goal = SelectionGoal::HorizontalPosition(
 6991                        display_map
 6992                            .x_for_display_point(head, text_layout_details)
 6993                            .into(),
 6994                    );
 6995                    selection.collapse_to(head, goal);
 6996
 6997                    let transpose_start = display_map
 6998                        .buffer_snapshot
 6999                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7000                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7001                        let transpose_end = display_map
 7002                            .buffer_snapshot
 7003                            .clip_offset(transpose_offset + 1, Bias::Right);
 7004                        if let Some(ch) =
 7005                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7006                        {
 7007                            edits.push((transpose_start..transpose_offset, String::new()));
 7008                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7009                        }
 7010                    }
 7011                });
 7012                edits
 7013            });
 7014            this.buffer
 7015                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7016            let selections = this.selections.all::<usize>(cx);
 7017            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7018                s.select(selections);
 7019            });
 7020        });
 7021    }
 7022
 7023    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7024        self.rewrap_impl(IsVimMode::No, cx)
 7025    }
 7026
 7027    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7028        let buffer = self.buffer.read(cx).snapshot(cx);
 7029        let selections = self.selections.all::<Point>(cx);
 7030        let mut selections = selections.iter().peekable();
 7031
 7032        let mut edits = Vec::new();
 7033        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7034
 7035        while let Some(selection) = selections.next() {
 7036            let mut start_row = selection.start.row;
 7037            let mut end_row = selection.end.row;
 7038
 7039            // Skip selections that overlap with a range that has already been rewrapped.
 7040            let selection_range = start_row..end_row;
 7041            if rewrapped_row_ranges
 7042                .iter()
 7043                .any(|range| range.overlaps(&selection_range))
 7044            {
 7045                continue;
 7046            }
 7047
 7048            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7049
 7050            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7051                match language_scope.language_name().as_ref() {
 7052                    "Markdown" | "Plain Text" => {
 7053                        should_rewrap = true;
 7054                    }
 7055                    _ => {}
 7056                }
 7057            }
 7058
 7059            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7060
 7061            // Since not all lines in the selection may be at the same indent
 7062            // level, choose the indent size that is the most common between all
 7063            // of the lines.
 7064            //
 7065            // If there is a tie, we use the deepest indent.
 7066            let (indent_size, indent_end) = {
 7067                let mut indent_size_occurrences = HashMap::default();
 7068                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7069
 7070                for row in start_row..=end_row {
 7071                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7072                    rows_by_indent_size.entry(indent).or_default().push(row);
 7073                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7074                }
 7075
 7076                let indent_size = indent_size_occurrences
 7077                    .into_iter()
 7078                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7079                    .map(|(indent, _)| indent)
 7080                    .unwrap_or_default();
 7081                let row = rows_by_indent_size[&indent_size][0];
 7082                let indent_end = Point::new(row, indent_size.len);
 7083
 7084                (indent_size, indent_end)
 7085            };
 7086
 7087            let mut line_prefix = indent_size.chars().collect::<String>();
 7088
 7089            if let Some(comment_prefix) =
 7090                buffer
 7091                    .language_scope_at(selection.head())
 7092                    .and_then(|language| {
 7093                        language
 7094                            .line_comment_prefixes()
 7095                            .iter()
 7096                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7097                            .cloned()
 7098                    })
 7099            {
 7100                line_prefix.push_str(&comment_prefix);
 7101                should_rewrap = true;
 7102            }
 7103
 7104            if !should_rewrap {
 7105                continue;
 7106            }
 7107
 7108            if selection.is_empty() {
 7109                'expand_upwards: while start_row > 0 {
 7110                    let prev_row = start_row - 1;
 7111                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7112                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7113                    {
 7114                        start_row = prev_row;
 7115                    } else {
 7116                        break 'expand_upwards;
 7117                    }
 7118                }
 7119
 7120                'expand_downwards: while end_row < buffer.max_point().row {
 7121                    let next_row = end_row + 1;
 7122                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7123                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7124                    {
 7125                        end_row = next_row;
 7126                    } else {
 7127                        break 'expand_downwards;
 7128                    }
 7129                }
 7130            }
 7131
 7132            let start = Point::new(start_row, 0);
 7133            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7134            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7135            let Some(lines_without_prefixes) = selection_text
 7136                .lines()
 7137                .map(|line| {
 7138                    line.strip_prefix(&line_prefix)
 7139                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7140                        .ok_or_else(|| {
 7141                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7142                        })
 7143                })
 7144                .collect::<Result<Vec<_>, _>>()
 7145                .log_err()
 7146            else {
 7147                continue;
 7148            };
 7149
 7150            let wrap_column = buffer
 7151                .settings_at(Point::new(start_row, 0), cx)
 7152                .preferred_line_length as usize;
 7153            let wrapped_text = wrap_with_prefix(
 7154                line_prefix,
 7155                lines_without_prefixes.join(" "),
 7156                wrap_column,
 7157                tab_size,
 7158            );
 7159
 7160            // TODO: should always use char-based diff while still supporting cursor behavior that
 7161            // matches vim.
 7162            let diff = match is_vim_mode {
 7163                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7164                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7165            };
 7166            let mut offset = start.to_offset(&buffer);
 7167            let mut moved_since_edit = true;
 7168
 7169            for change in diff.iter_all_changes() {
 7170                let value = change.value();
 7171                match change.tag() {
 7172                    ChangeTag::Equal => {
 7173                        offset += value.len();
 7174                        moved_since_edit = true;
 7175                    }
 7176                    ChangeTag::Delete => {
 7177                        let start = buffer.anchor_after(offset);
 7178                        let end = buffer.anchor_before(offset + value.len());
 7179
 7180                        if moved_since_edit {
 7181                            edits.push((start..end, String::new()));
 7182                        } else {
 7183                            edits.last_mut().unwrap().0.end = end;
 7184                        }
 7185
 7186                        offset += value.len();
 7187                        moved_since_edit = false;
 7188                    }
 7189                    ChangeTag::Insert => {
 7190                        if moved_since_edit {
 7191                            let anchor = buffer.anchor_after(offset);
 7192                            edits.push((anchor..anchor, value.to_string()));
 7193                        } else {
 7194                            edits.last_mut().unwrap().1.push_str(value);
 7195                        }
 7196
 7197                        moved_since_edit = false;
 7198                    }
 7199                }
 7200            }
 7201
 7202            rewrapped_row_ranges.push(start_row..=end_row);
 7203        }
 7204
 7205        self.buffer
 7206            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7207    }
 7208
 7209    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7210        let mut text = String::new();
 7211        let buffer = self.buffer.read(cx).snapshot(cx);
 7212        let mut selections = self.selections.all::<Point>(cx);
 7213        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7214        {
 7215            let max_point = buffer.max_point();
 7216            let mut is_first = true;
 7217            for selection in &mut selections {
 7218                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7219                if is_entire_line {
 7220                    selection.start = Point::new(selection.start.row, 0);
 7221                    if !selection.is_empty() && selection.end.column == 0 {
 7222                        selection.end = cmp::min(max_point, selection.end);
 7223                    } else {
 7224                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7225                    }
 7226                    selection.goal = SelectionGoal::None;
 7227                }
 7228                if is_first {
 7229                    is_first = false;
 7230                } else {
 7231                    text += "\n";
 7232                }
 7233                let mut len = 0;
 7234                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7235                    text.push_str(chunk);
 7236                    len += chunk.len();
 7237                }
 7238                clipboard_selections.push(ClipboardSelection {
 7239                    len,
 7240                    is_entire_line,
 7241                    first_line_indent: buffer
 7242                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7243                        .len,
 7244                });
 7245            }
 7246        }
 7247
 7248        self.transact(window, cx, |this, window, cx| {
 7249            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7250                s.select(selections);
 7251            });
 7252            this.insert("", window, cx);
 7253        });
 7254        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7255    }
 7256
 7257    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7258        let item = self.cut_common(window, cx);
 7259        cx.write_to_clipboard(item);
 7260    }
 7261
 7262    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7263        self.change_selections(None, window, cx, |s| {
 7264            s.move_with(|snapshot, sel| {
 7265                if sel.is_empty() {
 7266                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7267                }
 7268            });
 7269        });
 7270        let item = self.cut_common(window, cx);
 7271        cx.set_global(KillRing(item))
 7272    }
 7273
 7274    pub fn kill_ring_yank(
 7275        &mut self,
 7276        _: &KillRingYank,
 7277        window: &mut Window,
 7278        cx: &mut Context<Self>,
 7279    ) {
 7280        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7281            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7282                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7283            } else {
 7284                return;
 7285            }
 7286        } else {
 7287            return;
 7288        };
 7289        self.do_paste(&text, metadata, false, window, cx);
 7290    }
 7291
 7292    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7293        let selections = self.selections.all::<Point>(cx);
 7294        let buffer = self.buffer.read(cx).read(cx);
 7295        let mut text = String::new();
 7296
 7297        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7298        {
 7299            let max_point = buffer.max_point();
 7300            let mut is_first = true;
 7301            for selection in selections.iter() {
 7302                let mut start = selection.start;
 7303                let mut end = selection.end;
 7304                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7305                if is_entire_line {
 7306                    start = Point::new(start.row, 0);
 7307                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7308                }
 7309                if is_first {
 7310                    is_first = false;
 7311                } else {
 7312                    text += "\n";
 7313                }
 7314                let mut len = 0;
 7315                for chunk in buffer.text_for_range(start..end) {
 7316                    text.push_str(chunk);
 7317                    len += chunk.len();
 7318                }
 7319                clipboard_selections.push(ClipboardSelection {
 7320                    len,
 7321                    is_entire_line,
 7322                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7323                });
 7324            }
 7325        }
 7326
 7327        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7328            text,
 7329            clipboard_selections,
 7330        ));
 7331    }
 7332
 7333    pub fn do_paste(
 7334        &mut self,
 7335        text: &String,
 7336        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7337        handle_entire_lines: bool,
 7338        window: &mut Window,
 7339        cx: &mut Context<Self>,
 7340    ) {
 7341        if self.read_only(cx) {
 7342            return;
 7343        }
 7344
 7345        let clipboard_text = Cow::Borrowed(text);
 7346
 7347        self.transact(window, cx, |this, window, cx| {
 7348            if let Some(mut clipboard_selections) = clipboard_selections {
 7349                let old_selections = this.selections.all::<usize>(cx);
 7350                let all_selections_were_entire_line =
 7351                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7352                let first_selection_indent_column =
 7353                    clipboard_selections.first().map(|s| s.first_line_indent);
 7354                if clipboard_selections.len() != old_selections.len() {
 7355                    clipboard_selections.drain(..);
 7356                }
 7357                let cursor_offset = this.selections.last::<usize>(cx).head();
 7358                let mut auto_indent_on_paste = true;
 7359
 7360                this.buffer.update(cx, |buffer, cx| {
 7361                    let snapshot = buffer.read(cx);
 7362                    auto_indent_on_paste =
 7363                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7364
 7365                    let mut start_offset = 0;
 7366                    let mut edits = Vec::new();
 7367                    let mut original_indent_columns = Vec::new();
 7368                    for (ix, selection) in old_selections.iter().enumerate() {
 7369                        let to_insert;
 7370                        let entire_line;
 7371                        let original_indent_column;
 7372                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7373                            let end_offset = start_offset + clipboard_selection.len;
 7374                            to_insert = &clipboard_text[start_offset..end_offset];
 7375                            entire_line = clipboard_selection.is_entire_line;
 7376                            start_offset = end_offset + 1;
 7377                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7378                        } else {
 7379                            to_insert = clipboard_text.as_str();
 7380                            entire_line = all_selections_were_entire_line;
 7381                            original_indent_column = first_selection_indent_column
 7382                        }
 7383
 7384                        // If the corresponding selection was empty when this slice of the
 7385                        // clipboard text was written, then the entire line containing the
 7386                        // selection was copied. If this selection is also currently empty,
 7387                        // then paste the line before the current line of the buffer.
 7388                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7389                            let column = selection.start.to_point(&snapshot).column as usize;
 7390                            let line_start = selection.start - column;
 7391                            line_start..line_start
 7392                        } else {
 7393                            selection.range()
 7394                        };
 7395
 7396                        edits.push((range, to_insert));
 7397                        original_indent_columns.extend(original_indent_column);
 7398                    }
 7399                    drop(snapshot);
 7400
 7401                    buffer.edit(
 7402                        edits,
 7403                        if auto_indent_on_paste {
 7404                            Some(AutoindentMode::Block {
 7405                                original_indent_columns,
 7406                            })
 7407                        } else {
 7408                            None
 7409                        },
 7410                        cx,
 7411                    );
 7412                });
 7413
 7414                let selections = this.selections.all::<usize>(cx);
 7415                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7416                    s.select(selections)
 7417                });
 7418            } else {
 7419                this.insert(&clipboard_text, window, cx);
 7420            }
 7421        });
 7422    }
 7423
 7424    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7425        if let Some(item) = cx.read_from_clipboard() {
 7426            let entries = item.entries();
 7427
 7428            match entries.first() {
 7429                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7430                // of all the pasted entries.
 7431                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7432                    .do_paste(
 7433                        clipboard_string.text(),
 7434                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7435                        true,
 7436                        window,
 7437                        cx,
 7438                    ),
 7439                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7440            }
 7441        }
 7442    }
 7443
 7444    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7445        if self.read_only(cx) {
 7446            return;
 7447        }
 7448
 7449        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7450            if let Some((selections, _)) =
 7451                self.selection_history.transaction(transaction_id).cloned()
 7452            {
 7453                self.change_selections(None, window, cx, |s| {
 7454                    s.select_anchors(selections.to_vec());
 7455                });
 7456            }
 7457            self.request_autoscroll(Autoscroll::fit(), cx);
 7458            self.unmark_text(window, cx);
 7459            self.refresh_inline_completion(true, false, window, cx);
 7460            cx.emit(EditorEvent::Edited { transaction_id });
 7461            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7462        }
 7463    }
 7464
 7465    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7466        if self.read_only(cx) {
 7467            return;
 7468        }
 7469
 7470        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7471            if let Some((_, Some(selections))) =
 7472                self.selection_history.transaction(transaction_id).cloned()
 7473            {
 7474                self.change_selections(None, window, cx, |s| {
 7475                    s.select_anchors(selections.to_vec());
 7476                });
 7477            }
 7478            self.request_autoscroll(Autoscroll::fit(), cx);
 7479            self.unmark_text(window, cx);
 7480            self.refresh_inline_completion(true, false, window, cx);
 7481            cx.emit(EditorEvent::Edited { transaction_id });
 7482        }
 7483    }
 7484
 7485    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7486        self.buffer
 7487            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7488    }
 7489
 7490    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7491        self.buffer
 7492            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7493    }
 7494
 7495    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7496        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7497            let line_mode = s.line_mode;
 7498            s.move_with(|map, selection| {
 7499                let cursor = if selection.is_empty() && !line_mode {
 7500                    movement::left(map, selection.start)
 7501                } else {
 7502                    selection.start
 7503                };
 7504                selection.collapse_to(cursor, SelectionGoal::None);
 7505            });
 7506        })
 7507    }
 7508
 7509    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7510        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7511            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7512        })
 7513    }
 7514
 7515    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7516        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7517            let line_mode = s.line_mode;
 7518            s.move_with(|map, selection| {
 7519                let cursor = if selection.is_empty() && !line_mode {
 7520                    movement::right(map, selection.end)
 7521                } else {
 7522                    selection.end
 7523                };
 7524                selection.collapse_to(cursor, SelectionGoal::None)
 7525            });
 7526        })
 7527    }
 7528
 7529    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7530        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7531            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7532        })
 7533    }
 7534
 7535    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7536        if self.take_rename(true, window, cx).is_some() {
 7537            return;
 7538        }
 7539
 7540        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7541            cx.propagate();
 7542            return;
 7543        }
 7544
 7545        let text_layout_details = &self.text_layout_details(window);
 7546        let selection_count = self.selections.count();
 7547        let first_selection = self.selections.first_anchor();
 7548
 7549        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7550            let line_mode = s.line_mode;
 7551            s.move_with(|map, selection| {
 7552                if !selection.is_empty() && !line_mode {
 7553                    selection.goal = SelectionGoal::None;
 7554                }
 7555                let (cursor, goal) = movement::up(
 7556                    map,
 7557                    selection.start,
 7558                    selection.goal,
 7559                    false,
 7560                    text_layout_details,
 7561                );
 7562                selection.collapse_to(cursor, goal);
 7563            });
 7564        });
 7565
 7566        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7567        {
 7568            cx.propagate();
 7569        }
 7570    }
 7571
 7572    pub fn move_up_by_lines(
 7573        &mut self,
 7574        action: &MoveUpByLines,
 7575        window: &mut Window,
 7576        cx: &mut Context<Self>,
 7577    ) {
 7578        if self.take_rename(true, window, cx).is_some() {
 7579            return;
 7580        }
 7581
 7582        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7583            cx.propagate();
 7584            return;
 7585        }
 7586
 7587        let text_layout_details = &self.text_layout_details(window);
 7588
 7589        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7590            let line_mode = s.line_mode;
 7591            s.move_with(|map, selection| {
 7592                if !selection.is_empty() && !line_mode {
 7593                    selection.goal = SelectionGoal::None;
 7594                }
 7595                let (cursor, goal) = movement::up_by_rows(
 7596                    map,
 7597                    selection.start,
 7598                    action.lines,
 7599                    selection.goal,
 7600                    false,
 7601                    text_layout_details,
 7602                );
 7603                selection.collapse_to(cursor, goal);
 7604            });
 7605        })
 7606    }
 7607
 7608    pub fn move_down_by_lines(
 7609        &mut self,
 7610        action: &MoveDownByLines,
 7611        window: &mut Window,
 7612        cx: &mut Context<Self>,
 7613    ) {
 7614        if self.take_rename(true, window, cx).is_some() {
 7615            return;
 7616        }
 7617
 7618        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7619            cx.propagate();
 7620            return;
 7621        }
 7622
 7623        let text_layout_details = &self.text_layout_details(window);
 7624
 7625        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7626            let line_mode = s.line_mode;
 7627            s.move_with(|map, selection| {
 7628                if !selection.is_empty() && !line_mode {
 7629                    selection.goal = SelectionGoal::None;
 7630                }
 7631                let (cursor, goal) = movement::down_by_rows(
 7632                    map,
 7633                    selection.start,
 7634                    action.lines,
 7635                    selection.goal,
 7636                    false,
 7637                    text_layout_details,
 7638                );
 7639                selection.collapse_to(cursor, goal);
 7640            });
 7641        })
 7642    }
 7643
 7644    pub fn select_down_by_lines(
 7645        &mut self,
 7646        action: &SelectDownByLines,
 7647        window: &mut Window,
 7648        cx: &mut Context<Self>,
 7649    ) {
 7650        let text_layout_details = &self.text_layout_details(window);
 7651        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7652            s.move_heads_with(|map, head, goal| {
 7653                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7654            })
 7655        })
 7656    }
 7657
 7658    pub fn select_up_by_lines(
 7659        &mut self,
 7660        action: &SelectUpByLines,
 7661        window: &mut Window,
 7662        cx: &mut Context<Self>,
 7663    ) {
 7664        let text_layout_details = &self.text_layout_details(window);
 7665        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7666            s.move_heads_with(|map, head, goal| {
 7667                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7668            })
 7669        })
 7670    }
 7671
 7672    pub fn select_page_up(
 7673        &mut self,
 7674        _: &SelectPageUp,
 7675        window: &mut Window,
 7676        cx: &mut Context<Self>,
 7677    ) {
 7678        let Some(row_count) = self.visible_row_count() else {
 7679            return;
 7680        };
 7681
 7682        let text_layout_details = &self.text_layout_details(window);
 7683
 7684        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7685            s.move_heads_with(|map, head, goal| {
 7686                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7687            })
 7688        })
 7689    }
 7690
 7691    pub fn move_page_up(
 7692        &mut self,
 7693        action: &MovePageUp,
 7694        window: &mut Window,
 7695        cx: &mut Context<Self>,
 7696    ) {
 7697        if self.take_rename(true, window, cx).is_some() {
 7698            return;
 7699        }
 7700
 7701        if self
 7702            .context_menu
 7703            .borrow_mut()
 7704            .as_mut()
 7705            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7706            .unwrap_or(false)
 7707        {
 7708            return;
 7709        }
 7710
 7711        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7712            cx.propagate();
 7713            return;
 7714        }
 7715
 7716        let Some(row_count) = self.visible_row_count() else {
 7717            return;
 7718        };
 7719
 7720        let autoscroll = if action.center_cursor {
 7721            Autoscroll::center()
 7722        } else {
 7723            Autoscroll::fit()
 7724        };
 7725
 7726        let text_layout_details = &self.text_layout_details(window);
 7727
 7728        self.change_selections(Some(autoscroll), window, cx, |s| {
 7729            let line_mode = s.line_mode;
 7730            s.move_with(|map, selection| {
 7731                if !selection.is_empty() && !line_mode {
 7732                    selection.goal = SelectionGoal::None;
 7733                }
 7734                let (cursor, goal) = movement::up_by_rows(
 7735                    map,
 7736                    selection.end,
 7737                    row_count,
 7738                    selection.goal,
 7739                    false,
 7740                    text_layout_details,
 7741                );
 7742                selection.collapse_to(cursor, goal);
 7743            });
 7744        });
 7745    }
 7746
 7747    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 7748        let text_layout_details = &self.text_layout_details(window);
 7749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7750            s.move_heads_with(|map, head, goal| {
 7751                movement::up(map, head, goal, false, text_layout_details)
 7752            })
 7753        })
 7754    }
 7755
 7756    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 7757        self.take_rename(true, window, cx);
 7758
 7759        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7760            cx.propagate();
 7761            return;
 7762        }
 7763
 7764        let text_layout_details = &self.text_layout_details(window);
 7765        let selection_count = self.selections.count();
 7766        let first_selection = self.selections.first_anchor();
 7767
 7768        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7769            let line_mode = s.line_mode;
 7770            s.move_with(|map, selection| {
 7771                if !selection.is_empty() && !line_mode {
 7772                    selection.goal = SelectionGoal::None;
 7773                }
 7774                let (cursor, goal) = movement::down(
 7775                    map,
 7776                    selection.end,
 7777                    selection.goal,
 7778                    false,
 7779                    text_layout_details,
 7780                );
 7781                selection.collapse_to(cursor, goal);
 7782            });
 7783        });
 7784
 7785        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7786        {
 7787            cx.propagate();
 7788        }
 7789    }
 7790
 7791    pub fn select_page_down(
 7792        &mut self,
 7793        _: &SelectPageDown,
 7794        window: &mut Window,
 7795        cx: &mut Context<Self>,
 7796    ) {
 7797        let Some(row_count) = self.visible_row_count() else {
 7798            return;
 7799        };
 7800
 7801        let text_layout_details = &self.text_layout_details(window);
 7802
 7803        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7804            s.move_heads_with(|map, head, goal| {
 7805                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7806            })
 7807        })
 7808    }
 7809
 7810    pub fn move_page_down(
 7811        &mut self,
 7812        action: &MovePageDown,
 7813        window: &mut Window,
 7814        cx: &mut Context<Self>,
 7815    ) {
 7816        if self.take_rename(true, window, cx).is_some() {
 7817            return;
 7818        }
 7819
 7820        if self
 7821            .context_menu
 7822            .borrow_mut()
 7823            .as_mut()
 7824            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7825            .unwrap_or(false)
 7826        {
 7827            return;
 7828        }
 7829
 7830        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7831            cx.propagate();
 7832            return;
 7833        }
 7834
 7835        let Some(row_count) = self.visible_row_count() else {
 7836            return;
 7837        };
 7838
 7839        let autoscroll = if action.center_cursor {
 7840            Autoscroll::center()
 7841        } else {
 7842            Autoscroll::fit()
 7843        };
 7844
 7845        let text_layout_details = &self.text_layout_details(window);
 7846        self.change_selections(Some(autoscroll), window, cx, |s| {
 7847            let line_mode = s.line_mode;
 7848            s.move_with(|map, selection| {
 7849                if !selection.is_empty() && !line_mode {
 7850                    selection.goal = SelectionGoal::None;
 7851                }
 7852                let (cursor, goal) = movement::down_by_rows(
 7853                    map,
 7854                    selection.end,
 7855                    row_count,
 7856                    selection.goal,
 7857                    false,
 7858                    text_layout_details,
 7859                );
 7860                selection.collapse_to(cursor, goal);
 7861            });
 7862        });
 7863    }
 7864
 7865    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 7866        let text_layout_details = &self.text_layout_details(window);
 7867        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7868            s.move_heads_with(|map, head, goal| {
 7869                movement::down(map, head, goal, false, text_layout_details)
 7870            })
 7871        });
 7872    }
 7873
 7874    pub fn context_menu_first(
 7875        &mut self,
 7876        _: &ContextMenuFirst,
 7877        _window: &mut Window,
 7878        cx: &mut Context<Self>,
 7879    ) {
 7880        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7881            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7882        }
 7883    }
 7884
 7885    pub fn context_menu_prev(
 7886        &mut self,
 7887        _: &ContextMenuPrev,
 7888        _window: &mut Window,
 7889        cx: &mut Context<Self>,
 7890    ) {
 7891        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7892            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7893        }
 7894    }
 7895
 7896    pub fn context_menu_next(
 7897        &mut self,
 7898        _: &ContextMenuNext,
 7899        _window: &mut Window,
 7900        cx: &mut Context<Self>,
 7901    ) {
 7902        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7903            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7904        }
 7905    }
 7906
 7907    pub fn context_menu_last(
 7908        &mut self,
 7909        _: &ContextMenuLast,
 7910        _window: &mut Window,
 7911        cx: &mut Context<Self>,
 7912    ) {
 7913        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7914            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7915        }
 7916    }
 7917
 7918    pub fn move_to_previous_word_start(
 7919        &mut self,
 7920        _: &MoveToPreviousWordStart,
 7921        window: &mut Window,
 7922        cx: &mut Context<Self>,
 7923    ) {
 7924        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7925            s.move_cursors_with(|map, head, _| {
 7926                (
 7927                    movement::previous_word_start(map, head),
 7928                    SelectionGoal::None,
 7929                )
 7930            });
 7931        })
 7932    }
 7933
 7934    pub fn move_to_previous_subword_start(
 7935        &mut self,
 7936        _: &MoveToPreviousSubwordStart,
 7937        window: &mut Window,
 7938        cx: &mut Context<Self>,
 7939    ) {
 7940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7941            s.move_cursors_with(|map, head, _| {
 7942                (
 7943                    movement::previous_subword_start(map, head),
 7944                    SelectionGoal::None,
 7945                )
 7946            });
 7947        })
 7948    }
 7949
 7950    pub fn select_to_previous_word_start(
 7951        &mut self,
 7952        _: &SelectToPreviousWordStart,
 7953        window: &mut Window,
 7954        cx: &mut Context<Self>,
 7955    ) {
 7956        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7957            s.move_heads_with(|map, head, _| {
 7958                (
 7959                    movement::previous_word_start(map, head),
 7960                    SelectionGoal::None,
 7961                )
 7962            });
 7963        })
 7964    }
 7965
 7966    pub fn select_to_previous_subword_start(
 7967        &mut self,
 7968        _: &SelectToPreviousSubwordStart,
 7969        window: &mut Window,
 7970        cx: &mut Context<Self>,
 7971    ) {
 7972        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7973            s.move_heads_with(|map, head, _| {
 7974                (
 7975                    movement::previous_subword_start(map, head),
 7976                    SelectionGoal::None,
 7977                )
 7978            });
 7979        })
 7980    }
 7981
 7982    pub fn delete_to_previous_word_start(
 7983        &mut self,
 7984        action: &DeleteToPreviousWordStart,
 7985        window: &mut Window,
 7986        cx: &mut Context<Self>,
 7987    ) {
 7988        self.transact(window, cx, |this, window, cx| {
 7989            this.select_autoclose_pair(window, cx);
 7990            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7991                let line_mode = s.line_mode;
 7992                s.move_with(|map, selection| {
 7993                    if selection.is_empty() && !line_mode {
 7994                        let cursor = if action.ignore_newlines {
 7995                            movement::previous_word_start(map, selection.head())
 7996                        } else {
 7997                            movement::previous_word_start_or_newline(map, selection.head())
 7998                        };
 7999                        selection.set_head(cursor, SelectionGoal::None);
 8000                    }
 8001                });
 8002            });
 8003            this.insert("", window, cx);
 8004        });
 8005    }
 8006
 8007    pub fn delete_to_previous_subword_start(
 8008        &mut self,
 8009        _: &DeleteToPreviousSubwordStart,
 8010        window: &mut Window,
 8011        cx: &mut Context<Self>,
 8012    ) {
 8013        self.transact(window, cx, |this, window, cx| {
 8014            this.select_autoclose_pair(window, cx);
 8015            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8016                let line_mode = s.line_mode;
 8017                s.move_with(|map, selection| {
 8018                    if selection.is_empty() && !line_mode {
 8019                        let cursor = movement::previous_subword_start(map, selection.head());
 8020                        selection.set_head(cursor, SelectionGoal::None);
 8021                    }
 8022                });
 8023            });
 8024            this.insert("", window, cx);
 8025        });
 8026    }
 8027
 8028    pub fn move_to_next_word_end(
 8029        &mut self,
 8030        _: &MoveToNextWordEnd,
 8031        window: &mut Window,
 8032        cx: &mut Context<Self>,
 8033    ) {
 8034        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8035            s.move_cursors_with(|map, head, _| {
 8036                (movement::next_word_end(map, head), SelectionGoal::None)
 8037            });
 8038        })
 8039    }
 8040
 8041    pub fn move_to_next_subword_end(
 8042        &mut self,
 8043        _: &MoveToNextSubwordEnd,
 8044        window: &mut Window,
 8045        cx: &mut Context<Self>,
 8046    ) {
 8047        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8048            s.move_cursors_with(|map, head, _| {
 8049                (movement::next_subword_end(map, head), SelectionGoal::None)
 8050            });
 8051        })
 8052    }
 8053
 8054    pub fn select_to_next_word_end(
 8055        &mut self,
 8056        _: &SelectToNextWordEnd,
 8057        window: &mut Window,
 8058        cx: &mut Context<Self>,
 8059    ) {
 8060        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8061            s.move_heads_with(|map, head, _| {
 8062                (movement::next_word_end(map, head), SelectionGoal::None)
 8063            });
 8064        })
 8065    }
 8066
 8067    pub fn select_to_next_subword_end(
 8068        &mut self,
 8069        _: &SelectToNextSubwordEnd,
 8070        window: &mut Window,
 8071        cx: &mut Context<Self>,
 8072    ) {
 8073        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8074            s.move_heads_with(|map, head, _| {
 8075                (movement::next_subword_end(map, head), SelectionGoal::None)
 8076            });
 8077        })
 8078    }
 8079
 8080    pub fn delete_to_next_word_end(
 8081        &mut self,
 8082        action: &DeleteToNextWordEnd,
 8083        window: &mut Window,
 8084        cx: &mut Context<Self>,
 8085    ) {
 8086        self.transact(window, cx, |this, window, cx| {
 8087            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8088                let line_mode = s.line_mode;
 8089                s.move_with(|map, selection| {
 8090                    if selection.is_empty() && !line_mode {
 8091                        let cursor = if action.ignore_newlines {
 8092                            movement::next_word_end(map, selection.head())
 8093                        } else {
 8094                            movement::next_word_end_or_newline(map, selection.head())
 8095                        };
 8096                        selection.set_head(cursor, SelectionGoal::None);
 8097                    }
 8098                });
 8099            });
 8100            this.insert("", window, cx);
 8101        });
 8102    }
 8103
 8104    pub fn delete_to_next_subword_end(
 8105        &mut self,
 8106        _: &DeleteToNextSubwordEnd,
 8107        window: &mut Window,
 8108        cx: &mut Context<Self>,
 8109    ) {
 8110        self.transact(window, cx, |this, window, cx| {
 8111            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8112                s.move_with(|map, selection| {
 8113                    if selection.is_empty() {
 8114                        let cursor = movement::next_subword_end(map, selection.head());
 8115                        selection.set_head(cursor, SelectionGoal::None);
 8116                    }
 8117                });
 8118            });
 8119            this.insert("", window, cx);
 8120        });
 8121    }
 8122
 8123    pub fn move_to_beginning_of_line(
 8124        &mut self,
 8125        action: &MoveToBeginningOfLine,
 8126        window: &mut Window,
 8127        cx: &mut Context<Self>,
 8128    ) {
 8129        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8130            s.move_cursors_with(|map, head, _| {
 8131                (
 8132                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8133                    SelectionGoal::None,
 8134                )
 8135            });
 8136        })
 8137    }
 8138
 8139    pub fn select_to_beginning_of_line(
 8140        &mut self,
 8141        action: &SelectToBeginningOfLine,
 8142        window: &mut Window,
 8143        cx: &mut Context<Self>,
 8144    ) {
 8145        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8146            s.move_heads_with(|map, head, _| {
 8147                (
 8148                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8149                    SelectionGoal::None,
 8150                )
 8151            });
 8152        });
 8153    }
 8154
 8155    pub fn delete_to_beginning_of_line(
 8156        &mut self,
 8157        _: &DeleteToBeginningOfLine,
 8158        window: &mut Window,
 8159        cx: &mut Context<Self>,
 8160    ) {
 8161        self.transact(window, cx, |this, window, cx| {
 8162            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8163                s.move_with(|_, selection| {
 8164                    selection.reversed = true;
 8165                });
 8166            });
 8167
 8168            this.select_to_beginning_of_line(
 8169                &SelectToBeginningOfLine {
 8170                    stop_at_soft_wraps: false,
 8171                },
 8172                window,
 8173                cx,
 8174            );
 8175            this.backspace(&Backspace, window, cx);
 8176        });
 8177    }
 8178
 8179    pub fn move_to_end_of_line(
 8180        &mut self,
 8181        action: &MoveToEndOfLine,
 8182        window: &mut Window,
 8183        cx: &mut Context<Self>,
 8184    ) {
 8185        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8186            s.move_cursors_with(|map, head, _| {
 8187                (
 8188                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8189                    SelectionGoal::None,
 8190                )
 8191            });
 8192        })
 8193    }
 8194
 8195    pub fn select_to_end_of_line(
 8196        &mut self,
 8197        action: &SelectToEndOfLine,
 8198        window: &mut Window,
 8199        cx: &mut Context<Self>,
 8200    ) {
 8201        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8202            s.move_heads_with(|map, head, _| {
 8203                (
 8204                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8205                    SelectionGoal::None,
 8206                )
 8207            });
 8208        })
 8209    }
 8210
 8211    pub fn delete_to_end_of_line(
 8212        &mut self,
 8213        _: &DeleteToEndOfLine,
 8214        window: &mut Window,
 8215        cx: &mut Context<Self>,
 8216    ) {
 8217        self.transact(window, cx, |this, window, cx| {
 8218            this.select_to_end_of_line(
 8219                &SelectToEndOfLine {
 8220                    stop_at_soft_wraps: false,
 8221                },
 8222                window,
 8223                cx,
 8224            );
 8225            this.delete(&Delete, window, cx);
 8226        });
 8227    }
 8228
 8229    pub fn cut_to_end_of_line(
 8230        &mut self,
 8231        _: &CutToEndOfLine,
 8232        window: &mut Window,
 8233        cx: &mut Context<Self>,
 8234    ) {
 8235        self.transact(window, cx, |this, window, cx| {
 8236            this.select_to_end_of_line(
 8237                &SelectToEndOfLine {
 8238                    stop_at_soft_wraps: false,
 8239                },
 8240                window,
 8241                cx,
 8242            );
 8243            this.cut(&Cut, window, cx);
 8244        });
 8245    }
 8246
 8247    pub fn move_to_start_of_paragraph(
 8248        &mut self,
 8249        _: &MoveToStartOfParagraph,
 8250        window: &mut Window,
 8251        cx: &mut Context<Self>,
 8252    ) {
 8253        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8254            cx.propagate();
 8255            return;
 8256        }
 8257
 8258        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8259            s.move_with(|map, selection| {
 8260                selection.collapse_to(
 8261                    movement::start_of_paragraph(map, selection.head(), 1),
 8262                    SelectionGoal::None,
 8263                )
 8264            });
 8265        })
 8266    }
 8267
 8268    pub fn move_to_end_of_paragraph(
 8269        &mut self,
 8270        _: &MoveToEndOfParagraph,
 8271        window: &mut Window,
 8272        cx: &mut Context<Self>,
 8273    ) {
 8274        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8275            cx.propagate();
 8276            return;
 8277        }
 8278
 8279        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8280            s.move_with(|map, selection| {
 8281                selection.collapse_to(
 8282                    movement::end_of_paragraph(map, selection.head(), 1),
 8283                    SelectionGoal::None,
 8284                )
 8285            });
 8286        })
 8287    }
 8288
 8289    pub fn select_to_start_of_paragraph(
 8290        &mut self,
 8291        _: &SelectToStartOfParagraph,
 8292        window: &mut Window,
 8293        cx: &mut Context<Self>,
 8294    ) {
 8295        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8296            cx.propagate();
 8297            return;
 8298        }
 8299
 8300        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8301            s.move_heads_with(|map, head, _| {
 8302                (
 8303                    movement::start_of_paragraph(map, head, 1),
 8304                    SelectionGoal::None,
 8305                )
 8306            });
 8307        })
 8308    }
 8309
 8310    pub fn select_to_end_of_paragraph(
 8311        &mut self,
 8312        _: &SelectToEndOfParagraph,
 8313        window: &mut Window,
 8314        cx: &mut Context<Self>,
 8315    ) {
 8316        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8317            cx.propagate();
 8318            return;
 8319        }
 8320
 8321        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8322            s.move_heads_with(|map, head, _| {
 8323                (
 8324                    movement::end_of_paragraph(map, head, 1),
 8325                    SelectionGoal::None,
 8326                )
 8327            });
 8328        })
 8329    }
 8330
 8331    pub fn move_to_beginning(
 8332        &mut self,
 8333        _: &MoveToBeginning,
 8334        window: &mut Window,
 8335        cx: &mut Context<Self>,
 8336    ) {
 8337        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8338            cx.propagate();
 8339            return;
 8340        }
 8341
 8342        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8343            s.select_ranges(vec![0..0]);
 8344        });
 8345    }
 8346
 8347    pub fn select_to_beginning(
 8348        &mut self,
 8349        _: &SelectToBeginning,
 8350        window: &mut Window,
 8351        cx: &mut Context<Self>,
 8352    ) {
 8353        let mut selection = self.selections.last::<Point>(cx);
 8354        selection.set_head(Point::zero(), SelectionGoal::None);
 8355
 8356        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8357            s.select(vec![selection]);
 8358        });
 8359    }
 8360
 8361    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8362        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8363            cx.propagate();
 8364            return;
 8365        }
 8366
 8367        let cursor = self.buffer.read(cx).read(cx).len();
 8368        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8369            s.select_ranges(vec![cursor..cursor])
 8370        });
 8371    }
 8372
 8373    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8374        self.nav_history = nav_history;
 8375    }
 8376
 8377    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8378        self.nav_history.as_ref()
 8379    }
 8380
 8381    fn push_to_nav_history(
 8382        &mut self,
 8383        cursor_anchor: Anchor,
 8384        new_position: Option<Point>,
 8385        cx: &mut Context<Self>,
 8386    ) {
 8387        if let Some(nav_history) = self.nav_history.as_mut() {
 8388            let buffer = self.buffer.read(cx).read(cx);
 8389            let cursor_position = cursor_anchor.to_point(&buffer);
 8390            let scroll_state = self.scroll_manager.anchor();
 8391            let scroll_top_row = scroll_state.top_row(&buffer);
 8392            drop(buffer);
 8393
 8394            if let Some(new_position) = new_position {
 8395                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8396                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8397                    return;
 8398                }
 8399            }
 8400
 8401            nav_history.push(
 8402                Some(NavigationData {
 8403                    cursor_anchor,
 8404                    cursor_position,
 8405                    scroll_anchor: scroll_state,
 8406                    scroll_top_row,
 8407                }),
 8408                cx,
 8409            );
 8410        }
 8411    }
 8412
 8413    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8414        let buffer = self.buffer.read(cx).snapshot(cx);
 8415        let mut selection = self.selections.first::<usize>(cx);
 8416        selection.set_head(buffer.len(), SelectionGoal::None);
 8417        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8418            s.select(vec![selection]);
 8419        });
 8420    }
 8421
 8422    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8423        let end = self.buffer.read(cx).read(cx).len();
 8424        self.change_selections(None, window, cx, |s| {
 8425            s.select_ranges(vec![0..end]);
 8426        });
 8427    }
 8428
 8429    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8430        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8431        let mut selections = self.selections.all::<Point>(cx);
 8432        let max_point = display_map.buffer_snapshot.max_point();
 8433        for selection in &mut selections {
 8434            let rows = selection.spanned_rows(true, &display_map);
 8435            selection.start = Point::new(rows.start.0, 0);
 8436            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8437            selection.reversed = false;
 8438        }
 8439        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8440            s.select(selections);
 8441        });
 8442    }
 8443
 8444    pub fn split_selection_into_lines(
 8445        &mut self,
 8446        _: &SplitSelectionIntoLines,
 8447        window: &mut Window,
 8448        cx: &mut Context<Self>,
 8449    ) {
 8450        let mut to_unfold = Vec::new();
 8451        let mut new_selection_ranges = Vec::new();
 8452        {
 8453            let selections = self.selections.all::<Point>(cx);
 8454            let buffer = self.buffer.read(cx).read(cx);
 8455            for selection in selections {
 8456                for row in selection.start.row..selection.end.row {
 8457                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8458                    new_selection_ranges.push(cursor..cursor);
 8459                }
 8460                new_selection_ranges.push(selection.end..selection.end);
 8461                to_unfold.push(selection.start..selection.end);
 8462            }
 8463        }
 8464        self.unfold_ranges(&to_unfold, true, true, cx);
 8465        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8466            s.select_ranges(new_selection_ranges);
 8467        });
 8468    }
 8469
 8470    pub fn add_selection_above(
 8471        &mut self,
 8472        _: &AddSelectionAbove,
 8473        window: &mut Window,
 8474        cx: &mut Context<Self>,
 8475    ) {
 8476        self.add_selection(true, window, cx);
 8477    }
 8478
 8479    pub fn add_selection_below(
 8480        &mut self,
 8481        _: &AddSelectionBelow,
 8482        window: &mut Window,
 8483        cx: &mut Context<Self>,
 8484    ) {
 8485        self.add_selection(false, window, cx);
 8486    }
 8487
 8488    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8489        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8490        let mut selections = self.selections.all::<Point>(cx);
 8491        let text_layout_details = self.text_layout_details(window);
 8492        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8493            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8494            let range = oldest_selection.display_range(&display_map).sorted();
 8495
 8496            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8497            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8498            let positions = start_x.min(end_x)..start_x.max(end_x);
 8499
 8500            selections.clear();
 8501            let mut stack = Vec::new();
 8502            for row in range.start.row().0..=range.end.row().0 {
 8503                if let Some(selection) = self.selections.build_columnar_selection(
 8504                    &display_map,
 8505                    DisplayRow(row),
 8506                    &positions,
 8507                    oldest_selection.reversed,
 8508                    &text_layout_details,
 8509                ) {
 8510                    stack.push(selection.id);
 8511                    selections.push(selection);
 8512                }
 8513            }
 8514
 8515            if above {
 8516                stack.reverse();
 8517            }
 8518
 8519            AddSelectionsState { above, stack }
 8520        });
 8521
 8522        let last_added_selection = *state.stack.last().unwrap();
 8523        let mut new_selections = Vec::new();
 8524        if above == state.above {
 8525            let end_row = if above {
 8526                DisplayRow(0)
 8527            } else {
 8528                display_map.max_point().row()
 8529            };
 8530
 8531            'outer: for selection in selections {
 8532                if selection.id == last_added_selection {
 8533                    let range = selection.display_range(&display_map).sorted();
 8534                    debug_assert_eq!(range.start.row(), range.end.row());
 8535                    let mut row = range.start.row();
 8536                    let positions =
 8537                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8538                            px(start)..px(end)
 8539                        } else {
 8540                            let start_x =
 8541                                display_map.x_for_display_point(range.start, &text_layout_details);
 8542                            let end_x =
 8543                                display_map.x_for_display_point(range.end, &text_layout_details);
 8544                            start_x.min(end_x)..start_x.max(end_x)
 8545                        };
 8546
 8547                    while row != end_row {
 8548                        if above {
 8549                            row.0 -= 1;
 8550                        } else {
 8551                            row.0 += 1;
 8552                        }
 8553
 8554                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8555                            &display_map,
 8556                            row,
 8557                            &positions,
 8558                            selection.reversed,
 8559                            &text_layout_details,
 8560                        ) {
 8561                            state.stack.push(new_selection.id);
 8562                            if above {
 8563                                new_selections.push(new_selection);
 8564                                new_selections.push(selection);
 8565                            } else {
 8566                                new_selections.push(selection);
 8567                                new_selections.push(new_selection);
 8568                            }
 8569
 8570                            continue 'outer;
 8571                        }
 8572                    }
 8573                }
 8574
 8575                new_selections.push(selection);
 8576            }
 8577        } else {
 8578            new_selections = selections;
 8579            new_selections.retain(|s| s.id != last_added_selection);
 8580            state.stack.pop();
 8581        }
 8582
 8583        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8584            s.select(new_selections);
 8585        });
 8586        if state.stack.len() > 1 {
 8587            self.add_selections_state = Some(state);
 8588        }
 8589    }
 8590
 8591    pub fn select_next_match_internal(
 8592        &mut self,
 8593        display_map: &DisplaySnapshot,
 8594        replace_newest: bool,
 8595        autoscroll: Option<Autoscroll>,
 8596        window: &mut Window,
 8597        cx: &mut Context<Self>,
 8598    ) -> Result<()> {
 8599        fn select_next_match_ranges(
 8600            this: &mut Editor,
 8601            range: Range<usize>,
 8602            replace_newest: bool,
 8603            auto_scroll: Option<Autoscroll>,
 8604            window: &mut Window,
 8605            cx: &mut Context<Editor>,
 8606        ) {
 8607            this.unfold_ranges(&[range.clone()], false, true, cx);
 8608            this.change_selections(auto_scroll, window, cx, |s| {
 8609                if replace_newest {
 8610                    s.delete(s.newest_anchor().id);
 8611                }
 8612                s.insert_range(range.clone());
 8613            });
 8614        }
 8615
 8616        let buffer = &display_map.buffer_snapshot;
 8617        let mut selections = self.selections.all::<usize>(cx);
 8618        if let Some(mut select_next_state) = self.select_next_state.take() {
 8619            let query = &select_next_state.query;
 8620            if !select_next_state.done {
 8621                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8622                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8623                let mut next_selected_range = None;
 8624
 8625                let bytes_after_last_selection =
 8626                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8627                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8628                let query_matches = query
 8629                    .stream_find_iter(bytes_after_last_selection)
 8630                    .map(|result| (last_selection.end, result))
 8631                    .chain(
 8632                        query
 8633                            .stream_find_iter(bytes_before_first_selection)
 8634                            .map(|result| (0, result)),
 8635                    );
 8636
 8637                for (start_offset, query_match) in query_matches {
 8638                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8639                    let offset_range =
 8640                        start_offset + query_match.start()..start_offset + query_match.end();
 8641                    let display_range = offset_range.start.to_display_point(display_map)
 8642                        ..offset_range.end.to_display_point(display_map);
 8643
 8644                    if !select_next_state.wordwise
 8645                        || (!movement::is_inside_word(display_map, display_range.start)
 8646                            && !movement::is_inside_word(display_map, display_range.end))
 8647                    {
 8648                        // TODO: This is n^2, because we might check all the selections
 8649                        if !selections
 8650                            .iter()
 8651                            .any(|selection| selection.range().overlaps(&offset_range))
 8652                        {
 8653                            next_selected_range = Some(offset_range);
 8654                            break;
 8655                        }
 8656                    }
 8657                }
 8658
 8659                if let Some(next_selected_range) = next_selected_range {
 8660                    select_next_match_ranges(
 8661                        self,
 8662                        next_selected_range,
 8663                        replace_newest,
 8664                        autoscroll,
 8665                        window,
 8666                        cx,
 8667                    );
 8668                } else {
 8669                    select_next_state.done = true;
 8670                }
 8671            }
 8672
 8673            self.select_next_state = Some(select_next_state);
 8674        } else {
 8675            let mut only_carets = true;
 8676            let mut same_text_selected = true;
 8677            let mut selected_text = None;
 8678
 8679            let mut selections_iter = selections.iter().peekable();
 8680            while let Some(selection) = selections_iter.next() {
 8681                if selection.start != selection.end {
 8682                    only_carets = false;
 8683                }
 8684
 8685                if same_text_selected {
 8686                    if selected_text.is_none() {
 8687                        selected_text =
 8688                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8689                    }
 8690
 8691                    if let Some(next_selection) = selections_iter.peek() {
 8692                        if next_selection.range().len() == selection.range().len() {
 8693                            let next_selected_text = buffer
 8694                                .text_for_range(next_selection.range())
 8695                                .collect::<String>();
 8696                            if Some(next_selected_text) != selected_text {
 8697                                same_text_selected = false;
 8698                                selected_text = None;
 8699                            }
 8700                        } else {
 8701                            same_text_selected = false;
 8702                            selected_text = None;
 8703                        }
 8704                    }
 8705                }
 8706            }
 8707
 8708            if only_carets {
 8709                for selection in &mut selections {
 8710                    let word_range = movement::surrounding_word(
 8711                        display_map,
 8712                        selection.start.to_display_point(display_map),
 8713                    );
 8714                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8715                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8716                    selection.goal = SelectionGoal::None;
 8717                    selection.reversed = false;
 8718                    select_next_match_ranges(
 8719                        self,
 8720                        selection.start..selection.end,
 8721                        replace_newest,
 8722                        autoscroll,
 8723                        window,
 8724                        cx,
 8725                    );
 8726                }
 8727
 8728                if selections.len() == 1 {
 8729                    let selection = selections
 8730                        .last()
 8731                        .expect("ensured that there's only one selection");
 8732                    let query = buffer
 8733                        .text_for_range(selection.start..selection.end)
 8734                        .collect::<String>();
 8735                    let is_empty = query.is_empty();
 8736                    let select_state = SelectNextState {
 8737                        query: AhoCorasick::new(&[query])?,
 8738                        wordwise: true,
 8739                        done: is_empty,
 8740                    };
 8741                    self.select_next_state = Some(select_state);
 8742                } else {
 8743                    self.select_next_state = None;
 8744                }
 8745            } else if let Some(selected_text) = selected_text {
 8746                self.select_next_state = Some(SelectNextState {
 8747                    query: AhoCorasick::new(&[selected_text])?,
 8748                    wordwise: false,
 8749                    done: false,
 8750                });
 8751                self.select_next_match_internal(
 8752                    display_map,
 8753                    replace_newest,
 8754                    autoscroll,
 8755                    window,
 8756                    cx,
 8757                )?;
 8758            }
 8759        }
 8760        Ok(())
 8761    }
 8762
 8763    pub fn select_all_matches(
 8764        &mut self,
 8765        _action: &SelectAllMatches,
 8766        window: &mut Window,
 8767        cx: &mut Context<Self>,
 8768    ) -> Result<()> {
 8769        self.push_to_selection_history();
 8770        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8771
 8772        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 8773        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8774            return Ok(());
 8775        };
 8776        if select_next_state.done {
 8777            return Ok(());
 8778        }
 8779
 8780        let mut new_selections = self.selections.all::<usize>(cx);
 8781
 8782        let buffer = &display_map.buffer_snapshot;
 8783        let query_matches = select_next_state
 8784            .query
 8785            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8786
 8787        for query_match in query_matches {
 8788            let query_match = query_match.unwrap(); // can only fail due to I/O
 8789            let offset_range = query_match.start()..query_match.end();
 8790            let display_range = offset_range.start.to_display_point(&display_map)
 8791                ..offset_range.end.to_display_point(&display_map);
 8792
 8793            if !select_next_state.wordwise
 8794                || (!movement::is_inside_word(&display_map, display_range.start)
 8795                    && !movement::is_inside_word(&display_map, display_range.end))
 8796            {
 8797                self.selections.change_with(cx, |selections| {
 8798                    new_selections.push(Selection {
 8799                        id: selections.new_selection_id(),
 8800                        start: offset_range.start,
 8801                        end: offset_range.end,
 8802                        reversed: false,
 8803                        goal: SelectionGoal::None,
 8804                    });
 8805                });
 8806            }
 8807        }
 8808
 8809        new_selections.sort_by_key(|selection| selection.start);
 8810        let mut ix = 0;
 8811        while ix + 1 < new_selections.len() {
 8812            let current_selection = &new_selections[ix];
 8813            let next_selection = &new_selections[ix + 1];
 8814            if current_selection.range().overlaps(&next_selection.range()) {
 8815                if current_selection.id < next_selection.id {
 8816                    new_selections.remove(ix + 1);
 8817                } else {
 8818                    new_selections.remove(ix);
 8819                }
 8820            } else {
 8821                ix += 1;
 8822            }
 8823        }
 8824
 8825        select_next_state.done = true;
 8826        self.unfold_ranges(
 8827            &new_selections
 8828                .iter()
 8829                .map(|selection| selection.range())
 8830                .collect::<Vec<_>>(),
 8831            false,
 8832            false,
 8833            cx,
 8834        );
 8835        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 8836            selections.select(new_selections)
 8837        });
 8838
 8839        Ok(())
 8840    }
 8841
 8842    pub fn select_next(
 8843        &mut self,
 8844        action: &SelectNext,
 8845        window: &mut Window,
 8846        cx: &mut Context<Self>,
 8847    ) -> Result<()> {
 8848        self.push_to_selection_history();
 8849        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8850        self.select_next_match_internal(
 8851            &display_map,
 8852            action.replace_newest,
 8853            Some(Autoscroll::newest()),
 8854            window,
 8855            cx,
 8856        )?;
 8857        Ok(())
 8858    }
 8859
 8860    pub fn select_previous(
 8861        &mut self,
 8862        action: &SelectPrevious,
 8863        window: &mut Window,
 8864        cx: &mut Context<Self>,
 8865    ) -> Result<()> {
 8866        self.push_to_selection_history();
 8867        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8868        let buffer = &display_map.buffer_snapshot;
 8869        let mut selections = self.selections.all::<usize>(cx);
 8870        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8871            let query = &select_prev_state.query;
 8872            if !select_prev_state.done {
 8873                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8874                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8875                let mut next_selected_range = None;
 8876                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8877                let bytes_before_last_selection =
 8878                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8879                let bytes_after_first_selection =
 8880                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8881                let query_matches = query
 8882                    .stream_find_iter(bytes_before_last_selection)
 8883                    .map(|result| (last_selection.start, result))
 8884                    .chain(
 8885                        query
 8886                            .stream_find_iter(bytes_after_first_selection)
 8887                            .map(|result| (buffer.len(), result)),
 8888                    );
 8889                for (end_offset, query_match) in query_matches {
 8890                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8891                    let offset_range =
 8892                        end_offset - query_match.end()..end_offset - query_match.start();
 8893                    let display_range = offset_range.start.to_display_point(&display_map)
 8894                        ..offset_range.end.to_display_point(&display_map);
 8895
 8896                    if !select_prev_state.wordwise
 8897                        || (!movement::is_inside_word(&display_map, display_range.start)
 8898                            && !movement::is_inside_word(&display_map, display_range.end))
 8899                    {
 8900                        next_selected_range = Some(offset_range);
 8901                        break;
 8902                    }
 8903                }
 8904
 8905                if let Some(next_selected_range) = next_selected_range {
 8906                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8907                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8908                        if action.replace_newest {
 8909                            s.delete(s.newest_anchor().id);
 8910                        }
 8911                        s.insert_range(next_selected_range);
 8912                    });
 8913                } else {
 8914                    select_prev_state.done = true;
 8915                }
 8916            }
 8917
 8918            self.select_prev_state = Some(select_prev_state);
 8919        } else {
 8920            let mut only_carets = true;
 8921            let mut same_text_selected = true;
 8922            let mut selected_text = None;
 8923
 8924            let mut selections_iter = selections.iter().peekable();
 8925            while let Some(selection) = selections_iter.next() {
 8926                if selection.start != selection.end {
 8927                    only_carets = false;
 8928                }
 8929
 8930                if same_text_selected {
 8931                    if selected_text.is_none() {
 8932                        selected_text =
 8933                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8934                    }
 8935
 8936                    if let Some(next_selection) = selections_iter.peek() {
 8937                        if next_selection.range().len() == selection.range().len() {
 8938                            let next_selected_text = buffer
 8939                                .text_for_range(next_selection.range())
 8940                                .collect::<String>();
 8941                            if Some(next_selected_text) != selected_text {
 8942                                same_text_selected = false;
 8943                                selected_text = None;
 8944                            }
 8945                        } else {
 8946                            same_text_selected = false;
 8947                            selected_text = None;
 8948                        }
 8949                    }
 8950                }
 8951            }
 8952
 8953            if only_carets {
 8954                for selection in &mut selections {
 8955                    let word_range = movement::surrounding_word(
 8956                        &display_map,
 8957                        selection.start.to_display_point(&display_map),
 8958                    );
 8959                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8960                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8961                    selection.goal = SelectionGoal::None;
 8962                    selection.reversed = false;
 8963                }
 8964                if selections.len() == 1 {
 8965                    let selection = selections
 8966                        .last()
 8967                        .expect("ensured that there's only one selection");
 8968                    let query = buffer
 8969                        .text_for_range(selection.start..selection.end)
 8970                        .collect::<String>();
 8971                    let is_empty = query.is_empty();
 8972                    let select_state = SelectNextState {
 8973                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8974                        wordwise: true,
 8975                        done: is_empty,
 8976                    };
 8977                    self.select_prev_state = Some(select_state);
 8978                } else {
 8979                    self.select_prev_state = None;
 8980                }
 8981
 8982                self.unfold_ranges(
 8983                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8984                    false,
 8985                    true,
 8986                    cx,
 8987                );
 8988                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8989                    s.select(selections);
 8990                });
 8991            } else if let Some(selected_text) = selected_text {
 8992                self.select_prev_state = Some(SelectNextState {
 8993                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8994                    wordwise: false,
 8995                    done: false,
 8996                });
 8997                self.select_previous(action, window, cx)?;
 8998            }
 8999        }
 9000        Ok(())
 9001    }
 9002
 9003    pub fn toggle_comments(
 9004        &mut self,
 9005        action: &ToggleComments,
 9006        window: &mut Window,
 9007        cx: &mut Context<Self>,
 9008    ) {
 9009        if self.read_only(cx) {
 9010            return;
 9011        }
 9012        let text_layout_details = &self.text_layout_details(window);
 9013        self.transact(window, cx, |this, window, cx| {
 9014            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9015            let mut edits = Vec::new();
 9016            let mut selection_edit_ranges = Vec::new();
 9017            let mut last_toggled_row = None;
 9018            let snapshot = this.buffer.read(cx).read(cx);
 9019            let empty_str: Arc<str> = Arc::default();
 9020            let mut suffixes_inserted = Vec::new();
 9021            let ignore_indent = action.ignore_indent;
 9022
 9023            fn comment_prefix_range(
 9024                snapshot: &MultiBufferSnapshot,
 9025                row: MultiBufferRow,
 9026                comment_prefix: &str,
 9027                comment_prefix_whitespace: &str,
 9028                ignore_indent: bool,
 9029            ) -> Range<Point> {
 9030                let indent_size = if ignore_indent {
 9031                    0
 9032                } else {
 9033                    snapshot.indent_size_for_line(row).len
 9034                };
 9035
 9036                let start = Point::new(row.0, indent_size);
 9037
 9038                let mut line_bytes = snapshot
 9039                    .bytes_in_range(start..snapshot.max_point())
 9040                    .flatten()
 9041                    .copied();
 9042
 9043                // If this line currently begins with the line comment prefix, then record
 9044                // the range containing the prefix.
 9045                if line_bytes
 9046                    .by_ref()
 9047                    .take(comment_prefix.len())
 9048                    .eq(comment_prefix.bytes())
 9049                {
 9050                    // Include any whitespace that matches the comment prefix.
 9051                    let matching_whitespace_len = line_bytes
 9052                        .zip(comment_prefix_whitespace.bytes())
 9053                        .take_while(|(a, b)| a == b)
 9054                        .count() as u32;
 9055                    let end = Point::new(
 9056                        start.row,
 9057                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9058                    );
 9059                    start..end
 9060                } else {
 9061                    start..start
 9062                }
 9063            }
 9064
 9065            fn comment_suffix_range(
 9066                snapshot: &MultiBufferSnapshot,
 9067                row: MultiBufferRow,
 9068                comment_suffix: &str,
 9069                comment_suffix_has_leading_space: bool,
 9070            ) -> Range<Point> {
 9071                let end = Point::new(row.0, snapshot.line_len(row));
 9072                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9073
 9074                let mut line_end_bytes = snapshot
 9075                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9076                    .flatten()
 9077                    .copied();
 9078
 9079                let leading_space_len = if suffix_start_column > 0
 9080                    && line_end_bytes.next() == Some(b' ')
 9081                    && comment_suffix_has_leading_space
 9082                {
 9083                    1
 9084                } else {
 9085                    0
 9086                };
 9087
 9088                // If this line currently begins with the line comment prefix, then record
 9089                // the range containing the prefix.
 9090                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9091                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9092                    start..end
 9093                } else {
 9094                    end..end
 9095                }
 9096            }
 9097
 9098            // TODO: Handle selections that cross excerpts
 9099            for selection in &mut selections {
 9100                let start_column = snapshot
 9101                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9102                    .len;
 9103                let language = if let Some(language) =
 9104                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9105                {
 9106                    language
 9107                } else {
 9108                    continue;
 9109                };
 9110
 9111                selection_edit_ranges.clear();
 9112
 9113                // If multiple selections contain a given row, avoid processing that
 9114                // row more than once.
 9115                let mut start_row = MultiBufferRow(selection.start.row);
 9116                if last_toggled_row == Some(start_row) {
 9117                    start_row = start_row.next_row();
 9118                }
 9119                let end_row =
 9120                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9121                        MultiBufferRow(selection.end.row - 1)
 9122                    } else {
 9123                        MultiBufferRow(selection.end.row)
 9124                    };
 9125                last_toggled_row = Some(end_row);
 9126
 9127                if start_row > end_row {
 9128                    continue;
 9129                }
 9130
 9131                // If the language has line comments, toggle those.
 9132                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9133
 9134                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9135                if ignore_indent {
 9136                    full_comment_prefixes = full_comment_prefixes
 9137                        .into_iter()
 9138                        .map(|s| Arc::from(s.trim_end()))
 9139                        .collect();
 9140                }
 9141
 9142                if !full_comment_prefixes.is_empty() {
 9143                    let first_prefix = full_comment_prefixes
 9144                        .first()
 9145                        .expect("prefixes is non-empty");
 9146                    let prefix_trimmed_lengths = full_comment_prefixes
 9147                        .iter()
 9148                        .map(|p| p.trim_end_matches(' ').len())
 9149                        .collect::<SmallVec<[usize; 4]>>();
 9150
 9151                    let mut all_selection_lines_are_comments = true;
 9152
 9153                    for row in start_row.0..=end_row.0 {
 9154                        let row = MultiBufferRow(row);
 9155                        if start_row < end_row && snapshot.is_line_blank(row) {
 9156                            continue;
 9157                        }
 9158
 9159                        let prefix_range = full_comment_prefixes
 9160                            .iter()
 9161                            .zip(prefix_trimmed_lengths.iter().copied())
 9162                            .map(|(prefix, trimmed_prefix_len)| {
 9163                                comment_prefix_range(
 9164                                    snapshot.deref(),
 9165                                    row,
 9166                                    &prefix[..trimmed_prefix_len],
 9167                                    &prefix[trimmed_prefix_len..],
 9168                                    ignore_indent,
 9169                                )
 9170                            })
 9171                            .max_by_key(|range| range.end.column - range.start.column)
 9172                            .expect("prefixes is non-empty");
 9173
 9174                        if prefix_range.is_empty() {
 9175                            all_selection_lines_are_comments = false;
 9176                        }
 9177
 9178                        selection_edit_ranges.push(prefix_range);
 9179                    }
 9180
 9181                    if all_selection_lines_are_comments {
 9182                        edits.extend(
 9183                            selection_edit_ranges
 9184                                .iter()
 9185                                .cloned()
 9186                                .map(|range| (range, empty_str.clone())),
 9187                        );
 9188                    } else {
 9189                        let min_column = selection_edit_ranges
 9190                            .iter()
 9191                            .map(|range| range.start.column)
 9192                            .min()
 9193                            .unwrap_or(0);
 9194                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9195                            let position = Point::new(range.start.row, min_column);
 9196                            (position..position, first_prefix.clone())
 9197                        }));
 9198                    }
 9199                } else if let Some((full_comment_prefix, comment_suffix)) =
 9200                    language.block_comment_delimiters()
 9201                {
 9202                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9203                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9204                    let prefix_range = comment_prefix_range(
 9205                        snapshot.deref(),
 9206                        start_row,
 9207                        comment_prefix,
 9208                        comment_prefix_whitespace,
 9209                        ignore_indent,
 9210                    );
 9211                    let suffix_range = comment_suffix_range(
 9212                        snapshot.deref(),
 9213                        end_row,
 9214                        comment_suffix.trim_start_matches(' '),
 9215                        comment_suffix.starts_with(' '),
 9216                    );
 9217
 9218                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9219                        edits.push((
 9220                            prefix_range.start..prefix_range.start,
 9221                            full_comment_prefix.clone(),
 9222                        ));
 9223                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9224                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9225                    } else {
 9226                        edits.push((prefix_range, empty_str.clone()));
 9227                        edits.push((suffix_range, empty_str.clone()));
 9228                    }
 9229                } else {
 9230                    continue;
 9231                }
 9232            }
 9233
 9234            drop(snapshot);
 9235            this.buffer.update(cx, |buffer, cx| {
 9236                buffer.edit(edits, None, cx);
 9237            });
 9238
 9239            // Adjust selections so that they end before any comment suffixes that
 9240            // were inserted.
 9241            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9242            let mut selections = this.selections.all::<Point>(cx);
 9243            let snapshot = this.buffer.read(cx).read(cx);
 9244            for selection in &mut selections {
 9245                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9246                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9247                        Ordering::Less => {
 9248                            suffixes_inserted.next();
 9249                            continue;
 9250                        }
 9251                        Ordering::Greater => break,
 9252                        Ordering::Equal => {
 9253                            if selection.end.column == snapshot.line_len(row) {
 9254                                if selection.is_empty() {
 9255                                    selection.start.column -= suffix_len as u32;
 9256                                }
 9257                                selection.end.column -= suffix_len as u32;
 9258                            }
 9259                            break;
 9260                        }
 9261                    }
 9262                }
 9263            }
 9264
 9265            drop(snapshot);
 9266            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9267                s.select(selections)
 9268            });
 9269
 9270            let selections = this.selections.all::<Point>(cx);
 9271            let selections_on_single_row = selections.windows(2).all(|selections| {
 9272                selections[0].start.row == selections[1].start.row
 9273                    && selections[0].end.row == selections[1].end.row
 9274                    && selections[0].start.row == selections[0].end.row
 9275            });
 9276            let selections_selecting = selections
 9277                .iter()
 9278                .any(|selection| selection.start != selection.end);
 9279            let advance_downwards = action.advance_downwards
 9280                && selections_on_single_row
 9281                && !selections_selecting
 9282                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9283
 9284            if advance_downwards {
 9285                let snapshot = this.buffer.read(cx).snapshot(cx);
 9286
 9287                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9288                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9289                        let mut point = display_point.to_point(display_snapshot);
 9290                        point.row += 1;
 9291                        point = snapshot.clip_point(point, Bias::Left);
 9292                        let display_point = point.to_display_point(display_snapshot);
 9293                        let goal = SelectionGoal::HorizontalPosition(
 9294                            display_snapshot
 9295                                .x_for_display_point(display_point, text_layout_details)
 9296                                .into(),
 9297                        );
 9298                        (display_point, goal)
 9299                    })
 9300                });
 9301            }
 9302        });
 9303    }
 9304
 9305    pub fn select_enclosing_symbol(
 9306        &mut self,
 9307        _: &SelectEnclosingSymbol,
 9308        window: &mut Window,
 9309        cx: &mut Context<Self>,
 9310    ) {
 9311        let buffer = self.buffer.read(cx).snapshot(cx);
 9312        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9313
 9314        fn update_selection(
 9315            selection: &Selection<usize>,
 9316            buffer_snap: &MultiBufferSnapshot,
 9317        ) -> Option<Selection<usize>> {
 9318            let cursor = selection.head();
 9319            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9320            for symbol in symbols.iter().rev() {
 9321                let start = symbol.range.start.to_offset(buffer_snap);
 9322                let end = symbol.range.end.to_offset(buffer_snap);
 9323                let new_range = start..end;
 9324                if start < selection.start || end > selection.end {
 9325                    return Some(Selection {
 9326                        id: selection.id,
 9327                        start: new_range.start,
 9328                        end: new_range.end,
 9329                        goal: SelectionGoal::None,
 9330                        reversed: selection.reversed,
 9331                    });
 9332                }
 9333            }
 9334            None
 9335        }
 9336
 9337        let mut selected_larger_symbol = false;
 9338        let new_selections = old_selections
 9339            .iter()
 9340            .map(|selection| match update_selection(selection, &buffer) {
 9341                Some(new_selection) => {
 9342                    if new_selection.range() != selection.range() {
 9343                        selected_larger_symbol = true;
 9344                    }
 9345                    new_selection
 9346                }
 9347                None => selection.clone(),
 9348            })
 9349            .collect::<Vec<_>>();
 9350
 9351        if selected_larger_symbol {
 9352            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9353                s.select(new_selections);
 9354            });
 9355        }
 9356    }
 9357
 9358    pub fn select_larger_syntax_node(
 9359        &mut self,
 9360        _: &SelectLargerSyntaxNode,
 9361        window: &mut Window,
 9362        cx: &mut Context<Self>,
 9363    ) {
 9364        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9365        let buffer = self.buffer.read(cx).snapshot(cx);
 9366        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9367
 9368        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9369        let mut selected_larger_node = false;
 9370        let new_selections = old_selections
 9371            .iter()
 9372            .map(|selection| {
 9373                let old_range = selection.start..selection.end;
 9374                let mut new_range = old_range.clone();
 9375                let mut new_node = None;
 9376                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9377                {
 9378                    new_node = Some(node);
 9379                    new_range = containing_range;
 9380                    if !display_map.intersects_fold(new_range.start)
 9381                        && !display_map.intersects_fold(new_range.end)
 9382                    {
 9383                        break;
 9384                    }
 9385                }
 9386
 9387                if let Some(node) = new_node {
 9388                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9389                    // nodes. Parent and grandparent are also logged because this operation will not
 9390                    // visit nodes that have the same range as their parent.
 9391                    log::info!("Node: {node:?}");
 9392                    let parent = node.parent();
 9393                    log::info!("Parent: {parent:?}");
 9394                    let grandparent = parent.and_then(|x| x.parent());
 9395                    log::info!("Grandparent: {grandparent:?}");
 9396                }
 9397
 9398                selected_larger_node |= new_range != old_range;
 9399                Selection {
 9400                    id: selection.id,
 9401                    start: new_range.start,
 9402                    end: new_range.end,
 9403                    goal: SelectionGoal::None,
 9404                    reversed: selection.reversed,
 9405                }
 9406            })
 9407            .collect::<Vec<_>>();
 9408
 9409        if selected_larger_node {
 9410            stack.push(old_selections);
 9411            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9412                s.select(new_selections);
 9413            });
 9414        }
 9415        self.select_larger_syntax_node_stack = stack;
 9416    }
 9417
 9418    pub fn select_smaller_syntax_node(
 9419        &mut self,
 9420        _: &SelectSmallerSyntaxNode,
 9421        window: &mut Window,
 9422        cx: &mut Context<Self>,
 9423    ) {
 9424        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9425        if let Some(selections) = stack.pop() {
 9426            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9427                s.select(selections.to_vec());
 9428            });
 9429        }
 9430        self.select_larger_syntax_node_stack = stack;
 9431    }
 9432
 9433    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9434        if !EditorSettings::get_global(cx).gutter.runnables {
 9435            self.clear_tasks();
 9436            return Task::ready(());
 9437        }
 9438        let project = self.project.as_ref().map(Entity::downgrade);
 9439        cx.spawn_in(window, |this, mut cx| async move {
 9440            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9441            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9442                return;
 9443            };
 9444            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9445                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9446            }) else {
 9447                return;
 9448            };
 9449
 9450            let hide_runnables = project
 9451                .update(&mut cx, |project, cx| {
 9452                    // Do not display any test indicators in non-dev server remote projects.
 9453                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9454                })
 9455                .unwrap_or(true);
 9456            if hide_runnables {
 9457                return;
 9458            }
 9459            let new_rows =
 9460                cx.background_executor()
 9461                    .spawn({
 9462                        let snapshot = display_snapshot.clone();
 9463                        async move {
 9464                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9465                        }
 9466                    })
 9467                    .await;
 9468
 9469            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9470            this.update(&mut cx, |this, _| {
 9471                this.clear_tasks();
 9472                for (key, value) in rows {
 9473                    this.insert_tasks(key, value);
 9474                }
 9475            })
 9476            .ok();
 9477        })
 9478    }
 9479    fn fetch_runnable_ranges(
 9480        snapshot: &DisplaySnapshot,
 9481        range: Range<Anchor>,
 9482    ) -> Vec<language::RunnableRange> {
 9483        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9484    }
 9485
 9486    fn runnable_rows(
 9487        project: Entity<Project>,
 9488        snapshot: DisplaySnapshot,
 9489        runnable_ranges: Vec<RunnableRange>,
 9490        mut cx: AsyncWindowContext,
 9491    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9492        runnable_ranges
 9493            .into_iter()
 9494            .filter_map(|mut runnable| {
 9495                let tasks = cx
 9496                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9497                    .ok()?;
 9498                if tasks.is_empty() {
 9499                    return None;
 9500                }
 9501
 9502                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9503
 9504                let row = snapshot
 9505                    .buffer_snapshot
 9506                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9507                    .1
 9508                    .start
 9509                    .row;
 9510
 9511                let context_range =
 9512                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9513                Some((
 9514                    (runnable.buffer_id, row),
 9515                    RunnableTasks {
 9516                        templates: tasks,
 9517                        offset: MultiBufferOffset(runnable.run_range.start),
 9518                        context_range,
 9519                        column: point.column,
 9520                        extra_variables: runnable.extra_captures,
 9521                    },
 9522                ))
 9523            })
 9524            .collect()
 9525    }
 9526
 9527    fn templates_with_tags(
 9528        project: &Entity<Project>,
 9529        runnable: &mut Runnable,
 9530        cx: &mut App,
 9531    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9532        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9533            let (worktree_id, file) = project
 9534                .buffer_for_id(runnable.buffer, cx)
 9535                .and_then(|buffer| buffer.read(cx).file())
 9536                .map(|file| (file.worktree_id(cx), file.clone()))
 9537                .unzip();
 9538
 9539            (
 9540                project.task_store().read(cx).task_inventory().cloned(),
 9541                worktree_id,
 9542                file,
 9543            )
 9544        });
 9545
 9546        let tags = mem::take(&mut runnable.tags);
 9547        let mut tags: Vec<_> = tags
 9548            .into_iter()
 9549            .flat_map(|tag| {
 9550                let tag = tag.0.clone();
 9551                inventory
 9552                    .as_ref()
 9553                    .into_iter()
 9554                    .flat_map(|inventory| {
 9555                        inventory.read(cx).list_tasks(
 9556                            file.clone(),
 9557                            Some(runnable.language.clone()),
 9558                            worktree_id,
 9559                            cx,
 9560                        )
 9561                    })
 9562                    .filter(move |(_, template)| {
 9563                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9564                    })
 9565            })
 9566            .sorted_by_key(|(kind, _)| kind.to_owned())
 9567            .collect();
 9568        if let Some((leading_tag_source, _)) = tags.first() {
 9569            // Strongest source wins; if we have worktree tag binding, prefer that to
 9570            // global and language bindings;
 9571            // if we have a global binding, prefer that to language binding.
 9572            let first_mismatch = tags
 9573                .iter()
 9574                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9575            if let Some(index) = first_mismatch {
 9576                tags.truncate(index);
 9577            }
 9578        }
 9579
 9580        tags
 9581    }
 9582
 9583    pub fn move_to_enclosing_bracket(
 9584        &mut self,
 9585        _: &MoveToEnclosingBracket,
 9586        window: &mut Window,
 9587        cx: &mut Context<Self>,
 9588    ) {
 9589        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9590            s.move_offsets_with(|snapshot, selection| {
 9591                let Some(enclosing_bracket_ranges) =
 9592                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9593                else {
 9594                    return;
 9595                };
 9596
 9597                let mut best_length = usize::MAX;
 9598                let mut best_inside = false;
 9599                let mut best_in_bracket_range = false;
 9600                let mut best_destination = None;
 9601                for (open, close) in enclosing_bracket_ranges {
 9602                    let close = close.to_inclusive();
 9603                    let length = close.end() - open.start;
 9604                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9605                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9606                        || close.contains(&selection.head());
 9607
 9608                    // If best is next to a bracket and current isn't, skip
 9609                    if !in_bracket_range && best_in_bracket_range {
 9610                        continue;
 9611                    }
 9612
 9613                    // Prefer smaller lengths unless best is inside and current isn't
 9614                    if length > best_length && (best_inside || !inside) {
 9615                        continue;
 9616                    }
 9617
 9618                    best_length = length;
 9619                    best_inside = inside;
 9620                    best_in_bracket_range = in_bracket_range;
 9621                    best_destination = Some(
 9622                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9623                            if inside {
 9624                                open.end
 9625                            } else {
 9626                                open.start
 9627                            }
 9628                        } else if inside {
 9629                            *close.start()
 9630                        } else {
 9631                            *close.end()
 9632                        },
 9633                    );
 9634                }
 9635
 9636                if let Some(destination) = best_destination {
 9637                    selection.collapse_to(destination, SelectionGoal::None);
 9638                }
 9639            })
 9640        });
 9641    }
 9642
 9643    pub fn undo_selection(
 9644        &mut self,
 9645        _: &UndoSelection,
 9646        window: &mut Window,
 9647        cx: &mut Context<Self>,
 9648    ) {
 9649        self.end_selection(window, cx);
 9650        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9651        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9652            self.change_selections(None, window, cx, |s| {
 9653                s.select_anchors(entry.selections.to_vec())
 9654            });
 9655            self.select_next_state = entry.select_next_state;
 9656            self.select_prev_state = entry.select_prev_state;
 9657            self.add_selections_state = entry.add_selections_state;
 9658            self.request_autoscroll(Autoscroll::newest(), cx);
 9659        }
 9660        self.selection_history.mode = SelectionHistoryMode::Normal;
 9661    }
 9662
 9663    pub fn redo_selection(
 9664        &mut self,
 9665        _: &RedoSelection,
 9666        window: &mut Window,
 9667        cx: &mut Context<Self>,
 9668    ) {
 9669        self.end_selection(window, cx);
 9670        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9671        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9672            self.change_selections(None, window, cx, |s| {
 9673                s.select_anchors(entry.selections.to_vec())
 9674            });
 9675            self.select_next_state = entry.select_next_state;
 9676            self.select_prev_state = entry.select_prev_state;
 9677            self.add_selections_state = entry.add_selections_state;
 9678            self.request_autoscroll(Autoscroll::newest(), cx);
 9679        }
 9680        self.selection_history.mode = SelectionHistoryMode::Normal;
 9681    }
 9682
 9683    pub fn expand_excerpts(
 9684        &mut self,
 9685        action: &ExpandExcerpts,
 9686        _: &mut Window,
 9687        cx: &mut Context<Self>,
 9688    ) {
 9689        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9690    }
 9691
 9692    pub fn expand_excerpts_down(
 9693        &mut self,
 9694        action: &ExpandExcerptsDown,
 9695        _: &mut Window,
 9696        cx: &mut Context<Self>,
 9697    ) {
 9698        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9699    }
 9700
 9701    pub fn expand_excerpts_up(
 9702        &mut self,
 9703        action: &ExpandExcerptsUp,
 9704        _: &mut Window,
 9705        cx: &mut Context<Self>,
 9706    ) {
 9707        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9708    }
 9709
 9710    pub fn expand_excerpts_for_direction(
 9711        &mut self,
 9712        lines: u32,
 9713        direction: ExpandExcerptDirection,
 9714
 9715        cx: &mut Context<Self>,
 9716    ) {
 9717        let selections = self.selections.disjoint_anchors();
 9718
 9719        let lines = if lines == 0 {
 9720            EditorSettings::get_global(cx).expand_excerpt_lines
 9721        } else {
 9722            lines
 9723        };
 9724
 9725        self.buffer.update(cx, |buffer, cx| {
 9726            let snapshot = buffer.snapshot(cx);
 9727            let mut excerpt_ids = selections
 9728                .iter()
 9729                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
 9730                .collect::<Vec<_>>();
 9731            excerpt_ids.sort();
 9732            excerpt_ids.dedup();
 9733            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9734        })
 9735    }
 9736
 9737    pub fn expand_excerpt(
 9738        &mut self,
 9739        excerpt: ExcerptId,
 9740        direction: ExpandExcerptDirection,
 9741        cx: &mut Context<Self>,
 9742    ) {
 9743        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9744        self.buffer.update(cx, |buffer, cx| {
 9745            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9746        })
 9747    }
 9748
 9749    pub fn go_to_singleton_buffer_point(
 9750        &mut self,
 9751        point: Point,
 9752        window: &mut Window,
 9753        cx: &mut Context<Self>,
 9754    ) {
 9755        self.go_to_singleton_buffer_range(point..point, window, cx);
 9756    }
 9757
 9758    pub fn go_to_singleton_buffer_range(
 9759        &mut self,
 9760        range: Range<Point>,
 9761        window: &mut Window,
 9762        cx: &mut Context<Self>,
 9763    ) {
 9764        let multibuffer = self.buffer().read(cx);
 9765        let Some(buffer) = multibuffer.as_singleton() else {
 9766            return;
 9767        };
 9768        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
 9769            return;
 9770        };
 9771        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
 9772            return;
 9773        };
 9774        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
 9775            s.select_anchor_ranges([start..end])
 9776        });
 9777    }
 9778
 9779    fn go_to_diagnostic(
 9780        &mut self,
 9781        _: &GoToDiagnostic,
 9782        window: &mut Window,
 9783        cx: &mut Context<Self>,
 9784    ) {
 9785        self.go_to_diagnostic_impl(Direction::Next, window, cx)
 9786    }
 9787
 9788    fn go_to_prev_diagnostic(
 9789        &mut self,
 9790        _: &GoToPrevDiagnostic,
 9791        window: &mut Window,
 9792        cx: &mut Context<Self>,
 9793    ) {
 9794        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
 9795    }
 9796
 9797    pub fn go_to_diagnostic_impl(
 9798        &mut self,
 9799        direction: Direction,
 9800        window: &mut Window,
 9801        cx: &mut Context<Self>,
 9802    ) {
 9803        let buffer = self.buffer.read(cx).snapshot(cx);
 9804        let selection = self.selections.newest::<usize>(cx);
 9805
 9806        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9807        if direction == Direction::Next {
 9808            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9809                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
 9810                    return;
 9811                };
 9812                self.activate_diagnostics(
 9813                    buffer_id,
 9814                    popover.local_diagnostic.diagnostic.group_id,
 9815                    window,
 9816                    cx,
 9817                );
 9818                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9819                    let primary_range_start = active_diagnostics.primary_range.start;
 9820                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9821                        let mut new_selection = s.newest_anchor().clone();
 9822                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9823                        s.select_anchors(vec![new_selection.clone()]);
 9824                    });
 9825                    self.refresh_inline_completion(false, true, window, cx);
 9826                }
 9827                return;
 9828            }
 9829        }
 9830
 9831        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9832            active_diagnostics
 9833                .primary_range
 9834                .to_offset(&buffer)
 9835                .to_inclusive()
 9836        });
 9837        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9838            if active_primary_range.contains(&selection.head()) {
 9839                *active_primary_range.start()
 9840            } else {
 9841                selection.head()
 9842            }
 9843        } else {
 9844            selection.head()
 9845        };
 9846        let snapshot = self.snapshot(window, cx);
 9847        loop {
 9848            let mut diagnostics;
 9849            if direction == Direction::Prev {
 9850                diagnostics = buffer
 9851                    .diagnostics_in_range::<_, usize>(0..search_start)
 9852                    .collect::<Vec<_>>();
 9853                diagnostics.reverse();
 9854            } else {
 9855                diagnostics = buffer
 9856                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
 9857                    .collect::<Vec<_>>();
 9858            };
 9859            let group = diagnostics
 9860                .into_iter()
 9861                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
 9862                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9863                // be sorted in a stable way
 9864                // skip until we are at current active diagnostic, if it exists
 9865                .skip_while(|entry| {
 9866                    let is_in_range = match direction {
 9867                        Direction::Prev => entry.range.end > search_start,
 9868                        Direction::Next => entry.range.start < search_start,
 9869                    };
 9870                    is_in_range
 9871                        && self
 9872                            .active_diagnostics
 9873                            .as_ref()
 9874                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9875                })
 9876                .find_map(|entry| {
 9877                    if entry.diagnostic.is_primary
 9878                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9879                        && entry.range.start != entry.range.end
 9880                        // if we match with the active diagnostic, skip it
 9881                        && Some(entry.diagnostic.group_id)
 9882                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9883                    {
 9884                        Some((entry.range, entry.diagnostic.group_id))
 9885                    } else {
 9886                        None
 9887                    }
 9888                });
 9889
 9890            if let Some((primary_range, group_id)) = group {
 9891                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
 9892                    return;
 9893                };
 9894                self.activate_diagnostics(buffer_id, group_id, window, cx);
 9895                if self.active_diagnostics.is_some() {
 9896                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9897                        s.select(vec![Selection {
 9898                            id: selection.id,
 9899                            start: primary_range.start,
 9900                            end: primary_range.start,
 9901                            reversed: false,
 9902                            goal: SelectionGoal::None,
 9903                        }]);
 9904                    });
 9905                    self.refresh_inline_completion(false, true, window, cx);
 9906                }
 9907                break;
 9908            } else {
 9909                // Cycle around to the start of the buffer, potentially moving back to the start of
 9910                // the currently active diagnostic.
 9911                active_primary_range.take();
 9912                if direction == Direction::Prev {
 9913                    if search_start == buffer.len() {
 9914                        break;
 9915                    } else {
 9916                        search_start = buffer.len();
 9917                    }
 9918                } else if search_start == 0 {
 9919                    break;
 9920                } else {
 9921                    search_start = 0;
 9922                }
 9923            }
 9924        }
 9925    }
 9926
 9927    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
 9928        let snapshot = self.snapshot(window, cx);
 9929        let selection = self.selections.newest::<Point>(cx);
 9930        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
 9931    }
 9932
 9933    fn go_to_hunk_after_position(
 9934        &mut self,
 9935        snapshot: &EditorSnapshot,
 9936        position: Point,
 9937        window: &mut Window,
 9938        cx: &mut Context<Editor>,
 9939    ) -> Option<MultiBufferDiffHunk> {
 9940        let mut hunk = snapshot
 9941            .buffer_snapshot
 9942            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
 9943            .find(|hunk| hunk.row_range.start.0 > position.row);
 9944        if hunk.is_none() {
 9945            hunk = snapshot
 9946                .buffer_snapshot
 9947                .diff_hunks_in_range(Point::zero()..position)
 9948                .find(|hunk| hunk.row_range.end.0 < position.row)
 9949        }
 9950        if let Some(hunk) = &hunk {
 9951            let destination = Point::new(hunk.row_range.start.0, 0);
 9952            self.unfold_ranges(&[destination..destination], false, false, cx);
 9953            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9954                s.select_ranges(vec![destination..destination]);
 9955            });
 9956        }
 9957
 9958        hunk
 9959    }
 9960
 9961    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
 9962        let snapshot = self.snapshot(window, cx);
 9963        let selection = self.selections.newest::<Point>(cx);
 9964        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
 9965    }
 9966
 9967    fn go_to_hunk_before_position(
 9968        &mut self,
 9969        snapshot: &EditorSnapshot,
 9970        position: Point,
 9971        window: &mut Window,
 9972        cx: &mut Context<Editor>,
 9973    ) -> Option<MultiBufferDiffHunk> {
 9974        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
 9975        if hunk.is_none() {
 9976            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
 9977        }
 9978        if let Some(hunk) = &hunk {
 9979            let destination = Point::new(hunk.row_range.start.0, 0);
 9980            self.unfold_ranges(&[destination..destination], false, false, cx);
 9981            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9982                s.select_ranges(vec![destination..destination]);
 9983            });
 9984        }
 9985
 9986        hunk
 9987    }
 9988
 9989    pub fn go_to_definition(
 9990        &mut self,
 9991        _: &GoToDefinition,
 9992        window: &mut Window,
 9993        cx: &mut Context<Self>,
 9994    ) -> Task<Result<Navigated>> {
 9995        let definition =
 9996            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
 9997        cx.spawn_in(window, |editor, mut cx| async move {
 9998            if definition.await? == Navigated::Yes {
 9999                return Ok(Navigated::Yes);
10000            }
10001            match editor.update_in(&mut cx, |editor, window, cx| {
10002                editor.find_all_references(&FindAllReferences, window, cx)
10003            })? {
10004                Some(references) => references.await,
10005                None => Ok(Navigated::No),
10006            }
10007        })
10008    }
10009
10010    pub fn go_to_declaration(
10011        &mut self,
10012        _: &GoToDeclaration,
10013        window: &mut Window,
10014        cx: &mut Context<Self>,
10015    ) -> Task<Result<Navigated>> {
10016        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10017    }
10018
10019    pub fn go_to_declaration_split(
10020        &mut self,
10021        _: &GoToDeclaration,
10022        window: &mut Window,
10023        cx: &mut Context<Self>,
10024    ) -> Task<Result<Navigated>> {
10025        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10026    }
10027
10028    pub fn go_to_implementation(
10029        &mut self,
10030        _: &GoToImplementation,
10031        window: &mut Window,
10032        cx: &mut Context<Self>,
10033    ) -> Task<Result<Navigated>> {
10034        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10035    }
10036
10037    pub fn go_to_implementation_split(
10038        &mut self,
10039        _: &GoToImplementationSplit,
10040        window: &mut Window,
10041        cx: &mut Context<Self>,
10042    ) -> Task<Result<Navigated>> {
10043        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10044    }
10045
10046    pub fn go_to_type_definition(
10047        &mut self,
10048        _: &GoToTypeDefinition,
10049        window: &mut Window,
10050        cx: &mut Context<Self>,
10051    ) -> Task<Result<Navigated>> {
10052        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10053    }
10054
10055    pub fn go_to_definition_split(
10056        &mut self,
10057        _: &GoToDefinitionSplit,
10058        window: &mut Window,
10059        cx: &mut Context<Self>,
10060    ) -> Task<Result<Navigated>> {
10061        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10062    }
10063
10064    pub fn go_to_type_definition_split(
10065        &mut self,
10066        _: &GoToTypeDefinitionSplit,
10067        window: &mut Window,
10068        cx: &mut Context<Self>,
10069    ) -> Task<Result<Navigated>> {
10070        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10071    }
10072
10073    fn go_to_definition_of_kind(
10074        &mut self,
10075        kind: GotoDefinitionKind,
10076        split: bool,
10077        window: &mut Window,
10078        cx: &mut Context<Self>,
10079    ) -> Task<Result<Navigated>> {
10080        let Some(provider) = self.semantics_provider.clone() else {
10081            return Task::ready(Ok(Navigated::No));
10082        };
10083        let head = self.selections.newest::<usize>(cx).head();
10084        let buffer = self.buffer.read(cx);
10085        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10086            text_anchor
10087        } else {
10088            return Task::ready(Ok(Navigated::No));
10089        };
10090
10091        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10092            return Task::ready(Ok(Navigated::No));
10093        };
10094
10095        cx.spawn_in(window, |editor, mut cx| async move {
10096            let definitions = definitions.await?;
10097            let navigated = editor
10098                .update_in(&mut cx, |editor, window, cx| {
10099                    editor.navigate_to_hover_links(
10100                        Some(kind),
10101                        definitions
10102                            .into_iter()
10103                            .filter(|location| {
10104                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10105                            })
10106                            .map(HoverLink::Text)
10107                            .collect::<Vec<_>>(),
10108                        split,
10109                        window,
10110                        cx,
10111                    )
10112                })?
10113                .await?;
10114            anyhow::Ok(navigated)
10115        })
10116    }
10117
10118    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10119        let selection = self.selections.newest_anchor();
10120        let head = selection.head();
10121        let tail = selection.tail();
10122
10123        let Some((buffer, start_position)) =
10124            self.buffer.read(cx).text_anchor_for_position(head, cx)
10125        else {
10126            return;
10127        };
10128
10129        let end_position = if head != tail {
10130            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10131                return;
10132            };
10133            Some(pos)
10134        } else {
10135            None
10136        };
10137
10138        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10139            let url = if let Some(end_pos) = end_position {
10140                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10141            } else {
10142                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10143            };
10144
10145            if let Some(url) = url {
10146                editor.update(&mut cx, |_, cx| {
10147                    cx.open_url(&url);
10148                })
10149            } else {
10150                Ok(())
10151            }
10152        });
10153
10154        url_finder.detach();
10155    }
10156
10157    pub fn open_selected_filename(
10158        &mut self,
10159        _: &OpenSelectedFilename,
10160        window: &mut Window,
10161        cx: &mut Context<Self>,
10162    ) {
10163        let Some(workspace) = self.workspace() else {
10164            return;
10165        };
10166
10167        let position = self.selections.newest_anchor().head();
10168
10169        let Some((buffer, buffer_position)) =
10170            self.buffer.read(cx).text_anchor_for_position(position, cx)
10171        else {
10172            return;
10173        };
10174
10175        let project = self.project.clone();
10176
10177        cx.spawn_in(window, |_, mut cx| async move {
10178            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10179
10180            if let Some((_, path)) = result {
10181                workspace
10182                    .update_in(&mut cx, |workspace, window, cx| {
10183                        workspace.open_resolved_path(path, window, cx)
10184                    })?
10185                    .await?;
10186            }
10187            anyhow::Ok(())
10188        })
10189        .detach();
10190    }
10191
10192    pub(crate) fn navigate_to_hover_links(
10193        &mut self,
10194        kind: Option<GotoDefinitionKind>,
10195        mut definitions: Vec<HoverLink>,
10196        split: bool,
10197        window: &mut Window,
10198        cx: &mut Context<Editor>,
10199    ) -> Task<Result<Navigated>> {
10200        // If there is one definition, just open it directly
10201        if definitions.len() == 1 {
10202            let definition = definitions.pop().unwrap();
10203
10204            enum TargetTaskResult {
10205                Location(Option<Location>),
10206                AlreadyNavigated,
10207            }
10208
10209            let target_task = match definition {
10210                HoverLink::Text(link) => {
10211                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10212                }
10213                HoverLink::InlayHint(lsp_location, server_id) => {
10214                    let computation =
10215                        self.compute_target_location(lsp_location, server_id, window, cx);
10216                    cx.background_executor().spawn(async move {
10217                        let location = computation.await?;
10218                        Ok(TargetTaskResult::Location(location))
10219                    })
10220                }
10221                HoverLink::Url(url) => {
10222                    cx.open_url(&url);
10223                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10224                }
10225                HoverLink::File(path) => {
10226                    if let Some(workspace) = self.workspace() {
10227                        cx.spawn_in(window, |_, mut cx| async move {
10228                            workspace
10229                                .update_in(&mut cx, |workspace, window, cx| {
10230                                    workspace.open_resolved_path(path, window, cx)
10231                                })?
10232                                .await
10233                                .map(|_| TargetTaskResult::AlreadyNavigated)
10234                        })
10235                    } else {
10236                        Task::ready(Ok(TargetTaskResult::Location(None)))
10237                    }
10238                }
10239            };
10240            cx.spawn_in(window, |editor, mut cx| async move {
10241                let target = match target_task.await.context("target resolution task")? {
10242                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10243                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10244                    TargetTaskResult::Location(Some(target)) => target,
10245                };
10246
10247                editor.update_in(&mut cx, |editor, window, cx| {
10248                    let Some(workspace) = editor.workspace() else {
10249                        return Navigated::No;
10250                    };
10251                    let pane = workspace.read(cx).active_pane().clone();
10252
10253                    let range = target.range.to_point(target.buffer.read(cx));
10254                    let range = editor.range_for_match(&range);
10255                    let range = collapse_multiline_range(range);
10256
10257                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10258                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10259                    } else {
10260                        window.defer(cx, move |window, cx| {
10261                            let target_editor: Entity<Self> =
10262                                workspace.update(cx, |workspace, cx| {
10263                                    let pane = if split {
10264                                        workspace.adjacent_pane(window, cx)
10265                                    } else {
10266                                        workspace.active_pane().clone()
10267                                    };
10268
10269                                    workspace.open_project_item(
10270                                        pane,
10271                                        target.buffer.clone(),
10272                                        true,
10273                                        true,
10274                                        window,
10275                                        cx,
10276                                    )
10277                                });
10278                            target_editor.update(cx, |target_editor, cx| {
10279                                // When selecting a definition in a different buffer, disable the nav history
10280                                // to avoid creating a history entry at the previous cursor location.
10281                                pane.update(cx, |pane, _| pane.disable_history());
10282                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10283                                pane.update(cx, |pane, _| pane.enable_history());
10284                            });
10285                        });
10286                    }
10287                    Navigated::Yes
10288                })
10289            })
10290        } else if !definitions.is_empty() {
10291            cx.spawn_in(window, |editor, mut cx| async move {
10292                let (title, location_tasks, workspace) = editor
10293                    .update_in(&mut cx, |editor, window, cx| {
10294                        let tab_kind = match kind {
10295                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10296                            _ => "Definitions",
10297                        };
10298                        let title = definitions
10299                            .iter()
10300                            .find_map(|definition| match definition {
10301                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10302                                    let buffer = origin.buffer.read(cx);
10303                                    format!(
10304                                        "{} for {}",
10305                                        tab_kind,
10306                                        buffer
10307                                            .text_for_range(origin.range.clone())
10308                                            .collect::<String>()
10309                                    )
10310                                }),
10311                                HoverLink::InlayHint(_, _) => None,
10312                                HoverLink::Url(_) => None,
10313                                HoverLink::File(_) => None,
10314                            })
10315                            .unwrap_or(tab_kind.to_string());
10316                        let location_tasks = definitions
10317                            .into_iter()
10318                            .map(|definition| match definition {
10319                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10320                                HoverLink::InlayHint(lsp_location, server_id) => editor
10321                                    .compute_target_location(lsp_location, server_id, window, cx),
10322                                HoverLink::Url(_) => Task::ready(Ok(None)),
10323                                HoverLink::File(_) => Task::ready(Ok(None)),
10324                            })
10325                            .collect::<Vec<_>>();
10326                        (title, location_tasks, editor.workspace().clone())
10327                    })
10328                    .context("location tasks preparation")?;
10329
10330                let locations = future::join_all(location_tasks)
10331                    .await
10332                    .into_iter()
10333                    .filter_map(|location| location.transpose())
10334                    .collect::<Result<_>>()
10335                    .context("location tasks")?;
10336
10337                let Some(workspace) = workspace else {
10338                    return Ok(Navigated::No);
10339                };
10340                let opened = workspace
10341                    .update_in(&mut cx, |workspace, window, cx| {
10342                        Self::open_locations_in_multibuffer(
10343                            workspace,
10344                            locations,
10345                            title,
10346                            split,
10347                            MultibufferSelectionMode::First,
10348                            window,
10349                            cx,
10350                        )
10351                    })
10352                    .ok();
10353
10354                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10355            })
10356        } else {
10357            Task::ready(Ok(Navigated::No))
10358        }
10359    }
10360
10361    fn compute_target_location(
10362        &self,
10363        lsp_location: lsp::Location,
10364        server_id: LanguageServerId,
10365        window: &mut Window,
10366        cx: &mut Context<Self>,
10367    ) -> Task<anyhow::Result<Option<Location>>> {
10368        let Some(project) = self.project.clone() else {
10369            return Task::ready(Ok(None));
10370        };
10371
10372        cx.spawn_in(window, move |editor, mut cx| async move {
10373            let location_task = editor.update(&mut cx, |_, cx| {
10374                project.update(cx, |project, cx| {
10375                    let language_server_name = project
10376                        .language_server_statuses(cx)
10377                        .find(|(id, _)| server_id == *id)
10378                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10379                    language_server_name.map(|language_server_name| {
10380                        project.open_local_buffer_via_lsp(
10381                            lsp_location.uri.clone(),
10382                            server_id,
10383                            language_server_name,
10384                            cx,
10385                        )
10386                    })
10387                })
10388            })?;
10389            let location = match location_task {
10390                Some(task) => Some({
10391                    let target_buffer_handle = task.await.context("open local buffer")?;
10392                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10393                        let target_start = target_buffer
10394                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10395                        let target_end = target_buffer
10396                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10397                        target_buffer.anchor_after(target_start)
10398                            ..target_buffer.anchor_before(target_end)
10399                    })?;
10400                    Location {
10401                        buffer: target_buffer_handle,
10402                        range,
10403                    }
10404                }),
10405                None => None,
10406            };
10407            Ok(location)
10408        })
10409    }
10410
10411    pub fn find_all_references(
10412        &mut self,
10413        _: &FindAllReferences,
10414        window: &mut Window,
10415        cx: &mut Context<Self>,
10416    ) -> Option<Task<Result<Navigated>>> {
10417        let selection = self.selections.newest::<usize>(cx);
10418        let multi_buffer = self.buffer.read(cx);
10419        let head = selection.head();
10420
10421        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10422        let head_anchor = multi_buffer_snapshot.anchor_at(
10423            head,
10424            if head < selection.tail() {
10425                Bias::Right
10426            } else {
10427                Bias::Left
10428            },
10429        );
10430
10431        match self
10432            .find_all_references_task_sources
10433            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10434        {
10435            Ok(_) => {
10436                log::info!(
10437                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10438                );
10439                return None;
10440            }
10441            Err(i) => {
10442                self.find_all_references_task_sources.insert(i, head_anchor);
10443            }
10444        }
10445
10446        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10447        let workspace = self.workspace()?;
10448        let project = workspace.read(cx).project().clone();
10449        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10450        Some(cx.spawn_in(window, |editor, mut cx| async move {
10451            let _cleanup = defer({
10452                let mut cx = cx.clone();
10453                move || {
10454                    let _ = editor.update(&mut cx, |editor, _| {
10455                        if let Ok(i) =
10456                            editor
10457                                .find_all_references_task_sources
10458                                .binary_search_by(|anchor| {
10459                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10460                                })
10461                        {
10462                            editor.find_all_references_task_sources.remove(i);
10463                        }
10464                    });
10465                }
10466            });
10467
10468            let locations = references.await?;
10469            if locations.is_empty() {
10470                return anyhow::Ok(Navigated::No);
10471            }
10472
10473            workspace.update_in(&mut cx, |workspace, window, cx| {
10474                let title = locations
10475                    .first()
10476                    .as_ref()
10477                    .map(|location| {
10478                        let buffer = location.buffer.read(cx);
10479                        format!(
10480                            "References to `{}`",
10481                            buffer
10482                                .text_for_range(location.range.clone())
10483                                .collect::<String>()
10484                        )
10485                    })
10486                    .unwrap();
10487                Self::open_locations_in_multibuffer(
10488                    workspace,
10489                    locations,
10490                    title,
10491                    false,
10492                    MultibufferSelectionMode::First,
10493                    window,
10494                    cx,
10495                );
10496                Navigated::Yes
10497            })
10498        }))
10499    }
10500
10501    /// Opens a multibuffer with the given project locations in it
10502    pub fn open_locations_in_multibuffer(
10503        workspace: &mut Workspace,
10504        mut locations: Vec<Location>,
10505        title: String,
10506        split: bool,
10507        multibuffer_selection_mode: MultibufferSelectionMode,
10508        window: &mut Window,
10509        cx: &mut Context<Workspace>,
10510    ) {
10511        // If there are multiple definitions, open them in a multibuffer
10512        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10513        let mut locations = locations.into_iter().peekable();
10514        let mut ranges = Vec::new();
10515        let capability = workspace.project().read(cx).capability();
10516
10517        let excerpt_buffer = cx.new(|cx| {
10518            let mut multibuffer = MultiBuffer::new(capability);
10519            while let Some(location) = locations.next() {
10520                let buffer = location.buffer.read(cx);
10521                let mut ranges_for_buffer = Vec::new();
10522                let range = location.range.to_offset(buffer);
10523                ranges_for_buffer.push(range.clone());
10524
10525                while let Some(next_location) = locations.peek() {
10526                    if next_location.buffer == location.buffer {
10527                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10528                        locations.next();
10529                    } else {
10530                        break;
10531                    }
10532                }
10533
10534                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10535                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10536                    location.buffer.clone(),
10537                    ranges_for_buffer,
10538                    DEFAULT_MULTIBUFFER_CONTEXT,
10539                    cx,
10540                ))
10541            }
10542
10543            multibuffer.with_title(title)
10544        });
10545
10546        let editor = cx.new(|cx| {
10547            Editor::for_multibuffer(
10548                excerpt_buffer,
10549                Some(workspace.project().clone()),
10550                true,
10551                window,
10552                cx,
10553            )
10554        });
10555        editor.update(cx, |editor, cx| {
10556            match multibuffer_selection_mode {
10557                MultibufferSelectionMode::First => {
10558                    if let Some(first_range) = ranges.first() {
10559                        editor.change_selections(None, window, cx, |selections| {
10560                            selections.clear_disjoint();
10561                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10562                        });
10563                    }
10564                    editor.highlight_background::<Self>(
10565                        &ranges,
10566                        |theme| theme.editor_highlighted_line_background,
10567                        cx,
10568                    );
10569                }
10570                MultibufferSelectionMode::All => {
10571                    editor.change_selections(None, window, cx, |selections| {
10572                        selections.clear_disjoint();
10573                        selections.select_anchor_ranges(ranges);
10574                    });
10575                }
10576            }
10577            editor.register_buffers_with_language_servers(cx);
10578        });
10579
10580        let item = Box::new(editor);
10581        let item_id = item.item_id();
10582
10583        if split {
10584            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10585        } else {
10586            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10587                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10588                    pane.close_current_preview_item(window, cx)
10589                } else {
10590                    None
10591                }
10592            });
10593            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10594        }
10595        workspace.active_pane().update(cx, |pane, cx| {
10596            pane.set_preview_item_id(Some(item_id), cx);
10597        });
10598    }
10599
10600    pub fn rename(
10601        &mut self,
10602        _: &Rename,
10603        window: &mut Window,
10604        cx: &mut Context<Self>,
10605    ) -> Option<Task<Result<()>>> {
10606        use language::ToOffset as _;
10607
10608        let provider = self.semantics_provider.clone()?;
10609        let selection = self.selections.newest_anchor().clone();
10610        let (cursor_buffer, cursor_buffer_position) = self
10611            .buffer
10612            .read(cx)
10613            .text_anchor_for_position(selection.head(), cx)?;
10614        let (tail_buffer, cursor_buffer_position_end) = self
10615            .buffer
10616            .read(cx)
10617            .text_anchor_for_position(selection.tail(), cx)?;
10618        if tail_buffer != cursor_buffer {
10619            return None;
10620        }
10621
10622        let snapshot = cursor_buffer.read(cx).snapshot();
10623        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10624        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10625        let prepare_rename = provider
10626            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10627            .unwrap_or_else(|| Task::ready(Ok(None)));
10628        drop(snapshot);
10629
10630        Some(cx.spawn_in(window, |this, mut cx| async move {
10631            let rename_range = if let Some(range) = prepare_rename.await? {
10632                Some(range)
10633            } else {
10634                this.update(&mut cx, |this, cx| {
10635                    let buffer = this.buffer.read(cx).snapshot(cx);
10636                    let mut buffer_highlights = this
10637                        .document_highlights_for_position(selection.head(), &buffer)
10638                        .filter(|highlight| {
10639                            highlight.start.excerpt_id == selection.head().excerpt_id
10640                                && highlight.end.excerpt_id == selection.head().excerpt_id
10641                        });
10642                    buffer_highlights
10643                        .next()
10644                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10645                })?
10646            };
10647            if let Some(rename_range) = rename_range {
10648                this.update_in(&mut cx, |this, window, cx| {
10649                    let snapshot = cursor_buffer.read(cx).snapshot();
10650                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10651                    let cursor_offset_in_rename_range =
10652                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10653                    let cursor_offset_in_rename_range_end =
10654                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10655
10656                    this.take_rename(false, window, cx);
10657                    let buffer = this.buffer.read(cx).read(cx);
10658                    let cursor_offset = selection.head().to_offset(&buffer);
10659                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10660                    let rename_end = rename_start + rename_buffer_range.len();
10661                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10662                    let mut old_highlight_id = None;
10663                    let old_name: Arc<str> = buffer
10664                        .chunks(rename_start..rename_end, true)
10665                        .map(|chunk| {
10666                            if old_highlight_id.is_none() {
10667                                old_highlight_id = chunk.syntax_highlight_id;
10668                            }
10669                            chunk.text
10670                        })
10671                        .collect::<String>()
10672                        .into();
10673
10674                    drop(buffer);
10675
10676                    // Position the selection in the rename editor so that it matches the current selection.
10677                    this.show_local_selections = false;
10678                    let rename_editor = cx.new(|cx| {
10679                        let mut editor = Editor::single_line(window, cx);
10680                        editor.buffer.update(cx, |buffer, cx| {
10681                            buffer.edit([(0..0, old_name.clone())], None, cx)
10682                        });
10683                        let rename_selection_range = match cursor_offset_in_rename_range
10684                            .cmp(&cursor_offset_in_rename_range_end)
10685                        {
10686                            Ordering::Equal => {
10687                                editor.select_all(&SelectAll, window, cx);
10688                                return editor;
10689                            }
10690                            Ordering::Less => {
10691                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10692                            }
10693                            Ordering::Greater => {
10694                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10695                            }
10696                        };
10697                        if rename_selection_range.end > old_name.len() {
10698                            editor.select_all(&SelectAll, window, cx);
10699                        } else {
10700                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10701                                s.select_ranges([rename_selection_range]);
10702                            });
10703                        }
10704                        editor
10705                    });
10706                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10707                        if e == &EditorEvent::Focused {
10708                            cx.emit(EditorEvent::FocusedIn)
10709                        }
10710                    })
10711                    .detach();
10712
10713                    let write_highlights =
10714                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10715                    let read_highlights =
10716                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10717                    let ranges = write_highlights
10718                        .iter()
10719                        .flat_map(|(_, ranges)| ranges.iter())
10720                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10721                        .cloned()
10722                        .collect();
10723
10724                    this.highlight_text::<Rename>(
10725                        ranges,
10726                        HighlightStyle {
10727                            fade_out: Some(0.6),
10728                            ..Default::default()
10729                        },
10730                        cx,
10731                    );
10732                    let rename_focus_handle = rename_editor.focus_handle(cx);
10733                    window.focus(&rename_focus_handle);
10734                    let block_id = this.insert_blocks(
10735                        [BlockProperties {
10736                            style: BlockStyle::Flex,
10737                            placement: BlockPlacement::Below(range.start),
10738                            height: 1,
10739                            render: Arc::new({
10740                                let rename_editor = rename_editor.clone();
10741                                move |cx: &mut BlockContext| {
10742                                    let mut text_style = cx.editor_style.text.clone();
10743                                    if let Some(highlight_style) = old_highlight_id
10744                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10745                                    {
10746                                        text_style = text_style.highlight(highlight_style);
10747                                    }
10748                                    div()
10749                                        .block_mouse_down()
10750                                        .pl(cx.anchor_x)
10751                                        .child(EditorElement::new(
10752                                            &rename_editor,
10753                                            EditorStyle {
10754                                                background: cx.theme().system().transparent,
10755                                                local_player: cx.editor_style.local_player,
10756                                                text: text_style,
10757                                                scrollbar_width: cx.editor_style.scrollbar_width,
10758                                                syntax: cx.editor_style.syntax.clone(),
10759                                                status: cx.editor_style.status.clone(),
10760                                                inlay_hints_style: HighlightStyle {
10761                                                    font_weight: Some(FontWeight::BOLD),
10762                                                    ..make_inlay_hints_style(cx.app)
10763                                                },
10764                                                inline_completion_styles: make_suggestion_styles(
10765                                                    cx.app,
10766                                                ),
10767                                                ..EditorStyle::default()
10768                                            },
10769                                        ))
10770                                        .into_any_element()
10771                                }
10772                            }),
10773                            priority: 0,
10774                        }],
10775                        Some(Autoscroll::fit()),
10776                        cx,
10777                    )[0];
10778                    this.pending_rename = Some(RenameState {
10779                        range,
10780                        old_name,
10781                        editor: rename_editor,
10782                        block_id,
10783                    });
10784                })?;
10785            }
10786
10787            Ok(())
10788        }))
10789    }
10790
10791    pub fn confirm_rename(
10792        &mut self,
10793        _: &ConfirmRename,
10794        window: &mut Window,
10795        cx: &mut Context<Self>,
10796    ) -> Option<Task<Result<()>>> {
10797        let rename = self.take_rename(false, window, cx)?;
10798        let workspace = self.workspace()?.downgrade();
10799        let (buffer, start) = self
10800            .buffer
10801            .read(cx)
10802            .text_anchor_for_position(rename.range.start, cx)?;
10803        let (end_buffer, _) = self
10804            .buffer
10805            .read(cx)
10806            .text_anchor_for_position(rename.range.end, cx)?;
10807        if buffer != end_buffer {
10808            return None;
10809        }
10810
10811        let old_name = rename.old_name;
10812        let new_name = rename.editor.read(cx).text(cx);
10813
10814        let rename = self.semantics_provider.as_ref()?.perform_rename(
10815            &buffer,
10816            start,
10817            new_name.clone(),
10818            cx,
10819        )?;
10820
10821        Some(cx.spawn_in(window, |editor, mut cx| async move {
10822            let project_transaction = rename.await?;
10823            Self::open_project_transaction(
10824                &editor,
10825                workspace,
10826                project_transaction,
10827                format!("Rename: {}{}", old_name, new_name),
10828                cx.clone(),
10829            )
10830            .await?;
10831
10832            editor.update(&mut cx, |editor, cx| {
10833                editor.refresh_document_highlights(cx);
10834            })?;
10835            Ok(())
10836        }))
10837    }
10838
10839    fn take_rename(
10840        &mut self,
10841        moving_cursor: bool,
10842        window: &mut Window,
10843        cx: &mut Context<Self>,
10844    ) -> Option<RenameState> {
10845        let rename = self.pending_rename.take()?;
10846        if rename.editor.focus_handle(cx).is_focused(window) {
10847            window.focus(&self.focus_handle);
10848        }
10849
10850        self.remove_blocks(
10851            [rename.block_id].into_iter().collect(),
10852            Some(Autoscroll::fit()),
10853            cx,
10854        );
10855        self.clear_highlights::<Rename>(cx);
10856        self.show_local_selections = true;
10857
10858        if moving_cursor {
10859            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10860                editor.selections.newest::<usize>(cx).head()
10861            });
10862
10863            // Update the selection to match the position of the selection inside
10864            // the rename editor.
10865            let snapshot = self.buffer.read(cx).read(cx);
10866            let rename_range = rename.range.to_offset(&snapshot);
10867            let cursor_in_editor = snapshot
10868                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10869                .min(rename_range.end);
10870            drop(snapshot);
10871
10872            self.change_selections(None, window, cx, |s| {
10873                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10874            });
10875        } else {
10876            self.refresh_document_highlights(cx);
10877        }
10878
10879        Some(rename)
10880    }
10881
10882    pub fn pending_rename(&self) -> Option<&RenameState> {
10883        self.pending_rename.as_ref()
10884    }
10885
10886    fn format(
10887        &mut self,
10888        _: &Format,
10889        window: &mut Window,
10890        cx: &mut Context<Self>,
10891    ) -> Option<Task<Result<()>>> {
10892        let project = match &self.project {
10893            Some(project) => project.clone(),
10894            None => return None,
10895        };
10896
10897        Some(self.perform_format(
10898            project,
10899            FormatTrigger::Manual,
10900            FormatTarget::Buffers,
10901            window,
10902            cx,
10903        ))
10904    }
10905
10906    fn format_selections(
10907        &mut self,
10908        _: &FormatSelections,
10909        window: &mut Window,
10910        cx: &mut Context<Self>,
10911    ) -> Option<Task<Result<()>>> {
10912        let project = match &self.project {
10913            Some(project) => project.clone(),
10914            None => return None,
10915        };
10916
10917        let ranges = self
10918            .selections
10919            .all_adjusted(cx)
10920            .into_iter()
10921            .map(|selection| selection.range())
10922            .collect_vec();
10923
10924        Some(self.perform_format(
10925            project,
10926            FormatTrigger::Manual,
10927            FormatTarget::Ranges(ranges),
10928            window,
10929            cx,
10930        ))
10931    }
10932
10933    fn perform_format(
10934        &mut self,
10935        project: Entity<Project>,
10936        trigger: FormatTrigger,
10937        target: FormatTarget,
10938        window: &mut Window,
10939        cx: &mut Context<Self>,
10940    ) -> Task<Result<()>> {
10941        let buffer = self.buffer.clone();
10942        let (buffers, target) = match target {
10943            FormatTarget::Buffers => {
10944                let mut buffers = buffer.read(cx).all_buffers();
10945                if trigger == FormatTrigger::Save {
10946                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10947                }
10948                (buffers, LspFormatTarget::Buffers)
10949            }
10950            FormatTarget::Ranges(selection_ranges) => {
10951                let multi_buffer = buffer.read(cx);
10952                let snapshot = multi_buffer.read(cx);
10953                let mut buffers = HashSet::default();
10954                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10955                    BTreeMap::new();
10956                for selection_range in selection_ranges {
10957                    for (buffer, buffer_range, _) in
10958                        snapshot.range_to_buffer_ranges(selection_range)
10959                    {
10960                        let buffer_id = buffer.remote_id();
10961                        let start = buffer.anchor_before(buffer_range.start);
10962                        let end = buffer.anchor_after(buffer_range.end);
10963                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10964                        buffer_id_to_ranges
10965                            .entry(buffer_id)
10966                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10967                            .or_insert_with(|| vec![start..end]);
10968                    }
10969                }
10970                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10971            }
10972        };
10973
10974        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10975        let format = project.update(cx, |project, cx| {
10976            project.format(buffers, target, true, trigger, cx)
10977        });
10978
10979        cx.spawn_in(window, |_, mut cx| async move {
10980            let transaction = futures::select_biased! {
10981                () = timeout => {
10982                    log::warn!("timed out waiting for formatting");
10983                    None
10984                }
10985                transaction = format.log_err().fuse() => transaction,
10986            };
10987
10988            buffer
10989                .update(&mut cx, |buffer, cx| {
10990                    if let Some(transaction) = transaction {
10991                        if !buffer.is_singleton() {
10992                            buffer.push_transaction(&transaction.0, cx);
10993                        }
10994                    }
10995
10996                    cx.notify();
10997                })
10998                .ok();
10999
11000            Ok(())
11001        })
11002    }
11003
11004    fn restart_language_server(
11005        &mut self,
11006        _: &RestartLanguageServer,
11007        _: &mut Window,
11008        cx: &mut Context<Self>,
11009    ) {
11010        if let Some(project) = self.project.clone() {
11011            self.buffer.update(cx, |multi_buffer, cx| {
11012                project.update(cx, |project, cx| {
11013                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11014                });
11015            })
11016        }
11017    }
11018
11019    fn cancel_language_server_work(
11020        &mut self,
11021        _: &actions::CancelLanguageServerWork,
11022        _: &mut Window,
11023        cx: &mut Context<Self>,
11024    ) {
11025        if let Some(project) = self.project.clone() {
11026            self.buffer.update(cx, |multi_buffer, cx| {
11027                project.update(cx, |project, cx| {
11028                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11029                });
11030            })
11031        }
11032    }
11033
11034    fn show_character_palette(
11035        &mut self,
11036        _: &ShowCharacterPalette,
11037        window: &mut Window,
11038        _: &mut Context<Self>,
11039    ) {
11040        window.show_character_palette();
11041    }
11042
11043    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11044        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11045            let buffer = self.buffer.read(cx).snapshot(cx);
11046            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11047            let is_valid = buffer
11048                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11049                .any(|entry| {
11050                    entry.diagnostic.is_primary
11051                        && !entry.range.is_empty()
11052                        && entry.range.start == primary_range_start
11053                        && entry.diagnostic.message == active_diagnostics.primary_message
11054                });
11055
11056            if is_valid != active_diagnostics.is_valid {
11057                active_diagnostics.is_valid = is_valid;
11058                let mut new_styles = HashMap::default();
11059                for (block_id, diagnostic) in &active_diagnostics.blocks {
11060                    new_styles.insert(
11061                        *block_id,
11062                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11063                    );
11064                }
11065                self.display_map.update(cx, |display_map, _cx| {
11066                    display_map.replace_blocks(new_styles)
11067                });
11068            }
11069        }
11070    }
11071
11072    fn activate_diagnostics(
11073        &mut self,
11074        buffer_id: BufferId,
11075        group_id: usize,
11076        window: &mut Window,
11077        cx: &mut Context<Self>,
11078    ) {
11079        self.dismiss_diagnostics(cx);
11080        let snapshot = self.snapshot(window, cx);
11081        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11082            let buffer = self.buffer.read(cx).snapshot(cx);
11083
11084            let mut primary_range = None;
11085            let mut primary_message = None;
11086            let diagnostic_group = buffer
11087                .diagnostic_group(buffer_id, group_id)
11088                .filter_map(|entry| {
11089                    let start = entry.range.start;
11090                    let end = entry.range.end;
11091                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11092                        && (start.row == end.row
11093                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11094                    {
11095                        return None;
11096                    }
11097                    if entry.diagnostic.is_primary {
11098                        primary_range = Some(entry.range.clone());
11099                        primary_message = Some(entry.diagnostic.message.clone());
11100                    }
11101                    Some(entry)
11102                })
11103                .collect::<Vec<_>>();
11104            let primary_range = primary_range?;
11105            let primary_message = primary_message?;
11106
11107            let blocks = display_map
11108                .insert_blocks(
11109                    diagnostic_group.iter().map(|entry| {
11110                        let diagnostic = entry.diagnostic.clone();
11111                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11112                        BlockProperties {
11113                            style: BlockStyle::Fixed,
11114                            placement: BlockPlacement::Below(
11115                                buffer.anchor_after(entry.range.start),
11116                            ),
11117                            height: message_height,
11118                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11119                            priority: 0,
11120                        }
11121                    }),
11122                    cx,
11123                )
11124                .into_iter()
11125                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11126                .collect();
11127
11128            Some(ActiveDiagnosticGroup {
11129                primary_range: buffer.anchor_before(primary_range.start)
11130                    ..buffer.anchor_after(primary_range.end),
11131                primary_message,
11132                group_id,
11133                blocks,
11134                is_valid: true,
11135            })
11136        });
11137    }
11138
11139    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11140        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11141            self.display_map.update(cx, |display_map, cx| {
11142                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11143            });
11144            cx.notify();
11145        }
11146    }
11147
11148    pub fn set_selections_from_remote(
11149        &mut self,
11150        selections: Vec<Selection<Anchor>>,
11151        pending_selection: Option<Selection<Anchor>>,
11152        window: &mut Window,
11153        cx: &mut Context<Self>,
11154    ) {
11155        let old_cursor_position = self.selections.newest_anchor().head();
11156        self.selections.change_with(cx, |s| {
11157            s.select_anchors(selections);
11158            if let Some(pending_selection) = pending_selection {
11159                s.set_pending(pending_selection, SelectMode::Character);
11160            } else {
11161                s.clear_pending();
11162            }
11163        });
11164        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11165    }
11166
11167    fn push_to_selection_history(&mut self) {
11168        self.selection_history.push(SelectionHistoryEntry {
11169            selections: self.selections.disjoint_anchors(),
11170            select_next_state: self.select_next_state.clone(),
11171            select_prev_state: self.select_prev_state.clone(),
11172            add_selections_state: self.add_selections_state.clone(),
11173        });
11174    }
11175
11176    pub fn transact(
11177        &mut self,
11178        window: &mut Window,
11179        cx: &mut Context<Self>,
11180        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11181    ) -> Option<TransactionId> {
11182        self.start_transaction_at(Instant::now(), window, cx);
11183        update(self, window, cx);
11184        self.end_transaction_at(Instant::now(), cx)
11185    }
11186
11187    pub fn start_transaction_at(
11188        &mut self,
11189        now: Instant,
11190        window: &mut Window,
11191        cx: &mut Context<Self>,
11192    ) {
11193        self.end_selection(window, cx);
11194        if let Some(tx_id) = self
11195            .buffer
11196            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11197        {
11198            self.selection_history
11199                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11200            cx.emit(EditorEvent::TransactionBegun {
11201                transaction_id: tx_id,
11202            })
11203        }
11204    }
11205
11206    pub fn end_transaction_at(
11207        &mut self,
11208        now: Instant,
11209        cx: &mut Context<Self>,
11210    ) -> Option<TransactionId> {
11211        if let Some(transaction_id) = self
11212            .buffer
11213            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11214        {
11215            if let Some((_, end_selections)) =
11216                self.selection_history.transaction_mut(transaction_id)
11217            {
11218                *end_selections = Some(self.selections.disjoint_anchors());
11219            } else {
11220                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11221            }
11222
11223            cx.emit(EditorEvent::Edited { transaction_id });
11224            Some(transaction_id)
11225        } else {
11226            None
11227        }
11228    }
11229
11230    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11231        if self.selection_mark_mode {
11232            self.change_selections(None, window, cx, |s| {
11233                s.move_with(|_, sel| {
11234                    sel.collapse_to(sel.head(), SelectionGoal::None);
11235                });
11236            })
11237        }
11238        self.selection_mark_mode = true;
11239        cx.notify();
11240    }
11241
11242    pub fn swap_selection_ends(
11243        &mut self,
11244        _: &actions::SwapSelectionEnds,
11245        window: &mut Window,
11246        cx: &mut Context<Self>,
11247    ) {
11248        self.change_selections(None, window, cx, |s| {
11249            s.move_with(|_, sel| {
11250                if sel.start != sel.end {
11251                    sel.reversed = !sel.reversed
11252                }
11253            });
11254        });
11255        self.request_autoscroll(Autoscroll::newest(), cx);
11256        cx.notify();
11257    }
11258
11259    pub fn toggle_fold(
11260        &mut self,
11261        _: &actions::ToggleFold,
11262        window: &mut Window,
11263        cx: &mut Context<Self>,
11264    ) {
11265        if self.is_singleton(cx) {
11266            let selection = self.selections.newest::<Point>(cx);
11267
11268            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11269            let range = if selection.is_empty() {
11270                let point = selection.head().to_display_point(&display_map);
11271                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11272                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11273                    .to_point(&display_map);
11274                start..end
11275            } else {
11276                selection.range()
11277            };
11278            if display_map.folds_in_range(range).next().is_some() {
11279                self.unfold_lines(&Default::default(), window, cx)
11280            } else {
11281                self.fold(&Default::default(), window, cx)
11282            }
11283        } else {
11284            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11285            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11286                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11287                .map(|(snapshot, _, _)| snapshot.remote_id())
11288                .collect();
11289
11290            for buffer_id in buffer_ids {
11291                if self.is_buffer_folded(buffer_id, cx) {
11292                    self.unfold_buffer(buffer_id, cx);
11293                } else {
11294                    self.fold_buffer(buffer_id, cx);
11295                }
11296            }
11297        }
11298    }
11299
11300    pub fn toggle_fold_recursive(
11301        &mut self,
11302        _: &actions::ToggleFoldRecursive,
11303        window: &mut Window,
11304        cx: &mut Context<Self>,
11305    ) {
11306        let selection = self.selections.newest::<Point>(cx);
11307
11308        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11309        let range = if selection.is_empty() {
11310            let point = selection.head().to_display_point(&display_map);
11311            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11312            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11313                .to_point(&display_map);
11314            start..end
11315        } else {
11316            selection.range()
11317        };
11318        if display_map.folds_in_range(range).next().is_some() {
11319            self.unfold_recursive(&Default::default(), window, cx)
11320        } else {
11321            self.fold_recursive(&Default::default(), window, cx)
11322        }
11323    }
11324
11325    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11326        if self.is_singleton(cx) {
11327            let mut to_fold = Vec::new();
11328            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11329            let selections = self.selections.all_adjusted(cx);
11330
11331            for selection in selections {
11332                let range = selection.range().sorted();
11333                let buffer_start_row = range.start.row;
11334
11335                if range.start.row != range.end.row {
11336                    let mut found = false;
11337                    let mut row = range.start.row;
11338                    while row <= range.end.row {
11339                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11340                        {
11341                            found = true;
11342                            row = crease.range().end.row + 1;
11343                            to_fold.push(crease);
11344                        } else {
11345                            row += 1
11346                        }
11347                    }
11348                    if found {
11349                        continue;
11350                    }
11351                }
11352
11353                for row in (0..=range.start.row).rev() {
11354                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11355                        if crease.range().end.row >= buffer_start_row {
11356                            to_fold.push(crease);
11357                            if row <= range.start.row {
11358                                break;
11359                            }
11360                        }
11361                    }
11362                }
11363            }
11364
11365            self.fold_creases(to_fold, true, window, cx);
11366        } else {
11367            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11368
11369            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11370                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11371                .map(|(snapshot, _, _)| snapshot.remote_id())
11372                .collect();
11373            for buffer_id in buffer_ids {
11374                self.fold_buffer(buffer_id, cx);
11375            }
11376        }
11377    }
11378
11379    fn fold_at_level(
11380        &mut self,
11381        fold_at: &FoldAtLevel,
11382        window: &mut Window,
11383        cx: &mut Context<Self>,
11384    ) {
11385        if !self.buffer.read(cx).is_singleton() {
11386            return;
11387        }
11388
11389        let fold_at_level = fold_at.level;
11390        let snapshot = self.buffer.read(cx).snapshot(cx);
11391        let mut to_fold = Vec::new();
11392        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11393
11394        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11395            while start_row < end_row {
11396                match self
11397                    .snapshot(window, cx)
11398                    .crease_for_buffer_row(MultiBufferRow(start_row))
11399                {
11400                    Some(crease) => {
11401                        let nested_start_row = crease.range().start.row + 1;
11402                        let nested_end_row = crease.range().end.row;
11403
11404                        if current_level < fold_at_level {
11405                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11406                        } else if current_level == fold_at_level {
11407                            to_fold.push(crease);
11408                        }
11409
11410                        start_row = nested_end_row + 1;
11411                    }
11412                    None => start_row += 1,
11413                }
11414            }
11415        }
11416
11417        self.fold_creases(to_fold, true, window, cx);
11418    }
11419
11420    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11421        if self.buffer.read(cx).is_singleton() {
11422            let mut fold_ranges = Vec::new();
11423            let snapshot = self.buffer.read(cx).snapshot(cx);
11424
11425            for row in 0..snapshot.max_row().0 {
11426                if let Some(foldable_range) = self
11427                    .snapshot(window, cx)
11428                    .crease_for_buffer_row(MultiBufferRow(row))
11429                {
11430                    fold_ranges.push(foldable_range);
11431                }
11432            }
11433
11434            self.fold_creases(fold_ranges, true, window, cx);
11435        } else {
11436            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11437                editor
11438                    .update_in(&mut cx, |editor, _, cx| {
11439                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11440                            editor.fold_buffer(buffer_id, cx);
11441                        }
11442                    })
11443                    .ok();
11444            });
11445        }
11446    }
11447
11448    pub fn fold_function_bodies(
11449        &mut self,
11450        _: &actions::FoldFunctionBodies,
11451        window: &mut Window,
11452        cx: &mut Context<Self>,
11453    ) {
11454        let snapshot = self.buffer.read(cx).snapshot(cx);
11455
11456        let ranges = snapshot
11457            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11458            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11459            .collect::<Vec<_>>();
11460
11461        let creases = ranges
11462            .into_iter()
11463            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11464            .collect();
11465
11466        self.fold_creases(creases, true, window, cx);
11467    }
11468
11469    pub fn fold_recursive(
11470        &mut self,
11471        _: &actions::FoldRecursive,
11472        window: &mut Window,
11473        cx: &mut Context<Self>,
11474    ) {
11475        let mut to_fold = Vec::new();
11476        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11477        let selections = self.selections.all_adjusted(cx);
11478
11479        for selection in selections {
11480            let range = selection.range().sorted();
11481            let buffer_start_row = range.start.row;
11482
11483            if range.start.row != range.end.row {
11484                let mut found = false;
11485                for row in range.start.row..=range.end.row {
11486                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11487                        found = true;
11488                        to_fold.push(crease);
11489                    }
11490                }
11491                if found {
11492                    continue;
11493                }
11494            }
11495
11496            for row in (0..=range.start.row).rev() {
11497                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11498                    if crease.range().end.row >= buffer_start_row {
11499                        to_fold.push(crease);
11500                    } else {
11501                        break;
11502                    }
11503                }
11504            }
11505        }
11506
11507        self.fold_creases(to_fold, true, window, cx);
11508    }
11509
11510    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11511        let buffer_row = fold_at.buffer_row;
11512        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11513
11514        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11515            let autoscroll = self
11516                .selections
11517                .all::<Point>(cx)
11518                .iter()
11519                .any(|selection| crease.range().overlaps(&selection.range()));
11520
11521            self.fold_creases(vec![crease], autoscroll, window, cx);
11522        }
11523    }
11524
11525    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11526        if self.is_singleton(cx) {
11527            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11528            let buffer = &display_map.buffer_snapshot;
11529            let selections = self.selections.all::<Point>(cx);
11530            let ranges = selections
11531                .iter()
11532                .map(|s| {
11533                    let range = s.display_range(&display_map).sorted();
11534                    let mut start = range.start.to_point(&display_map);
11535                    let mut end = range.end.to_point(&display_map);
11536                    start.column = 0;
11537                    end.column = buffer.line_len(MultiBufferRow(end.row));
11538                    start..end
11539                })
11540                .collect::<Vec<_>>();
11541
11542            self.unfold_ranges(&ranges, true, true, cx);
11543        } else {
11544            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11545            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11546                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11547                .map(|(snapshot, _, _)| snapshot.remote_id())
11548                .collect();
11549            for buffer_id in buffer_ids {
11550                self.unfold_buffer(buffer_id, cx);
11551            }
11552        }
11553    }
11554
11555    pub fn unfold_recursive(
11556        &mut self,
11557        _: &UnfoldRecursive,
11558        _window: &mut Window,
11559        cx: &mut Context<Self>,
11560    ) {
11561        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11562        let selections = self.selections.all::<Point>(cx);
11563        let ranges = selections
11564            .iter()
11565            .map(|s| {
11566                let mut range = s.display_range(&display_map).sorted();
11567                *range.start.column_mut() = 0;
11568                *range.end.column_mut() = display_map.line_len(range.end.row());
11569                let start = range.start.to_point(&display_map);
11570                let end = range.end.to_point(&display_map);
11571                start..end
11572            })
11573            .collect::<Vec<_>>();
11574
11575        self.unfold_ranges(&ranges, true, true, cx);
11576    }
11577
11578    pub fn unfold_at(
11579        &mut self,
11580        unfold_at: &UnfoldAt,
11581        _window: &mut Window,
11582        cx: &mut Context<Self>,
11583    ) {
11584        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11585
11586        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11587            ..Point::new(
11588                unfold_at.buffer_row.0,
11589                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11590            );
11591
11592        let autoscroll = self
11593            .selections
11594            .all::<Point>(cx)
11595            .iter()
11596            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11597
11598        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11599    }
11600
11601    pub fn unfold_all(
11602        &mut self,
11603        _: &actions::UnfoldAll,
11604        _window: &mut Window,
11605        cx: &mut Context<Self>,
11606    ) {
11607        if self.buffer.read(cx).is_singleton() {
11608            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11609            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11610        } else {
11611            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11612                editor
11613                    .update(&mut cx, |editor, cx| {
11614                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11615                            editor.unfold_buffer(buffer_id, cx);
11616                        }
11617                    })
11618                    .ok();
11619            });
11620        }
11621    }
11622
11623    pub fn fold_selected_ranges(
11624        &mut self,
11625        _: &FoldSelectedRanges,
11626        window: &mut Window,
11627        cx: &mut Context<Self>,
11628    ) {
11629        let selections = self.selections.all::<Point>(cx);
11630        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11631        let line_mode = self.selections.line_mode;
11632        let ranges = selections
11633            .into_iter()
11634            .map(|s| {
11635                if line_mode {
11636                    let start = Point::new(s.start.row, 0);
11637                    let end = Point::new(
11638                        s.end.row,
11639                        display_map
11640                            .buffer_snapshot
11641                            .line_len(MultiBufferRow(s.end.row)),
11642                    );
11643                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11644                } else {
11645                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11646                }
11647            })
11648            .collect::<Vec<_>>();
11649        self.fold_creases(ranges, true, window, cx);
11650    }
11651
11652    pub fn fold_ranges<T: ToOffset + Clone>(
11653        &mut self,
11654        ranges: Vec<Range<T>>,
11655        auto_scroll: bool,
11656        window: &mut Window,
11657        cx: &mut Context<Self>,
11658    ) {
11659        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11660        let ranges = ranges
11661            .into_iter()
11662            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11663            .collect::<Vec<_>>();
11664        self.fold_creases(ranges, auto_scroll, window, cx);
11665    }
11666
11667    pub fn fold_creases<T: ToOffset + Clone>(
11668        &mut self,
11669        creases: Vec<Crease<T>>,
11670        auto_scroll: bool,
11671        window: &mut Window,
11672        cx: &mut Context<Self>,
11673    ) {
11674        if creases.is_empty() {
11675            return;
11676        }
11677
11678        let mut buffers_affected = HashSet::default();
11679        let multi_buffer = self.buffer().read(cx);
11680        for crease in &creases {
11681            if let Some((_, buffer, _)) =
11682                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11683            {
11684                buffers_affected.insert(buffer.read(cx).remote_id());
11685            };
11686        }
11687
11688        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11689
11690        if auto_scroll {
11691            self.request_autoscroll(Autoscroll::fit(), cx);
11692        }
11693
11694        cx.notify();
11695
11696        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11697            // Clear diagnostics block when folding a range that contains it.
11698            let snapshot = self.snapshot(window, cx);
11699            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11700                drop(snapshot);
11701                self.active_diagnostics = Some(active_diagnostics);
11702                self.dismiss_diagnostics(cx);
11703            } else {
11704                self.active_diagnostics = Some(active_diagnostics);
11705            }
11706        }
11707
11708        self.scrollbar_marker_state.dirty = true;
11709    }
11710
11711    /// Removes any folds whose ranges intersect any of the given ranges.
11712    pub fn unfold_ranges<T: ToOffset + Clone>(
11713        &mut self,
11714        ranges: &[Range<T>],
11715        inclusive: bool,
11716        auto_scroll: bool,
11717        cx: &mut Context<Self>,
11718    ) {
11719        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11720            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11721        });
11722    }
11723
11724    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11725        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11726            return;
11727        }
11728        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11729            return;
11730        };
11731        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11732        self.display_map
11733            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11734        cx.emit(EditorEvent::BufferFoldToggled {
11735            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11736            folded: true,
11737        });
11738        cx.notify();
11739    }
11740
11741    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11742        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11743            return;
11744        }
11745        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11746            return;
11747        };
11748        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11749        self.display_map.update(cx, |display_map, cx| {
11750            display_map.unfold_buffer(buffer_id, cx);
11751        });
11752        cx.emit(EditorEvent::BufferFoldToggled {
11753            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11754            folded: false,
11755        });
11756        cx.notify();
11757    }
11758
11759    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11760        self.display_map.read(cx).is_buffer_folded(buffer)
11761    }
11762
11763    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
11764        self.display_map.read(cx).folded_buffers()
11765    }
11766
11767    /// Removes any folds with the given ranges.
11768    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11769        &mut self,
11770        ranges: &[Range<T>],
11771        type_id: TypeId,
11772        auto_scroll: bool,
11773        cx: &mut Context<Self>,
11774    ) {
11775        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11776            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11777        });
11778    }
11779
11780    fn remove_folds_with<T: ToOffset + Clone>(
11781        &mut self,
11782        ranges: &[Range<T>],
11783        auto_scroll: bool,
11784        cx: &mut Context<Self>,
11785        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
11786    ) {
11787        if ranges.is_empty() {
11788            return;
11789        }
11790
11791        let mut buffers_affected = HashSet::default();
11792        let multi_buffer = self.buffer().read(cx);
11793        for range in ranges {
11794            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11795                buffers_affected.insert(buffer.read(cx).remote_id());
11796            };
11797        }
11798
11799        self.display_map.update(cx, update);
11800
11801        if auto_scroll {
11802            self.request_autoscroll(Autoscroll::fit(), cx);
11803        }
11804
11805        cx.notify();
11806        self.scrollbar_marker_state.dirty = true;
11807        self.active_indent_guides_state.dirty = true;
11808    }
11809
11810    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
11811        self.display_map.read(cx).fold_placeholder.clone()
11812    }
11813
11814    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
11815        self.buffer.update(cx, |buffer, cx| {
11816            buffer.set_all_diff_hunks_expanded(cx);
11817        });
11818    }
11819
11820    pub fn expand_all_diff_hunks(
11821        &mut self,
11822        _: &ExpandAllHunkDiffs,
11823        _window: &mut Window,
11824        cx: &mut Context<Self>,
11825    ) {
11826        self.buffer.update(cx, |buffer, cx| {
11827            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11828        });
11829    }
11830
11831    pub fn toggle_selected_diff_hunks(
11832        &mut self,
11833        _: &ToggleSelectedDiffHunks,
11834        _window: &mut Window,
11835        cx: &mut Context<Self>,
11836    ) {
11837        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11838        self.toggle_diff_hunks_in_ranges(ranges, cx);
11839    }
11840
11841    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
11842        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11843        self.buffer
11844            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11845    }
11846
11847    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
11848        self.buffer.update(cx, |buffer, cx| {
11849            let ranges = vec![Anchor::min()..Anchor::max()];
11850            if !buffer.all_diff_hunks_expanded()
11851                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11852            {
11853                buffer.collapse_diff_hunks(ranges, cx);
11854                true
11855            } else {
11856                false
11857            }
11858        })
11859    }
11860
11861    fn toggle_diff_hunks_in_ranges(
11862        &mut self,
11863        ranges: Vec<Range<Anchor>>,
11864        cx: &mut Context<'_, Editor>,
11865    ) {
11866        self.buffer.update(cx, |buffer, cx| {
11867            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11868                buffer.collapse_diff_hunks(ranges, cx)
11869            } else {
11870                buffer.expand_diff_hunks(ranges, cx)
11871            }
11872        })
11873    }
11874
11875    pub(crate) fn apply_all_diff_hunks(
11876        &mut self,
11877        _: &ApplyAllDiffHunks,
11878        window: &mut Window,
11879        cx: &mut Context<Self>,
11880    ) {
11881        let buffers = self.buffer.read(cx).all_buffers();
11882        for branch_buffer in buffers {
11883            branch_buffer.update(cx, |branch_buffer, cx| {
11884                branch_buffer.merge_into_base(Vec::new(), cx);
11885            });
11886        }
11887
11888        if let Some(project) = self.project.clone() {
11889            self.save(true, project, window, cx).detach_and_log_err(cx);
11890        }
11891    }
11892
11893    pub(crate) fn apply_selected_diff_hunks(
11894        &mut self,
11895        _: &ApplyDiffHunk,
11896        window: &mut Window,
11897        cx: &mut Context<Self>,
11898    ) {
11899        let snapshot = self.snapshot(window, cx);
11900        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11901        let mut ranges_by_buffer = HashMap::default();
11902        self.transact(window, cx, |editor, _window, cx| {
11903            for hunk in hunks {
11904                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11905                    ranges_by_buffer
11906                        .entry(buffer.clone())
11907                        .or_insert_with(Vec::new)
11908                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11909                }
11910            }
11911
11912            for (buffer, ranges) in ranges_by_buffer {
11913                buffer.update(cx, |buffer, cx| {
11914                    buffer.merge_into_base(ranges, cx);
11915                });
11916            }
11917        });
11918
11919        if let Some(project) = self.project.clone() {
11920            self.save(true, project, window, cx).detach_and_log_err(cx);
11921        }
11922    }
11923
11924    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
11925        if hovered != self.gutter_hovered {
11926            self.gutter_hovered = hovered;
11927            cx.notify();
11928        }
11929    }
11930
11931    pub fn insert_blocks(
11932        &mut self,
11933        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11934        autoscroll: Option<Autoscroll>,
11935        cx: &mut Context<Self>,
11936    ) -> Vec<CustomBlockId> {
11937        let blocks = self
11938            .display_map
11939            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11940        if let Some(autoscroll) = autoscroll {
11941            self.request_autoscroll(autoscroll, cx);
11942        }
11943        cx.notify();
11944        blocks
11945    }
11946
11947    pub fn resize_blocks(
11948        &mut self,
11949        heights: HashMap<CustomBlockId, u32>,
11950        autoscroll: Option<Autoscroll>,
11951        cx: &mut Context<Self>,
11952    ) {
11953        self.display_map
11954            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11955        if let Some(autoscroll) = autoscroll {
11956            self.request_autoscroll(autoscroll, cx);
11957        }
11958        cx.notify();
11959    }
11960
11961    pub fn replace_blocks(
11962        &mut self,
11963        renderers: HashMap<CustomBlockId, RenderBlock>,
11964        autoscroll: Option<Autoscroll>,
11965        cx: &mut Context<Self>,
11966    ) {
11967        self.display_map
11968            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11969        if let Some(autoscroll) = autoscroll {
11970            self.request_autoscroll(autoscroll, cx);
11971        }
11972        cx.notify();
11973    }
11974
11975    pub fn remove_blocks(
11976        &mut self,
11977        block_ids: HashSet<CustomBlockId>,
11978        autoscroll: Option<Autoscroll>,
11979        cx: &mut Context<Self>,
11980    ) {
11981        self.display_map.update(cx, |display_map, cx| {
11982            display_map.remove_blocks(block_ids, cx)
11983        });
11984        if let Some(autoscroll) = autoscroll {
11985            self.request_autoscroll(autoscroll, cx);
11986        }
11987        cx.notify();
11988    }
11989
11990    pub fn row_for_block(
11991        &self,
11992        block_id: CustomBlockId,
11993        cx: &mut Context<Self>,
11994    ) -> Option<DisplayRow> {
11995        self.display_map
11996            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11997    }
11998
11999    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12000        self.focused_block = Some(focused_block);
12001    }
12002
12003    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12004        self.focused_block.take()
12005    }
12006
12007    pub fn insert_creases(
12008        &mut self,
12009        creases: impl IntoIterator<Item = Crease<Anchor>>,
12010        cx: &mut Context<Self>,
12011    ) -> Vec<CreaseId> {
12012        self.display_map
12013            .update(cx, |map, cx| map.insert_creases(creases, cx))
12014    }
12015
12016    pub fn remove_creases(
12017        &mut self,
12018        ids: impl IntoIterator<Item = CreaseId>,
12019        cx: &mut Context<Self>,
12020    ) {
12021        self.display_map
12022            .update(cx, |map, cx| map.remove_creases(ids, cx));
12023    }
12024
12025    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12026        self.display_map
12027            .update(cx, |map, cx| map.snapshot(cx))
12028            .longest_row()
12029    }
12030
12031    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12032        self.display_map
12033            .update(cx, |map, cx| map.snapshot(cx))
12034            .max_point()
12035    }
12036
12037    pub fn text(&self, cx: &App) -> String {
12038        self.buffer.read(cx).read(cx).text()
12039    }
12040
12041    pub fn text_option(&self, cx: &App) -> Option<String> {
12042        let text = self.text(cx);
12043        let text = text.trim();
12044
12045        if text.is_empty() {
12046            return None;
12047        }
12048
12049        Some(text.to_string())
12050    }
12051
12052    pub fn set_text(
12053        &mut self,
12054        text: impl Into<Arc<str>>,
12055        window: &mut Window,
12056        cx: &mut Context<Self>,
12057    ) {
12058        self.transact(window, cx, |this, _, cx| {
12059            this.buffer
12060                .read(cx)
12061                .as_singleton()
12062                .expect("you can only call set_text on editors for singleton buffers")
12063                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12064        });
12065    }
12066
12067    pub fn display_text(&self, cx: &mut App) -> String {
12068        self.display_map
12069            .update(cx, |map, cx| map.snapshot(cx))
12070            .text()
12071    }
12072
12073    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12074        let mut wrap_guides = smallvec::smallvec![];
12075
12076        if self.show_wrap_guides == Some(false) {
12077            return wrap_guides;
12078        }
12079
12080        let settings = self.buffer.read(cx).settings_at(0, cx);
12081        if settings.show_wrap_guides {
12082            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12083                wrap_guides.push((soft_wrap as usize, true));
12084            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12085                wrap_guides.push((soft_wrap as usize, true));
12086            }
12087            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12088        }
12089
12090        wrap_guides
12091    }
12092
12093    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12094        let settings = self.buffer.read(cx).settings_at(0, cx);
12095        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12096        match mode {
12097            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12098                SoftWrap::None
12099            }
12100            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12101            language_settings::SoftWrap::PreferredLineLength => {
12102                SoftWrap::Column(settings.preferred_line_length)
12103            }
12104            language_settings::SoftWrap::Bounded => {
12105                SoftWrap::Bounded(settings.preferred_line_length)
12106            }
12107        }
12108    }
12109
12110    pub fn set_soft_wrap_mode(
12111        &mut self,
12112        mode: language_settings::SoftWrap,
12113
12114        cx: &mut Context<Self>,
12115    ) {
12116        self.soft_wrap_mode_override = Some(mode);
12117        cx.notify();
12118    }
12119
12120    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12121        self.text_style_refinement = Some(style);
12122    }
12123
12124    /// called by the Element so we know what style we were most recently rendered with.
12125    pub(crate) fn set_style(
12126        &mut self,
12127        style: EditorStyle,
12128        window: &mut Window,
12129        cx: &mut Context<Self>,
12130    ) {
12131        let rem_size = window.rem_size();
12132        self.display_map.update(cx, |map, cx| {
12133            map.set_font(
12134                style.text.font(),
12135                style.text.font_size.to_pixels(rem_size),
12136                cx,
12137            )
12138        });
12139        self.style = Some(style);
12140    }
12141
12142    pub fn style(&self) -> Option<&EditorStyle> {
12143        self.style.as_ref()
12144    }
12145
12146    // Called by the element. This method is not designed to be called outside of the editor
12147    // element's layout code because it does not notify when rewrapping is computed synchronously.
12148    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12149        self.display_map
12150            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12151    }
12152
12153    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12154        if self.soft_wrap_mode_override.is_some() {
12155            self.soft_wrap_mode_override.take();
12156        } else {
12157            let soft_wrap = match self.soft_wrap_mode(cx) {
12158                SoftWrap::GitDiff => return,
12159                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12160                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12161                    language_settings::SoftWrap::None
12162                }
12163            };
12164            self.soft_wrap_mode_override = Some(soft_wrap);
12165        }
12166        cx.notify();
12167    }
12168
12169    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12170        let Some(workspace) = self.workspace() else {
12171            return;
12172        };
12173        let fs = workspace.read(cx).app_state().fs.clone();
12174        let current_show = TabBarSettings::get_global(cx).show;
12175        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12176            setting.show = Some(!current_show);
12177        });
12178    }
12179
12180    pub fn toggle_indent_guides(
12181        &mut self,
12182        _: &ToggleIndentGuides,
12183        _: &mut Window,
12184        cx: &mut Context<Self>,
12185    ) {
12186        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12187            self.buffer
12188                .read(cx)
12189                .settings_at(0, cx)
12190                .indent_guides
12191                .enabled
12192        });
12193        self.show_indent_guides = Some(!currently_enabled);
12194        cx.notify();
12195    }
12196
12197    fn should_show_indent_guides(&self) -> Option<bool> {
12198        self.show_indent_guides
12199    }
12200
12201    pub fn toggle_line_numbers(
12202        &mut self,
12203        _: &ToggleLineNumbers,
12204        _: &mut Window,
12205        cx: &mut Context<Self>,
12206    ) {
12207        let mut editor_settings = EditorSettings::get_global(cx).clone();
12208        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12209        EditorSettings::override_global(editor_settings, cx);
12210    }
12211
12212    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12213        self.use_relative_line_numbers
12214            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12215    }
12216
12217    pub fn toggle_relative_line_numbers(
12218        &mut self,
12219        _: &ToggleRelativeLineNumbers,
12220        _: &mut Window,
12221        cx: &mut Context<Self>,
12222    ) {
12223        let is_relative = self.should_use_relative_line_numbers(cx);
12224        self.set_relative_line_number(Some(!is_relative), cx)
12225    }
12226
12227    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12228        self.use_relative_line_numbers = is_relative;
12229        cx.notify();
12230    }
12231
12232    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12233        self.show_gutter = show_gutter;
12234        cx.notify();
12235    }
12236
12237    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12238        self.show_scrollbars = show_scrollbars;
12239        cx.notify();
12240    }
12241
12242    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12243        self.show_line_numbers = Some(show_line_numbers);
12244        cx.notify();
12245    }
12246
12247    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12248        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12249        cx.notify();
12250    }
12251
12252    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12253        self.show_code_actions = Some(show_code_actions);
12254        cx.notify();
12255    }
12256
12257    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12258        self.show_runnables = Some(show_runnables);
12259        cx.notify();
12260    }
12261
12262    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12263        if self.display_map.read(cx).masked != masked {
12264            self.display_map.update(cx, |map, _| map.masked = masked);
12265        }
12266        cx.notify()
12267    }
12268
12269    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12270        self.show_wrap_guides = Some(show_wrap_guides);
12271        cx.notify();
12272    }
12273
12274    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12275        self.show_indent_guides = Some(show_indent_guides);
12276        cx.notify();
12277    }
12278
12279    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12280        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12281            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12282                if let Some(dir) = file.abs_path(cx).parent() {
12283                    return Some(dir.to_owned());
12284                }
12285            }
12286
12287            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12288                return Some(project_path.path.to_path_buf());
12289            }
12290        }
12291
12292        None
12293    }
12294
12295    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12296        self.active_excerpt(cx)?
12297            .1
12298            .read(cx)
12299            .file()
12300            .and_then(|f| f.as_local())
12301    }
12302
12303    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12304        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12305            let project_path = buffer.read(cx).project_path(cx)?;
12306            let project = self.project.as_ref()?.read(cx);
12307            project.absolute_path(&project_path, cx)
12308        })
12309    }
12310
12311    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12312        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12313            let project_path = buffer.read(cx).project_path(cx)?;
12314            let project = self.project.as_ref()?.read(cx);
12315            let entry = project.entry_for_path(&project_path, cx)?;
12316            let path = entry.path.to_path_buf();
12317            Some(path)
12318        })
12319    }
12320
12321    pub fn reveal_in_finder(
12322        &mut self,
12323        _: &RevealInFileManager,
12324        _window: &mut Window,
12325        cx: &mut Context<Self>,
12326    ) {
12327        if let Some(target) = self.target_file(cx) {
12328            cx.reveal_path(&target.abs_path(cx));
12329        }
12330    }
12331
12332    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12333        if let Some(path) = self.target_file_abs_path(cx) {
12334            if let Some(path) = path.to_str() {
12335                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12336            }
12337        }
12338    }
12339
12340    pub fn copy_relative_path(
12341        &mut self,
12342        _: &CopyRelativePath,
12343        _window: &mut Window,
12344        cx: &mut Context<Self>,
12345    ) {
12346        if let Some(path) = self.target_file_path(cx) {
12347            if let Some(path) = path.to_str() {
12348                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12349            }
12350        }
12351    }
12352
12353    pub fn toggle_git_blame(
12354        &mut self,
12355        _: &ToggleGitBlame,
12356        window: &mut Window,
12357        cx: &mut Context<Self>,
12358    ) {
12359        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12360
12361        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12362            self.start_git_blame(true, window, cx);
12363        }
12364
12365        cx.notify();
12366    }
12367
12368    pub fn toggle_git_blame_inline(
12369        &mut self,
12370        _: &ToggleGitBlameInline,
12371        window: &mut Window,
12372        cx: &mut Context<Self>,
12373    ) {
12374        self.toggle_git_blame_inline_internal(true, window, cx);
12375        cx.notify();
12376    }
12377
12378    pub fn git_blame_inline_enabled(&self) -> bool {
12379        self.git_blame_inline_enabled
12380    }
12381
12382    pub fn toggle_selection_menu(
12383        &mut self,
12384        _: &ToggleSelectionMenu,
12385        _: &mut Window,
12386        cx: &mut Context<Self>,
12387    ) {
12388        self.show_selection_menu = self
12389            .show_selection_menu
12390            .map(|show_selections_menu| !show_selections_menu)
12391            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12392
12393        cx.notify();
12394    }
12395
12396    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12397        self.show_selection_menu
12398            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12399    }
12400
12401    fn start_git_blame(
12402        &mut self,
12403        user_triggered: bool,
12404        window: &mut Window,
12405        cx: &mut Context<Self>,
12406    ) {
12407        if let Some(project) = self.project.as_ref() {
12408            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12409                return;
12410            };
12411
12412            if buffer.read(cx).file().is_none() {
12413                return;
12414            }
12415
12416            let focused = self.focus_handle(cx).contains_focused(window, cx);
12417
12418            let project = project.clone();
12419            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12420            self.blame_subscription =
12421                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12422            self.blame = Some(blame);
12423        }
12424    }
12425
12426    fn toggle_git_blame_inline_internal(
12427        &mut self,
12428        user_triggered: bool,
12429        window: &mut Window,
12430        cx: &mut Context<Self>,
12431    ) {
12432        if self.git_blame_inline_enabled {
12433            self.git_blame_inline_enabled = false;
12434            self.show_git_blame_inline = false;
12435            self.show_git_blame_inline_delay_task.take();
12436        } else {
12437            self.git_blame_inline_enabled = true;
12438            self.start_git_blame_inline(user_triggered, window, cx);
12439        }
12440
12441        cx.notify();
12442    }
12443
12444    fn start_git_blame_inline(
12445        &mut self,
12446        user_triggered: bool,
12447        window: &mut Window,
12448        cx: &mut Context<Self>,
12449    ) {
12450        self.start_git_blame(user_triggered, window, cx);
12451
12452        if ProjectSettings::get_global(cx)
12453            .git
12454            .inline_blame_delay()
12455            .is_some()
12456        {
12457            self.start_inline_blame_timer(window, cx);
12458        } else {
12459            self.show_git_blame_inline = true
12460        }
12461    }
12462
12463    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12464        self.blame.as_ref()
12465    }
12466
12467    pub fn show_git_blame_gutter(&self) -> bool {
12468        self.show_git_blame_gutter
12469    }
12470
12471    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12472        self.show_git_blame_gutter && self.has_blame_entries(cx)
12473    }
12474
12475    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12476        self.show_git_blame_inline
12477            && self.focus_handle.is_focused(window)
12478            && !self.newest_selection_head_on_empty_line(cx)
12479            && self.has_blame_entries(cx)
12480    }
12481
12482    fn has_blame_entries(&self, cx: &App) -> bool {
12483        self.blame()
12484            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12485    }
12486
12487    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12488        let cursor_anchor = self.selections.newest_anchor().head();
12489
12490        let snapshot = self.buffer.read(cx).snapshot(cx);
12491        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12492
12493        snapshot.line_len(buffer_row) == 0
12494    }
12495
12496    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12497        let buffer_and_selection = maybe!({
12498            let selection = self.selections.newest::<Point>(cx);
12499            let selection_range = selection.range();
12500
12501            let multi_buffer = self.buffer().read(cx);
12502            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12503            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12504
12505            let (buffer, range, _) = if selection.reversed {
12506                buffer_ranges.first()
12507            } else {
12508                buffer_ranges.last()
12509            }?;
12510
12511            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12512                ..text::ToPoint::to_point(&range.end, &buffer).row;
12513            Some((
12514                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12515                selection,
12516            ))
12517        });
12518
12519        let Some((buffer, selection)) = buffer_and_selection else {
12520            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12521        };
12522
12523        let Some(project) = self.project.as_ref() else {
12524            return Task::ready(Err(anyhow!("editor does not have project")));
12525        };
12526
12527        project.update(cx, |project, cx| {
12528            project.get_permalink_to_line(&buffer, selection, cx)
12529        })
12530    }
12531
12532    pub fn copy_permalink_to_line(
12533        &mut self,
12534        _: &CopyPermalinkToLine,
12535        window: &mut Window,
12536        cx: &mut Context<Self>,
12537    ) {
12538        let permalink_task = self.get_permalink_to_line(cx);
12539        let workspace = self.workspace();
12540
12541        cx.spawn_in(window, |_, mut cx| async move {
12542            match permalink_task.await {
12543                Ok(permalink) => {
12544                    cx.update(|_, cx| {
12545                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12546                    })
12547                    .ok();
12548                }
12549                Err(err) => {
12550                    let message = format!("Failed to copy permalink: {err}");
12551
12552                    Err::<(), anyhow::Error>(err).log_err();
12553
12554                    if let Some(workspace) = workspace {
12555                        workspace
12556                            .update_in(&mut cx, |workspace, _, cx| {
12557                                struct CopyPermalinkToLine;
12558
12559                                workspace.show_toast(
12560                                    Toast::new(
12561                                        NotificationId::unique::<CopyPermalinkToLine>(),
12562                                        message,
12563                                    ),
12564                                    cx,
12565                                )
12566                            })
12567                            .ok();
12568                    }
12569                }
12570            }
12571        })
12572        .detach();
12573    }
12574
12575    pub fn copy_file_location(
12576        &mut self,
12577        _: &CopyFileLocation,
12578        _: &mut Window,
12579        cx: &mut Context<Self>,
12580    ) {
12581        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12582        if let Some(file) = self.target_file(cx) {
12583            if let Some(path) = file.path().to_str() {
12584                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12585            }
12586        }
12587    }
12588
12589    pub fn open_permalink_to_line(
12590        &mut self,
12591        _: &OpenPermalinkToLine,
12592        window: &mut Window,
12593        cx: &mut Context<Self>,
12594    ) {
12595        let permalink_task = self.get_permalink_to_line(cx);
12596        let workspace = self.workspace();
12597
12598        cx.spawn_in(window, |_, mut cx| async move {
12599            match permalink_task.await {
12600                Ok(permalink) => {
12601                    cx.update(|_, cx| {
12602                        cx.open_url(permalink.as_ref());
12603                    })
12604                    .ok();
12605                }
12606                Err(err) => {
12607                    let message = format!("Failed to open permalink: {err}");
12608
12609                    Err::<(), anyhow::Error>(err).log_err();
12610
12611                    if let Some(workspace) = workspace {
12612                        workspace
12613                            .update(&mut cx, |workspace, cx| {
12614                                struct OpenPermalinkToLine;
12615
12616                                workspace.show_toast(
12617                                    Toast::new(
12618                                        NotificationId::unique::<OpenPermalinkToLine>(),
12619                                        message,
12620                                    ),
12621                                    cx,
12622                                )
12623                            })
12624                            .ok();
12625                    }
12626                }
12627            }
12628        })
12629        .detach();
12630    }
12631
12632    pub fn insert_uuid_v4(
12633        &mut self,
12634        _: &InsertUuidV4,
12635        window: &mut Window,
12636        cx: &mut Context<Self>,
12637    ) {
12638        self.insert_uuid(UuidVersion::V4, window, cx);
12639    }
12640
12641    pub fn insert_uuid_v7(
12642        &mut self,
12643        _: &InsertUuidV7,
12644        window: &mut Window,
12645        cx: &mut Context<Self>,
12646    ) {
12647        self.insert_uuid(UuidVersion::V7, window, cx);
12648    }
12649
12650    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12651        self.transact(window, cx, |this, window, cx| {
12652            let edits = this
12653                .selections
12654                .all::<Point>(cx)
12655                .into_iter()
12656                .map(|selection| {
12657                    let uuid = match version {
12658                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12659                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12660                    };
12661
12662                    (selection.range(), uuid.to_string())
12663                });
12664            this.edit(edits, cx);
12665            this.refresh_inline_completion(true, false, window, cx);
12666        });
12667    }
12668
12669    pub fn open_selections_in_multibuffer(
12670        &mut self,
12671        _: &OpenSelectionsInMultibuffer,
12672        window: &mut Window,
12673        cx: &mut Context<Self>,
12674    ) {
12675        let multibuffer = self.buffer.read(cx);
12676
12677        let Some(buffer) = multibuffer.as_singleton() else {
12678            return;
12679        };
12680
12681        let Some(workspace) = self.workspace() else {
12682            return;
12683        };
12684
12685        let locations = self
12686            .selections
12687            .disjoint_anchors()
12688            .iter()
12689            .map(|range| Location {
12690                buffer: buffer.clone(),
12691                range: range.start.text_anchor..range.end.text_anchor,
12692            })
12693            .collect::<Vec<_>>();
12694
12695        let title = multibuffer.title(cx).to_string();
12696
12697        cx.spawn_in(window, |_, mut cx| async move {
12698            workspace.update_in(&mut cx, |workspace, window, cx| {
12699                Self::open_locations_in_multibuffer(
12700                    workspace,
12701                    locations,
12702                    format!("Selections for '{title}'"),
12703                    false,
12704                    MultibufferSelectionMode::All,
12705                    window,
12706                    cx,
12707                );
12708            })
12709        })
12710        .detach();
12711    }
12712
12713    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12714    /// last highlight added will be used.
12715    ///
12716    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12717    pub fn highlight_rows<T: 'static>(
12718        &mut self,
12719        range: Range<Anchor>,
12720        color: Hsla,
12721        should_autoscroll: bool,
12722        cx: &mut Context<Self>,
12723    ) {
12724        let snapshot = self.buffer().read(cx).snapshot(cx);
12725        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12726        let ix = row_highlights.binary_search_by(|highlight| {
12727            Ordering::Equal
12728                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12729                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12730        });
12731
12732        if let Err(mut ix) = ix {
12733            let index = post_inc(&mut self.highlight_order);
12734
12735            // If this range intersects with the preceding highlight, then merge it with
12736            // the preceding highlight. Otherwise insert a new highlight.
12737            let mut merged = false;
12738            if ix > 0 {
12739                let prev_highlight = &mut row_highlights[ix - 1];
12740                if prev_highlight
12741                    .range
12742                    .end
12743                    .cmp(&range.start, &snapshot)
12744                    .is_ge()
12745                {
12746                    ix -= 1;
12747                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12748                        prev_highlight.range.end = range.end;
12749                    }
12750                    merged = true;
12751                    prev_highlight.index = index;
12752                    prev_highlight.color = color;
12753                    prev_highlight.should_autoscroll = should_autoscroll;
12754                }
12755            }
12756
12757            if !merged {
12758                row_highlights.insert(
12759                    ix,
12760                    RowHighlight {
12761                        range: range.clone(),
12762                        index,
12763                        color,
12764                        should_autoscroll,
12765                    },
12766                );
12767            }
12768
12769            // If any of the following highlights intersect with this one, merge them.
12770            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12771                let highlight = &row_highlights[ix];
12772                if next_highlight
12773                    .range
12774                    .start
12775                    .cmp(&highlight.range.end, &snapshot)
12776                    .is_le()
12777                {
12778                    if next_highlight
12779                        .range
12780                        .end
12781                        .cmp(&highlight.range.end, &snapshot)
12782                        .is_gt()
12783                    {
12784                        row_highlights[ix].range.end = next_highlight.range.end;
12785                    }
12786                    row_highlights.remove(ix + 1);
12787                } else {
12788                    break;
12789                }
12790            }
12791        }
12792    }
12793
12794    /// Remove any highlighted row ranges of the given type that intersect the
12795    /// given ranges.
12796    pub fn remove_highlighted_rows<T: 'static>(
12797        &mut self,
12798        ranges_to_remove: Vec<Range<Anchor>>,
12799        cx: &mut Context<Self>,
12800    ) {
12801        let snapshot = self.buffer().read(cx).snapshot(cx);
12802        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12803        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12804        row_highlights.retain(|highlight| {
12805            while let Some(range_to_remove) = ranges_to_remove.peek() {
12806                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12807                    Ordering::Less | Ordering::Equal => {
12808                        ranges_to_remove.next();
12809                    }
12810                    Ordering::Greater => {
12811                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12812                            Ordering::Less | Ordering::Equal => {
12813                                return false;
12814                            }
12815                            Ordering::Greater => break,
12816                        }
12817                    }
12818                }
12819            }
12820
12821            true
12822        })
12823    }
12824
12825    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12826    pub fn clear_row_highlights<T: 'static>(&mut self) {
12827        self.highlighted_rows.remove(&TypeId::of::<T>());
12828    }
12829
12830    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12831    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12832        self.highlighted_rows
12833            .get(&TypeId::of::<T>())
12834            .map_or(&[] as &[_], |vec| vec.as_slice())
12835            .iter()
12836            .map(|highlight| (highlight.range.clone(), highlight.color))
12837    }
12838
12839    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12840    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12841    /// Allows to ignore certain kinds of highlights.
12842    pub fn highlighted_display_rows(
12843        &self,
12844        window: &mut Window,
12845        cx: &mut App,
12846    ) -> BTreeMap<DisplayRow, Hsla> {
12847        let snapshot = self.snapshot(window, cx);
12848        let mut used_highlight_orders = HashMap::default();
12849        self.highlighted_rows
12850            .iter()
12851            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12852            .fold(
12853                BTreeMap::<DisplayRow, Hsla>::new(),
12854                |mut unique_rows, highlight| {
12855                    let start = highlight.range.start.to_display_point(&snapshot);
12856                    let end = highlight.range.end.to_display_point(&snapshot);
12857                    let start_row = start.row().0;
12858                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12859                        && end.column() == 0
12860                    {
12861                        end.row().0.saturating_sub(1)
12862                    } else {
12863                        end.row().0
12864                    };
12865                    for row in start_row..=end_row {
12866                        let used_index =
12867                            used_highlight_orders.entry(row).or_insert(highlight.index);
12868                        if highlight.index >= *used_index {
12869                            *used_index = highlight.index;
12870                            unique_rows.insert(DisplayRow(row), highlight.color);
12871                        }
12872                    }
12873                    unique_rows
12874                },
12875            )
12876    }
12877
12878    pub fn highlighted_display_row_for_autoscroll(
12879        &self,
12880        snapshot: &DisplaySnapshot,
12881    ) -> Option<DisplayRow> {
12882        self.highlighted_rows
12883            .values()
12884            .flat_map(|highlighted_rows| highlighted_rows.iter())
12885            .filter_map(|highlight| {
12886                if highlight.should_autoscroll {
12887                    Some(highlight.range.start.to_display_point(snapshot).row())
12888                } else {
12889                    None
12890                }
12891            })
12892            .min()
12893    }
12894
12895    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
12896        self.highlight_background::<SearchWithinRange>(
12897            ranges,
12898            |colors| colors.editor_document_highlight_read_background,
12899            cx,
12900        )
12901    }
12902
12903    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12904        self.breadcrumb_header = Some(new_header);
12905    }
12906
12907    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
12908        self.clear_background_highlights::<SearchWithinRange>(cx);
12909    }
12910
12911    pub fn highlight_background<T: 'static>(
12912        &mut self,
12913        ranges: &[Range<Anchor>],
12914        color_fetcher: fn(&ThemeColors) -> Hsla,
12915        cx: &mut Context<Self>,
12916    ) {
12917        self.background_highlights
12918            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12919        self.scrollbar_marker_state.dirty = true;
12920        cx.notify();
12921    }
12922
12923    pub fn clear_background_highlights<T: 'static>(
12924        &mut self,
12925        cx: &mut Context<Self>,
12926    ) -> Option<BackgroundHighlight> {
12927        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12928        if !text_highlights.1.is_empty() {
12929            self.scrollbar_marker_state.dirty = true;
12930            cx.notify();
12931        }
12932        Some(text_highlights)
12933    }
12934
12935    pub fn highlight_gutter<T: 'static>(
12936        &mut self,
12937        ranges: &[Range<Anchor>],
12938        color_fetcher: fn(&App) -> Hsla,
12939        cx: &mut Context<Self>,
12940    ) {
12941        self.gutter_highlights
12942            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12943        cx.notify();
12944    }
12945
12946    pub fn clear_gutter_highlights<T: 'static>(
12947        &mut self,
12948        cx: &mut Context<Self>,
12949    ) -> Option<GutterHighlight> {
12950        cx.notify();
12951        self.gutter_highlights.remove(&TypeId::of::<T>())
12952    }
12953
12954    #[cfg(feature = "test-support")]
12955    pub fn all_text_background_highlights(
12956        &self,
12957        window: &mut Window,
12958        cx: &mut Context<Self>,
12959    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12960        let snapshot = self.snapshot(window, cx);
12961        let buffer = &snapshot.buffer_snapshot;
12962        let start = buffer.anchor_before(0);
12963        let end = buffer.anchor_after(buffer.len());
12964        let theme = cx.theme().colors();
12965        self.background_highlights_in_range(start..end, &snapshot, theme)
12966    }
12967
12968    #[cfg(feature = "test-support")]
12969    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
12970        let snapshot = self.buffer().read(cx).snapshot(cx);
12971
12972        let highlights = self
12973            .background_highlights
12974            .get(&TypeId::of::<items::BufferSearchHighlights>());
12975
12976        if let Some((_color, ranges)) = highlights {
12977            ranges
12978                .iter()
12979                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12980                .collect_vec()
12981        } else {
12982            vec![]
12983        }
12984    }
12985
12986    fn document_highlights_for_position<'a>(
12987        &'a self,
12988        position: Anchor,
12989        buffer: &'a MultiBufferSnapshot,
12990    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12991        let read_highlights = self
12992            .background_highlights
12993            .get(&TypeId::of::<DocumentHighlightRead>())
12994            .map(|h| &h.1);
12995        let write_highlights = self
12996            .background_highlights
12997            .get(&TypeId::of::<DocumentHighlightWrite>())
12998            .map(|h| &h.1);
12999        let left_position = position.bias_left(buffer);
13000        let right_position = position.bias_right(buffer);
13001        read_highlights
13002            .into_iter()
13003            .chain(write_highlights)
13004            .flat_map(move |ranges| {
13005                let start_ix = match ranges.binary_search_by(|probe| {
13006                    let cmp = probe.end.cmp(&left_position, buffer);
13007                    if cmp.is_ge() {
13008                        Ordering::Greater
13009                    } else {
13010                        Ordering::Less
13011                    }
13012                }) {
13013                    Ok(i) | Err(i) => i,
13014                };
13015
13016                ranges[start_ix..]
13017                    .iter()
13018                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13019            })
13020    }
13021
13022    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13023        self.background_highlights
13024            .get(&TypeId::of::<T>())
13025            .map_or(false, |(_, highlights)| !highlights.is_empty())
13026    }
13027
13028    pub fn background_highlights_in_range(
13029        &self,
13030        search_range: Range<Anchor>,
13031        display_snapshot: &DisplaySnapshot,
13032        theme: &ThemeColors,
13033    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13034        let mut results = Vec::new();
13035        for (color_fetcher, ranges) in self.background_highlights.values() {
13036            let color = color_fetcher(theme);
13037            let start_ix = match ranges.binary_search_by(|probe| {
13038                let cmp = probe
13039                    .end
13040                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13041                if cmp.is_gt() {
13042                    Ordering::Greater
13043                } else {
13044                    Ordering::Less
13045                }
13046            }) {
13047                Ok(i) | Err(i) => i,
13048            };
13049            for range in &ranges[start_ix..] {
13050                if range
13051                    .start
13052                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13053                    .is_ge()
13054                {
13055                    break;
13056                }
13057
13058                let start = range.start.to_display_point(display_snapshot);
13059                let end = range.end.to_display_point(display_snapshot);
13060                results.push((start..end, color))
13061            }
13062        }
13063        results
13064    }
13065
13066    pub fn background_highlight_row_ranges<T: 'static>(
13067        &self,
13068        search_range: Range<Anchor>,
13069        display_snapshot: &DisplaySnapshot,
13070        count: usize,
13071    ) -> Vec<RangeInclusive<DisplayPoint>> {
13072        let mut results = Vec::new();
13073        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13074            return vec![];
13075        };
13076
13077        let start_ix = match ranges.binary_search_by(|probe| {
13078            let cmp = probe
13079                .end
13080                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13081            if cmp.is_gt() {
13082                Ordering::Greater
13083            } else {
13084                Ordering::Less
13085            }
13086        }) {
13087            Ok(i) | Err(i) => i,
13088        };
13089        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13090            if let (Some(start_display), Some(end_display)) = (start, end) {
13091                results.push(
13092                    start_display.to_display_point(display_snapshot)
13093                        ..=end_display.to_display_point(display_snapshot),
13094                );
13095            }
13096        };
13097        let mut start_row: Option<Point> = None;
13098        let mut end_row: Option<Point> = None;
13099        if ranges.len() > count {
13100            return Vec::new();
13101        }
13102        for range in &ranges[start_ix..] {
13103            if range
13104                .start
13105                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13106                .is_ge()
13107            {
13108                break;
13109            }
13110            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13111            if let Some(current_row) = &end_row {
13112                if end.row == current_row.row {
13113                    continue;
13114                }
13115            }
13116            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13117            if start_row.is_none() {
13118                assert_eq!(end_row, None);
13119                start_row = Some(start);
13120                end_row = Some(end);
13121                continue;
13122            }
13123            if let Some(current_end) = end_row.as_mut() {
13124                if start.row > current_end.row + 1 {
13125                    push_region(start_row, end_row);
13126                    start_row = Some(start);
13127                    end_row = Some(end);
13128                } else {
13129                    // Merge two hunks.
13130                    *current_end = end;
13131                }
13132            } else {
13133                unreachable!();
13134            }
13135        }
13136        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13137        push_region(start_row, end_row);
13138        results
13139    }
13140
13141    pub fn gutter_highlights_in_range(
13142        &self,
13143        search_range: Range<Anchor>,
13144        display_snapshot: &DisplaySnapshot,
13145        cx: &App,
13146    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13147        let mut results = Vec::new();
13148        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13149            let color = color_fetcher(cx);
13150            let start_ix = match ranges.binary_search_by(|probe| {
13151                let cmp = probe
13152                    .end
13153                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13154                if cmp.is_gt() {
13155                    Ordering::Greater
13156                } else {
13157                    Ordering::Less
13158                }
13159            }) {
13160                Ok(i) | Err(i) => i,
13161            };
13162            for range in &ranges[start_ix..] {
13163                if range
13164                    .start
13165                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13166                    .is_ge()
13167                {
13168                    break;
13169                }
13170
13171                let start = range.start.to_display_point(display_snapshot);
13172                let end = range.end.to_display_point(display_snapshot);
13173                results.push((start..end, color))
13174            }
13175        }
13176        results
13177    }
13178
13179    /// Get the text ranges corresponding to the redaction query
13180    pub fn redacted_ranges(
13181        &self,
13182        search_range: Range<Anchor>,
13183        display_snapshot: &DisplaySnapshot,
13184        cx: &App,
13185    ) -> Vec<Range<DisplayPoint>> {
13186        display_snapshot
13187            .buffer_snapshot
13188            .redacted_ranges(search_range, |file| {
13189                if let Some(file) = file {
13190                    file.is_private()
13191                        && EditorSettings::get(
13192                            Some(SettingsLocation {
13193                                worktree_id: file.worktree_id(cx),
13194                                path: file.path().as_ref(),
13195                            }),
13196                            cx,
13197                        )
13198                        .redact_private_values
13199                } else {
13200                    false
13201                }
13202            })
13203            .map(|range| {
13204                range.start.to_display_point(display_snapshot)
13205                    ..range.end.to_display_point(display_snapshot)
13206            })
13207            .collect()
13208    }
13209
13210    pub fn highlight_text<T: 'static>(
13211        &mut self,
13212        ranges: Vec<Range<Anchor>>,
13213        style: HighlightStyle,
13214        cx: &mut Context<Self>,
13215    ) {
13216        self.display_map.update(cx, |map, _| {
13217            map.highlight_text(TypeId::of::<T>(), ranges, style)
13218        });
13219        cx.notify();
13220    }
13221
13222    pub(crate) fn highlight_inlays<T: 'static>(
13223        &mut self,
13224        highlights: Vec<InlayHighlight>,
13225        style: HighlightStyle,
13226        cx: &mut Context<Self>,
13227    ) {
13228        self.display_map.update(cx, |map, _| {
13229            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13230        });
13231        cx.notify();
13232    }
13233
13234    pub fn text_highlights<'a, T: 'static>(
13235        &'a self,
13236        cx: &'a App,
13237    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13238        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13239    }
13240
13241    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13242        let cleared = self
13243            .display_map
13244            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13245        if cleared {
13246            cx.notify();
13247        }
13248    }
13249
13250    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13251        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13252            && self.focus_handle.is_focused(window)
13253    }
13254
13255    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13256        self.show_cursor_when_unfocused = is_enabled;
13257        cx.notify();
13258    }
13259
13260    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13261        self.project
13262            .as_ref()
13263            .map(|project| project.read(cx).lsp_store())
13264    }
13265
13266    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13267        cx.notify();
13268    }
13269
13270    fn on_buffer_event(
13271        &mut self,
13272        multibuffer: &Entity<MultiBuffer>,
13273        event: &multi_buffer::Event,
13274        window: &mut Window,
13275        cx: &mut Context<Self>,
13276    ) {
13277        match event {
13278            multi_buffer::Event::Edited {
13279                singleton_buffer_edited,
13280                edited_buffer: buffer_edited,
13281            } => {
13282                self.scrollbar_marker_state.dirty = true;
13283                self.active_indent_guides_state.dirty = true;
13284                self.refresh_active_diagnostics(cx);
13285                self.refresh_code_actions(window, cx);
13286                if self.has_active_inline_completion() {
13287                    self.update_visible_inline_completion(window, cx);
13288                }
13289                if let Some(buffer) = buffer_edited {
13290                    let buffer_id = buffer.read(cx).remote_id();
13291                    if !self.registered_buffers.contains_key(&buffer_id) {
13292                        if let Some(lsp_store) = self.lsp_store(cx) {
13293                            lsp_store.update(cx, |lsp_store, cx| {
13294                                self.registered_buffers.insert(
13295                                    buffer_id,
13296                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13297                                );
13298                            })
13299                        }
13300                    }
13301                }
13302                cx.emit(EditorEvent::BufferEdited);
13303                cx.emit(SearchEvent::MatchesInvalidated);
13304                if *singleton_buffer_edited {
13305                    if let Some(project) = &self.project {
13306                        let project = project.read(cx);
13307                        #[allow(clippy::mutable_key_type)]
13308                        let languages_affected = multibuffer
13309                            .read(cx)
13310                            .all_buffers()
13311                            .into_iter()
13312                            .filter_map(|buffer| {
13313                                let buffer = buffer.read(cx);
13314                                let language = buffer.language()?;
13315                                if project.is_local()
13316                                    && project
13317                                        .language_servers_for_local_buffer(buffer, cx)
13318                                        .count()
13319                                        == 0
13320                                {
13321                                    None
13322                                } else {
13323                                    Some(language)
13324                                }
13325                            })
13326                            .cloned()
13327                            .collect::<HashSet<_>>();
13328                        if !languages_affected.is_empty() {
13329                            self.refresh_inlay_hints(
13330                                InlayHintRefreshReason::BufferEdited(languages_affected),
13331                                cx,
13332                            );
13333                        }
13334                    }
13335                }
13336
13337                let Some(project) = &self.project else { return };
13338                let (telemetry, is_via_ssh) = {
13339                    let project = project.read(cx);
13340                    let telemetry = project.client().telemetry().clone();
13341                    let is_via_ssh = project.is_via_ssh();
13342                    (telemetry, is_via_ssh)
13343                };
13344                refresh_linked_ranges(self, window, cx);
13345                telemetry.log_edit_event("editor", is_via_ssh);
13346            }
13347            multi_buffer::Event::ExcerptsAdded {
13348                buffer,
13349                predecessor,
13350                excerpts,
13351            } => {
13352                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13353                let buffer_id = buffer.read(cx).remote_id();
13354                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13355                    if let Some(project) = &self.project {
13356                        get_unstaged_changes_for_buffers(
13357                            project,
13358                            [buffer.clone()],
13359                            self.buffer.clone(),
13360                            cx,
13361                        );
13362                    }
13363                }
13364                cx.emit(EditorEvent::ExcerptsAdded {
13365                    buffer: buffer.clone(),
13366                    predecessor: *predecessor,
13367                    excerpts: excerpts.clone(),
13368                });
13369                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13370            }
13371            multi_buffer::Event::ExcerptsRemoved { ids } => {
13372                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13373                let buffer = self.buffer.read(cx);
13374                self.registered_buffers
13375                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13376                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13377            }
13378            multi_buffer::Event::ExcerptsEdited { ids } => {
13379                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13380            }
13381            multi_buffer::Event::ExcerptsExpanded { ids } => {
13382                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13383                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13384            }
13385            multi_buffer::Event::Reparsed(buffer_id) => {
13386                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13387
13388                cx.emit(EditorEvent::Reparsed(*buffer_id));
13389            }
13390            multi_buffer::Event::DiffHunksToggled => {
13391                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13392            }
13393            multi_buffer::Event::LanguageChanged(buffer_id) => {
13394                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13395                cx.emit(EditorEvent::Reparsed(*buffer_id));
13396                cx.notify();
13397            }
13398            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13399            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13400            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13401                cx.emit(EditorEvent::TitleChanged)
13402            }
13403            // multi_buffer::Event::DiffBaseChanged => {
13404            //     self.scrollbar_marker_state.dirty = true;
13405            //     cx.emit(EditorEvent::DiffBaseChanged);
13406            //     cx.notify();
13407            // }
13408            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13409            multi_buffer::Event::DiagnosticsUpdated => {
13410                self.refresh_active_diagnostics(cx);
13411                self.scrollbar_marker_state.dirty = true;
13412                cx.notify();
13413            }
13414            _ => {}
13415        };
13416    }
13417
13418    fn on_display_map_changed(
13419        &mut self,
13420        _: Entity<DisplayMap>,
13421        _: &mut Window,
13422        cx: &mut Context<Self>,
13423    ) {
13424        cx.notify();
13425    }
13426
13427    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13428        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13429        self.refresh_inline_completion(true, false, window, cx);
13430        self.refresh_inlay_hints(
13431            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13432                self.selections.newest_anchor().head(),
13433                &self.buffer.read(cx).snapshot(cx),
13434                cx,
13435            )),
13436            cx,
13437        );
13438
13439        let old_cursor_shape = self.cursor_shape;
13440
13441        {
13442            let editor_settings = EditorSettings::get_global(cx);
13443            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13444            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13445            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13446        }
13447
13448        if old_cursor_shape != self.cursor_shape {
13449            cx.emit(EditorEvent::CursorShapeChanged);
13450        }
13451
13452        let project_settings = ProjectSettings::get_global(cx);
13453        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13454
13455        if self.mode == EditorMode::Full {
13456            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13457            if self.git_blame_inline_enabled != inline_blame_enabled {
13458                self.toggle_git_blame_inline_internal(false, window, cx);
13459            }
13460        }
13461
13462        cx.notify();
13463    }
13464
13465    pub fn set_searchable(&mut self, searchable: bool) {
13466        self.searchable = searchable;
13467    }
13468
13469    pub fn searchable(&self) -> bool {
13470        self.searchable
13471    }
13472
13473    fn open_proposed_changes_editor(
13474        &mut self,
13475        _: &OpenProposedChangesEditor,
13476        window: &mut Window,
13477        cx: &mut Context<Self>,
13478    ) {
13479        let Some(workspace) = self.workspace() else {
13480            cx.propagate();
13481            return;
13482        };
13483
13484        let selections = self.selections.all::<usize>(cx);
13485        let multi_buffer = self.buffer.read(cx);
13486        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13487        let mut new_selections_by_buffer = HashMap::default();
13488        for selection in selections {
13489            for (buffer, range, _) in
13490                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13491            {
13492                let mut range = range.to_point(buffer);
13493                range.start.column = 0;
13494                range.end.column = buffer.line_len(range.end.row);
13495                new_selections_by_buffer
13496                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13497                    .or_insert(Vec::new())
13498                    .push(range)
13499            }
13500        }
13501
13502        let proposed_changes_buffers = new_selections_by_buffer
13503            .into_iter()
13504            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13505            .collect::<Vec<_>>();
13506        let proposed_changes_editor = cx.new(|cx| {
13507            ProposedChangesEditor::new(
13508                "Proposed changes",
13509                proposed_changes_buffers,
13510                self.project.clone(),
13511                window,
13512                cx,
13513            )
13514        });
13515
13516        window.defer(cx, move |window, cx| {
13517            workspace.update(cx, |workspace, cx| {
13518                workspace.active_pane().update(cx, |pane, cx| {
13519                    pane.add_item(
13520                        Box::new(proposed_changes_editor),
13521                        true,
13522                        true,
13523                        None,
13524                        window,
13525                        cx,
13526                    );
13527                });
13528            });
13529        });
13530    }
13531
13532    pub fn open_excerpts_in_split(
13533        &mut self,
13534        _: &OpenExcerptsSplit,
13535        window: &mut Window,
13536        cx: &mut Context<Self>,
13537    ) {
13538        self.open_excerpts_common(None, true, window, cx)
13539    }
13540
13541    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13542        self.open_excerpts_common(None, false, window, cx)
13543    }
13544
13545    fn open_excerpts_common(
13546        &mut self,
13547        jump_data: Option<JumpData>,
13548        split: bool,
13549        window: &mut Window,
13550        cx: &mut Context<Self>,
13551    ) {
13552        let Some(workspace) = self.workspace() else {
13553            cx.propagate();
13554            return;
13555        };
13556
13557        if self.buffer.read(cx).is_singleton() {
13558            cx.propagate();
13559            return;
13560        }
13561
13562        let mut new_selections_by_buffer = HashMap::default();
13563        match &jump_data {
13564            Some(JumpData::MultiBufferPoint {
13565                excerpt_id,
13566                position,
13567                anchor,
13568                line_offset_from_top,
13569            }) => {
13570                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13571                if let Some(buffer) = multi_buffer_snapshot
13572                    .buffer_id_for_excerpt(*excerpt_id)
13573                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13574                {
13575                    let buffer_snapshot = buffer.read(cx).snapshot();
13576                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13577                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13578                    } else {
13579                        buffer_snapshot.clip_point(*position, Bias::Left)
13580                    };
13581                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13582                    new_selections_by_buffer.insert(
13583                        buffer,
13584                        (
13585                            vec![jump_to_offset..jump_to_offset],
13586                            Some(*line_offset_from_top),
13587                        ),
13588                    );
13589                }
13590            }
13591            Some(JumpData::MultiBufferRow {
13592                row,
13593                line_offset_from_top,
13594            }) => {
13595                let point = MultiBufferPoint::new(row.0, 0);
13596                if let Some((buffer, buffer_point, _)) =
13597                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13598                {
13599                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13600                    new_selections_by_buffer
13601                        .entry(buffer)
13602                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13603                        .0
13604                        .push(buffer_offset..buffer_offset)
13605                }
13606            }
13607            None => {
13608                let selections = self.selections.all::<usize>(cx);
13609                let multi_buffer = self.buffer.read(cx);
13610                for selection in selections {
13611                    for (buffer, mut range, _) in multi_buffer
13612                        .snapshot(cx)
13613                        .range_to_buffer_ranges(selection.range())
13614                    {
13615                        // When editing branch buffers, jump to the corresponding location
13616                        // in their base buffer.
13617                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13618                        let buffer = buffer_handle.read(cx);
13619                        if let Some(base_buffer) = buffer.base_buffer() {
13620                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13621                            buffer_handle = base_buffer;
13622                        }
13623
13624                        if selection.reversed {
13625                            mem::swap(&mut range.start, &mut range.end);
13626                        }
13627                        new_selections_by_buffer
13628                            .entry(buffer_handle)
13629                            .or_insert((Vec::new(), None))
13630                            .0
13631                            .push(range)
13632                    }
13633                }
13634            }
13635        }
13636
13637        if new_selections_by_buffer.is_empty() {
13638            return;
13639        }
13640
13641        // We defer the pane interaction because we ourselves are a workspace item
13642        // and activating a new item causes the pane to call a method on us reentrantly,
13643        // which panics if we're on the stack.
13644        window.defer(cx, move |window, cx| {
13645            workspace.update(cx, |workspace, cx| {
13646                let pane = if split {
13647                    workspace.adjacent_pane(window, cx)
13648                } else {
13649                    workspace.active_pane().clone()
13650                };
13651
13652                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13653                    let editor = buffer
13654                        .read(cx)
13655                        .file()
13656                        .is_none()
13657                        .then(|| {
13658                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13659                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13660                            // Instead, we try to activate the existing editor in the pane first.
13661                            let (editor, pane_item_index) =
13662                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13663                                    let editor = item.downcast::<Editor>()?;
13664                                    let singleton_buffer =
13665                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13666                                    if singleton_buffer == buffer {
13667                                        Some((editor, i))
13668                                    } else {
13669                                        None
13670                                    }
13671                                })?;
13672                            pane.update(cx, |pane, cx| {
13673                                pane.activate_item(pane_item_index, true, true, window, cx)
13674                            });
13675                            Some(editor)
13676                        })
13677                        .flatten()
13678                        .unwrap_or_else(|| {
13679                            workspace.open_project_item::<Self>(
13680                                pane.clone(),
13681                                buffer,
13682                                true,
13683                                true,
13684                                window,
13685                                cx,
13686                            )
13687                        });
13688
13689                    editor.update(cx, |editor, cx| {
13690                        let autoscroll = match scroll_offset {
13691                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13692                            None => Autoscroll::newest(),
13693                        };
13694                        let nav_history = editor.nav_history.take();
13695                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13696                            s.select_ranges(ranges);
13697                        });
13698                        editor.nav_history = nav_history;
13699                    });
13700                }
13701            })
13702        });
13703    }
13704
13705    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13706        let snapshot = self.buffer.read(cx).read(cx);
13707        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13708        Some(
13709            ranges
13710                .iter()
13711                .map(move |range| {
13712                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13713                })
13714                .collect(),
13715        )
13716    }
13717
13718    fn selection_replacement_ranges(
13719        &self,
13720        range: Range<OffsetUtf16>,
13721        cx: &mut App,
13722    ) -> Vec<Range<OffsetUtf16>> {
13723        let selections = self.selections.all::<OffsetUtf16>(cx);
13724        let newest_selection = selections
13725            .iter()
13726            .max_by_key(|selection| selection.id)
13727            .unwrap();
13728        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13729        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13730        let snapshot = self.buffer.read(cx).read(cx);
13731        selections
13732            .into_iter()
13733            .map(|mut selection| {
13734                selection.start.0 =
13735                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
13736                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13737                snapshot.clip_offset_utf16(selection.start, Bias::Left)
13738                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13739            })
13740            .collect()
13741    }
13742
13743    fn report_editor_event(
13744        &self,
13745        event_type: &'static str,
13746        file_extension: Option<String>,
13747        cx: &App,
13748    ) {
13749        if cfg!(any(test, feature = "test-support")) {
13750            return;
13751        }
13752
13753        let Some(project) = &self.project else { return };
13754
13755        // If None, we are in a file without an extension
13756        let file = self
13757            .buffer
13758            .read(cx)
13759            .as_singleton()
13760            .and_then(|b| b.read(cx).file());
13761        let file_extension = file_extension.or(file
13762            .as_ref()
13763            .and_then(|file| Path::new(file.file_name(cx)).extension())
13764            .and_then(|e| e.to_str())
13765            .map(|a| a.to_string()));
13766
13767        let vim_mode = cx
13768            .global::<SettingsStore>()
13769            .raw_user_settings()
13770            .get("vim_mode")
13771            == Some(&serde_json::Value::Bool(true));
13772
13773        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13774            == language::language_settings::InlineCompletionProvider::Copilot;
13775        let copilot_enabled_for_language = self
13776            .buffer
13777            .read(cx)
13778            .settings_at(0, cx)
13779            .show_inline_completions;
13780
13781        let project = project.read(cx);
13782        telemetry::event!(
13783            event_type,
13784            file_extension,
13785            vim_mode,
13786            copilot_enabled,
13787            copilot_enabled_for_language,
13788            is_via_ssh = project.is_via_ssh(),
13789        );
13790    }
13791
13792    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13793    /// with each line being an array of {text, highlight} objects.
13794    fn copy_highlight_json(
13795        &mut self,
13796        _: &CopyHighlightJson,
13797        window: &mut Window,
13798        cx: &mut Context<Self>,
13799    ) {
13800        #[derive(Serialize)]
13801        struct Chunk<'a> {
13802            text: String,
13803            highlight: Option<&'a str>,
13804        }
13805
13806        let snapshot = self.buffer.read(cx).snapshot(cx);
13807        let range = self
13808            .selected_text_range(false, window, cx)
13809            .and_then(|selection| {
13810                if selection.range.is_empty() {
13811                    None
13812                } else {
13813                    Some(selection.range)
13814                }
13815            })
13816            .unwrap_or_else(|| 0..snapshot.len());
13817
13818        let chunks = snapshot.chunks(range, true);
13819        let mut lines = Vec::new();
13820        let mut line: VecDeque<Chunk> = VecDeque::new();
13821
13822        let Some(style) = self.style.as_ref() else {
13823            return;
13824        };
13825
13826        for chunk in chunks {
13827            let highlight = chunk
13828                .syntax_highlight_id
13829                .and_then(|id| id.name(&style.syntax));
13830            let mut chunk_lines = chunk.text.split('\n').peekable();
13831            while let Some(text) = chunk_lines.next() {
13832                let mut merged_with_last_token = false;
13833                if let Some(last_token) = line.back_mut() {
13834                    if last_token.highlight == highlight {
13835                        last_token.text.push_str(text);
13836                        merged_with_last_token = true;
13837                    }
13838                }
13839
13840                if !merged_with_last_token {
13841                    line.push_back(Chunk {
13842                        text: text.into(),
13843                        highlight,
13844                    });
13845                }
13846
13847                if chunk_lines.peek().is_some() {
13848                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13849                        line.pop_front();
13850                    }
13851                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13852                        line.pop_back();
13853                    }
13854
13855                    lines.push(mem::take(&mut line));
13856                }
13857            }
13858        }
13859
13860        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13861            return;
13862        };
13863        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13864    }
13865
13866    pub fn open_context_menu(
13867        &mut self,
13868        _: &OpenContextMenu,
13869        window: &mut Window,
13870        cx: &mut Context<Self>,
13871    ) {
13872        self.request_autoscroll(Autoscroll::newest(), cx);
13873        let position = self.selections.newest_display(cx).start;
13874        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
13875    }
13876
13877    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13878        &self.inlay_hint_cache
13879    }
13880
13881    pub fn replay_insert_event(
13882        &mut self,
13883        text: &str,
13884        relative_utf16_range: Option<Range<isize>>,
13885        window: &mut Window,
13886        cx: &mut Context<Self>,
13887    ) {
13888        if !self.input_enabled {
13889            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13890            return;
13891        }
13892        if let Some(relative_utf16_range) = relative_utf16_range {
13893            let selections = self.selections.all::<OffsetUtf16>(cx);
13894            self.change_selections(None, window, cx, |s| {
13895                let new_ranges = selections.into_iter().map(|range| {
13896                    let start = OffsetUtf16(
13897                        range
13898                            .head()
13899                            .0
13900                            .saturating_add_signed(relative_utf16_range.start),
13901                    );
13902                    let end = OffsetUtf16(
13903                        range
13904                            .head()
13905                            .0
13906                            .saturating_add_signed(relative_utf16_range.end),
13907                    );
13908                    start..end
13909                });
13910                s.select_ranges(new_ranges);
13911            });
13912        }
13913
13914        self.handle_input(text, window, cx);
13915    }
13916
13917    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
13918        let Some(provider) = self.semantics_provider.as_ref() else {
13919            return false;
13920        };
13921
13922        let mut supports = false;
13923        self.buffer().read(cx).for_each_buffer(|buffer| {
13924            supports |= provider.supports_inlay_hints(buffer, cx);
13925        });
13926        supports
13927    }
13928    pub fn is_focused(&self, window: &mut Window) -> bool {
13929        self.focus_handle.is_focused(window)
13930    }
13931
13932    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13933        cx.emit(EditorEvent::Focused);
13934
13935        if let Some(descendant) = self
13936            .last_focused_descendant
13937            .take()
13938            .and_then(|descendant| descendant.upgrade())
13939        {
13940            window.focus(&descendant);
13941        } else {
13942            if let Some(blame) = self.blame.as_ref() {
13943                blame.update(cx, GitBlame::focus)
13944            }
13945
13946            self.blink_manager.update(cx, BlinkManager::enable);
13947            self.show_cursor_names(window, cx);
13948            self.buffer.update(cx, |buffer, cx| {
13949                buffer.finalize_last_transaction(cx);
13950                if self.leader_peer_id.is_none() {
13951                    buffer.set_active_selections(
13952                        &self.selections.disjoint_anchors(),
13953                        self.selections.line_mode,
13954                        self.cursor_shape,
13955                        cx,
13956                    );
13957                }
13958            });
13959        }
13960    }
13961
13962    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
13963        cx.emit(EditorEvent::FocusedIn)
13964    }
13965
13966    fn handle_focus_out(
13967        &mut self,
13968        event: FocusOutEvent,
13969        _window: &mut Window,
13970        _cx: &mut Context<Self>,
13971    ) {
13972        if event.blurred != self.focus_handle {
13973            self.last_focused_descendant = Some(event.blurred);
13974        }
13975    }
13976
13977    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13978        self.blink_manager.update(cx, BlinkManager::disable);
13979        self.buffer
13980            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13981
13982        if let Some(blame) = self.blame.as_ref() {
13983            blame.update(cx, GitBlame::blur)
13984        }
13985        if !self.hover_state.focused(window, cx) {
13986            hide_hover(self, cx);
13987        }
13988
13989        self.hide_context_menu(window, cx);
13990        cx.emit(EditorEvent::Blurred);
13991        cx.notify();
13992    }
13993
13994    pub fn register_action<A: Action>(
13995        &mut self,
13996        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
13997    ) -> Subscription {
13998        let id = self.next_editor_action_id.post_inc();
13999        let listener = Arc::new(listener);
14000        self.editor_actions.borrow_mut().insert(
14001            id,
14002            Box::new(move |window, _| {
14003                let listener = listener.clone();
14004                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14005                    let action = action.downcast_ref().unwrap();
14006                    if phase == DispatchPhase::Bubble {
14007                        listener(action, window, cx)
14008                    }
14009                })
14010            }),
14011        );
14012
14013        let editor_actions = self.editor_actions.clone();
14014        Subscription::new(move || {
14015            editor_actions.borrow_mut().remove(&id);
14016        })
14017    }
14018
14019    pub fn file_header_size(&self) -> u32 {
14020        FILE_HEADER_HEIGHT
14021    }
14022
14023    pub fn revert(
14024        &mut self,
14025        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14026        window: &mut Window,
14027        cx: &mut Context<Self>,
14028    ) {
14029        self.buffer().update(cx, |multi_buffer, cx| {
14030            for (buffer_id, changes) in revert_changes {
14031                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14032                    buffer.update(cx, |buffer, cx| {
14033                        buffer.edit(
14034                            changes.into_iter().map(|(range, text)| {
14035                                (range, text.to_string().map(Arc::<str>::from))
14036                            }),
14037                            None,
14038                            cx,
14039                        );
14040                    });
14041                }
14042            }
14043        });
14044        self.change_selections(None, window, cx, |selections| selections.refresh());
14045    }
14046
14047    pub fn to_pixel_point(
14048        &self,
14049        source: multi_buffer::Anchor,
14050        editor_snapshot: &EditorSnapshot,
14051        window: &mut Window,
14052    ) -> Option<gpui::Point<Pixels>> {
14053        let source_point = source.to_display_point(editor_snapshot);
14054        self.display_to_pixel_point(source_point, editor_snapshot, window)
14055    }
14056
14057    pub fn display_to_pixel_point(
14058        &self,
14059        source: DisplayPoint,
14060        editor_snapshot: &EditorSnapshot,
14061        window: &mut Window,
14062    ) -> Option<gpui::Point<Pixels>> {
14063        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14064        let text_layout_details = self.text_layout_details(window);
14065        let scroll_top = text_layout_details
14066            .scroll_anchor
14067            .scroll_position(editor_snapshot)
14068            .y;
14069
14070        if source.row().as_f32() < scroll_top.floor() {
14071            return None;
14072        }
14073        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14074        let source_y = line_height * (source.row().as_f32() - scroll_top);
14075        Some(gpui::Point::new(source_x, source_y))
14076    }
14077
14078    pub fn has_active_completions_menu(&self) -> bool {
14079        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14080            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14081        })
14082    }
14083
14084    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14085        self.addons
14086            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14087    }
14088
14089    pub fn unregister_addon<T: Addon>(&mut self) {
14090        self.addons.remove(&std::any::TypeId::of::<T>());
14091    }
14092
14093    pub fn addon<T: Addon>(&self) -> Option<&T> {
14094        let type_id = std::any::TypeId::of::<T>();
14095        self.addons
14096            .get(&type_id)
14097            .and_then(|item| item.to_any().downcast_ref::<T>())
14098    }
14099
14100    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14101        let text_layout_details = self.text_layout_details(window);
14102        let style = &text_layout_details.editor_style;
14103        let font_id = window.text_system().resolve_font(&style.text.font());
14104        let font_size = style.text.font_size.to_pixels(window.rem_size());
14105        let line_height = style.text.line_height_in_pixels(window.rem_size());
14106
14107        let em_width = window
14108            .text_system()
14109            .typographic_bounds(font_id, font_size, 'm')
14110            .unwrap()
14111            .size
14112            .width;
14113
14114        gpui::Size::new(em_width, line_height)
14115    }
14116}
14117
14118fn get_unstaged_changes_for_buffers(
14119    project: &Entity<Project>,
14120    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14121    buffer: Entity<MultiBuffer>,
14122    cx: &mut App,
14123) {
14124    let mut tasks = Vec::new();
14125    project.update(cx, |project, cx| {
14126        for buffer in buffers {
14127            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14128        }
14129    });
14130    cx.spawn(|mut cx| async move {
14131        let change_sets = futures::future::join_all(tasks).await;
14132        buffer
14133            .update(&mut cx, |buffer, cx| {
14134                for change_set in change_sets {
14135                    if let Some(change_set) = change_set.log_err() {
14136                        buffer.add_change_set(change_set, cx);
14137                    }
14138                }
14139            })
14140            .ok();
14141    })
14142    .detach();
14143}
14144
14145fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14146    let tab_size = tab_size.get() as usize;
14147    let mut width = offset;
14148
14149    for ch in text.chars() {
14150        width += if ch == '\t' {
14151            tab_size - (width % tab_size)
14152        } else {
14153            1
14154        };
14155    }
14156
14157    width - offset
14158}
14159
14160#[cfg(test)]
14161mod tests {
14162    use super::*;
14163
14164    #[test]
14165    fn test_string_size_with_expanded_tabs() {
14166        let nz = |val| NonZeroU32::new(val).unwrap();
14167        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14168        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14169        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14170        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14171        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14172        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14173        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14174        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14175    }
14176}
14177
14178/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14179struct WordBreakingTokenizer<'a> {
14180    input: &'a str,
14181}
14182
14183impl<'a> WordBreakingTokenizer<'a> {
14184    fn new(input: &'a str) -> Self {
14185        Self { input }
14186    }
14187}
14188
14189fn is_char_ideographic(ch: char) -> bool {
14190    use unicode_script::Script::*;
14191    use unicode_script::UnicodeScript;
14192    matches!(ch.script(), Han | Tangut | Yi)
14193}
14194
14195fn is_grapheme_ideographic(text: &str) -> bool {
14196    text.chars().any(is_char_ideographic)
14197}
14198
14199fn is_grapheme_whitespace(text: &str) -> bool {
14200    text.chars().any(|x| x.is_whitespace())
14201}
14202
14203fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14204    text.chars().next().map_or(false, |ch| {
14205        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14206    })
14207}
14208
14209#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14210struct WordBreakToken<'a> {
14211    token: &'a str,
14212    grapheme_len: usize,
14213    is_whitespace: bool,
14214}
14215
14216impl<'a> Iterator for WordBreakingTokenizer<'a> {
14217    /// Yields a span, the count of graphemes in the token, and whether it was
14218    /// whitespace. Note that it also breaks at word boundaries.
14219    type Item = WordBreakToken<'a>;
14220
14221    fn next(&mut self) -> Option<Self::Item> {
14222        use unicode_segmentation::UnicodeSegmentation;
14223        if self.input.is_empty() {
14224            return None;
14225        }
14226
14227        let mut iter = self.input.graphemes(true).peekable();
14228        let mut offset = 0;
14229        let mut graphemes = 0;
14230        if let Some(first_grapheme) = iter.next() {
14231            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14232            offset += first_grapheme.len();
14233            graphemes += 1;
14234            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14235                if let Some(grapheme) = iter.peek().copied() {
14236                    if should_stay_with_preceding_ideograph(grapheme) {
14237                        offset += grapheme.len();
14238                        graphemes += 1;
14239                    }
14240                }
14241            } else {
14242                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14243                let mut next_word_bound = words.peek().copied();
14244                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14245                    next_word_bound = words.next();
14246                }
14247                while let Some(grapheme) = iter.peek().copied() {
14248                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14249                        break;
14250                    };
14251                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14252                        break;
14253                    };
14254                    offset += grapheme.len();
14255                    graphemes += 1;
14256                    iter.next();
14257                }
14258            }
14259            let token = &self.input[..offset];
14260            self.input = &self.input[offset..];
14261            if is_whitespace {
14262                Some(WordBreakToken {
14263                    token: " ",
14264                    grapheme_len: 1,
14265                    is_whitespace: true,
14266                })
14267            } else {
14268                Some(WordBreakToken {
14269                    token,
14270                    grapheme_len: graphemes,
14271                    is_whitespace: false,
14272                })
14273            }
14274        } else {
14275            None
14276        }
14277    }
14278}
14279
14280#[test]
14281fn test_word_breaking_tokenizer() {
14282    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14283        ("", &[]),
14284        ("  ", &[(" ", 1, true)]),
14285        ("Ʒ", &[("Ʒ", 1, false)]),
14286        ("Ǽ", &[("Ǽ", 1, false)]),
14287        ("", &[("", 1, false)]),
14288        ("⋑⋑", &[("⋑⋑", 2, false)]),
14289        (
14290            "原理,进而",
14291            &[
14292                ("", 1, false),
14293                ("理,", 2, false),
14294                ("", 1, false),
14295                ("", 1, false),
14296            ],
14297        ),
14298        (
14299            "hello world",
14300            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14301        ),
14302        (
14303            "hello, world",
14304            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14305        ),
14306        (
14307            "  hello world",
14308            &[
14309                (" ", 1, true),
14310                ("hello", 5, false),
14311                (" ", 1, true),
14312                ("world", 5, false),
14313            ],
14314        ),
14315        (
14316            "这是什么 \n 钢笔",
14317            &[
14318                ("", 1, false),
14319                ("", 1, false),
14320                ("", 1, false),
14321                ("", 1, false),
14322                (" ", 1, true),
14323                ("", 1, false),
14324                ("", 1, false),
14325            ],
14326        ),
14327        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14328    ];
14329
14330    for (input, result) in tests {
14331        assert_eq!(
14332            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14333            result
14334                .iter()
14335                .copied()
14336                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14337                    token,
14338                    grapheme_len,
14339                    is_whitespace,
14340                })
14341                .collect::<Vec<_>>()
14342        );
14343    }
14344}
14345
14346fn wrap_with_prefix(
14347    line_prefix: String,
14348    unwrapped_text: String,
14349    wrap_column: usize,
14350    tab_size: NonZeroU32,
14351) -> String {
14352    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14353    let mut wrapped_text = String::new();
14354    let mut current_line = line_prefix.clone();
14355
14356    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14357    let mut current_line_len = line_prefix_len;
14358    for WordBreakToken {
14359        token,
14360        grapheme_len,
14361        is_whitespace,
14362    } in tokenizer
14363    {
14364        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14365            wrapped_text.push_str(current_line.trim_end());
14366            wrapped_text.push('\n');
14367            current_line.truncate(line_prefix.len());
14368            current_line_len = line_prefix_len;
14369            if !is_whitespace {
14370                current_line.push_str(token);
14371                current_line_len += grapheme_len;
14372            }
14373        } else if !is_whitespace {
14374            current_line.push_str(token);
14375            current_line_len += grapheme_len;
14376        } else if current_line_len != line_prefix_len {
14377            current_line.push(' ');
14378            current_line_len += 1;
14379        }
14380    }
14381
14382    if !current_line.is_empty() {
14383        wrapped_text.push_str(&current_line);
14384    }
14385    wrapped_text
14386}
14387
14388#[test]
14389fn test_wrap_with_prefix() {
14390    assert_eq!(
14391        wrap_with_prefix(
14392            "# ".to_string(),
14393            "abcdefg".to_string(),
14394            4,
14395            NonZeroU32::new(4).unwrap()
14396        ),
14397        "# abcdefg"
14398    );
14399    assert_eq!(
14400        wrap_with_prefix(
14401            "".to_string(),
14402            "\thello world".to_string(),
14403            8,
14404            NonZeroU32::new(4).unwrap()
14405        ),
14406        "hello\nworld"
14407    );
14408    assert_eq!(
14409        wrap_with_prefix(
14410            "// ".to_string(),
14411            "xx \nyy zz aa bb cc".to_string(),
14412            12,
14413            NonZeroU32::new(4).unwrap()
14414        ),
14415        "// xx yy zz\n// aa bb cc"
14416    );
14417    assert_eq!(
14418        wrap_with_prefix(
14419            String::new(),
14420            "这是什么 \n 钢笔".to_string(),
14421            3,
14422            NonZeroU32::new(4).unwrap()
14423        ),
14424        "这是什\n么 钢\n"
14425    );
14426}
14427
14428pub trait CollaborationHub {
14429    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14430    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14431    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14432}
14433
14434impl CollaborationHub for Entity<Project> {
14435    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14436        self.read(cx).collaborators()
14437    }
14438
14439    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14440        self.read(cx).user_store().read(cx).participant_indices()
14441    }
14442
14443    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14444        let this = self.read(cx);
14445        let user_ids = this.collaborators().values().map(|c| c.user_id);
14446        this.user_store().read_with(cx, |user_store, cx| {
14447            user_store.participant_names(user_ids, cx)
14448        })
14449    }
14450}
14451
14452pub trait SemanticsProvider {
14453    fn hover(
14454        &self,
14455        buffer: &Entity<Buffer>,
14456        position: text::Anchor,
14457        cx: &mut App,
14458    ) -> Option<Task<Vec<project::Hover>>>;
14459
14460    fn inlay_hints(
14461        &self,
14462        buffer_handle: Entity<Buffer>,
14463        range: Range<text::Anchor>,
14464        cx: &mut App,
14465    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14466
14467    fn resolve_inlay_hint(
14468        &self,
14469        hint: InlayHint,
14470        buffer_handle: Entity<Buffer>,
14471        server_id: LanguageServerId,
14472        cx: &mut App,
14473    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14474
14475    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14476
14477    fn document_highlights(
14478        &self,
14479        buffer: &Entity<Buffer>,
14480        position: text::Anchor,
14481        cx: &mut App,
14482    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14483
14484    fn definitions(
14485        &self,
14486        buffer: &Entity<Buffer>,
14487        position: text::Anchor,
14488        kind: GotoDefinitionKind,
14489        cx: &mut App,
14490    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14491
14492    fn range_for_rename(
14493        &self,
14494        buffer: &Entity<Buffer>,
14495        position: text::Anchor,
14496        cx: &mut App,
14497    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14498
14499    fn perform_rename(
14500        &self,
14501        buffer: &Entity<Buffer>,
14502        position: text::Anchor,
14503        new_name: String,
14504        cx: &mut App,
14505    ) -> Option<Task<Result<ProjectTransaction>>>;
14506}
14507
14508pub trait CompletionProvider {
14509    fn completions(
14510        &self,
14511        buffer: &Entity<Buffer>,
14512        buffer_position: text::Anchor,
14513        trigger: CompletionContext,
14514        window: &mut Window,
14515        cx: &mut Context<Editor>,
14516    ) -> Task<Result<Vec<Completion>>>;
14517
14518    fn resolve_completions(
14519        &self,
14520        buffer: Entity<Buffer>,
14521        completion_indices: Vec<usize>,
14522        completions: Rc<RefCell<Box<[Completion]>>>,
14523        cx: &mut Context<Editor>,
14524    ) -> Task<Result<bool>>;
14525
14526    fn apply_additional_edits_for_completion(
14527        &self,
14528        _buffer: Entity<Buffer>,
14529        _completions: Rc<RefCell<Box<[Completion]>>>,
14530        _completion_index: usize,
14531        _push_to_history: bool,
14532        _cx: &mut Context<Editor>,
14533    ) -> Task<Result<Option<language::Transaction>>> {
14534        Task::ready(Ok(None))
14535    }
14536
14537    fn is_completion_trigger(
14538        &self,
14539        buffer: &Entity<Buffer>,
14540        position: language::Anchor,
14541        text: &str,
14542        trigger_in_words: bool,
14543        cx: &mut Context<Editor>,
14544    ) -> bool;
14545
14546    fn sort_completions(&self) -> bool {
14547        true
14548    }
14549}
14550
14551pub trait CodeActionProvider {
14552    fn id(&self) -> Arc<str>;
14553
14554    fn code_actions(
14555        &self,
14556        buffer: &Entity<Buffer>,
14557        range: Range<text::Anchor>,
14558        window: &mut Window,
14559        cx: &mut App,
14560    ) -> Task<Result<Vec<CodeAction>>>;
14561
14562    fn apply_code_action(
14563        &self,
14564        buffer_handle: Entity<Buffer>,
14565        action: CodeAction,
14566        excerpt_id: ExcerptId,
14567        push_to_history: bool,
14568        window: &mut Window,
14569        cx: &mut App,
14570    ) -> Task<Result<ProjectTransaction>>;
14571}
14572
14573impl CodeActionProvider for Entity<Project> {
14574    fn id(&self) -> Arc<str> {
14575        "project".into()
14576    }
14577
14578    fn code_actions(
14579        &self,
14580        buffer: &Entity<Buffer>,
14581        range: Range<text::Anchor>,
14582        _window: &mut Window,
14583        cx: &mut App,
14584    ) -> Task<Result<Vec<CodeAction>>> {
14585        self.update(cx, |project, cx| {
14586            project.code_actions(buffer, range, None, cx)
14587        })
14588    }
14589
14590    fn apply_code_action(
14591        &self,
14592        buffer_handle: Entity<Buffer>,
14593        action: CodeAction,
14594        _excerpt_id: ExcerptId,
14595        push_to_history: bool,
14596        _window: &mut Window,
14597        cx: &mut App,
14598    ) -> Task<Result<ProjectTransaction>> {
14599        self.update(cx, |project, cx| {
14600            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14601        })
14602    }
14603}
14604
14605fn snippet_completions(
14606    project: &Project,
14607    buffer: &Entity<Buffer>,
14608    buffer_position: text::Anchor,
14609    cx: &mut App,
14610) -> Task<Result<Vec<Completion>>> {
14611    let language = buffer.read(cx).language_at(buffer_position);
14612    let language_name = language.as_ref().map(|language| language.lsp_id());
14613    let snippet_store = project.snippets().read(cx);
14614    let snippets = snippet_store.snippets_for(language_name, cx);
14615
14616    if snippets.is_empty() {
14617        return Task::ready(Ok(vec![]));
14618    }
14619    let snapshot = buffer.read(cx).text_snapshot();
14620    let chars: String = snapshot
14621        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14622        .collect();
14623
14624    let scope = language.map(|language| language.default_scope());
14625    let executor = cx.background_executor().clone();
14626
14627    cx.background_executor().spawn(async move {
14628        let classifier = CharClassifier::new(scope).for_completion(true);
14629        let mut last_word = chars
14630            .chars()
14631            .take_while(|c| classifier.is_word(*c))
14632            .collect::<String>();
14633        last_word = last_word.chars().rev().collect();
14634
14635        if last_word.is_empty() {
14636            return Ok(vec![]);
14637        }
14638
14639        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14640        let to_lsp = |point: &text::Anchor| {
14641            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14642            point_to_lsp(end)
14643        };
14644        let lsp_end = to_lsp(&buffer_position);
14645
14646        let candidates = snippets
14647            .iter()
14648            .enumerate()
14649            .flat_map(|(ix, snippet)| {
14650                snippet
14651                    .prefix
14652                    .iter()
14653                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14654            })
14655            .collect::<Vec<StringMatchCandidate>>();
14656
14657        let mut matches = fuzzy::match_strings(
14658            &candidates,
14659            &last_word,
14660            last_word.chars().any(|c| c.is_uppercase()),
14661            100,
14662            &Default::default(),
14663            executor,
14664        )
14665        .await;
14666
14667        // Remove all candidates where the query's start does not match the start of any word in the candidate
14668        if let Some(query_start) = last_word.chars().next() {
14669            matches.retain(|string_match| {
14670                split_words(&string_match.string).any(|word| {
14671                    // Check that the first codepoint of the word as lowercase matches the first
14672                    // codepoint of the query as lowercase
14673                    word.chars()
14674                        .flat_map(|codepoint| codepoint.to_lowercase())
14675                        .zip(query_start.to_lowercase())
14676                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14677                })
14678            });
14679        }
14680
14681        let matched_strings = matches
14682            .into_iter()
14683            .map(|m| m.string)
14684            .collect::<HashSet<_>>();
14685
14686        let result: Vec<Completion> = snippets
14687            .into_iter()
14688            .filter_map(|snippet| {
14689                let matching_prefix = snippet
14690                    .prefix
14691                    .iter()
14692                    .find(|prefix| matched_strings.contains(*prefix))?;
14693                let start = as_offset - last_word.len();
14694                let start = snapshot.anchor_before(start);
14695                let range = start..buffer_position;
14696                let lsp_start = to_lsp(&start);
14697                let lsp_range = lsp::Range {
14698                    start: lsp_start,
14699                    end: lsp_end,
14700                };
14701                Some(Completion {
14702                    old_range: range,
14703                    new_text: snippet.body.clone(),
14704                    resolved: false,
14705                    label: CodeLabel {
14706                        text: matching_prefix.clone(),
14707                        runs: vec![],
14708                        filter_range: 0..matching_prefix.len(),
14709                    },
14710                    server_id: LanguageServerId(usize::MAX),
14711                    documentation: snippet.description.clone().map(Documentation::SingleLine),
14712                    lsp_completion: lsp::CompletionItem {
14713                        label: snippet.prefix.first().unwrap().clone(),
14714                        kind: Some(CompletionItemKind::SNIPPET),
14715                        label_details: snippet.description.as_ref().map(|description| {
14716                            lsp::CompletionItemLabelDetails {
14717                                detail: Some(description.clone()),
14718                                description: None,
14719                            }
14720                        }),
14721                        insert_text_format: Some(InsertTextFormat::SNIPPET),
14722                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14723                            lsp::InsertReplaceEdit {
14724                                new_text: snippet.body.clone(),
14725                                insert: lsp_range,
14726                                replace: lsp_range,
14727                            },
14728                        )),
14729                        filter_text: Some(snippet.body.clone()),
14730                        sort_text: Some(char::MAX.to_string()),
14731                        ..Default::default()
14732                    },
14733                    confirm: None,
14734                })
14735            })
14736            .collect();
14737
14738        Ok(result)
14739    })
14740}
14741
14742impl CompletionProvider for Entity<Project> {
14743    fn completions(
14744        &self,
14745        buffer: &Entity<Buffer>,
14746        buffer_position: text::Anchor,
14747        options: CompletionContext,
14748        _window: &mut Window,
14749        cx: &mut Context<Editor>,
14750    ) -> Task<Result<Vec<Completion>>> {
14751        self.update(cx, |project, cx| {
14752            let snippets = snippet_completions(project, buffer, buffer_position, cx);
14753            let project_completions = project.completions(buffer, buffer_position, options, cx);
14754            cx.background_executor().spawn(async move {
14755                let mut completions = project_completions.await?;
14756                let snippets_completions = snippets.await?;
14757                completions.extend(snippets_completions);
14758                Ok(completions)
14759            })
14760        })
14761    }
14762
14763    fn resolve_completions(
14764        &self,
14765        buffer: Entity<Buffer>,
14766        completion_indices: Vec<usize>,
14767        completions: Rc<RefCell<Box<[Completion]>>>,
14768        cx: &mut Context<Editor>,
14769    ) -> Task<Result<bool>> {
14770        self.update(cx, |project, cx| {
14771            project.lsp_store().update(cx, |lsp_store, cx| {
14772                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
14773            })
14774        })
14775    }
14776
14777    fn apply_additional_edits_for_completion(
14778        &self,
14779        buffer: Entity<Buffer>,
14780        completions: Rc<RefCell<Box<[Completion]>>>,
14781        completion_index: usize,
14782        push_to_history: bool,
14783        cx: &mut Context<Editor>,
14784    ) -> Task<Result<Option<language::Transaction>>> {
14785        self.update(cx, |project, cx| {
14786            project.lsp_store().update(cx, |lsp_store, cx| {
14787                lsp_store.apply_additional_edits_for_completion(
14788                    buffer,
14789                    completions,
14790                    completion_index,
14791                    push_to_history,
14792                    cx,
14793                )
14794            })
14795        })
14796    }
14797
14798    fn is_completion_trigger(
14799        &self,
14800        buffer: &Entity<Buffer>,
14801        position: language::Anchor,
14802        text: &str,
14803        trigger_in_words: bool,
14804        cx: &mut Context<Editor>,
14805    ) -> bool {
14806        let mut chars = text.chars();
14807        let char = if let Some(char) = chars.next() {
14808            char
14809        } else {
14810            return false;
14811        };
14812        if chars.next().is_some() {
14813            return false;
14814        }
14815
14816        let buffer = buffer.read(cx);
14817        let snapshot = buffer.snapshot();
14818        if !snapshot.settings_at(position, cx).show_completions_on_input {
14819            return false;
14820        }
14821        let classifier = snapshot.char_classifier_at(position).for_completion(true);
14822        if trigger_in_words && classifier.is_word(char) {
14823            return true;
14824        }
14825
14826        buffer.completion_triggers().contains(text)
14827    }
14828}
14829
14830impl SemanticsProvider for Entity<Project> {
14831    fn hover(
14832        &self,
14833        buffer: &Entity<Buffer>,
14834        position: text::Anchor,
14835        cx: &mut App,
14836    ) -> Option<Task<Vec<project::Hover>>> {
14837        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14838    }
14839
14840    fn document_highlights(
14841        &self,
14842        buffer: &Entity<Buffer>,
14843        position: text::Anchor,
14844        cx: &mut App,
14845    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14846        Some(self.update(cx, |project, cx| {
14847            project.document_highlights(buffer, position, cx)
14848        }))
14849    }
14850
14851    fn definitions(
14852        &self,
14853        buffer: &Entity<Buffer>,
14854        position: text::Anchor,
14855        kind: GotoDefinitionKind,
14856        cx: &mut App,
14857    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14858        Some(self.update(cx, |project, cx| match kind {
14859            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14860            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14861            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14862            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14863        }))
14864    }
14865
14866    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
14867        // TODO: make this work for remote projects
14868        self.read(cx)
14869            .language_servers_for_local_buffer(buffer.read(cx), cx)
14870            .any(
14871                |(_, server)| match server.capabilities().inlay_hint_provider {
14872                    Some(lsp::OneOf::Left(enabled)) => enabled,
14873                    Some(lsp::OneOf::Right(_)) => true,
14874                    None => false,
14875                },
14876            )
14877    }
14878
14879    fn inlay_hints(
14880        &self,
14881        buffer_handle: Entity<Buffer>,
14882        range: Range<text::Anchor>,
14883        cx: &mut App,
14884    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14885        Some(self.update(cx, |project, cx| {
14886            project.inlay_hints(buffer_handle, range, cx)
14887        }))
14888    }
14889
14890    fn resolve_inlay_hint(
14891        &self,
14892        hint: InlayHint,
14893        buffer_handle: Entity<Buffer>,
14894        server_id: LanguageServerId,
14895        cx: &mut App,
14896    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14897        Some(self.update(cx, |project, cx| {
14898            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14899        }))
14900    }
14901
14902    fn range_for_rename(
14903        &self,
14904        buffer: &Entity<Buffer>,
14905        position: text::Anchor,
14906        cx: &mut App,
14907    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14908        Some(self.update(cx, |project, cx| {
14909            let buffer = buffer.clone();
14910            let task = project.prepare_rename(buffer.clone(), position, cx);
14911            cx.spawn(|_, mut cx| async move {
14912                Ok(match task.await? {
14913                    PrepareRenameResponse::Success(range) => Some(range),
14914                    PrepareRenameResponse::InvalidPosition => None,
14915                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14916                        // Fallback on using TreeSitter info to determine identifier range
14917                        buffer.update(&mut cx, |buffer, _| {
14918                            let snapshot = buffer.snapshot();
14919                            let (range, kind) = snapshot.surrounding_word(position);
14920                            if kind != Some(CharKind::Word) {
14921                                return None;
14922                            }
14923                            Some(
14924                                snapshot.anchor_before(range.start)
14925                                    ..snapshot.anchor_after(range.end),
14926                            )
14927                        })?
14928                    }
14929                })
14930            })
14931        }))
14932    }
14933
14934    fn perform_rename(
14935        &self,
14936        buffer: &Entity<Buffer>,
14937        position: text::Anchor,
14938        new_name: String,
14939        cx: &mut App,
14940    ) -> Option<Task<Result<ProjectTransaction>>> {
14941        Some(self.update(cx, |project, cx| {
14942            project.perform_rename(buffer.clone(), position, new_name, cx)
14943        }))
14944    }
14945}
14946
14947fn inlay_hint_settings(
14948    location: Anchor,
14949    snapshot: &MultiBufferSnapshot,
14950    cx: &mut Context<Editor>,
14951) -> InlayHintSettings {
14952    let file = snapshot.file_at(location);
14953    let language = snapshot.language_at(location).map(|l| l.name());
14954    language_settings(language, file, cx).inlay_hints
14955}
14956
14957fn consume_contiguous_rows(
14958    contiguous_row_selections: &mut Vec<Selection<Point>>,
14959    selection: &Selection<Point>,
14960    display_map: &DisplaySnapshot,
14961    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14962) -> (MultiBufferRow, MultiBufferRow) {
14963    contiguous_row_selections.push(selection.clone());
14964    let start_row = MultiBufferRow(selection.start.row);
14965    let mut end_row = ending_row(selection, display_map);
14966
14967    while let Some(next_selection) = selections.peek() {
14968        if next_selection.start.row <= end_row.0 {
14969            end_row = ending_row(next_selection, display_map);
14970            contiguous_row_selections.push(selections.next().unwrap().clone());
14971        } else {
14972            break;
14973        }
14974    }
14975    (start_row, end_row)
14976}
14977
14978fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14979    if next_selection.end.column > 0 || next_selection.is_empty() {
14980        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14981    } else {
14982        MultiBufferRow(next_selection.end.row)
14983    }
14984}
14985
14986impl EditorSnapshot {
14987    pub fn remote_selections_in_range<'a>(
14988        &'a self,
14989        range: &'a Range<Anchor>,
14990        collaboration_hub: &dyn CollaborationHub,
14991        cx: &'a App,
14992    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14993        let participant_names = collaboration_hub.user_names(cx);
14994        let participant_indices = collaboration_hub.user_participant_indices(cx);
14995        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14996        let collaborators_by_replica_id = collaborators_by_peer_id
14997            .iter()
14998            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14999            .collect::<HashMap<_, _>>();
15000        self.buffer_snapshot
15001            .selections_in_range(range, false)
15002            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15003                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15004                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15005                let user_name = participant_names.get(&collaborator.user_id).cloned();
15006                Some(RemoteSelection {
15007                    replica_id,
15008                    selection,
15009                    cursor_shape,
15010                    line_mode,
15011                    participant_index,
15012                    peer_id: collaborator.peer_id,
15013                    user_name,
15014                })
15015            })
15016    }
15017
15018    pub fn hunks_for_ranges(
15019        &self,
15020        ranges: impl Iterator<Item = Range<Point>>,
15021    ) -> Vec<MultiBufferDiffHunk> {
15022        let mut hunks = Vec::new();
15023        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15024            HashMap::default();
15025        for query_range in ranges {
15026            let query_rows =
15027                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15028            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15029                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15030            ) {
15031                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15032                // when the caret is just above or just below the deleted hunk.
15033                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15034                let related_to_selection = if allow_adjacent {
15035                    hunk.row_range.overlaps(&query_rows)
15036                        || hunk.row_range.start == query_rows.end
15037                        || hunk.row_range.end == query_rows.start
15038                } else {
15039                    hunk.row_range.overlaps(&query_rows)
15040                };
15041                if related_to_selection {
15042                    if !processed_buffer_rows
15043                        .entry(hunk.buffer_id)
15044                        .or_default()
15045                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15046                    {
15047                        continue;
15048                    }
15049                    hunks.push(hunk);
15050                }
15051            }
15052        }
15053
15054        hunks
15055    }
15056
15057    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15058        self.display_snapshot.buffer_snapshot.language_at(position)
15059    }
15060
15061    pub fn is_focused(&self) -> bool {
15062        self.is_focused
15063    }
15064
15065    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15066        self.placeholder_text.as_ref()
15067    }
15068
15069    pub fn scroll_position(&self) -> gpui::Point<f32> {
15070        self.scroll_anchor.scroll_position(&self.display_snapshot)
15071    }
15072
15073    fn gutter_dimensions(
15074        &self,
15075        font_id: FontId,
15076        font_size: Pixels,
15077        em_width: Pixels,
15078        em_advance: Pixels,
15079        max_line_number_width: Pixels,
15080        cx: &App,
15081    ) -> GutterDimensions {
15082        if !self.show_gutter {
15083            return GutterDimensions::default();
15084        }
15085        let descent = cx.text_system().descent(font_id, font_size);
15086
15087        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15088            matches!(
15089                ProjectSettings::get_global(cx).git.git_gutter,
15090                Some(GitGutterSetting::TrackedFiles)
15091            )
15092        });
15093        let gutter_settings = EditorSettings::get_global(cx).gutter;
15094        let show_line_numbers = self
15095            .show_line_numbers
15096            .unwrap_or(gutter_settings.line_numbers);
15097        let line_gutter_width = if show_line_numbers {
15098            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15099            let min_width_for_number_on_gutter = em_advance * 4.0;
15100            max_line_number_width.max(min_width_for_number_on_gutter)
15101        } else {
15102            0.0.into()
15103        };
15104
15105        let show_code_actions = self
15106            .show_code_actions
15107            .unwrap_or(gutter_settings.code_actions);
15108
15109        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15110
15111        let git_blame_entries_width =
15112            self.git_blame_gutter_max_author_length
15113                .map(|max_author_length| {
15114                    // Length of the author name, but also space for the commit hash,
15115                    // the spacing and the timestamp.
15116                    let max_char_count = max_author_length
15117                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15118                        + 7 // length of commit sha
15119                        + 14 // length of max relative timestamp ("60 minutes ago")
15120                        + 4; // gaps and margins
15121
15122                    em_advance * max_char_count
15123                });
15124
15125        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15126        left_padding += if show_code_actions || show_runnables {
15127            em_width * 3.0
15128        } else if show_git_gutter && show_line_numbers {
15129            em_width * 2.0
15130        } else if show_git_gutter || show_line_numbers {
15131            em_width
15132        } else {
15133            px(0.)
15134        };
15135
15136        let right_padding = if gutter_settings.folds && show_line_numbers {
15137            em_width * 4.0
15138        } else if gutter_settings.folds {
15139            em_width * 3.0
15140        } else if show_line_numbers {
15141            em_width
15142        } else {
15143            px(0.)
15144        };
15145
15146        GutterDimensions {
15147            left_padding,
15148            right_padding,
15149            width: line_gutter_width + left_padding + right_padding,
15150            margin: -descent,
15151            git_blame_entries_width,
15152        }
15153    }
15154
15155    pub fn render_crease_toggle(
15156        &self,
15157        buffer_row: MultiBufferRow,
15158        row_contains_cursor: bool,
15159        editor: Entity<Editor>,
15160        window: &mut Window,
15161        cx: &mut App,
15162    ) -> Option<AnyElement> {
15163        let folded = self.is_line_folded(buffer_row);
15164        let mut is_foldable = false;
15165
15166        if let Some(crease) = self
15167            .crease_snapshot
15168            .query_row(buffer_row, &self.buffer_snapshot)
15169        {
15170            is_foldable = true;
15171            match crease {
15172                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15173                    if let Some(render_toggle) = render_toggle {
15174                        let toggle_callback =
15175                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15176                                if folded {
15177                                    editor.update(cx, |editor, cx| {
15178                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15179                                    });
15180                                } else {
15181                                    editor.update(cx, |editor, cx| {
15182                                        editor.unfold_at(
15183                                            &crate::UnfoldAt { buffer_row },
15184                                            window,
15185                                            cx,
15186                                        )
15187                                    });
15188                                }
15189                            });
15190                        return Some((render_toggle)(
15191                            buffer_row,
15192                            folded,
15193                            toggle_callback,
15194                            window,
15195                            cx,
15196                        ));
15197                    }
15198                }
15199            }
15200        }
15201
15202        is_foldable |= self.starts_indent(buffer_row);
15203
15204        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15205            Some(
15206                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15207                    .toggle_state(folded)
15208                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15209                        if folded {
15210                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15211                        } else {
15212                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15213                        }
15214                    }))
15215                    .into_any_element(),
15216            )
15217        } else {
15218            None
15219        }
15220    }
15221
15222    pub fn render_crease_trailer(
15223        &self,
15224        buffer_row: MultiBufferRow,
15225        window: &mut Window,
15226        cx: &mut App,
15227    ) -> Option<AnyElement> {
15228        let folded = self.is_line_folded(buffer_row);
15229        if let Crease::Inline { render_trailer, .. } = self
15230            .crease_snapshot
15231            .query_row(buffer_row, &self.buffer_snapshot)?
15232        {
15233            let render_trailer = render_trailer.as_ref()?;
15234            Some(render_trailer(buffer_row, folded, window, cx))
15235        } else {
15236            None
15237        }
15238    }
15239}
15240
15241impl Deref for EditorSnapshot {
15242    type Target = DisplaySnapshot;
15243
15244    fn deref(&self) -> &Self::Target {
15245        &self.display_snapshot
15246    }
15247}
15248
15249#[derive(Clone, Debug, PartialEq, Eq)]
15250pub enum EditorEvent {
15251    InputIgnored {
15252        text: Arc<str>,
15253    },
15254    InputHandled {
15255        utf16_range_to_replace: Option<Range<isize>>,
15256        text: Arc<str>,
15257    },
15258    ExcerptsAdded {
15259        buffer: Entity<Buffer>,
15260        predecessor: ExcerptId,
15261        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15262    },
15263    ExcerptsRemoved {
15264        ids: Vec<ExcerptId>,
15265    },
15266    BufferFoldToggled {
15267        ids: Vec<ExcerptId>,
15268        folded: bool,
15269    },
15270    ExcerptsEdited {
15271        ids: Vec<ExcerptId>,
15272    },
15273    ExcerptsExpanded {
15274        ids: Vec<ExcerptId>,
15275    },
15276    BufferEdited,
15277    Edited {
15278        transaction_id: clock::Lamport,
15279    },
15280    Reparsed(BufferId),
15281    Focused,
15282    FocusedIn,
15283    Blurred,
15284    DirtyChanged,
15285    Saved,
15286    TitleChanged,
15287    DiffBaseChanged,
15288    SelectionsChanged {
15289        local: bool,
15290    },
15291    ScrollPositionChanged {
15292        local: bool,
15293        autoscroll: bool,
15294    },
15295    Closed,
15296    TransactionUndone {
15297        transaction_id: clock::Lamport,
15298    },
15299    TransactionBegun {
15300        transaction_id: clock::Lamport,
15301    },
15302    Reloaded,
15303    CursorShapeChanged,
15304}
15305
15306impl EventEmitter<EditorEvent> for Editor {}
15307
15308impl Focusable for Editor {
15309    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15310        self.focus_handle.clone()
15311    }
15312}
15313
15314impl Render for Editor {
15315    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15316        let settings = ThemeSettings::get_global(cx);
15317
15318        let mut text_style = match self.mode {
15319            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15320                color: cx.theme().colors().editor_foreground,
15321                font_family: settings.ui_font.family.clone(),
15322                font_features: settings.ui_font.features.clone(),
15323                font_fallbacks: settings.ui_font.fallbacks.clone(),
15324                font_size: rems(0.875).into(),
15325                font_weight: settings.ui_font.weight,
15326                line_height: relative(settings.buffer_line_height.value()),
15327                ..Default::default()
15328            },
15329            EditorMode::Full => TextStyle {
15330                color: cx.theme().colors().editor_foreground,
15331                font_family: settings.buffer_font.family.clone(),
15332                font_features: settings.buffer_font.features.clone(),
15333                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15334                font_size: settings.buffer_font_size().into(),
15335                font_weight: settings.buffer_font.weight,
15336                line_height: relative(settings.buffer_line_height.value()),
15337                ..Default::default()
15338            },
15339        };
15340        if let Some(text_style_refinement) = &self.text_style_refinement {
15341            text_style.refine(text_style_refinement)
15342        }
15343
15344        let background = match self.mode {
15345            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15346            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15347            EditorMode::Full => cx.theme().colors().editor_background,
15348        };
15349
15350        EditorElement::new(
15351            &cx.entity(),
15352            EditorStyle {
15353                background,
15354                local_player: cx.theme().players().local(),
15355                text: text_style,
15356                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15357                syntax: cx.theme().syntax().clone(),
15358                status: cx.theme().status().clone(),
15359                inlay_hints_style: make_inlay_hints_style(cx),
15360                inline_completion_styles: make_suggestion_styles(cx),
15361                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15362            },
15363        )
15364    }
15365}
15366
15367impl EntityInputHandler for Editor {
15368    fn text_for_range(
15369        &mut self,
15370        range_utf16: Range<usize>,
15371        adjusted_range: &mut Option<Range<usize>>,
15372        _: &mut Window,
15373        cx: &mut Context<Self>,
15374    ) -> Option<String> {
15375        let snapshot = self.buffer.read(cx).read(cx);
15376        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15377        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15378        if (start.0..end.0) != range_utf16 {
15379            adjusted_range.replace(start.0..end.0);
15380        }
15381        Some(snapshot.text_for_range(start..end).collect())
15382    }
15383
15384    fn selected_text_range(
15385        &mut self,
15386        ignore_disabled_input: bool,
15387        _: &mut Window,
15388        cx: &mut Context<Self>,
15389    ) -> Option<UTF16Selection> {
15390        // Prevent the IME menu from appearing when holding down an alphabetic key
15391        // while input is disabled.
15392        if !ignore_disabled_input && !self.input_enabled {
15393            return None;
15394        }
15395
15396        let selection = self.selections.newest::<OffsetUtf16>(cx);
15397        let range = selection.range();
15398
15399        Some(UTF16Selection {
15400            range: range.start.0..range.end.0,
15401            reversed: selection.reversed,
15402        })
15403    }
15404
15405    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15406        let snapshot = self.buffer.read(cx).read(cx);
15407        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15408        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15409    }
15410
15411    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15412        self.clear_highlights::<InputComposition>(cx);
15413        self.ime_transaction.take();
15414    }
15415
15416    fn replace_text_in_range(
15417        &mut self,
15418        range_utf16: Option<Range<usize>>,
15419        text: &str,
15420        window: &mut Window,
15421        cx: &mut Context<Self>,
15422    ) {
15423        if !self.input_enabled {
15424            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15425            return;
15426        }
15427
15428        self.transact(window, cx, |this, window, cx| {
15429            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15430                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15431                Some(this.selection_replacement_ranges(range_utf16, cx))
15432            } else {
15433                this.marked_text_ranges(cx)
15434            };
15435
15436            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15437                let newest_selection_id = this.selections.newest_anchor().id;
15438                this.selections
15439                    .all::<OffsetUtf16>(cx)
15440                    .iter()
15441                    .zip(ranges_to_replace.iter())
15442                    .find_map(|(selection, range)| {
15443                        if selection.id == newest_selection_id {
15444                            Some(
15445                                (range.start.0 as isize - selection.head().0 as isize)
15446                                    ..(range.end.0 as isize - selection.head().0 as isize),
15447                            )
15448                        } else {
15449                            None
15450                        }
15451                    })
15452            });
15453
15454            cx.emit(EditorEvent::InputHandled {
15455                utf16_range_to_replace: range_to_replace,
15456                text: text.into(),
15457            });
15458
15459            if let Some(new_selected_ranges) = new_selected_ranges {
15460                this.change_selections(None, window, cx, |selections| {
15461                    selections.select_ranges(new_selected_ranges)
15462                });
15463                this.backspace(&Default::default(), window, cx);
15464            }
15465
15466            this.handle_input(text, window, cx);
15467        });
15468
15469        if let Some(transaction) = self.ime_transaction {
15470            self.buffer.update(cx, |buffer, cx| {
15471                buffer.group_until_transaction(transaction, cx);
15472            });
15473        }
15474
15475        self.unmark_text(window, cx);
15476    }
15477
15478    fn replace_and_mark_text_in_range(
15479        &mut self,
15480        range_utf16: Option<Range<usize>>,
15481        text: &str,
15482        new_selected_range_utf16: Option<Range<usize>>,
15483        window: &mut Window,
15484        cx: &mut Context<Self>,
15485    ) {
15486        if !self.input_enabled {
15487            return;
15488        }
15489
15490        let transaction = self.transact(window, cx, |this, window, cx| {
15491            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15492                let snapshot = this.buffer.read(cx).read(cx);
15493                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15494                    for marked_range in &mut marked_ranges {
15495                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15496                        marked_range.start.0 += relative_range_utf16.start;
15497                        marked_range.start =
15498                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15499                        marked_range.end =
15500                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15501                    }
15502                }
15503                Some(marked_ranges)
15504            } else if let Some(range_utf16) = range_utf16 {
15505                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15506                Some(this.selection_replacement_ranges(range_utf16, cx))
15507            } else {
15508                None
15509            };
15510
15511            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15512                let newest_selection_id = this.selections.newest_anchor().id;
15513                this.selections
15514                    .all::<OffsetUtf16>(cx)
15515                    .iter()
15516                    .zip(ranges_to_replace.iter())
15517                    .find_map(|(selection, range)| {
15518                        if selection.id == newest_selection_id {
15519                            Some(
15520                                (range.start.0 as isize - selection.head().0 as isize)
15521                                    ..(range.end.0 as isize - selection.head().0 as isize),
15522                            )
15523                        } else {
15524                            None
15525                        }
15526                    })
15527            });
15528
15529            cx.emit(EditorEvent::InputHandled {
15530                utf16_range_to_replace: range_to_replace,
15531                text: text.into(),
15532            });
15533
15534            if let Some(ranges) = ranges_to_replace {
15535                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15536            }
15537
15538            let marked_ranges = {
15539                let snapshot = this.buffer.read(cx).read(cx);
15540                this.selections
15541                    .disjoint_anchors()
15542                    .iter()
15543                    .map(|selection| {
15544                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15545                    })
15546                    .collect::<Vec<_>>()
15547            };
15548
15549            if text.is_empty() {
15550                this.unmark_text(window, cx);
15551            } else {
15552                this.highlight_text::<InputComposition>(
15553                    marked_ranges.clone(),
15554                    HighlightStyle {
15555                        underline: Some(UnderlineStyle {
15556                            thickness: px(1.),
15557                            color: None,
15558                            wavy: false,
15559                        }),
15560                        ..Default::default()
15561                    },
15562                    cx,
15563                );
15564            }
15565
15566            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15567            let use_autoclose = this.use_autoclose;
15568            let use_auto_surround = this.use_auto_surround;
15569            this.set_use_autoclose(false);
15570            this.set_use_auto_surround(false);
15571            this.handle_input(text, window, cx);
15572            this.set_use_autoclose(use_autoclose);
15573            this.set_use_auto_surround(use_auto_surround);
15574
15575            if let Some(new_selected_range) = new_selected_range_utf16 {
15576                let snapshot = this.buffer.read(cx).read(cx);
15577                let new_selected_ranges = marked_ranges
15578                    .into_iter()
15579                    .map(|marked_range| {
15580                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15581                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15582                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15583                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15584                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15585                    })
15586                    .collect::<Vec<_>>();
15587
15588                drop(snapshot);
15589                this.change_selections(None, window, cx, |selections| {
15590                    selections.select_ranges(new_selected_ranges)
15591                });
15592            }
15593        });
15594
15595        self.ime_transaction = self.ime_transaction.or(transaction);
15596        if let Some(transaction) = self.ime_transaction {
15597            self.buffer.update(cx, |buffer, cx| {
15598                buffer.group_until_transaction(transaction, cx);
15599            });
15600        }
15601
15602        if self.text_highlights::<InputComposition>(cx).is_none() {
15603            self.ime_transaction.take();
15604        }
15605    }
15606
15607    fn bounds_for_range(
15608        &mut self,
15609        range_utf16: Range<usize>,
15610        element_bounds: gpui::Bounds<Pixels>,
15611        window: &mut Window,
15612        cx: &mut Context<Self>,
15613    ) -> Option<gpui::Bounds<Pixels>> {
15614        let text_layout_details = self.text_layout_details(window);
15615        let gpui::Size {
15616            width: em_width,
15617            height: line_height,
15618        } = self.character_size(window);
15619
15620        let snapshot = self.snapshot(window, cx);
15621        let scroll_position = snapshot.scroll_position();
15622        let scroll_left = scroll_position.x * em_width;
15623
15624        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15625        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15626            + self.gutter_dimensions.width
15627            + self.gutter_dimensions.margin;
15628        let y = line_height * (start.row().as_f32() - scroll_position.y);
15629
15630        Some(Bounds {
15631            origin: element_bounds.origin + point(x, y),
15632            size: size(em_width, line_height),
15633        })
15634    }
15635
15636    fn character_index_for_point(
15637        &mut self,
15638        point: gpui::Point<Pixels>,
15639        _window: &mut Window,
15640        _cx: &mut Context<Self>,
15641    ) -> Option<usize> {
15642        let position_map = self.last_position_map.as_ref()?;
15643        if !position_map.text_hitbox.contains(&point) {
15644            return None;
15645        }
15646        let display_point = position_map.point_for_position(point).previous_valid;
15647        let anchor = position_map
15648            .snapshot
15649            .display_point_to_anchor(display_point, Bias::Left);
15650        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
15651        Some(utf16_offset.0)
15652    }
15653}
15654
15655trait SelectionExt {
15656    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15657    fn spanned_rows(
15658        &self,
15659        include_end_if_at_line_start: bool,
15660        map: &DisplaySnapshot,
15661    ) -> Range<MultiBufferRow>;
15662}
15663
15664impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15665    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15666        let start = self
15667            .start
15668            .to_point(&map.buffer_snapshot)
15669            .to_display_point(map);
15670        let end = self
15671            .end
15672            .to_point(&map.buffer_snapshot)
15673            .to_display_point(map);
15674        if self.reversed {
15675            end..start
15676        } else {
15677            start..end
15678        }
15679    }
15680
15681    fn spanned_rows(
15682        &self,
15683        include_end_if_at_line_start: bool,
15684        map: &DisplaySnapshot,
15685    ) -> Range<MultiBufferRow> {
15686        let start = self.start.to_point(&map.buffer_snapshot);
15687        let mut end = self.end.to_point(&map.buffer_snapshot);
15688        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15689            end.row -= 1;
15690        }
15691
15692        let buffer_start = map.prev_line_boundary(start).0;
15693        let buffer_end = map.next_line_boundary(end).0;
15694        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15695    }
15696}
15697
15698impl<T: InvalidationRegion> InvalidationStack<T> {
15699    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15700    where
15701        S: Clone + ToOffset,
15702    {
15703        while let Some(region) = self.last() {
15704            let all_selections_inside_invalidation_ranges =
15705                if selections.len() == region.ranges().len() {
15706                    selections
15707                        .iter()
15708                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15709                        .all(|(selection, invalidation_range)| {
15710                            let head = selection.head().to_offset(buffer);
15711                            invalidation_range.start <= head && invalidation_range.end >= head
15712                        })
15713                } else {
15714                    false
15715                };
15716
15717            if all_selections_inside_invalidation_ranges {
15718                break;
15719            } else {
15720                self.pop();
15721            }
15722        }
15723    }
15724}
15725
15726impl<T> Default for InvalidationStack<T> {
15727    fn default() -> Self {
15728        Self(Default::default())
15729    }
15730}
15731
15732impl<T> Deref for InvalidationStack<T> {
15733    type Target = Vec<T>;
15734
15735    fn deref(&self) -> &Self::Target {
15736        &self.0
15737    }
15738}
15739
15740impl<T> DerefMut for InvalidationStack<T> {
15741    fn deref_mut(&mut self) -> &mut Self::Target {
15742        &mut self.0
15743    }
15744}
15745
15746impl InvalidationRegion for SnippetState {
15747    fn ranges(&self) -> &[Range<Anchor>] {
15748        &self.ranges[self.active_index]
15749    }
15750}
15751
15752pub fn diagnostic_block_renderer(
15753    diagnostic: Diagnostic,
15754    max_message_rows: Option<u8>,
15755    allow_closing: bool,
15756    _is_valid: bool,
15757) -> RenderBlock {
15758    let (text_without_backticks, code_ranges) =
15759        highlight_diagnostic_message(&diagnostic, max_message_rows);
15760
15761    Arc::new(move |cx: &mut BlockContext| {
15762        let group_id: SharedString = cx.block_id.to_string().into();
15763
15764        let mut text_style = cx.window.text_style().clone();
15765        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15766        let theme_settings = ThemeSettings::get_global(cx);
15767        text_style.font_family = theme_settings.buffer_font.family.clone();
15768        text_style.font_style = theme_settings.buffer_font.style;
15769        text_style.font_features = theme_settings.buffer_font.features.clone();
15770        text_style.font_weight = theme_settings.buffer_font.weight;
15771
15772        let multi_line_diagnostic = diagnostic.message.contains('\n');
15773
15774        let buttons = |diagnostic: &Diagnostic| {
15775            if multi_line_diagnostic {
15776                v_flex()
15777            } else {
15778                h_flex()
15779            }
15780            .when(allow_closing, |div| {
15781                div.children(diagnostic.is_primary.then(|| {
15782                    IconButton::new("close-block", IconName::XCircle)
15783                        .icon_color(Color::Muted)
15784                        .size(ButtonSize::Compact)
15785                        .style(ButtonStyle::Transparent)
15786                        .visible_on_hover(group_id.clone())
15787                        .on_click(move |_click, window, cx| {
15788                            window.dispatch_action(Box::new(Cancel), cx)
15789                        })
15790                        .tooltip(|window, cx| {
15791                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
15792                        })
15793                }))
15794            })
15795            .child(
15796                IconButton::new("copy-block", IconName::Copy)
15797                    .icon_color(Color::Muted)
15798                    .size(ButtonSize::Compact)
15799                    .style(ButtonStyle::Transparent)
15800                    .visible_on_hover(group_id.clone())
15801                    .on_click({
15802                        let message = diagnostic.message.clone();
15803                        move |_click, _, cx| {
15804                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15805                        }
15806                    })
15807                    .tooltip(Tooltip::text("Copy diagnostic message")),
15808            )
15809        };
15810
15811        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
15812            AvailableSpace::min_size(),
15813            cx.window,
15814            cx.app,
15815        );
15816
15817        h_flex()
15818            .id(cx.block_id)
15819            .group(group_id.clone())
15820            .relative()
15821            .size_full()
15822            .block_mouse_down()
15823            .pl(cx.gutter_dimensions.width)
15824            .w(cx.max_width - cx.gutter_dimensions.full_width())
15825            .child(
15826                div()
15827                    .flex()
15828                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15829                    .flex_shrink(),
15830            )
15831            .child(buttons(&diagnostic))
15832            .child(div().flex().flex_shrink_0().child(
15833                StyledText::new(text_without_backticks.clone()).with_highlights(
15834                    &text_style,
15835                    code_ranges.iter().map(|range| {
15836                        (
15837                            range.clone(),
15838                            HighlightStyle {
15839                                font_weight: Some(FontWeight::BOLD),
15840                                ..Default::default()
15841                            },
15842                        )
15843                    }),
15844                ),
15845            ))
15846            .into_any_element()
15847    })
15848}
15849
15850fn inline_completion_edit_text(
15851    editor_snapshot: &EditorSnapshot,
15852    edits: &Vec<(Range<Anchor>, String)>,
15853    include_deletions: bool,
15854    cx: &App,
15855) -> InlineCompletionText {
15856    let edit_start = edits
15857        .first()
15858        .unwrap()
15859        .0
15860        .start
15861        .to_display_point(editor_snapshot);
15862
15863    let mut text = String::new();
15864    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
15865    let mut highlights = Vec::new();
15866    for (old_range, new_text) in edits {
15867        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
15868        text.extend(
15869            editor_snapshot
15870                .buffer_snapshot
15871                .chunks(offset..old_offset_range.start, false)
15872                .map(|chunk| chunk.text),
15873        );
15874        offset = old_offset_range.end;
15875
15876        let start = text.len();
15877        let color = if include_deletions && new_text.is_empty() {
15878            text.extend(
15879                editor_snapshot
15880                    .buffer_snapshot
15881                    .chunks(old_offset_range.start..offset, false)
15882                    .map(|chunk| chunk.text),
15883            );
15884            cx.theme().status().deleted_background
15885        } else {
15886            text.push_str(new_text);
15887            cx.theme().status().created_background
15888        };
15889        let end = text.len();
15890
15891        highlights.push((
15892            start..end,
15893            HighlightStyle {
15894                background_color: Some(color),
15895                ..Default::default()
15896            },
15897        ));
15898    }
15899
15900    let edit_end = edits
15901        .last()
15902        .unwrap()
15903        .0
15904        .end
15905        .to_display_point(editor_snapshot);
15906    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
15907        .to_offset(editor_snapshot, Bias::Right);
15908    text.extend(
15909        editor_snapshot
15910            .buffer_snapshot
15911            .chunks(offset..end_of_line, false)
15912            .map(|chunk| chunk.text),
15913    );
15914
15915    InlineCompletionText::Edit {
15916        text: text.into(),
15917        highlights,
15918    }
15919}
15920
15921pub fn highlight_diagnostic_message(
15922    diagnostic: &Diagnostic,
15923    mut max_message_rows: Option<u8>,
15924) -> (SharedString, Vec<Range<usize>>) {
15925    let mut text_without_backticks = String::new();
15926    let mut code_ranges = Vec::new();
15927
15928    if let Some(source) = &diagnostic.source {
15929        text_without_backticks.push_str(source);
15930        code_ranges.push(0..source.len());
15931        text_without_backticks.push_str(": ");
15932    }
15933
15934    let mut prev_offset = 0;
15935    let mut in_code_block = false;
15936    let has_row_limit = max_message_rows.is_some();
15937    let mut newline_indices = diagnostic
15938        .message
15939        .match_indices('\n')
15940        .filter(|_| has_row_limit)
15941        .map(|(ix, _)| ix)
15942        .fuse()
15943        .peekable();
15944
15945    for (quote_ix, _) in diagnostic
15946        .message
15947        .match_indices('`')
15948        .chain([(diagnostic.message.len(), "")])
15949    {
15950        let mut first_newline_ix = None;
15951        let mut last_newline_ix = None;
15952        while let Some(newline_ix) = newline_indices.peek() {
15953            if *newline_ix < quote_ix {
15954                if first_newline_ix.is_none() {
15955                    first_newline_ix = Some(*newline_ix);
15956                }
15957                last_newline_ix = Some(*newline_ix);
15958
15959                if let Some(rows_left) = &mut max_message_rows {
15960                    if *rows_left == 0 {
15961                        break;
15962                    } else {
15963                        *rows_left -= 1;
15964                    }
15965                }
15966                let _ = newline_indices.next();
15967            } else {
15968                break;
15969            }
15970        }
15971        let prev_len = text_without_backticks.len();
15972        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15973        text_without_backticks.push_str(new_text);
15974        if in_code_block {
15975            code_ranges.push(prev_len..text_without_backticks.len());
15976        }
15977        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15978        in_code_block = !in_code_block;
15979        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15980            text_without_backticks.push_str("...");
15981            break;
15982        }
15983    }
15984
15985    (text_without_backticks.into(), code_ranges)
15986}
15987
15988fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15989    match severity {
15990        DiagnosticSeverity::ERROR => colors.error,
15991        DiagnosticSeverity::WARNING => colors.warning,
15992        DiagnosticSeverity::INFORMATION => colors.info,
15993        DiagnosticSeverity::HINT => colors.info,
15994        _ => colors.ignored,
15995    }
15996}
15997
15998pub fn styled_runs_for_code_label<'a>(
15999    label: &'a CodeLabel,
16000    syntax_theme: &'a theme::SyntaxTheme,
16001) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16002    let fade_out = HighlightStyle {
16003        fade_out: Some(0.35),
16004        ..Default::default()
16005    };
16006
16007    let mut prev_end = label.filter_range.end;
16008    label
16009        .runs
16010        .iter()
16011        .enumerate()
16012        .flat_map(move |(ix, (range, highlight_id))| {
16013            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16014                style
16015            } else {
16016                return Default::default();
16017            };
16018            let mut muted_style = style;
16019            muted_style.highlight(fade_out);
16020
16021            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16022            if range.start >= label.filter_range.end {
16023                if range.start > prev_end {
16024                    runs.push((prev_end..range.start, fade_out));
16025                }
16026                runs.push((range.clone(), muted_style));
16027            } else if range.end <= label.filter_range.end {
16028                runs.push((range.clone(), style));
16029            } else {
16030                runs.push((range.start..label.filter_range.end, style));
16031                runs.push((label.filter_range.end..range.end, muted_style));
16032            }
16033            prev_end = cmp::max(prev_end, range.end);
16034
16035            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16036                runs.push((prev_end..label.text.len(), fade_out));
16037            }
16038
16039            runs
16040        })
16041}
16042
16043pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16044    let mut prev_index = 0;
16045    let mut prev_codepoint: Option<char> = None;
16046    text.char_indices()
16047        .chain([(text.len(), '\0')])
16048        .filter_map(move |(index, codepoint)| {
16049            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16050            let is_boundary = index == text.len()
16051                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16052                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16053            if is_boundary {
16054                let chunk = &text[prev_index..index];
16055                prev_index = index;
16056                Some(chunk)
16057            } else {
16058                None
16059            }
16060        })
16061}
16062
16063pub trait RangeToAnchorExt: Sized {
16064    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16065
16066    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16067        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16068        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16069    }
16070}
16071
16072impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16073    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16074        let start_offset = self.start.to_offset(snapshot);
16075        let end_offset = self.end.to_offset(snapshot);
16076        if start_offset == end_offset {
16077            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16078        } else {
16079            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16080        }
16081    }
16082}
16083
16084pub trait RowExt {
16085    fn as_f32(&self) -> f32;
16086
16087    fn next_row(&self) -> Self;
16088
16089    fn previous_row(&self) -> Self;
16090
16091    fn minus(&self, other: Self) -> u32;
16092}
16093
16094impl RowExt for DisplayRow {
16095    fn as_f32(&self) -> f32 {
16096        self.0 as f32
16097    }
16098
16099    fn next_row(&self) -> Self {
16100        Self(self.0 + 1)
16101    }
16102
16103    fn previous_row(&self) -> Self {
16104        Self(self.0.saturating_sub(1))
16105    }
16106
16107    fn minus(&self, other: Self) -> u32 {
16108        self.0 - other.0
16109    }
16110}
16111
16112impl RowExt for MultiBufferRow {
16113    fn as_f32(&self) -> f32 {
16114        self.0 as f32
16115    }
16116
16117    fn next_row(&self) -> Self {
16118        Self(self.0 + 1)
16119    }
16120
16121    fn previous_row(&self) -> Self {
16122        Self(self.0.saturating_sub(1))
16123    }
16124
16125    fn minus(&self, other: Self) -> u32 {
16126        self.0 - other.0
16127    }
16128}
16129
16130trait RowRangeExt {
16131    type Row;
16132
16133    fn len(&self) -> usize;
16134
16135    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16136}
16137
16138impl RowRangeExt for Range<MultiBufferRow> {
16139    type Row = MultiBufferRow;
16140
16141    fn len(&self) -> usize {
16142        (self.end.0 - self.start.0) as usize
16143    }
16144
16145    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16146        (self.start.0..self.end.0).map(MultiBufferRow)
16147    }
16148}
16149
16150impl RowRangeExt for Range<DisplayRow> {
16151    type Row = DisplayRow;
16152
16153    fn len(&self) -> usize {
16154        (self.end.0 - self.start.0) as usize
16155    }
16156
16157    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16158        (self.start.0..self.end.0).map(DisplayRow)
16159    }
16160}
16161
16162/// If select range has more than one line, we
16163/// just point the cursor to range.start.
16164fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16165    if range.start.row == range.end.row {
16166        range
16167    } else {
16168        range.start..range.start
16169    }
16170}
16171pub struct KillRing(ClipboardItem);
16172impl Global for KillRing {}
16173
16174const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16175
16176fn all_edits_insertions_or_deletions(
16177    edits: &Vec<(Range<Anchor>, String)>,
16178    snapshot: &MultiBufferSnapshot,
16179) -> bool {
16180    let mut all_insertions = true;
16181    let mut all_deletions = true;
16182
16183    for (range, new_text) in edits.iter() {
16184        let range_is_empty = range.to_offset(&snapshot).is_empty();
16185        let text_is_empty = new_text.is_empty();
16186
16187        if range_is_empty != text_is_empty {
16188            if range_is_empty {
16189                all_deletions = false;
16190            } else {
16191                all_insertions = false;
16192            }
16193        } else {
16194            return false;
16195        }
16196
16197        if !all_insertions && !all_deletions {
16198            return false;
16199        }
16200    }
16201    all_insertions || all_deletions
16202}