editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::StringMatchCandidate;
   72use zed_predict_onboarding::ZedPredictModal;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, App,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   83    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   84    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size,
   85    Styled, StyledText, Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection,
   86    UnderlineStyle, 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    CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
  100    IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  101    TransactionId, TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  128};
  129use project::{
  130    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  131    project_settings::{GitGutterSetting, ProjectSettings},
  132    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  133    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  134};
  135use rand::prelude::*;
  136use rpc::{proto::*, ErrorExt};
  137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  138use selections_collection::{
  139    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  140};
  141use serde::{Deserialize, Serialize};
  142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  143use smallvec::SmallVec;
  144use snippet::Snippet;
  145use std::{
  146    any::TypeId,
  147    borrow::Cow,
  148    cell::RefCell,
  149    cmp::{self, Ordering, Reverse},
  150    mem,
  151    num::NonZeroU32,
  152    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  153    path::{Path, PathBuf},
  154    rc::Rc,
  155    sync::Arc,
  156    time::{Duration, Instant},
  157};
  158pub use sum_tree::Bias;
  159use sum_tree::TreeMap;
  160use text::{BufferId, OffsetUtf16, Rope};
  161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  167use workspace::item::{ItemHandle, PreviewTabsSettings};
  168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  169use workspace::{
  170    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  171};
  172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  173
  174use crate::hover_links::{find_url, find_url_from_range};
  175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  176
  177pub const FILE_HEADER_HEIGHT: u32 = 2;
  178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  182const MAX_LINE_LEN: usize = 1024;
  183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  186#[doc(hidden)]
  187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  188
  189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  191
  192pub fn render_parsed_markdown(
  193    element_id: impl Into<ElementId>,
  194    parsed: &language::ParsedMarkdown,
  195    editor_style: &EditorStyle,
  196    workspace: Option<WeakEntity<Workspace>>,
  197    cx: &mut App,
  198) -> InteractiveText {
  199    let code_span_background_color = cx
  200        .theme()
  201        .colors()
  202        .editor_document_highlight_read_background;
  203
  204    let highlights = gpui::combine_highlights(
  205        parsed.highlights.iter().filter_map(|(range, highlight)| {
  206            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  207            Some((range.clone(), highlight))
  208        }),
  209        parsed
  210            .regions
  211            .iter()
  212            .zip(&parsed.region_ranges)
  213            .filter_map(|(region, range)| {
  214                if region.code {
  215                    Some((
  216                        range.clone(),
  217                        HighlightStyle {
  218                            background_color: Some(code_span_background_color),
  219                            ..Default::default()
  220                        },
  221                    ))
  222                } else {
  223                    None
  224                }
  225            }),
  226    );
  227
  228    let mut links = Vec::new();
  229    let mut link_ranges = Vec::new();
  230    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  231        if let Some(link) = region.link.clone() {
  232            links.push(link);
  233            link_ranges.push(range.clone());
  234        }
  235    }
  236
  237    InteractiveText::new(
  238        element_id,
  239        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  240    )
  241    .on_click(
  242        link_ranges,
  243        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace
  249                            .open_abs_path(path.clone(), false, window, cx)
  250                            .detach();
  251                    });
  252                }
  253            }
  254        },
  255    )
  256}
  257
  258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  259pub enum InlayId {
  260    InlineCompletion(usize),
  261    Hint(usize),
  262}
  263
  264impl InlayId {
  265    fn id(&self) -> usize {
  266        match self {
  267            Self::InlineCompletion(id) => *id,
  268            Self::Hint(id) => *id,
  269        }
  270    }
  271}
  272
  273enum DocumentHighlightRead {}
  274enum DocumentHighlightWrite {}
  275enum InputComposition {}
  276
  277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  278pub enum Navigated {
  279    Yes,
  280    No,
  281}
  282
  283impl Navigated {
  284    pub fn from_bool(yes: bool) -> Navigated {
  285        if yes {
  286            Navigated::Yes
  287        } else {
  288            Navigated::No
  289        }
  290    }
  291}
  292
  293pub fn init_settings(cx: &mut App) {
  294    EditorSettings::register(cx);
  295}
  296
  297pub fn init(cx: &mut App) {
  298    init_settings(cx);
  299
  300    workspace::register_project_item::<Editor>(cx);
  301    workspace::FollowableViewRegistry::register::<Editor>(cx);
  302    workspace::register_serializable_item::<Editor>(cx);
  303
  304    cx.observe_new(
  305        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  306            workspace.register_action(Editor::new_file);
  307            workspace.register_action(Editor::new_file_vertical);
  308            workspace.register_action(Editor::new_file_horizontal);
  309        },
  310    )
  311    .detach();
  312
  313    cx.on_action(move |_: &workspace::NewFile, cx| {
  314        let app_state = workspace::AppState::global(cx);
  315        if let Some(app_state) = app_state.upgrade() {
  316            workspace::open_new(
  317                Default::default(),
  318                app_state,
  319                cx,
  320                |workspace, window, cx| {
  321                    Editor::new_file(workspace, &Default::default(), window, cx)
  322                },
  323            )
  324            .detach();
  325        }
  326    });
  327    cx.on_action(move |_: &workspace::NewWindow, cx| {
  328        let app_state = workspace::AppState::global(cx);
  329        if let Some(app_state) = app_state.upgrade() {
  330            workspace::open_new(
  331                Default::default(),
  332                app_state,
  333                cx,
  334                |workspace, window, cx| {
  335                    Editor::new_file(workspace, &Default::default(), window, cx)
  336                },
  337            )
  338            .detach();
  339        }
  340    });
  341    git::project_diff::init(cx);
  342}
  343
  344pub struct SearchWithinRange;
  345
  346trait InvalidationRegion {
  347    fn ranges(&self) -> &[Range<Anchor>];
  348}
  349
  350#[derive(Clone, Debug, PartialEq)]
  351pub enum SelectPhase {
  352    Begin {
  353        position: DisplayPoint,
  354        add: bool,
  355        click_count: usize,
  356    },
  357    BeginColumnar {
  358        position: DisplayPoint,
  359        reset: bool,
  360        goal_column: u32,
  361    },
  362    Extend {
  363        position: DisplayPoint,
  364        click_count: usize,
  365    },
  366    Update {
  367        position: DisplayPoint,
  368        goal_column: u32,
  369        scroll_delta: gpui::Point<f32>,
  370    },
  371    End,
  372}
  373
  374#[derive(Clone, Debug)]
  375pub enum SelectMode {
  376    Character,
  377    Word(Range<Anchor>),
  378    Line(Range<Anchor>),
  379    All,
  380}
  381
  382#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  383pub enum EditorMode {
  384    SingleLine { auto_width: bool },
  385    AutoHeight { max_lines: usize },
  386    Full,
  387}
  388
  389#[derive(Copy, Clone, Debug)]
  390pub enum SoftWrap {
  391    /// Prefer not to wrap at all.
  392    ///
  393    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  394    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  395    GitDiff,
  396    /// Prefer a single line generally, unless an overly long line is encountered.
  397    None,
  398    /// Soft wrap lines that exceed the editor width.
  399    EditorWidth,
  400    /// Soft wrap lines at the preferred line length.
  401    Column(u32),
  402    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  403    Bounded(u32),
  404}
  405
  406#[derive(Clone)]
  407pub struct EditorStyle {
  408    pub background: Hsla,
  409    pub local_player: PlayerColor,
  410    pub text: TextStyle,
  411    pub scrollbar_width: Pixels,
  412    pub syntax: Arc<SyntaxTheme>,
  413    pub status: StatusColors,
  414    pub inlay_hints_style: HighlightStyle,
  415    pub inline_completion_styles: InlineCompletionStyles,
  416    pub unnecessary_code_fade: f32,
  417}
  418
  419impl Default for EditorStyle {
  420    fn default() -> Self {
  421        Self {
  422            background: Hsla::default(),
  423            local_player: PlayerColor::default(),
  424            text: TextStyle::default(),
  425            scrollbar_width: Pixels::default(),
  426            syntax: Default::default(),
  427            // HACK: Status colors don't have a real default.
  428            // We should look into removing the status colors from the editor
  429            // style and retrieve them directly from the theme.
  430            status: StatusColors::dark(),
  431            inlay_hints_style: HighlightStyle::default(),
  432            inline_completion_styles: InlineCompletionStyles {
  433                insertion: HighlightStyle::default(),
  434                whitespace: HighlightStyle::default(),
  435            },
  436            unnecessary_code_fade: Default::default(),
  437        }
  438    }
  439}
  440
  441pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  442    let show_background = language_settings::language_settings(None, None, cx)
  443        .inlay_hints
  444        .show_background;
  445
  446    HighlightStyle {
  447        color: Some(cx.theme().status().hint),
  448        background_color: show_background.then(|| cx.theme().status().hint_background),
  449        ..HighlightStyle::default()
  450    }
  451}
  452
  453pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  454    InlineCompletionStyles {
  455        insertion: HighlightStyle {
  456            color: Some(cx.theme().status().predictive),
  457            ..HighlightStyle::default()
  458        },
  459        whitespace: HighlightStyle {
  460            background_color: Some(cx.theme().status().created_background),
  461            ..HighlightStyle::default()
  462        },
  463    }
  464}
  465
  466type CompletionId = usize;
  467
  468#[derive(Debug, Clone)]
  469enum InlineCompletionMenuHint {
  470    Loading,
  471    Loaded { text: InlineCompletionText },
  472    PendingTermsAcceptance,
  473    None,
  474}
  475
  476impl InlineCompletionMenuHint {
  477    pub fn label(&self) -> &'static str {
  478        match self {
  479            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  480                "Edit Prediction"
  481            }
  482            InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
  483            InlineCompletionMenuHint::None => "No Prediction",
  484        }
  485    }
  486}
  487
  488#[derive(Clone, Debug)]
  489enum InlineCompletionText {
  490    Move(SharedString),
  491    Edit(HighlightedText),
  492}
  493
  494pub(crate) enum EditDisplayMode {
  495    TabAccept,
  496    DiffPopover,
  497    Inline,
  498}
  499
  500enum InlineCompletion {
  501    Edit {
  502        edits: Vec<(Range<Anchor>, String)>,
  503        edit_preview: Option<EditPreview>,
  504        display_mode: EditDisplayMode,
  505        snapshot: BufferSnapshot,
  506    },
  507    Move(Anchor),
  508}
  509
  510struct InlineCompletionState {
  511    inlay_ids: Vec<InlayId>,
  512    completion: InlineCompletion,
  513    invalidation_range: Range<Anchor>,
  514}
  515
  516enum InlineCompletionHighlight {}
  517
  518pub enum MenuInlineCompletionsPolicy {
  519    Never,
  520    ByProvider,
  521}
  522
  523#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  524struct EditorActionId(usize);
  525
  526impl EditorActionId {
  527    pub fn post_inc(&mut self) -> Self {
  528        let answer = self.0;
  529
  530        *self = Self(answer + 1);
  531
  532        Self(answer)
  533    }
  534}
  535
  536// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  537// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  538
  539type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  540type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  541
  542#[derive(Default)]
  543struct ScrollbarMarkerState {
  544    scrollbar_size: Size<Pixels>,
  545    dirty: bool,
  546    markers: Arc<[PaintQuad]>,
  547    pending_refresh: Option<Task<Result<()>>>,
  548}
  549
  550impl ScrollbarMarkerState {
  551    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  552        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  553    }
  554}
  555
  556#[derive(Clone, Debug)]
  557struct RunnableTasks {
  558    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  559    offset: MultiBufferOffset,
  560    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  561    column: u32,
  562    // Values of all named captures, including those starting with '_'
  563    extra_variables: HashMap<String, String>,
  564    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  565    context_range: Range<BufferOffset>,
  566}
  567
  568impl RunnableTasks {
  569    fn resolve<'a>(
  570        &'a self,
  571        cx: &'a task::TaskContext,
  572    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  573        self.templates.iter().filter_map(|(kind, template)| {
  574            template
  575                .resolve_task(&kind.to_id_base(), cx)
  576                .map(|task| (kind.clone(), task))
  577        })
  578    }
  579}
  580
  581#[derive(Clone)]
  582struct ResolvedTasks {
  583    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  584    position: Anchor,
  585}
  586#[derive(Copy, Clone, Debug)]
  587struct MultiBufferOffset(usize);
  588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  589struct BufferOffset(usize);
  590
  591// Addons allow storing per-editor state in other crates (e.g. Vim)
  592pub trait Addon: 'static {
  593    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  594
  595    fn to_any(&self) -> &dyn std::any::Any;
  596}
  597
  598#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  599pub enum IsVimMode {
  600    Yes,
  601    No,
  602}
  603
  604/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  605///
  606/// See the [module level documentation](self) for more information.
  607pub struct Editor {
  608    focus_handle: FocusHandle,
  609    last_focused_descendant: Option<WeakFocusHandle>,
  610    /// The text buffer being edited
  611    buffer: Entity<MultiBuffer>,
  612    /// Map of how text in the buffer should be displayed.
  613    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  614    pub display_map: Entity<DisplayMap>,
  615    pub selections: SelectionsCollection,
  616    pub scroll_manager: ScrollManager,
  617    /// When inline assist editors are linked, they all render cursors because
  618    /// typing enters text into each of them, even the ones that aren't focused.
  619    pub(crate) show_cursor_when_unfocused: bool,
  620    columnar_selection_tail: Option<Anchor>,
  621    add_selections_state: Option<AddSelectionsState>,
  622    select_next_state: Option<SelectNextState>,
  623    select_prev_state: Option<SelectNextState>,
  624    selection_history: SelectionHistory,
  625    autoclose_regions: Vec<AutocloseRegion>,
  626    snippet_stack: InvalidationStack<SnippetState>,
  627    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  628    ime_transaction: Option<TransactionId>,
  629    active_diagnostics: Option<ActiveDiagnosticGroup>,
  630    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  631
  632    project: Option<Entity<Project>>,
  633    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  634    completion_provider: Option<Box<dyn CompletionProvider>>,
  635    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  636    blink_manager: Entity<BlinkManager>,
  637    show_cursor_names: bool,
  638    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  639    pub show_local_selections: bool,
  640    mode: EditorMode,
  641    show_breadcrumbs: bool,
  642    show_gutter: bool,
  643    show_scrollbars: bool,
  644    show_line_numbers: Option<bool>,
  645    use_relative_line_numbers: Option<bool>,
  646    show_git_diff_gutter: Option<bool>,
  647    show_code_actions: Option<bool>,
  648    show_runnables: Option<bool>,
  649    show_wrap_guides: Option<bool>,
  650    show_indent_guides: Option<bool>,
  651    placeholder_text: Option<Arc<str>>,
  652    highlight_order: usize,
  653    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  654    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  655    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  656    scrollbar_marker_state: ScrollbarMarkerState,
  657    active_indent_guides_state: ActiveIndentGuidesState,
  658    nav_history: Option<ItemNavHistory>,
  659    context_menu: RefCell<Option<CodeContextMenu>>,
  660    mouse_context_menu: Option<MouseContextMenu>,
  661    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  662    signature_help_state: SignatureHelpState,
  663    auto_signature_help: Option<bool>,
  664    find_all_references_task_sources: Vec<Anchor>,
  665    next_completion_id: CompletionId,
  666    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  667    code_actions_task: Option<Task<Result<()>>>,
  668    document_highlights_task: Option<Task<()>>,
  669    linked_editing_range_task: Option<Task<Option<()>>>,
  670    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  671    pending_rename: Option<RenameState>,
  672    searchable: bool,
  673    cursor_shape: CursorShape,
  674    current_line_highlight: Option<CurrentLineHighlight>,
  675    collapse_matches: bool,
  676    autoindent_mode: Option<AutoindentMode>,
  677    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  678    input_enabled: bool,
  679    use_modal_editing: bool,
  680    read_only: bool,
  681    leader_peer_id: Option<PeerId>,
  682    remote_id: Option<ViewId>,
  683    hover_state: HoverState,
  684    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  685    gutter_hovered: bool,
  686    hovered_link_state: Option<HoveredLinkState>,
  687    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  688    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  689    active_inline_completion: Option<InlineCompletionState>,
  690    // enable_inline_completions is a switch that Vim can use to disable
  691    // inline completions based on its mode.
  692    enable_inline_completions: bool,
  693    show_inline_completions_override: Option<bool>,
  694    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  695    inlay_hint_cache: InlayHintCache,
  696    next_inlay_id: usize,
  697    _subscriptions: Vec<Subscription>,
  698    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  699    gutter_dimensions: GutterDimensions,
  700    style: Option<EditorStyle>,
  701    text_style_refinement: Option<TextStyleRefinement>,
  702    next_editor_action_id: EditorActionId,
  703    editor_actions:
  704        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  705    use_autoclose: bool,
  706    use_auto_surround: bool,
  707    auto_replace_emoji_shortcode: bool,
  708    show_git_blame_gutter: bool,
  709    show_git_blame_inline: bool,
  710    show_git_blame_inline_delay_task: Option<Task<()>>,
  711    git_blame_inline_enabled: bool,
  712    serialize_dirty_buffers: bool,
  713    show_selection_menu: Option<bool>,
  714    blame: Option<Entity<GitBlame>>,
  715    blame_subscription: Option<Subscription>,
  716    custom_context_menu: Option<
  717        Box<
  718            dyn 'static
  719                + Fn(
  720                    &mut Self,
  721                    DisplayPoint,
  722                    &mut Window,
  723                    &mut Context<Self>,
  724                ) -> Option<Entity<ui::ContextMenu>>,
  725        >,
  726    >,
  727    last_bounds: Option<Bounds<Pixels>>,
  728    expect_bounds_change: Option<Bounds<Pixels>>,
  729    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  730    tasks_update_task: Option<Task<()>>,
  731    in_project_search: bool,
  732    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  733    breadcrumb_header: Option<String>,
  734    focused_block: Option<FocusedBlock>,
  735    next_scroll_position: NextScrollCursorCenterTopBottom,
  736    addons: HashMap<TypeId, Box<dyn Addon>>,
  737    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  738    selection_mark_mode: bool,
  739    toggle_fold_multiple_buffers: Task<()>,
  740    _scroll_cursor_center_top_bottom_task: Task<()>,
  741}
  742
  743#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  744enum NextScrollCursorCenterTopBottom {
  745    #[default]
  746    Center,
  747    Top,
  748    Bottom,
  749}
  750
  751impl NextScrollCursorCenterTopBottom {
  752    fn next(&self) -> Self {
  753        match self {
  754            Self::Center => Self::Top,
  755            Self::Top => Self::Bottom,
  756            Self::Bottom => Self::Center,
  757        }
  758    }
  759}
  760
  761#[derive(Clone)]
  762pub struct EditorSnapshot {
  763    pub mode: EditorMode,
  764    show_gutter: bool,
  765    show_line_numbers: Option<bool>,
  766    show_git_diff_gutter: Option<bool>,
  767    show_code_actions: Option<bool>,
  768    show_runnables: Option<bool>,
  769    git_blame_gutter_max_author_length: Option<usize>,
  770    pub display_snapshot: DisplaySnapshot,
  771    pub placeholder_text: Option<Arc<str>>,
  772    is_focused: bool,
  773    scroll_anchor: ScrollAnchor,
  774    ongoing_scroll: OngoingScroll,
  775    current_line_highlight: CurrentLineHighlight,
  776    gutter_hovered: bool,
  777}
  778
  779const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  780
  781#[derive(Default, Debug, Clone, Copy)]
  782pub struct GutterDimensions {
  783    pub left_padding: Pixels,
  784    pub right_padding: Pixels,
  785    pub width: Pixels,
  786    pub margin: Pixels,
  787    pub git_blame_entries_width: Option<Pixels>,
  788}
  789
  790impl GutterDimensions {
  791    /// The full width of the space taken up by the gutter.
  792    pub fn full_width(&self) -> Pixels {
  793        self.margin + self.width
  794    }
  795
  796    /// The width of the space reserved for the fold indicators,
  797    /// use alongside 'justify_end' and `gutter_width` to
  798    /// right align content with the line numbers
  799    pub fn fold_area_width(&self) -> Pixels {
  800        self.margin + self.right_padding
  801    }
  802}
  803
  804#[derive(Debug)]
  805pub struct RemoteSelection {
  806    pub replica_id: ReplicaId,
  807    pub selection: Selection<Anchor>,
  808    pub cursor_shape: CursorShape,
  809    pub peer_id: PeerId,
  810    pub line_mode: bool,
  811    pub participant_index: Option<ParticipantIndex>,
  812    pub user_name: Option<SharedString>,
  813}
  814
  815#[derive(Clone, Debug)]
  816struct SelectionHistoryEntry {
  817    selections: Arc<[Selection<Anchor>]>,
  818    select_next_state: Option<SelectNextState>,
  819    select_prev_state: Option<SelectNextState>,
  820    add_selections_state: Option<AddSelectionsState>,
  821}
  822
  823enum SelectionHistoryMode {
  824    Normal,
  825    Undoing,
  826    Redoing,
  827}
  828
  829#[derive(Clone, PartialEq, Eq, Hash)]
  830struct HoveredCursor {
  831    replica_id: u16,
  832    selection_id: usize,
  833}
  834
  835impl Default for SelectionHistoryMode {
  836    fn default() -> Self {
  837        Self::Normal
  838    }
  839}
  840
  841#[derive(Default)]
  842struct SelectionHistory {
  843    #[allow(clippy::type_complexity)]
  844    selections_by_transaction:
  845        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  846    mode: SelectionHistoryMode,
  847    undo_stack: VecDeque<SelectionHistoryEntry>,
  848    redo_stack: VecDeque<SelectionHistoryEntry>,
  849}
  850
  851impl SelectionHistory {
  852    fn insert_transaction(
  853        &mut self,
  854        transaction_id: TransactionId,
  855        selections: Arc<[Selection<Anchor>]>,
  856    ) {
  857        self.selections_by_transaction
  858            .insert(transaction_id, (selections, None));
  859    }
  860
  861    #[allow(clippy::type_complexity)]
  862    fn transaction(
  863        &self,
  864        transaction_id: TransactionId,
  865    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  866        self.selections_by_transaction.get(&transaction_id)
  867    }
  868
  869    #[allow(clippy::type_complexity)]
  870    fn transaction_mut(
  871        &mut self,
  872        transaction_id: TransactionId,
  873    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  874        self.selections_by_transaction.get_mut(&transaction_id)
  875    }
  876
  877    fn push(&mut self, entry: SelectionHistoryEntry) {
  878        if !entry.selections.is_empty() {
  879            match self.mode {
  880                SelectionHistoryMode::Normal => {
  881                    self.push_undo(entry);
  882                    self.redo_stack.clear();
  883                }
  884                SelectionHistoryMode::Undoing => self.push_redo(entry),
  885                SelectionHistoryMode::Redoing => self.push_undo(entry),
  886            }
  887        }
  888    }
  889
  890    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  891        if self
  892            .undo_stack
  893            .back()
  894            .map_or(true, |e| e.selections != entry.selections)
  895        {
  896            self.undo_stack.push_back(entry);
  897            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  898                self.undo_stack.pop_front();
  899            }
  900        }
  901    }
  902
  903    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  904        if self
  905            .redo_stack
  906            .back()
  907            .map_or(true, |e| e.selections != entry.selections)
  908        {
  909            self.redo_stack.push_back(entry);
  910            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  911                self.redo_stack.pop_front();
  912            }
  913        }
  914    }
  915}
  916
  917struct RowHighlight {
  918    index: usize,
  919    range: Range<Anchor>,
  920    color: Hsla,
  921    should_autoscroll: bool,
  922}
  923
  924#[derive(Clone, Debug)]
  925struct AddSelectionsState {
  926    above: bool,
  927    stack: Vec<usize>,
  928}
  929
  930#[derive(Clone)]
  931struct SelectNextState {
  932    query: AhoCorasick,
  933    wordwise: bool,
  934    done: bool,
  935}
  936
  937impl std::fmt::Debug for SelectNextState {
  938    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  939        f.debug_struct(std::any::type_name::<Self>())
  940            .field("wordwise", &self.wordwise)
  941            .field("done", &self.done)
  942            .finish()
  943    }
  944}
  945
  946#[derive(Debug)]
  947struct AutocloseRegion {
  948    selection_id: usize,
  949    range: Range<Anchor>,
  950    pair: BracketPair,
  951}
  952
  953#[derive(Debug)]
  954struct SnippetState {
  955    ranges: Vec<Vec<Range<Anchor>>>,
  956    active_index: usize,
  957    choices: Vec<Option<Vec<String>>>,
  958}
  959
  960#[doc(hidden)]
  961pub struct RenameState {
  962    pub range: Range<Anchor>,
  963    pub old_name: Arc<str>,
  964    pub editor: Entity<Editor>,
  965    block_id: CustomBlockId,
  966}
  967
  968struct InvalidationStack<T>(Vec<T>);
  969
  970struct RegisteredInlineCompletionProvider {
  971    provider: Arc<dyn InlineCompletionProviderHandle>,
  972    _subscription: Subscription,
  973}
  974
  975#[derive(Debug)]
  976struct ActiveDiagnosticGroup {
  977    primary_range: Range<Anchor>,
  978    primary_message: String,
  979    group_id: usize,
  980    blocks: HashMap<CustomBlockId, Diagnostic>,
  981    is_valid: bool,
  982}
  983
  984#[derive(Serialize, Deserialize, Clone, Debug)]
  985pub struct ClipboardSelection {
  986    pub len: usize,
  987    pub is_entire_line: bool,
  988    pub first_line_indent: u32,
  989}
  990
  991#[derive(Debug)]
  992pub(crate) struct NavigationData {
  993    cursor_anchor: Anchor,
  994    cursor_position: Point,
  995    scroll_anchor: ScrollAnchor,
  996    scroll_top_row: u32,
  997}
  998
  999#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1000pub enum GotoDefinitionKind {
 1001    Symbol,
 1002    Declaration,
 1003    Type,
 1004    Implementation,
 1005}
 1006
 1007#[derive(Debug, Clone)]
 1008enum InlayHintRefreshReason {
 1009    Toggle(bool),
 1010    SettingsChange(InlayHintSettings),
 1011    NewLinesShown,
 1012    BufferEdited(HashSet<Arc<Language>>),
 1013    RefreshRequested,
 1014    ExcerptsRemoved(Vec<ExcerptId>),
 1015}
 1016
 1017impl InlayHintRefreshReason {
 1018    fn description(&self) -> &'static str {
 1019        match self {
 1020            Self::Toggle(_) => "toggle",
 1021            Self::SettingsChange(_) => "settings change",
 1022            Self::NewLinesShown => "new lines shown",
 1023            Self::BufferEdited(_) => "buffer edited",
 1024            Self::RefreshRequested => "refresh requested",
 1025            Self::ExcerptsRemoved(_) => "excerpts removed",
 1026        }
 1027    }
 1028}
 1029
 1030pub enum FormatTarget {
 1031    Buffers,
 1032    Ranges(Vec<Range<MultiBufferPoint>>),
 1033}
 1034
 1035pub(crate) struct FocusedBlock {
 1036    id: BlockId,
 1037    focus_handle: WeakFocusHandle,
 1038}
 1039
 1040#[derive(Clone)]
 1041enum JumpData {
 1042    MultiBufferRow {
 1043        row: MultiBufferRow,
 1044        line_offset_from_top: u32,
 1045    },
 1046    MultiBufferPoint {
 1047        excerpt_id: ExcerptId,
 1048        position: Point,
 1049        anchor: text::Anchor,
 1050        line_offset_from_top: u32,
 1051    },
 1052}
 1053
 1054pub enum MultibufferSelectionMode {
 1055    First,
 1056    All,
 1057}
 1058
 1059impl Editor {
 1060    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1061        let buffer = cx.new(|cx| Buffer::local("", cx));
 1062        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1063        Self::new(
 1064            EditorMode::SingleLine { auto_width: false },
 1065            buffer,
 1066            None,
 1067            false,
 1068            window,
 1069            cx,
 1070        )
 1071    }
 1072
 1073    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1074        let buffer = cx.new(|cx| Buffer::local("", cx));
 1075        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1076        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1077    }
 1078
 1079    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1080        let buffer = cx.new(|cx| Buffer::local("", cx));
 1081        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1082        Self::new(
 1083            EditorMode::SingleLine { auto_width: true },
 1084            buffer,
 1085            None,
 1086            false,
 1087            window,
 1088            cx,
 1089        )
 1090    }
 1091
 1092    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1093        let buffer = cx.new(|cx| Buffer::local("", cx));
 1094        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1095        Self::new(
 1096            EditorMode::AutoHeight { max_lines },
 1097            buffer,
 1098            None,
 1099            false,
 1100            window,
 1101            cx,
 1102        )
 1103    }
 1104
 1105    pub fn for_buffer(
 1106        buffer: Entity<Buffer>,
 1107        project: Option<Entity<Project>>,
 1108        window: &mut Window,
 1109        cx: &mut Context<Self>,
 1110    ) -> Self {
 1111        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1112        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1113    }
 1114
 1115    pub fn for_multibuffer(
 1116        buffer: Entity<MultiBuffer>,
 1117        project: Option<Entity<Project>>,
 1118        show_excerpt_controls: bool,
 1119        window: &mut Window,
 1120        cx: &mut Context<Self>,
 1121    ) -> Self {
 1122        Self::new(
 1123            EditorMode::Full,
 1124            buffer,
 1125            project,
 1126            show_excerpt_controls,
 1127            window,
 1128            cx,
 1129        )
 1130    }
 1131
 1132    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1133        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1134        let mut clone = Self::new(
 1135            self.mode,
 1136            self.buffer.clone(),
 1137            self.project.clone(),
 1138            show_excerpt_controls,
 1139            window,
 1140            cx,
 1141        );
 1142        self.display_map.update(cx, |display_map, cx| {
 1143            let snapshot = display_map.snapshot(cx);
 1144            clone.display_map.update(cx, |display_map, cx| {
 1145                display_map.set_state(&snapshot, cx);
 1146            });
 1147        });
 1148        clone.selections.clone_state(&self.selections);
 1149        clone.scroll_manager.clone_state(&self.scroll_manager);
 1150        clone.searchable = self.searchable;
 1151        clone
 1152    }
 1153
 1154    pub fn new(
 1155        mode: EditorMode,
 1156        buffer: Entity<MultiBuffer>,
 1157        project: Option<Entity<Project>>,
 1158        show_excerpt_controls: bool,
 1159        window: &mut Window,
 1160        cx: &mut Context<Self>,
 1161    ) -> Self {
 1162        let style = window.text_style();
 1163        let font_size = style.font_size.to_pixels(window.rem_size());
 1164        let editor = cx.entity().downgrade();
 1165        let fold_placeholder = FoldPlaceholder {
 1166            constrain_width: true,
 1167            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1168                let editor = editor.clone();
 1169                div()
 1170                    .id(fold_id)
 1171                    .bg(cx.theme().colors().ghost_element_background)
 1172                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1173                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1174                    .rounded_sm()
 1175                    .size_full()
 1176                    .cursor_pointer()
 1177                    .child("")
 1178                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1179                    .on_click(move |_, _window, cx| {
 1180                        editor
 1181                            .update(cx, |editor, cx| {
 1182                                editor.unfold_ranges(
 1183                                    &[fold_range.start..fold_range.end],
 1184                                    true,
 1185                                    false,
 1186                                    cx,
 1187                                );
 1188                                cx.stop_propagation();
 1189                            })
 1190                            .ok();
 1191                    })
 1192                    .into_any()
 1193            }),
 1194            merge_adjacent: true,
 1195            ..Default::default()
 1196        };
 1197        let display_map = cx.new(|cx| {
 1198            DisplayMap::new(
 1199                buffer.clone(),
 1200                style.font(),
 1201                font_size,
 1202                None,
 1203                show_excerpt_controls,
 1204                FILE_HEADER_HEIGHT,
 1205                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1206                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1207                fold_placeholder,
 1208                cx,
 1209            )
 1210        });
 1211
 1212        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1213
 1214        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1215
 1216        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1217            .then(|| language_settings::SoftWrap::None);
 1218
 1219        let mut project_subscriptions = Vec::new();
 1220        if mode == EditorMode::Full {
 1221            if let Some(project) = project.as_ref() {
 1222                if buffer.read(cx).is_singleton() {
 1223                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1224                        cx.emit(EditorEvent::TitleChanged);
 1225                    }));
 1226                }
 1227                project_subscriptions.push(cx.subscribe_in(
 1228                    project,
 1229                    window,
 1230                    |editor, _, event, window, cx| {
 1231                        if let project::Event::RefreshInlayHints = event {
 1232                            editor
 1233                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1234                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1235                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1236                                let focus_handle = editor.focus_handle(cx);
 1237                                if focus_handle.is_focused(window) {
 1238                                    let snapshot = buffer.read(cx).snapshot();
 1239                                    for (range, snippet) in snippet_edits {
 1240                                        let editor_range =
 1241                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1242                                        editor
 1243                                            .insert_snippet(
 1244                                                &[editor_range],
 1245                                                snippet.clone(),
 1246                                                window,
 1247                                                cx,
 1248                                            )
 1249                                            .ok();
 1250                                    }
 1251                                }
 1252                            }
 1253                        }
 1254                    },
 1255                ));
 1256                if let Some(task_inventory) = project
 1257                    .read(cx)
 1258                    .task_store()
 1259                    .read(cx)
 1260                    .task_inventory()
 1261                    .cloned()
 1262                {
 1263                    project_subscriptions.push(cx.observe_in(
 1264                        &task_inventory,
 1265                        window,
 1266                        |editor, _, window, cx| {
 1267                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1268                        },
 1269                    ));
 1270                }
 1271            }
 1272        }
 1273
 1274        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1275
 1276        let inlay_hint_settings =
 1277            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1278        let focus_handle = cx.focus_handle();
 1279        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1280            .detach();
 1281        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1282            .detach();
 1283        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1284            .detach();
 1285        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1286            .detach();
 1287
 1288        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1289            Some(false)
 1290        } else {
 1291            None
 1292        };
 1293
 1294        let mut code_action_providers = Vec::new();
 1295        if let Some(project) = project.clone() {
 1296            get_unstaged_changes_for_buffers(
 1297                &project,
 1298                buffer.read(cx).all_buffers(),
 1299                buffer.clone(),
 1300                cx,
 1301            );
 1302            code_action_providers.push(Rc::new(project) as Rc<_>);
 1303        }
 1304
 1305        let mut this = Self {
 1306            focus_handle,
 1307            show_cursor_when_unfocused: false,
 1308            last_focused_descendant: None,
 1309            buffer: buffer.clone(),
 1310            display_map: display_map.clone(),
 1311            selections,
 1312            scroll_manager: ScrollManager::new(cx),
 1313            columnar_selection_tail: None,
 1314            add_selections_state: None,
 1315            select_next_state: None,
 1316            select_prev_state: None,
 1317            selection_history: Default::default(),
 1318            autoclose_regions: Default::default(),
 1319            snippet_stack: Default::default(),
 1320            select_larger_syntax_node_stack: Vec::new(),
 1321            ime_transaction: Default::default(),
 1322            active_diagnostics: None,
 1323            soft_wrap_mode_override,
 1324            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1325            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1326            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1327            project,
 1328            blink_manager: blink_manager.clone(),
 1329            show_local_selections: true,
 1330            show_scrollbars: true,
 1331            mode,
 1332            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1333            show_gutter: mode == EditorMode::Full,
 1334            show_line_numbers: None,
 1335            use_relative_line_numbers: None,
 1336            show_git_diff_gutter: None,
 1337            show_code_actions: None,
 1338            show_runnables: None,
 1339            show_wrap_guides: None,
 1340            show_indent_guides,
 1341            placeholder_text: None,
 1342            highlight_order: 0,
 1343            highlighted_rows: HashMap::default(),
 1344            background_highlights: Default::default(),
 1345            gutter_highlights: TreeMap::default(),
 1346            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1347            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1348            nav_history: None,
 1349            context_menu: RefCell::new(None),
 1350            mouse_context_menu: None,
 1351            completion_tasks: Default::default(),
 1352            signature_help_state: SignatureHelpState::default(),
 1353            auto_signature_help: None,
 1354            find_all_references_task_sources: Vec::new(),
 1355            next_completion_id: 0,
 1356            next_inlay_id: 0,
 1357            code_action_providers,
 1358            available_code_actions: Default::default(),
 1359            code_actions_task: Default::default(),
 1360            document_highlights_task: Default::default(),
 1361            linked_editing_range_task: Default::default(),
 1362            pending_rename: Default::default(),
 1363            searchable: true,
 1364            cursor_shape: EditorSettings::get_global(cx)
 1365                .cursor_shape
 1366                .unwrap_or_default(),
 1367            current_line_highlight: None,
 1368            autoindent_mode: Some(AutoindentMode::EachLine),
 1369            collapse_matches: false,
 1370            workspace: None,
 1371            input_enabled: true,
 1372            use_modal_editing: mode == EditorMode::Full,
 1373            read_only: false,
 1374            use_autoclose: true,
 1375            use_auto_surround: true,
 1376            auto_replace_emoji_shortcode: false,
 1377            leader_peer_id: None,
 1378            remote_id: None,
 1379            hover_state: Default::default(),
 1380            pending_mouse_down: None,
 1381            hovered_link_state: Default::default(),
 1382            inline_completion_provider: None,
 1383            active_inline_completion: None,
 1384            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1385
 1386            gutter_hovered: false,
 1387            pixel_position_of_newest_cursor: None,
 1388            last_bounds: None,
 1389            expect_bounds_change: None,
 1390            gutter_dimensions: GutterDimensions::default(),
 1391            style: None,
 1392            show_cursor_names: false,
 1393            hovered_cursors: Default::default(),
 1394            next_editor_action_id: EditorActionId::default(),
 1395            editor_actions: Rc::default(),
 1396            show_inline_completions_override: None,
 1397            enable_inline_completions: true,
 1398            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1399            custom_context_menu: None,
 1400            show_git_blame_gutter: false,
 1401            show_git_blame_inline: false,
 1402            show_selection_menu: None,
 1403            show_git_blame_inline_delay_task: None,
 1404            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1405            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1406                .session
 1407                .restore_unsaved_buffers,
 1408            blame: None,
 1409            blame_subscription: None,
 1410            tasks: Default::default(),
 1411            _subscriptions: vec![
 1412                cx.observe(&buffer, Self::on_buffer_changed),
 1413                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1414                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1415                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1416                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1417                cx.observe_window_activation(window, |editor, window, cx| {
 1418                    let active = window.is_window_active();
 1419                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1420                        if active {
 1421                            blink_manager.enable(cx);
 1422                        } else {
 1423                            blink_manager.disable(cx);
 1424                        }
 1425                    });
 1426                }),
 1427            ],
 1428            tasks_update_task: None,
 1429            linked_edit_ranges: Default::default(),
 1430            in_project_search: false,
 1431            previous_search_ranges: None,
 1432            breadcrumb_header: None,
 1433            focused_block: None,
 1434            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1435            addons: HashMap::default(),
 1436            registered_buffers: HashMap::default(),
 1437            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1438            selection_mark_mode: false,
 1439            toggle_fold_multiple_buffers: Task::ready(()),
 1440            text_style_refinement: None,
 1441        };
 1442        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1443        this._subscriptions.extend(project_subscriptions);
 1444
 1445        this.end_selection(window, cx);
 1446        this.scroll_manager.show_scrollbar(window, cx);
 1447
 1448        if mode == EditorMode::Full {
 1449            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1450            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1451
 1452            if this.git_blame_inline_enabled {
 1453                this.git_blame_inline_enabled = true;
 1454                this.start_git_blame_inline(false, window, cx);
 1455            }
 1456
 1457            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1458                if let Some(project) = this.project.as_ref() {
 1459                    let lsp_store = project.read(cx).lsp_store();
 1460                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1461                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1462                    });
 1463                    this.registered_buffers
 1464                        .insert(buffer.read(cx).remote_id(), handle);
 1465                }
 1466            }
 1467        }
 1468
 1469        this.report_editor_event("Editor Opened", None, cx);
 1470        this
 1471    }
 1472
 1473    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1474        self.mouse_context_menu
 1475            .as_ref()
 1476            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1477    }
 1478
 1479    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1480        let mut key_context = KeyContext::new_with_defaults();
 1481        key_context.add("Editor");
 1482        let mode = match self.mode {
 1483            EditorMode::SingleLine { .. } => "single_line",
 1484            EditorMode::AutoHeight { .. } => "auto_height",
 1485            EditorMode::Full => "full",
 1486        };
 1487
 1488        if EditorSettings::jupyter_enabled(cx) {
 1489            key_context.add("jupyter");
 1490        }
 1491
 1492        key_context.set("mode", mode);
 1493        if self.pending_rename.is_some() {
 1494            key_context.add("renaming");
 1495        }
 1496        match self.context_menu.borrow().as_ref() {
 1497            Some(CodeContextMenu::Completions(_)) => {
 1498                key_context.add("menu");
 1499                key_context.add("showing_completions")
 1500            }
 1501            Some(CodeContextMenu::CodeActions(_)) => {
 1502                key_context.add("menu");
 1503                key_context.add("showing_code_actions")
 1504            }
 1505            None => {}
 1506        }
 1507
 1508        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1509        if !self.focus_handle(cx).contains_focused(window, cx)
 1510            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1511        {
 1512            for addon in self.addons.values() {
 1513                addon.extend_key_context(&mut key_context, cx)
 1514            }
 1515        }
 1516
 1517        if let Some(extension) = self
 1518            .buffer
 1519            .read(cx)
 1520            .as_singleton()
 1521            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1522        {
 1523            key_context.set("extension", extension.to_string());
 1524        }
 1525
 1526        if self.has_active_inline_completion() {
 1527            key_context.add("copilot_suggestion");
 1528            key_context.add("inline_completion");
 1529        }
 1530
 1531        if self.selection_mark_mode {
 1532            key_context.add("selection_mode");
 1533        }
 1534
 1535        key_context
 1536    }
 1537
 1538    pub fn new_file(
 1539        workspace: &mut Workspace,
 1540        _: &workspace::NewFile,
 1541        window: &mut Window,
 1542        cx: &mut Context<Workspace>,
 1543    ) {
 1544        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1545            "Failed to create buffer",
 1546            window,
 1547            cx,
 1548            |e, _, _| match e.error_code() {
 1549                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1550                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1551                e.error_tag("required").unwrap_or("the latest version")
 1552            )),
 1553                _ => None,
 1554            },
 1555        );
 1556    }
 1557
 1558    pub fn new_in_workspace(
 1559        workspace: &mut Workspace,
 1560        window: &mut Window,
 1561        cx: &mut Context<Workspace>,
 1562    ) -> Task<Result<Entity<Editor>>> {
 1563        let project = workspace.project().clone();
 1564        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1565
 1566        cx.spawn_in(window, |workspace, mut cx| async move {
 1567            let buffer = create.await?;
 1568            workspace.update_in(&mut cx, |workspace, window, cx| {
 1569                let editor =
 1570                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1571                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1572                editor
 1573            })
 1574        })
 1575    }
 1576
 1577    fn new_file_vertical(
 1578        workspace: &mut Workspace,
 1579        _: &workspace::NewFileSplitVertical,
 1580        window: &mut Window,
 1581        cx: &mut Context<Workspace>,
 1582    ) {
 1583        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1584    }
 1585
 1586    fn new_file_horizontal(
 1587        workspace: &mut Workspace,
 1588        _: &workspace::NewFileSplitHorizontal,
 1589        window: &mut Window,
 1590        cx: &mut Context<Workspace>,
 1591    ) {
 1592        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1593    }
 1594
 1595    fn new_file_in_direction(
 1596        workspace: &mut Workspace,
 1597        direction: SplitDirection,
 1598        window: &mut Window,
 1599        cx: &mut Context<Workspace>,
 1600    ) {
 1601        let project = workspace.project().clone();
 1602        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1603
 1604        cx.spawn_in(window, |workspace, mut cx| async move {
 1605            let buffer = create.await?;
 1606            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1607                workspace.split_item(
 1608                    direction,
 1609                    Box::new(
 1610                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1611                    ),
 1612                    window,
 1613                    cx,
 1614                )
 1615            })?;
 1616            anyhow::Ok(())
 1617        })
 1618        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1619            match e.error_code() {
 1620                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1621                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1622                e.error_tag("required").unwrap_or("the latest version")
 1623            )),
 1624                _ => None,
 1625            }
 1626        });
 1627    }
 1628
 1629    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1630        self.leader_peer_id
 1631    }
 1632
 1633    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1634        &self.buffer
 1635    }
 1636
 1637    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1638        self.workspace.as_ref()?.0.upgrade()
 1639    }
 1640
 1641    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1642        self.buffer().read(cx).title(cx)
 1643    }
 1644
 1645    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1646        let git_blame_gutter_max_author_length = self
 1647            .render_git_blame_gutter(cx)
 1648            .then(|| {
 1649                if let Some(blame) = self.blame.as_ref() {
 1650                    let max_author_length =
 1651                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1652                    Some(max_author_length)
 1653                } else {
 1654                    None
 1655                }
 1656            })
 1657            .flatten();
 1658
 1659        EditorSnapshot {
 1660            mode: self.mode,
 1661            show_gutter: self.show_gutter,
 1662            show_line_numbers: self.show_line_numbers,
 1663            show_git_diff_gutter: self.show_git_diff_gutter,
 1664            show_code_actions: self.show_code_actions,
 1665            show_runnables: self.show_runnables,
 1666            git_blame_gutter_max_author_length,
 1667            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1668            scroll_anchor: self.scroll_manager.anchor(),
 1669            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1670            placeholder_text: self.placeholder_text.clone(),
 1671            is_focused: self.focus_handle.is_focused(window),
 1672            current_line_highlight: self
 1673                .current_line_highlight
 1674                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1675            gutter_hovered: self.gutter_hovered,
 1676        }
 1677    }
 1678
 1679    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1680        self.buffer.read(cx).language_at(point, cx)
 1681    }
 1682
 1683    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1684        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1685    }
 1686
 1687    pub fn active_excerpt(
 1688        &self,
 1689        cx: &App,
 1690    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1691        self.buffer
 1692            .read(cx)
 1693            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1694    }
 1695
 1696    pub fn mode(&self) -> EditorMode {
 1697        self.mode
 1698    }
 1699
 1700    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1701        self.collaboration_hub.as_deref()
 1702    }
 1703
 1704    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1705        self.collaboration_hub = Some(hub);
 1706    }
 1707
 1708    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1709        self.in_project_search = in_project_search;
 1710    }
 1711
 1712    pub fn set_custom_context_menu(
 1713        &mut self,
 1714        f: impl 'static
 1715            + Fn(
 1716                &mut Self,
 1717                DisplayPoint,
 1718                &mut Window,
 1719                &mut Context<Self>,
 1720            ) -> Option<Entity<ui::ContextMenu>>,
 1721    ) {
 1722        self.custom_context_menu = Some(Box::new(f))
 1723    }
 1724
 1725    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1726        self.completion_provider = provider;
 1727    }
 1728
 1729    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1730        self.semantics_provider.clone()
 1731    }
 1732
 1733    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1734        self.semantics_provider = provider;
 1735    }
 1736
 1737    pub fn set_inline_completion_provider<T>(
 1738        &mut self,
 1739        provider: Option<Entity<T>>,
 1740        window: &mut Window,
 1741        cx: &mut Context<Self>,
 1742    ) where
 1743        T: InlineCompletionProvider,
 1744    {
 1745        self.inline_completion_provider =
 1746            provider.map(|provider| RegisteredInlineCompletionProvider {
 1747                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1748                    if this.focus_handle.is_focused(window) {
 1749                        this.update_visible_inline_completion(window, cx);
 1750                    }
 1751                }),
 1752                provider: Arc::new(provider),
 1753            });
 1754        self.refresh_inline_completion(false, false, window, cx);
 1755    }
 1756
 1757    pub fn placeholder_text(&self) -> Option<&str> {
 1758        self.placeholder_text.as_deref()
 1759    }
 1760
 1761    pub fn set_placeholder_text(
 1762        &mut self,
 1763        placeholder_text: impl Into<Arc<str>>,
 1764        cx: &mut Context<Self>,
 1765    ) {
 1766        let placeholder_text = Some(placeholder_text.into());
 1767        if self.placeholder_text != placeholder_text {
 1768            self.placeholder_text = placeholder_text;
 1769            cx.notify();
 1770        }
 1771    }
 1772
 1773    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1774        self.cursor_shape = cursor_shape;
 1775
 1776        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1777        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1778
 1779        cx.notify();
 1780    }
 1781
 1782    pub fn set_current_line_highlight(
 1783        &mut self,
 1784        current_line_highlight: Option<CurrentLineHighlight>,
 1785    ) {
 1786        self.current_line_highlight = current_line_highlight;
 1787    }
 1788
 1789    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1790        self.collapse_matches = collapse_matches;
 1791    }
 1792
 1793    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1794        let buffers = self.buffer.read(cx).all_buffers();
 1795        let Some(lsp_store) = self.lsp_store(cx) else {
 1796            return;
 1797        };
 1798        lsp_store.update(cx, |lsp_store, cx| {
 1799            for buffer in buffers {
 1800                self.registered_buffers
 1801                    .entry(buffer.read(cx).remote_id())
 1802                    .or_insert_with(|| {
 1803                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1804                    });
 1805            }
 1806        })
 1807    }
 1808
 1809    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1810        if self.collapse_matches {
 1811            return range.start..range.start;
 1812        }
 1813        range.clone()
 1814    }
 1815
 1816    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1817        if self.display_map.read(cx).clip_at_line_ends != clip {
 1818            self.display_map
 1819                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1820        }
 1821    }
 1822
 1823    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1824        self.input_enabled = input_enabled;
 1825    }
 1826
 1827    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1828        self.enable_inline_completions = enabled;
 1829        if !self.enable_inline_completions {
 1830            self.take_active_inline_completion(cx);
 1831            cx.notify();
 1832        }
 1833    }
 1834
 1835    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1836        self.menu_inline_completions_policy = value;
 1837    }
 1838
 1839    pub fn set_autoindent(&mut self, autoindent: bool) {
 1840        if autoindent {
 1841            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1842        } else {
 1843            self.autoindent_mode = None;
 1844        }
 1845    }
 1846
 1847    pub fn read_only(&self, cx: &App) -> bool {
 1848        self.read_only || self.buffer.read(cx).read_only()
 1849    }
 1850
 1851    pub fn set_read_only(&mut self, read_only: bool) {
 1852        self.read_only = read_only;
 1853    }
 1854
 1855    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1856        self.use_autoclose = autoclose;
 1857    }
 1858
 1859    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1860        self.use_auto_surround = auto_surround;
 1861    }
 1862
 1863    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1864        self.auto_replace_emoji_shortcode = auto_replace;
 1865    }
 1866
 1867    pub fn toggle_inline_completions(
 1868        &mut self,
 1869        _: &ToggleInlineCompletions,
 1870        window: &mut Window,
 1871        cx: &mut Context<Self>,
 1872    ) {
 1873        if self.show_inline_completions_override.is_some() {
 1874            self.set_show_inline_completions(None, window, cx);
 1875        } else {
 1876            let cursor = self.selections.newest_anchor().head();
 1877            if let Some((buffer, cursor_buffer_position)) =
 1878                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1879            {
 1880                let show_inline_completions =
 1881                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1882                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1883            }
 1884        }
 1885    }
 1886
 1887    pub fn set_show_inline_completions(
 1888        &mut self,
 1889        show_inline_completions: Option<bool>,
 1890        window: &mut Window,
 1891        cx: &mut Context<Self>,
 1892    ) {
 1893        self.show_inline_completions_override = show_inline_completions;
 1894        self.refresh_inline_completion(false, true, window, cx);
 1895    }
 1896
 1897    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1898        let cursor = self.selections.newest_anchor().head();
 1899        if let Some((buffer, buffer_position)) =
 1900            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1901        {
 1902            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1903        } else {
 1904            false
 1905        }
 1906    }
 1907
 1908    fn should_show_inline_completions(
 1909        &self,
 1910        buffer: &Entity<Buffer>,
 1911        buffer_position: language::Anchor,
 1912        cx: &App,
 1913    ) -> bool {
 1914        if !self.snippet_stack.is_empty() {
 1915            return false;
 1916        }
 1917
 1918        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1919            return false;
 1920        }
 1921
 1922        if let Some(provider) = self.inline_completion_provider() {
 1923            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1924                show_inline_completions
 1925            } else {
 1926                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1927            }
 1928        } else {
 1929            false
 1930        }
 1931    }
 1932
 1933    fn inline_completions_disabled_in_scope(
 1934        &self,
 1935        buffer: &Entity<Buffer>,
 1936        buffer_position: language::Anchor,
 1937        cx: &App,
 1938    ) -> bool {
 1939        let snapshot = buffer.read(cx).snapshot();
 1940        let settings = snapshot.settings_at(buffer_position, cx);
 1941
 1942        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1943            return false;
 1944        };
 1945
 1946        scope.override_name().map_or(false, |scope_name| {
 1947            settings
 1948                .inline_completions_disabled_in
 1949                .iter()
 1950                .any(|s| s == scope_name)
 1951        })
 1952    }
 1953
 1954    pub fn set_use_modal_editing(&mut self, to: bool) {
 1955        self.use_modal_editing = to;
 1956    }
 1957
 1958    pub fn use_modal_editing(&self) -> bool {
 1959        self.use_modal_editing
 1960    }
 1961
 1962    fn selections_did_change(
 1963        &mut self,
 1964        local: bool,
 1965        old_cursor_position: &Anchor,
 1966        show_completions: bool,
 1967        window: &mut Window,
 1968        cx: &mut Context<Self>,
 1969    ) {
 1970        window.invalidate_character_coordinates();
 1971
 1972        // Copy selections to primary selection buffer
 1973        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1974        if local {
 1975            let selections = self.selections.all::<usize>(cx);
 1976            let buffer_handle = self.buffer.read(cx).read(cx);
 1977
 1978            let mut text = String::new();
 1979            for (index, selection) in selections.iter().enumerate() {
 1980                let text_for_selection = buffer_handle
 1981                    .text_for_range(selection.start..selection.end)
 1982                    .collect::<String>();
 1983
 1984                text.push_str(&text_for_selection);
 1985                if index != selections.len() - 1 {
 1986                    text.push('\n');
 1987                }
 1988            }
 1989
 1990            if !text.is_empty() {
 1991                cx.write_to_primary(ClipboardItem::new_string(text));
 1992            }
 1993        }
 1994
 1995        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1996            self.buffer.update(cx, |buffer, cx| {
 1997                buffer.set_active_selections(
 1998                    &self.selections.disjoint_anchors(),
 1999                    self.selections.line_mode,
 2000                    self.cursor_shape,
 2001                    cx,
 2002                )
 2003            });
 2004        }
 2005        let display_map = self
 2006            .display_map
 2007            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2008        let buffer = &display_map.buffer_snapshot;
 2009        self.add_selections_state = None;
 2010        self.select_next_state = None;
 2011        self.select_prev_state = None;
 2012        self.select_larger_syntax_node_stack.clear();
 2013        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2014        self.snippet_stack
 2015            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2016        self.take_rename(false, window, cx);
 2017
 2018        let new_cursor_position = self.selections.newest_anchor().head();
 2019
 2020        self.push_to_nav_history(
 2021            *old_cursor_position,
 2022            Some(new_cursor_position.to_point(buffer)),
 2023            cx,
 2024        );
 2025
 2026        if local {
 2027            let new_cursor_position = self.selections.newest_anchor().head();
 2028            let mut context_menu = self.context_menu.borrow_mut();
 2029            let completion_menu = match context_menu.as_ref() {
 2030                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2031                _ => {
 2032                    *context_menu = None;
 2033                    None
 2034                }
 2035            };
 2036
 2037            if let Some(completion_menu) = completion_menu {
 2038                let cursor_position = new_cursor_position.to_offset(buffer);
 2039                let (word_range, kind) =
 2040                    buffer.surrounding_word(completion_menu.initial_position, true);
 2041                if kind == Some(CharKind::Word)
 2042                    && word_range.to_inclusive().contains(&cursor_position)
 2043                {
 2044                    let mut completion_menu = completion_menu.clone();
 2045                    drop(context_menu);
 2046
 2047                    let query = Self::completion_query(buffer, cursor_position);
 2048                    cx.spawn(move |this, mut cx| async move {
 2049                        completion_menu
 2050                            .filter(query.as_deref(), cx.background_executor().clone())
 2051                            .await;
 2052
 2053                        this.update(&mut cx, |this, cx| {
 2054                            let mut context_menu = this.context_menu.borrow_mut();
 2055                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2056                            else {
 2057                                return;
 2058                            };
 2059
 2060                            if menu.id > completion_menu.id {
 2061                                return;
 2062                            }
 2063
 2064                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2065                            drop(context_menu);
 2066                            cx.notify();
 2067                        })
 2068                    })
 2069                    .detach();
 2070
 2071                    if show_completions {
 2072                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2073                    }
 2074                } else {
 2075                    drop(context_menu);
 2076                    self.hide_context_menu(window, cx);
 2077                }
 2078            } else {
 2079                drop(context_menu);
 2080            }
 2081
 2082            hide_hover(self, cx);
 2083
 2084            if old_cursor_position.to_display_point(&display_map).row()
 2085                != new_cursor_position.to_display_point(&display_map).row()
 2086            {
 2087                self.available_code_actions.take();
 2088            }
 2089            self.refresh_code_actions(window, cx);
 2090            self.refresh_document_highlights(cx);
 2091            refresh_matching_bracket_highlights(self, window, cx);
 2092            self.update_visible_inline_completion(window, cx);
 2093            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2094            if self.git_blame_inline_enabled {
 2095                self.start_inline_blame_timer(window, cx);
 2096            }
 2097        }
 2098
 2099        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2100        cx.emit(EditorEvent::SelectionsChanged { local });
 2101
 2102        if self.selections.disjoint_anchors().len() == 1 {
 2103            cx.emit(SearchEvent::ActiveMatchChanged)
 2104        }
 2105        cx.notify();
 2106    }
 2107
 2108    pub fn change_selections<R>(
 2109        &mut self,
 2110        autoscroll: Option<Autoscroll>,
 2111        window: &mut Window,
 2112        cx: &mut Context<Self>,
 2113        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2114    ) -> R {
 2115        self.change_selections_inner(autoscroll, true, window, cx, change)
 2116    }
 2117
 2118    pub fn change_selections_inner<R>(
 2119        &mut self,
 2120        autoscroll: Option<Autoscroll>,
 2121        request_completions: bool,
 2122        window: &mut Window,
 2123        cx: &mut Context<Self>,
 2124        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2125    ) -> R {
 2126        let old_cursor_position = self.selections.newest_anchor().head();
 2127        self.push_to_selection_history();
 2128
 2129        let (changed, result) = self.selections.change_with(cx, change);
 2130
 2131        if changed {
 2132            if let Some(autoscroll) = autoscroll {
 2133                self.request_autoscroll(autoscroll, cx);
 2134            }
 2135            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2136
 2137            if self.should_open_signature_help_automatically(
 2138                &old_cursor_position,
 2139                self.signature_help_state.backspace_pressed(),
 2140                cx,
 2141            ) {
 2142                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2143            }
 2144            self.signature_help_state.set_backspace_pressed(false);
 2145        }
 2146
 2147        result
 2148    }
 2149
 2150    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2151    where
 2152        I: IntoIterator<Item = (Range<S>, T)>,
 2153        S: ToOffset,
 2154        T: Into<Arc<str>>,
 2155    {
 2156        if self.read_only(cx) {
 2157            return;
 2158        }
 2159
 2160        self.buffer
 2161            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2162    }
 2163
 2164    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2165    where
 2166        I: IntoIterator<Item = (Range<S>, T)>,
 2167        S: ToOffset,
 2168        T: Into<Arc<str>>,
 2169    {
 2170        if self.read_only(cx) {
 2171            return;
 2172        }
 2173
 2174        self.buffer.update(cx, |buffer, cx| {
 2175            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2176        });
 2177    }
 2178
 2179    pub fn edit_with_block_indent<I, S, T>(
 2180        &mut self,
 2181        edits: I,
 2182        original_indent_columns: Vec<u32>,
 2183        cx: &mut Context<Self>,
 2184    ) where
 2185        I: IntoIterator<Item = (Range<S>, T)>,
 2186        S: ToOffset,
 2187        T: Into<Arc<str>>,
 2188    {
 2189        if self.read_only(cx) {
 2190            return;
 2191        }
 2192
 2193        self.buffer.update(cx, |buffer, cx| {
 2194            buffer.edit(
 2195                edits,
 2196                Some(AutoindentMode::Block {
 2197                    original_indent_columns,
 2198                }),
 2199                cx,
 2200            )
 2201        });
 2202    }
 2203
 2204    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2205        self.hide_context_menu(window, cx);
 2206
 2207        match phase {
 2208            SelectPhase::Begin {
 2209                position,
 2210                add,
 2211                click_count,
 2212            } => self.begin_selection(position, add, click_count, window, cx),
 2213            SelectPhase::BeginColumnar {
 2214                position,
 2215                goal_column,
 2216                reset,
 2217            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2218            SelectPhase::Extend {
 2219                position,
 2220                click_count,
 2221            } => self.extend_selection(position, click_count, window, cx),
 2222            SelectPhase::Update {
 2223                position,
 2224                goal_column,
 2225                scroll_delta,
 2226            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2227            SelectPhase::End => self.end_selection(window, cx),
 2228        }
 2229    }
 2230
 2231    fn extend_selection(
 2232        &mut self,
 2233        position: DisplayPoint,
 2234        click_count: usize,
 2235        window: &mut Window,
 2236        cx: &mut Context<Self>,
 2237    ) {
 2238        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2239        let tail = self.selections.newest::<usize>(cx).tail();
 2240        self.begin_selection(position, false, click_count, window, cx);
 2241
 2242        let position = position.to_offset(&display_map, Bias::Left);
 2243        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2244
 2245        let mut pending_selection = self
 2246            .selections
 2247            .pending_anchor()
 2248            .expect("extend_selection not called with pending selection");
 2249        if position >= tail {
 2250            pending_selection.start = tail_anchor;
 2251        } else {
 2252            pending_selection.end = tail_anchor;
 2253            pending_selection.reversed = true;
 2254        }
 2255
 2256        let mut pending_mode = self.selections.pending_mode().unwrap();
 2257        match &mut pending_mode {
 2258            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2259            _ => {}
 2260        }
 2261
 2262        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2263            s.set_pending(pending_selection, pending_mode)
 2264        });
 2265    }
 2266
 2267    fn begin_selection(
 2268        &mut self,
 2269        position: DisplayPoint,
 2270        add: bool,
 2271        click_count: usize,
 2272        window: &mut Window,
 2273        cx: &mut Context<Self>,
 2274    ) {
 2275        if !self.focus_handle.is_focused(window) {
 2276            self.last_focused_descendant = None;
 2277            window.focus(&self.focus_handle);
 2278        }
 2279
 2280        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2281        let buffer = &display_map.buffer_snapshot;
 2282        let newest_selection = self.selections.newest_anchor().clone();
 2283        let position = display_map.clip_point(position, Bias::Left);
 2284
 2285        let start;
 2286        let end;
 2287        let mode;
 2288        let mut auto_scroll;
 2289        match click_count {
 2290            1 => {
 2291                start = buffer.anchor_before(position.to_point(&display_map));
 2292                end = start;
 2293                mode = SelectMode::Character;
 2294                auto_scroll = true;
 2295            }
 2296            2 => {
 2297                let range = movement::surrounding_word(&display_map, position);
 2298                start = buffer.anchor_before(range.start.to_point(&display_map));
 2299                end = buffer.anchor_before(range.end.to_point(&display_map));
 2300                mode = SelectMode::Word(start..end);
 2301                auto_scroll = true;
 2302            }
 2303            3 => {
 2304                let position = display_map
 2305                    .clip_point(position, Bias::Left)
 2306                    .to_point(&display_map);
 2307                let line_start = display_map.prev_line_boundary(position).0;
 2308                let next_line_start = buffer.clip_point(
 2309                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2310                    Bias::Left,
 2311                );
 2312                start = buffer.anchor_before(line_start);
 2313                end = buffer.anchor_before(next_line_start);
 2314                mode = SelectMode::Line(start..end);
 2315                auto_scroll = true;
 2316            }
 2317            _ => {
 2318                start = buffer.anchor_before(0);
 2319                end = buffer.anchor_before(buffer.len());
 2320                mode = SelectMode::All;
 2321                auto_scroll = false;
 2322            }
 2323        }
 2324        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2325
 2326        let point_to_delete: Option<usize> = {
 2327            let selected_points: Vec<Selection<Point>> =
 2328                self.selections.disjoint_in_range(start..end, cx);
 2329
 2330            if !add || click_count > 1 {
 2331                None
 2332            } else if !selected_points.is_empty() {
 2333                Some(selected_points[0].id)
 2334            } else {
 2335                let clicked_point_already_selected =
 2336                    self.selections.disjoint.iter().find(|selection| {
 2337                        selection.start.to_point(buffer) == start.to_point(buffer)
 2338                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2339                    });
 2340
 2341                clicked_point_already_selected.map(|selection| selection.id)
 2342            }
 2343        };
 2344
 2345        let selections_count = self.selections.count();
 2346
 2347        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2348            if let Some(point_to_delete) = point_to_delete {
 2349                s.delete(point_to_delete);
 2350
 2351                if selections_count == 1 {
 2352                    s.set_pending_anchor_range(start..end, mode);
 2353                }
 2354            } else {
 2355                if !add {
 2356                    s.clear_disjoint();
 2357                } else if click_count > 1 {
 2358                    s.delete(newest_selection.id)
 2359                }
 2360
 2361                s.set_pending_anchor_range(start..end, mode);
 2362            }
 2363        });
 2364    }
 2365
 2366    fn begin_columnar_selection(
 2367        &mut self,
 2368        position: DisplayPoint,
 2369        goal_column: u32,
 2370        reset: bool,
 2371        window: &mut Window,
 2372        cx: &mut Context<Self>,
 2373    ) {
 2374        if !self.focus_handle.is_focused(window) {
 2375            self.last_focused_descendant = None;
 2376            window.focus(&self.focus_handle);
 2377        }
 2378
 2379        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2380
 2381        if reset {
 2382            let pointer_position = display_map
 2383                .buffer_snapshot
 2384                .anchor_before(position.to_point(&display_map));
 2385
 2386            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2387                s.clear_disjoint();
 2388                s.set_pending_anchor_range(
 2389                    pointer_position..pointer_position,
 2390                    SelectMode::Character,
 2391                );
 2392            });
 2393        }
 2394
 2395        let tail = self.selections.newest::<Point>(cx).tail();
 2396        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2397
 2398        if !reset {
 2399            self.select_columns(
 2400                tail.to_display_point(&display_map),
 2401                position,
 2402                goal_column,
 2403                &display_map,
 2404                window,
 2405                cx,
 2406            );
 2407        }
 2408    }
 2409
 2410    fn update_selection(
 2411        &mut self,
 2412        position: DisplayPoint,
 2413        goal_column: u32,
 2414        scroll_delta: gpui::Point<f32>,
 2415        window: &mut Window,
 2416        cx: &mut Context<Self>,
 2417    ) {
 2418        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2419
 2420        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2421            let tail = tail.to_display_point(&display_map);
 2422            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2423        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2424            let buffer = self.buffer.read(cx).snapshot(cx);
 2425            let head;
 2426            let tail;
 2427            let mode = self.selections.pending_mode().unwrap();
 2428            match &mode {
 2429                SelectMode::Character => {
 2430                    head = position.to_point(&display_map);
 2431                    tail = pending.tail().to_point(&buffer);
 2432                }
 2433                SelectMode::Word(original_range) => {
 2434                    let original_display_range = original_range.start.to_display_point(&display_map)
 2435                        ..original_range.end.to_display_point(&display_map);
 2436                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2437                        ..original_display_range.end.to_point(&display_map);
 2438                    if movement::is_inside_word(&display_map, position)
 2439                        || original_display_range.contains(&position)
 2440                    {
 2441                        let word_range = movement::surrounding_word(&display_map, position);
 2442                        if word_range.start < original_display_range.start {
 2443                            head = word_range.start.to_point(&display_map);
 2444                        } else {
 2445                            head = word_range.end.to_point(&display_map);
 2446                        }
 2447                    } else {
 2448                        head = position.to_point(&display_map);
 2449                    }
 2450
 2451                    if head <= original_buffer_range.start {
 2452                        tail = original_buffer_range.end;
 2453                    } else {
 2454                        tail = original_buffer_range.start;
 2455                    }
 2456                }
 2457                SelectMode::Line(original_range) => {
 2458                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2459
 2460                    let position = display_map
 2461                        .clip_point(position, Bias::Left)
 2462                        .to_point(&display_map);
 2463                    let line_start = display_map.prev_line_boundary(position).0;
 2464                    let next_line_start = buffer.clip_point(
 2465                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2466                        Bias::Left,
 2467                    );
 2468
 2469                    if line_start < original_range.start {
 2470                        head = line_start
 2471                    } else {
 2472                        head = next_line_start
 2473                    }
 2474
 2475                    if head <= original_range.start {
 2476                        tail = original_range.end;
 2477                    } else {
 2478                        tail = original_range.start;
 2479                    }
 2480                }
 2481                SelectMode::All => {
 2482                    return;
 2483                }
 2484            };
 2485
 2486            if head < tail {
 2487                pending.start = buffer.anchor_before(head);
 2488                pending.end = buffer.anchor_before(tail);
 2489                pending.reversed = true;
 2490            } else {
 2491                pending.start = buffer.anchor_before(tail);
 2492                pending.end = buffer.anchor_before(head);
 2493                pending.reversed = false;
 2494            }
 2495
 2496            self.change_selections(None, window, cx, |s| {
 2497                s.set_pending(pending, mode);
 2498            });
 2499        } else {
 2500            log::error!("update_selection dispatched with no pending selection");
 2501            return;
 2502        }
 2503
 2504        self.apply_scroll_delta(scroll_delta, window, cx);
 2505        cx.notify();
 2506    }
 2507
 2508    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2509        self.columnar_selection_tail.take();
 2510        if self.selections.pending_anchor().is_some() {
 2511            let selections = self.selections.all::<usize>(cx);
 2512            self.change_selections(None, window, cx, |s| {
 2513                s.select(selections);
 2514                s.clear_pending();
 2515            });
 2516        }
 2517    }
 2518
 2519    fn select_columns(
 2520        &mut self,
 2521        tail: DisplayPoint,
 2522        head: DisplayPoint,
 2523        goal_column: u32,
 2524        display_map: &DisplaySnapshot,
 2525        window: &mut Window,
 2526        cx: &mut Context<Self>,
 2527    ) {
 2528        let start_row = cmp::min(tail.row(), head.row());
 2529        let end_row = cmp::max(tail.row(), head.row());
 2530        let start_column = cmp::min(tail.column(), goal_column);
 2531        let end_column = cmp::max(tail.column(), goal_column);
 2532        let reversed = start_column < tail.column();
 2533
 2534        let selection_ranges = (start_row.0..=end_row.0)
 2535            .map(DisplayRow)
 2536            .filter_map(|row| {
 2537                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2538                    let start = display_map
 2539                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2540                        .to_point(display_map);
 2541                    let end = display_map
 2542                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2543                        .to_point(display_map);
 2544                    if reversed {
 2545                        Some(end..start)
 2546                    } else {
 2547                        Some(start..end)
 2548                    }
 2549                } else {
 2550                    None
 2551                }
 2552            })
 2553            .collect::<Vec<_>>();
 2554
 2555        self.change_selections(None, window, cx, |s| {
 2556            s.select_ranges(selection_ranges);
 2557        });
 2558        cx.notify();
 2559    }
 2560
 2561    pub fn has_pending_nonempty_selection(&self) -> bool {
 2562        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2563            Some(Selection { start, end, .. }) => start != end,
 2564            None => false,
 2565        };
 2566
 2567        pending_nonempty_selection
 2568            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2569    }
 2570
 2571    pub fn has_pending_selection(&self) -> bool {
 2572        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2573    }
 2574
 2575    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2576        self.selection_mark_mode = false;
 2577
 2578        if self.clear_expanded_diff_hunks(cx) {
 2579            cx.notify();
 2580            return;
 2581        }
 2582        if self.dismiss_menus_and_popups(true, window, cx) {
 2583            return;
 2584        }
 2585
 2586        if self.mode == EditorMode::Full
 2587            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2588        {
 2589            return;
 2590        }
 2591
 2592        cx.propagate();
 2593    }
 2594
 2595    pub fn dismiss_menus_and_popups(
 2596        &mut self,
 2597        should_report_inline_completion_event: bool,
 2598        window: &mut Window,
 2599        cx: &mut Context<Self>,
 2600    ) -> bool {
 2601        if self.take_rename(false, window, cx).is_some() {
 2602            return true;
 2603        }
 2604
 2605        if hide_hover(self, cx) {
 2606            return true;
 2607        }
 2608
 2609        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2610            return true;
 2611        }
 2612
 2613        if self.hide_context_menu(window, cx).is_some() {
 2614            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2615                self.update_visible_inline_completion(window, cx);
 2616            }
 2617            return true;
 2618        }
 2619
 2620        if self.mouse_context_menu.take().is_some() {
 2621            return true;
 2622        }
 2623
 2624        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2625            return true;
 2626        }
 2627
 2628        if self.snippet_stack.pop().is_some() {
 2629            return true;
 2630        }
 2631
 2632        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2633            self.dismiss_diagnostics(cx);
 2634            return true;
 2635        }
 2636
 2637        false
 2638    }
 2639
 2640    fn linked_editing_ranges_for(
 2641        &self,
 2642        selection: Range<text::Anchor>,
 2643        cx: &App,
 2644    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2645        if self.linked_edit_ranges.is_empty() {
 2646            return None;
 2647        }
 2648        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2649            selection.end.buffer_id.and_then(|end_buffer_id| {
 2650                if selection.start.buffer_id != Some(end_buffer_id) {
 2651                    return None;
 2652                }
 2653                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2654                let snapshot = buffer.read(cx).snapshot();
 2655                self.linked_edit_ranges
 2656                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2657                    .map(|ranges| (ranges, snapshot, buffer))
 2658            })?;
 2659        use text::ToOffset as TO;
 2660        // find offset from the start of current range to current cursor position
 2661        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2662
 2663        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2664        let start_difference = start_offset - start_byte_offset;
 2665        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2666        let end_difference = end_offset - start_byte_offset;
 2667        // Current range has associated linked ranges.
 2668        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2669        for range in linked_ranges.iter() {
 2670            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2671            let end_offset = start_offset + end_difference;
 2672            let start_offset = start_offset + start_difference;
 2673            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2674                continue;
 2675            }
 2676            if self.selections.disjoint_anchor_ranges().any(|s| {
 2677                if s.start.buffer_id != selection.start.buffer_id
 2678                    || s.end.buffer_id != selection.end.buffer_id
 2679                {
 2680                    return false;
 2681                }
 2682                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2683                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2684            }) {
 2685                continue;
 2686            }
 2687            let start = buffer_snapshot.anchor_after(start_offset);
 2688            let end = buffer_snapshot.anchor_after(end_offset);
 2689            linked_edits
 2690                .entry(buffer.clone())
 2691                .or_default()
 2692                .push(start..end);
 2693        }
 2694        Some(linked_edits)
 2695    }
 2696
 2697    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2698        let text: Arc<str> = text.into();
 2699
 2700        if self.read_only(cx) {
 2701            return;
 2702        }
 2703
 2704        let selections = self.selections.all_adjusted(cx);
 2705        let mut bracket_inserted = false;
 2706        let mut edits = Vec::new();
 2707        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2708        let mut new_selections = Vec::with_capacity(selections.len());
 2709        let mut new_autoclose_regions = Vec::new();
 2710        let snapshot = self.buffer.read(cx).read(cx);
 2711
 2712        for (selection, autoclose_region) in
 2713            self.selections_with_autoclose_regions(selections, &snapshot)
 2714        {
 2715            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2716                // Determine if the inserted text matches the opening or closing
 2717                // bracket of any of this language's bracket pairs.
 2718                let mut bracket_pair = None;
 2719                let mut is_bracket_pair_start = false;
 2720                let mut is_bracket_pair_end = false;
 2721                if !text.is_empty() {
 2722                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2723                    //  and they are removing the character that triggered IME popup.
 2724                    for (pair, enabled) in scope.brackets() {
 2725                        if !pair.close && !pair.surround {
 2726                            continue;
 2727                        }
 2728
 2729                        if enabled && pair.start.ends_with(text.as_ref()) {
 2730                            let prefix_len = pair.start.len() - text.len();
 2731                            let preceding_text_matches_prefix = prefix_len == 0
 2732                                || (selection.start.column >= (prefix_len as u32)
 2733                                    && snapshot.contains_str_at(
 2734                                        Point::new(
 2735                                            selection.start.row,
 2736                                            selection.start.column - (prefix_len as u32),
 2737                                        ),
 2738                                        &pair.start[..prefix_len],
 2739                                    ));
 2740                            if preceding_text_matches_prefix {
 2741                                bracket_pair = Some(pair.clone());
 2742                                is_bracket_pair_start = true;
 2743                                break;
 2744                            }
 2745                        }
 2746                        if pair.end.as_str() == text.as_ref() {
 2747                            bracket_pair = Some(pair.clone());
 2748                            is_bracket_pair_end = true;
 2749                            break;
 2750                        }
 2751                    }
 2752                }
 2753
 2754                if let Some(bracket_pair) = bracket_pair {
 2755                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2756                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2757                    let auto_surround =
 2758                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2759                    if selection.is_empty() {
 2760                        if is_bracket_pair_start {
 2761                            // If the inserted text is a suffix of an opening bracket and the
 2762                            // selection is preceded by the rest of the opening bracket, then
 2763                            // insert the closing bracket.
 2764                            let following_text_allows_autoclose = snapshot
 2765                                .chars_at(selection.start)
 2766                                .next()
 2767                                .map_or(true, |c| scope.should_autoclose_before(c));
 2768
 2769                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2770                                && bracket_pair.start.len() == 1
 2771                            {
 2772                                let target = bracket_pair.start.chars().next().unwrap();
 2773                                let current_line_count = snapshot
 2774                                    .reversed_chars_at(selection.start)
 2775                                    .take_while(|&c| c != '\n')
 2776                                    .filter(|&c| c == target)
 2777                                    .count();
 2778                                current_line_count % 2 == 1
 2779                            } else {
 2780                                false
 2781                            };
 2782
 2783                            if autoclose
 2784                                && bracket_pair.close
 2785                                && following_text_allows_autoclose
 2786                                && !is_closing_quote
 2787                            {
 2788                                let anchor = snapshot.anchor_before(selection.end);
 2789                                new_selections.push((selection.map(|_| anchor), text.len()));
 2790                                new_autoclose_regions.push((
 2791                                    anchor,
 2792                                    text.len(),
 2793                                    selection.id,
 2794                                    bracket_pair.clone(),
 2795                                ));
 2796                                edits.push((
 2797                                    selection.range(),
 2798                                    format!("{}{}", text, bracket_pair.end).into(),
 2799                                ));
 2800                                bracket_inserted = true;
 2801                                continue;
 2802                            }
 2803                        }
 2804
 2805                        if let Some(region) = autoclose_region {
 2806                            // If the selection is followed by an auto-inserted closing bracket,
 2807                            // then don't insert that closing bracket again; just move the selection
 2808                            // past the closing bracket.
 2809                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2810                                && text.as_ref() == region.pair.end.as_str();
 2811                            if should_skip {
 2812                                let anchor = snapshot.anchor_after(selection.end);
 2813                                new_selections
 2814                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2815                                continue;
 2816                            }
 2817                        }
 2818
 2819                        let always_treat_brackets_as_autoclosed = snapshot
 2820                            .settings_at(selection.start, cx)
 2821                            .always_treat_brackets_as_autoclosed;
 2822                        if always_treat_brackets_as_autoclosed
 2823                            && is_bracket_pair_end
 2824                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2825                        {
 2826                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2827                            // and the inserted text is a closing bracket and the selection is followed
 2828                            // by the closing bracket then move the selection past the closing bracket.
 2829                            let anchor = snapshot.anchor_after(selection.end);
 2830                            new_selections.push((selection.map(|_| anchor), text.len()));
 2831                            continue;
 2832                        }
 2833                    }
 2834                    // If an opening bracket is 1 character long and is typed while
 2835                    // text is selected, then surround that text with the bracket pair.
 2836                    else if auto_surround
 2837                        && bracket_pair.surround
 2838                        && is_bracket_pair_start
 2839                        && bracket_pair.start.chars().count() == 1
 2840                    {
 2841                        edits.push((selection.start..selection.start, text.clone()));
 2842                        edits.push((
 2843                            selection.end..selection.end,
 2844                            bracket_pair.end.as_str().into(),
 2845                        ));
 2846                        bracket_inserted = true;
 2847                        new_selections.push((
 2848                            Selection {
 2849                                id: selection.id,
 2850                                start: snapshot.anchor_after(selection.start),
 2851                                end: snapshot.anchor_before(selection.end),
 2852                                reversed: selection.reversed,
 2853                                goal: selection.goal,
 2854                            },
 2855                            0,
 2856                        ));
 2857                        continue;
 2858                    }
 2859                }
 2860            }
 2861
 2862            if self.auto_replace_emoji_shortcode
 2863                && selection.is_empty()
 2864                && text.as_ref().ends_with(':')
 2865            {
 2866                if let Some(possible_emoji_short_code) =
 2867                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2868                {
 2869                    if !possible_emoji_short_code.is_empty() {
 2870                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2871                            let emoji_shortcode_start = Point::new(
 2872                                selection.start.row,
 2873                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2874                            );
 2875
 2876                            // Remove shortcode from buffer
 2877                            edits.push((
 2878                                emoji_shortcode_start..selection.start,
 2879                                "".to_string().into(),
 2880                            ));
 2881                            new_selections.push((
 2882                                Selection {
 2883                                    id: selection.id,
 2884                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2885                                    end: snapshot.anchor_before(selection.start),
 2886                                    reversed: selection.reversed,
 2887                                    goal: selection.goal,
 2888                                },
 2889                                0,
 2890                            ));
 2891
 2892                            // Insert emoji
 2893                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2894                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2895                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2896
 2897                            continue;
 2898                        }
 2899                    }
 2900                }
 2901            }
 2902
 2903            // If not handling any auto-close operation, then just replace the selected
 2904            // text with the given input and move the selection to the end of the
 2905            // newly inserted text.
 2906            let anchor = snapshot.anchor_after(selection.end);
 2907            if !self.linked_edit_ranges.is_empty() {
 2908                let start_anchor = snapshot.anchor_before(selection.start);
 2909
 2910                let is_word_char = text.chars().next().map_or(true, |char| {
 2911                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2912                    classifier.is_word(char)
 2913                });
 2914
 2915                if is_word_char {
 2916                    if let Some(ranges) = self
 2917                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2918                    {
 2919                        for (buffer, edits) in ranges {
 2920                            linked_edits
 2921                                .entry(buffer.clone())
 2922                                .or_default()
 2923                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2924                        }
 2925                    }
 2926                }
 2927            }
 2928
 2929            new_selections.push((selection.map(|_| anchor), 0));
 2930            edits.push((selection.start..selection.end, text.clone()));
 2931        }
 2932
 2933        drop(snapshot);
 2934
 2935        self.transact(window, cx, |this, window, cx| {
 2936            this.buffer.update(cx, |buffer, cx| {
 2937                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2938            });
 2939            for (buffer, edits) in linked_edits {
 2940                buffer.update(cx, |buffer, cx| {
 2941                    let snapshot = buffer.snapshot();
 2942                    let edits = edits
 2943                        .into_iter()
 2944                        .map(|(range, text)| {
 2945                            use text::ToPoint as TP;
 2946                            let end_point = TP::to_point(&range.end, &snapshot);
 2947                            let start_point = TP::to_point(&range.start, &snapshot);
 2948                            (start_point..end_point, text)
 2949                        })
 2950                        .sorted_by_key(|(range, _)| range.start)
 2951                        .collect::<Vec<_>>();
 2952                    buffer.edit(edits, None, cx);
 2953                })
 2954            }
 2955            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2956            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2957            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2958            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2959                .zip(new_selection_deltas)
 2960                .map(|(selection, delta)| Selection {
 2961                    id: selection.id,
 2962                    start: selection.start + delta,
 2963                    end: selection.end + delta,
 2964                    reversed: selection.reversed,
 2965                    goal: SelectionGoal::None,
 2966                })
 2967                .collect::<Vec<_>>();
 2968
 2969            let mut i = 0;
 2970            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2971                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2972                let start = map.buffer_snapshot.anchor_before(position);
 2973                let end = map.buffer_snapshot.anchor_after(position);
 2974                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2975                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2976                        Ordering::Less => i += 1,
 2977                        Ordering::Greater => break,
 2978                        Ordering::Equal => {
 2979                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2980                                Ordering::Less => i += 1,
 2981                                Ordering::Equal => break,
 2982                                Ordering::Greater => break,
 2983                            }
 2984                        }
 2985                    }
 2986                }
 2987                this.autoclose_regions.insert(
 2988                    i,
 2989                    AutocloseRegion {
 2990                        selection_id,
 2991                        range: start..end,
 2992                        pair,
 2993                    },
 2994                );
 2995            }
 2996
 2997            let had_active_inline_completion = this.has_active_inline_completion();
 2998            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2999                s.select(new_selections)
 3000            });
 3001
 3002            if !bracket_inserted {
 3003                if let Some(on_type_format_task) =
 3004                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3005                {
 3006                    on_type_format_task.detach_and_log_err(cx);
 3007                }
 3008            }
 3009
 3010            let editor_settings = EditorSettings::get_global(cx);
 3011            if bracket_inserted
 3012                && (editor_settings.auto_signature_help
 3013                    || editor_settings.show_signature_help_after_edits)
 3014            {
 3015                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3016            }
 3017
 3018            let trigger_in_words =
 3019                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3020            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3021            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3022            this.refresh_inline_completion(true, false, window, cx);
 3023        });
 3024    }
 3025
 3026    fn find_possible_emoji_shortcode_at_position(
 3027        snapshot: &MultiBufferSnapshot,
 3028        position: Point,
 3029    ) -> Option<String> {
 3030        let mut chars = Vec::new();
 3031        let mut found_colon = false;
 3032        for char in snapshot.reversed_chars_at(position).take(100) {
 3033            // Found a possible emoji shortcode in the middle of the buffer
 3034            if found_colon {
 3035                if char.is_whitespace() {
 3036                    chars.reverse();
 3037                    return Some(chars.iter().collect());
 3038                }
 3039                // If the previous character is not a whitespace, we are in the middle of a word
 3040                // and we only want to complete the shortcode if the word is made up of other emojis
 3041                let mut containing_word = String::new();
 3042                for ch in snapshot
 3043                    .reversed_chars_at(position)
 3044                    .skip(chars.len() + 1)
 3045                    .take(100)
 3046                {
 3047                    if ch.is_whitespace() {
 3048                        break;
 3049                    }
 3050                    containing_word.push(ch);
 3051                }
 3052                let containing_word = containing_word.chars().rev().collect::<String>();
 3053                if util::word_consists_of_emojis(containing_word.as_str()) {
 3054                    chars.reverse();
 3055                    return Some(chars.iter().collect());
 3056                }
 3057            }
 3058
 3059            if char.is_whitespace() || !char.is_ascii() {
 3060                return None;
 3061            }
 3062            if char == ':' {
 3063                found_colon = true;
 3064            } else {
 3065                chars.push(char);
 3066            }
 3067        }
 3068        // Found a possible emoji shortcode at the beginning of the buffer
 3069        chars.reverse();
 3070        Some(chars.iter().collect())
 3071    }
 3072
 3073    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3074        self.transact(window, cx, |this, window, cx| {
 3075            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3076                let selections = this.selections.all::<usize>(cx);
 3077                let multi_buffer = this.buffer.read(cx);
 3078                let buffer = multi_buffer.snapshot(cx);
 3079                selections
 3080                    .iter()
 3081                    .map(|selection| {
 3082                        let start_point = selection.start.to_point(&buffer);
 3083                        let mut indent =
 3084                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3085                        indent.len = cmp::min(indent.len, start_point.column);
 3086                        let start = selection.start;
 3087                        let end = selection.end;
 3088                        let selection_is_empty = start == end;
 3089                        let language_scope = buffer.language_scope_at(start);
 3090                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3091                            &language_scope
 3092                        {
 3093                            let leading_whitespace_len = buffer
 3094                                .reversed_chars_at(start)
 3095                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3096                                .map(|c| c.len_utf8())
 3097                                .sum::<usize>();
 3098
 3099                            let trailing_whitespace_len = buffer
 3100                                .chars_at(end)
 3101                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3102                                .map(|c| c.len_utf8())
 3103                                .sum::<usize>();
 3104
 3105                            let insert_extra_newline =
 3106                                language.brackets().any(|(pair, enabled)| {
 3107                                    let pair_start = pair.start.trim_end();
 3108                                    let pair_end = pair.end.trim_start();
 3109
 3110                                    enabled
 3111                                        && pair.newline
 3112                                        && buffer.contains_str_at(
 3113                                            end + trailing_whitespace_len,
 3114                                            pair_end,
 3115                                        )
 3116                                        && buffer.contains_str_at(
 3117                                            (start - leading_whitespace_len)
 3118                                                .saturating_sub(pair_start.len()),
 3119                                            pair_start,
 3120                                        )
 3121                                });
 3122
 3123                            // Comment extension on newline is allowed only for cursor selections
 3124                            let comment_delimiter = maybe!({
 3125                                if !selection_is_empty {
 3126                                    return None;
 3127                                }
 3128
 3129                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3130                                    return None;
 3131                                }
 3132
 3133                                let delimiters = language.line_comment_prefixes();
 3134                                let max_len_of_delimiter =
 3135                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3136                                let (snapshot, range) =
 3137                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3138
 3139                                let mut index_of_first_non_whitespace = 0;
 3140                                let comment_candidate = snapshot
 3141                                    .chars_for_range(range)
 3142                                    .skip_while(|c| {
 3143                                        let should_skip = c.is_whitespace();
 3144                                        if should_skip {
 3145                                            index_of_first_non_whitespace += 1;
 3146                                        }
 3147                                        should_skip
 3148                                    })
 3149                                    .take(max_len_of_delimiter)
 3150                                    .collect::<String>();
 3151                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3152                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3153                                })?;
 3154                                let cursor_is_placed_after_comment_marker =
 3155                                    index_of_first_non_whitespace + comment_prefix.len()
 3156                                        <= start_point.column as usize;
 3157                                if cursor_is_placed_after_comment_marker {
 3158                                    Some(comment_prefix.clone())
 3159                                } else {
 3160                                    None
 3161                                }
 3162                            });
 3163                            (comment_delimiter, insert_extra_newline)
 3164                        } else {
 3165                            (None, false)
 3166                        };
 3167
 3168                        let capacity_for_delimiter = comment_delimiter
 3169                            .as_deref()
 3170                            .map(str::len)
 3171                            .unwrap_or_default();
 3172                        let mut new_text =
 3173                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3174                        new_text.push('\n');
 3175                        new_text.extend(indent.chars());
 3176                        if let Some(delimiter) = &comment_delimiter {
 3177                            new_text.push_str(delimiter);
 3178                        }
 3179                        if insert_extra_newline {
 3180                            new_text = new_text.repeat(2);
 3181                        }
 3182
 3183                        let anchor = buffer.anchor_after(end);
 3184                        let new_selection = selection.map(|_| anchor);
 3185                        (
 3186                            (start..end, new_text),
 3187                            (insert_extra_newline, new_selection),
 3188                        )
 3189                    })
 3190                    .unzip()
 3191            };
 3192
 3193            this.edit_with_autoindent(edits, cx);
 3194            let buffer = this.buffer.read(cx).snapshot(cx);
 3195            let new_selections = selection_fixup_info
 3196                .into_iter()
 3197                .map(|(extra_newline_inserted, new_selection)| {
 3198                    let mut cursor = new_selection.end.to_point(&buffer);
 3199                    if extra_newline_inserted {
 3200                        cursor.row -= 1;
 3201                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3202                    }
 3203                    new_selection.map(|_| cursor)
 3204                })
 3205                .collect();
 3206
 3207            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3208                s.select(new_selections)
 3209            });
 3210            this.refresh_inline_completion(true, false, window, cx);
 3211        });
 3212    }
 3213
 3214    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3215        let buffer = self.buffer.read(cx);
 3216        let snapshot = buffer.snapshot(cx);
 3217
 3218        let mut edits = Vec::new();
 3219        let mut rows = Vec::new();
 3220
 3221        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3222            let cursor = selection.head();
 3223            let row = cursor.row;
 3224
 3225            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3226
 3227            let newline = "\n".to_string();
 3228            edits.push((start_of_line..start_of_line, newline));
 3229
 3230            rows.push(row + rows_inserted as u32);
 3231        }
 3232
 3233        self.transact(window, cx, |editor, window, cx| {
 3234            editor.edit(edits, cx);
 3235
 3236            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3237                let mut index = 0;
 3238                s.move_cursors_with(|map, _, _| {
 3239                    let row = rows[index];
 3240                    index += 1;
 3241
 3242                    let point = Point::new(row, 0);
 3243                    let boundary = map.next_line_boundary(point).1;
 3244                    let clipped = map.clip_point(boundary, Bias::Left);
 3245
 3246                    (clipped, SelectionGoal::None)
 3247                });
 3248            });
 3249
 3250            let mut indent_edits = Vec::new();
 3251            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3252            for row in rows {
 3253                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3254                for (row, indent) in indents {
 3255                    if indent.len == 0 {
 3256                        continue;
 3257                    }
 3258
 3259                    let text = match indent.kind {
 3260                        IndentKind::Space => " ".repeat(indent.len as usize),
 3261                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3262                    };
 3263                    let point = Point::new(row.0, 0);
 3264                    indent_edits.push((point..point, text));
 3265                }
 3266            }
 3267            editor.edit(indent_edits, cx);
 3268        });
 3269    }
 3270
 3271    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3272        let buffer = self.buffer.read(cx);
 3273        let snapshot = buffer.snapshot(cx);
 3274
 3275        let mut edits = Vec::new();
 3276        let mut rows = Vec::new();
 3277        let mut rows_inserted = 0;
 3278
 3279        for selection in self.selections.all_adjusted(cx) {
 3280            let cursor = selection.head();
 3281            let row = cursor.row;
 3282
 3283            let point = Point::new(row + 1, 0);
 3284            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3285
 3286            let newline = "\n".to_string();
 3287            edits.push((start_of_line..start_of_line, newline));
 3288
 3289            rows_inserted += 1;
 3290            rows.push(row + rows_inserted);
 3291        }
 3292
 3293        self.transact(window, cx, |editor, window, cx| {
 3294            editor.edit(edits, cx);
 3295
 3296            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3297                let mut index = 0;
 3298                s.move_cursors_with(|map, _, _| {
 3299                    let row = rows[index];
 3300                    index += 1;
 3301
 3302                    let point = Point::new(row, 0);
 3303                    let boundary = map.next_line_boundary(point).1;
 3304                    let clipped = map.clip_point(boundary, Bias::Left);
 3305
 3306                    (clipped, SelectionGoal::None)
 3307                });
 3308            });
 3309
 3310            let mut indent_edits = Vec::new();
 3311            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3312            for row in rows {
 3313                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3314                for (row, indent) in indents {
 3315                    if indent.len == 0 {
 3316                        continue;
 3317                    }
 3318
 3319                    let text = match indent.kind {
 3320                        IndentKind::Space => " ".repeat(indent.len as usize),
 3321                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3322                    };
 3323                    let point = Point::new(row.0, 0);
 3324                    indent_edits.push((point..point, text));
 3325                }
 3326            }
 3327            editor.edit(indent_edits, cx);
 3328        });
 3329    }
 3330
 3331    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3332        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3333            original_indent_columns: Vec::new(),
 3334        });
 3335        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3336    }
 3337
 3338    fn insert_with_autoindent_mode(
 3339        &mut self,
 3340        text: &str,
 3341        autoindent_mode: Option<AutoindentMode>,
 3342        window: &mut Window,
 3343        cx: &mut Context<Self>,
 3344    ) {
 3345        if self.read_only(cx) {
 3346            return;
 3347        }
 3348
 3349        let text: Arc<str> = text.into();
 3350        self.transact(window, cx, |this, window, cx| {
 3351            let old_selections = this.selections.all_adjusted(cx);
 3352            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3353                let anchors = {
 3354                    let snapshot = buffer.read(cx);
 3355                    old_selections
 3356                        .iter()
 3357                        .map(|s| {
 3358                            let anchor = snapshot.anchor_after(s.head());
 3359                            s.map(|_| anchor)
 3360                        })
 3361                        .collect::<Vec<_>>()
 3362                };
 3363                buffer.edit(
 3364                    old_selections
 3365                        .iter()
 3366                        .map(|s| (s.start..s.end, text.clone())),
 3367                    autoindent_mode,
 3368                    cx,
 3369                );
 3370                anchors
 3371            });
 3372
 3373            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3374                s.select_anchors(selection_anchors);
 3375            });
 3376
 3377            cx.notify();
 3378        });
 3379    }
 3380
 3381    fn trigger_completion_on_input(
 3382        &mut self,
 3383        text: &str,
 3384        trigger_in_words: bool,
 3385        window: &mut Window,
 3386        cx: &mut Context<Self>,
 3387    ) {
 3388        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3389            self.show_completions(
 3390                &ShowCompletions {
 3391                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3392                },
 3393                window,
 3394                cx,
 3395            );
 3396        } else {
 3397            self.hide_context_menu(window, cx);
 3398        }
 3399    }
 3400
 3401    fn is_completion_trigger(
 3402        &self,
 3403        text: &str,
 3404        trigger_in_words: bool,
 3405        cx: &mut Context<Self>,
 3406    ) -> bool {
 3407        let position = self.selections.newest_anchor().head();
 3408        let multibuffer = self.buffer.read(cx);
 3409        let Some(buffer) = position
 3410            .buffer_id
 3411            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3412        else {
 3413            return false;
 3414        };
 3415
 3416        if let Some(completion_provider) = &self.completion_provider {
 3417            completion_provider.is_completion_trigger(
 3418                &buffer,
 3419                position.text_anchor,
 3420                text,
 3421                trigger_in_words,
 3422                cx,
 3423            )
 3424        } else {
 3425            false
 3426        }
 3427    }
 3428
 3429    /// If any empty selections is touching the start of its innermost containing autoclose
 3430    /// region, expand it to select the brackets.
 3431    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3432        let selections = self.selections.all::<usize>(cx);
 3433        let buffer = self.buffer.read(cx).read(cx);
 3434        let new_selections = self
 3435            .selections_with_autoclose_regions(selections, &buffer)
 3436            .map(|(mut selection, region)| {
 3437                if !selection.is_empty() {
 3438                    return selection;
 3439                }
 3440
 3441                if let Some(region) = region {
 3442                    let mut range = region.range.to_offset(&buffer);
 3443                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3444                        range.start -= region.pair.start.len();
 3445                        if buffer.contains_str_at(range.start, &region.pair.start)
 3446                            && buffer.contains_str_at(range.end, &region.pair.end)
 3447                        {
 3448                            range.end += region.pair.end.len();
 3449                            selection.start = range.start;
 3450                            selection.end = range.end;
 3451
 3452                            return selection;
 3453                        }
 3454                    }
 3455                }
 3456
 3457                let always_treat_brackets_as_autoclosed = buffer
 3458                    .settings_at(selection.start, cx)
 3459                    .always_treat_brackets_as_autoclosed;
 3460
 3461                if !always_treat_brackets_as_autoclosed {
 3462                    return selection;
 3463                }
 3464
 3465                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3466                    for (pair, enabled) in scope.brackets() {
 3467                        if !enabled || !pair.close {
 3468                            continue;
 3469                        }
 3470
 3471                        if buffer.contains_str_at(selection.start, &pair.end) {
 3472                            let pair_start_len = pair.start.len();
 3473                            if buffer.contains_str_at(
 3474                                selection.start.saturating_sub(pair_start_len),
 3475                                &pair.start,
 3476                            ) {
 3477                                selection.start -= pair_start_len;
 3478                                selection.end += pair.end.len();
 3479
 3480                                return selection;
 3481                            }
 3482                        }
 3483                    }
 3484                }
 3485
 3486                selection
 3487            })
 3488            .collect();
 3489
 3490        drop(buffer);
 3491        self.change_selections(None, window, cx, |selections| {
 3492            selections.select(new_selections)
 3493        });
 3494    }
 3495
 3496    /// Iterate the given selections, and for each one, find the smallest surrounding
 3497    /// autoclose region. This uses the ordering of the selections and the autoclose
 3498    /// regions to avoid repeated comparisons.
 3499    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3500        &'a self,
 3501        selections: impl IntoIterator<Item = Selection<D>>,
 3502        buffer: &'a MultiBufferSnapshot,
 3503    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3504        let mut i = 0;
 3505        let mut regions = self.autoclose_regions.as_slice();
 3506        selections.into_iter().map(move |selection| {
 3507            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3508
 3509            let mut enclosing = None;
 3510            while let Some(pair_state) = regions.get(i) {
 3511                if pair_state.range.end.to_offset(buffer) < range.start {
 3512                    regions = &regions[i + 1..];
 3513                    i = 0;
 3514                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3515                    break;
 3516                } else {
 3517                    if pair_state.selection_id == selection.id {
 3518                        enclosing = Some(pair_state);
 3519                    }
 3520                    i += 1;
 3521                }
 3522            }
 3523
 3524            (selection, enclosing)
 3525        })
 3526    }
 3527
 3528    /// Remove any autoclose regions that no longer contain their selection.
 3529    fn invalidate_autoclose_regions(
 3530        &mut self,
 3531        mut selections: &[Selection<Anchor>],
 3532        buffer: &MultiBufferSnapshot,
 3533    ) {
 3534        self.autoclose_regions.retain(|state| {
 3535            let mut i = 0;
 3536            while let Some(selection) = selections.get(i) {
 3537                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3538                    selections = &selections[1..];
 3539                    continue;
 3540                }
 3541                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3542                    break;
 3543                }
 3544                if selection.id == state.selection_id {
 3545                    return true;
 3546                } else {
 3547                    i += 1;
 3548                }
 3549            }
 3550            false
 3551        });
 3552    }
 3553
 3554    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3555        let offset = position.to_offset(buffer);
 3556        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3557        if offset > word_range.start && kind == Some(CharKind::Word) {
 3558            Some(
 3559                buffer
 3560                    .text_for_range(word_range.start..offset)
 3561                    .collect::<String>(),
 3562            )
 3563        } else {
 3564            None
 3565        }
 3566    }
 3567
 3568    pub fn toggle_inlay_hints(
 3569        &mut self,
 3570        _: &ToggleInlayHints,
 3571        _: &mut Window,
 3572        cx: &mut Context<Self>,
 3573    ) {
 3574        self.refresh_inlay_hints(
 3575            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3576            cx,
 3577        );
 3578    }
 3579
 3580    pub fn inlay_hints_enabled(&self) -> bool {
 3581        self.inlay_hint_cache.enabled
 3582    }
 3583
 3584    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3585        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3586            return;
 3587        }
 3588
 3589        let reason_description = reason.description();
 3590        let ignore_debounce = matches!(
 3591            reason,
 3592            InlayHintRefreshReason::SettingsChange(_)
 3593                | InlayHintRefreshReason::Toggle(_)
 3594                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3595        );
 3596        let (invalidate_cache, required_languages) = match reason {
 3597            InlayHintRefreshReason::Toggle(enabled) => {
 3598                self.inlay_hint_cache.enabled = enabled;
 3599                if enabled {
 3600                    (InvalidationStrategy::RefreshRequested, None)
 3601                } else {
 3602                    self.inlay_hint_cache.clear();
 3603                    self.splice_inlays(
 3604                        self.visible_inlay_hints(cx)
 3605                            .iter()
 3606                            .map(|inlay| inlay.id)
 3607                            .collect(),
 3608                        Vec::new(),
 3609                        cx,
 3610                    );
 3611                    return;
 3612                }
 3613            }
 3614            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3615                match self.inlay_hint_cache.update_settings(
 3616                    &self.buffer,
 3617                    new_settings,
 3618                    self.visible_inlay_hints(cx),
 3619                    cx,
 3620                ) {
 3621                    ControlFlow::Break(Some(InlaySplice {
 3622                        to_remove,
 3623                        to_insert,
 3624                    })) => {
 3625                        self.splice_inlays(to_remove, to_insert, cx);
 3626                        return;
 3627                    }
 3628                    ControlFlow::Break(None) => return,
 3629                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3630                }
 3631            }
 3632            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3633                if let Some(InlaySplice {
 3634                    to_remove,
 3635                    to_insert,
 3636                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3637                {
 3638                    self.splice_inlays(to_remove, to_insert, cx);
 3639                }
 3640                return;
 3641            }
 3642            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3643            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3644                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3645            }
 3646            InlayHintRefreshReason::RefreshRequested => {
 3647                (InvalidationStrategy::RefreshRequested, None)
 3648            }
 3649        };
 3650
 3651        if let Some(InlaySplice {
 3652            to_remove,
 3653            to_insert,
 3654        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3655            reason_description,
 3656            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3657            invalidate_cache,
 3658            ignore_debounce,
 3659            cx,
 3660        ) {
 3661            self.splice_inlays(to_remove, to_insert, cx);
 3662        }
 3663    }
 3664
 3665    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3666        self.display_map
 3667            .read(cx)
 3668            .current_inlays()
 3669            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3670            .cloned()
 3671            .collect()
 3672    }
 3673
 3674    pub fn excerpts_for_inlay_hints_query(
 3675        &self,
 3676        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3677        cx: &mut Context<Editor>,
 3678    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3679        let Some(project) = self.project.as_ref() else {
 3680            return HashMap::default();
 3681        };
 3682        let project = project.read(cx);
 3683        let multi_buffer = self.buffer().read(cx);
 3684        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3685        let multi_buffer_visible_start = self
 3686            .scroll_manager
 3687            .anchor()
 3688            .anchor
 3689            .to_point(&multi_buffer_snapshot);
 3690        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3691            multi_buffer_visible_start
 3692                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3693            Bias::Left,
 3694        );
 3695        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3696        multi_buffer_snapshot
 3697            .range_to_buffer_ranges(multi_buffer_visible_range)
 3698            .into_iter()
 3699            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3700            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3701                let buffer_file = project::File::from_dyn(buffer.file())?;
 3702                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3703                let worktree_entry = buffer_worktree
 3704                    .read(cx)
 3705                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3706                if worktree_entry.is_ignored {
 3707                    return None;
 3708                }
 3709
 3710                let language = buffer.language()?;
 3711                if let Some(restrict_to_languages) = restrict_to_languages {
 3712                    if !restrict_to_languages.contains(language) {
 3713                        return None;
 3714                    }
 3715                }
 3716                Some((
 3717                    excerpt_id,
 3718                    (
 3719                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3720                        buffer.version().clone(),
 3721                        excerpt_visible_range,
 3722                    ),
 3723                ))
 3724            })
 3725            .collect()
 3726    }
 3727
 3728    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3729        TextLayoutDetails {
 3730            text_system: window.text_system().clone(),
 3731            editor_style: self.style.clone().unwrap(),
 3732            rem_size: window.rem_size(),
 3733            scroll_anchor: self.scroll_manager.anchor(),
 3734            visible_rows: self.visible_line_count(),
 3735            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3736        }
 3737    }
 3738
 3739    pub fn splice_inlays(
 3740        &self,
 3741        to_remove: Vec<InlayId>,
 3742        to_insert: Vec<Inlay>,
 3743        cx: &mut Context<Self>,
 3744    ) {
 3745        self.display_map.update(cx, |display_map, cx| {
 3746            display_map.splice_inlays(to_remove, to_insert, cx)
 3747        });
 3748        cx.notify();
 3749    }
 3750
 3751    fn trigger_on_type_formatting(
 3752        &self,
 3753        input: String,
 3754        window: &mut Window,
 3755        cx: &mut Context<Self>,
 3756    ) -> Option<Task<Result<()>>> {
 3757        if input.len() != 1 {
 3758            return None;
 3759        }
 3760
 3761        let project = self.project.as_ref()?;
 3762        let position = self.selections.newest_anchor().head();
 3763        let (buffer, buffer_position) = self
 3764            .buffer
 3765            .read(cx)
 3766            .text_anchor_for_position(position, cx)?;
 3767
 3768        let settings = language_settings::language_settings(
 3769            buffer
 3770                .read(cx)
 3771                .language_at(buffer_position)
 3772                .map(|l| l.name()),
 3773            buffer.read(cx).file(),
 3774            cx,
 3775        );
 3776        if !settings.use_on_type_format {
 3777            return None;
 3778        }
 3779
 3780        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3781        // hence we do LSP request & edit on host side only — add formats to host's history.
 3782        let push_to_lsp_host_history = true;
 3783        // If this is not the host, append its history with new edits.
 3784        let push_to_client_history = project.read(cx).is_via_collab();
 3785
 3786        let on_type_formatting = project.update(cx, |project, cx| {
 3787            project.on_type_format(
 3788                buffer.clone(),
 3789                buffer_position,
 3790                input,
 3791                push_to_lsp_host_history,
 3792                cx,
 3793            )
 3794        });
 3795        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3796            if let Some(transaction) = on_type_formatting.await? {
 3797                if push_to_client_history {
 3798                    buffer
 3799                        .update(&mut cx, |buffer, _| {
 3800                            buffer.push_transaction(transaction, Instant::now());
 3801                        })
 3802                        .ok();
 3803                }
 3804                editor.update(&mut cx, |editor, cx| {
 3805                    editor.refresh_document_highlights(cx);
 3806                })?;
 3807            }
 3808            Ok(())
 3809        }))
 3810    }
 3811
 3812    pub fn show_completions(
 3813        &mut self,
 3814        options: &ShowCompletions,
 3815        window: &mut Window,
 3816        cx: &mut Context<Self>,
 3817    ) {
 3818        if self.pending_rename.is_some() {
 3819            return;
 3820        }
 3821
 3822        let Some(provider) = self.completion_provider.as_ref() else {
 3823            return;
 3824        };
 3825
 3826        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3827            return;
 3828        }
 3829
 3830        let position = self.selections.newest_anchor().head();
 3831        if position.diff_base_anchor.is_some() {
 3832            return;
 3833        }
 3834        let (buffer, buffer_position) =
 3835            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3836                output
 3837            } else {
 3838                return;
 3839            };
 3840        let show_completion_documentation = buffer
 3841            .read(cx)
 3842            .snapshot()
 3843            .settings_at(buffer_position, cx)
 3844            .show_completion_documentation;
 3845
 3846        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3847
 3848        let trigger_kind = match &options.trigger {
 3849            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3850                CompletionTriggerKind::TRIGGER_CHARACTER
 3851            }
 3852            _ => CompletionTriggerKind::INVOKED,
 3853        };
 3854        let completion_context = CompletionContext {
 3855            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3856                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3857                    Some(String::from(trigger))
 3858                } else {
 3859                    None
 3860                }
 3861            }),
 3862            trigger_kind,
 3863        };
 3864        let completions =
 3865            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3866        let sort_completions = provider.sort_completions();
 3867
 3868        let id = post_inc(&mut self.next_completion_id);
 3869        let task = cx.spawn_in(window, |editor, mut cx| {
 3870            async move {
 3871                editor.update(&mut cx, |this, _| {
 3872                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3873                })?;
 3874                let completions = completions.await.log_err();
 3875                let menu = if let Some(completions) = completions {
 3876                    let mut menu = CompletionsMenu::new(
 3877                        id,
 3878                        sort_completions,
 3879                        show_completion_documentation,
 3880                        position,
 3881                        buffer.clone(),
 3882                        completions.into(),
 3883                    );
 3884
 3885                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3886                        .await;
 3887
 3888                    menu.visible().then_some(menu)
 3889                } else {
 3890                    None
 3891                };
 3892
 3893                editor.update_in(&mut cx, |editor, window, cx| {
 3894                    match editor.context_menu.borrow().as_ref() {
 3895                        None => {}
 3896                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3897                            if prev_menu.id > id {
 3898                                return;
 3899                            }
 3900                        }
 3901                        _ => return,
 3902                    }
 3903
 3904                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3905                        let mut menu = menu.unwrap();
 3906                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3907
 3908                        if editor.show_inline_completions_in_menu(cx) {
 3909                            if let Some(hint) = editor.inline_completion_menu_hint(window, cx) {
 3910                                menu.show_inline_completion_hint(hint);
 3911                            }
 3912                        } else {
 3913                            editor.discard_inline_completion(false, cx);
 3914                        }
 3915
 3916                        *editor.context_menu.borrow_mut() =
 3917                            Some(CodeContextMenu::Completions(menu));
 3918
 3919                        cx.notify();
 3920                    } else if editor.completion_tasks.len() <= 1 {
 3921                        // If there are no more completion tasks and the last menu was
 3922                        // empty, we should hide it.
 3923                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3924                        // If it was already hidden and we don't show inline
 3925                        // completions in the menu, we should also show the
 3926                        // inline-completion when available.
 3927                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3928                            editor.update_visible_inline_completion(window, cx);
 3929                        }
 3930                    }
 3931                })?;
 3932
 3933                Ok::<_, anyhow::Error>(())
 3934            }
 3935            .log_err()
 3936        });
 3937
 3938        self.completion_tasks.push((id, task));
 3939    }
 3940
 3941    pub fn confirm_completion(
 3942        &mut self,
 3943        action: &ConfirmCompletion,
 3944        window: &mut Window,
 3945        cx: &mut Context<Self>,
 3946    ) -> Option<Task<Result<()>>> {
 3947        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3948    }
 3949
 3950    pub fn compose_completion(
 3951        &mut self,
 3952        action: &ComposeCompletion,
 3953        window: &mut Window,
 3954        cx: &mut Context<Self>,
 3955    ) -> Option<Task<Result<()>>> {
 3956        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3957    }
 3958
 3959    fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3960        let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
 3961            return;
 3962        };
 3963
 3964        let project = project.read(cx);
 3965
 3966        ZedPredictModal::toggle(
 3967            workspace,
 3968            project.user_store().clone(),
 3969            project.client().clone(),
 3970            project.fs().clone(),
 3971            window,
 3972            cx,
 3973        );
 3974    }
 3975
 3976    fn do_completion(
 3977        &mut self,
 3978        item_ix: Option<usize>,
 3979        intent: CompletionIntent,
 3980        window: &mut Window,
 3981        cx: &mut Context<Editor>,
 3982    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3983        use language::ToOffset as _;
 3984
 3985        {
 3986            let context_menu = self.context_menu.borrow();
 3987            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3988                let entries = menu.entries.borrow();
 3989                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3990                match entry {
 3991                    Some(CompletionEntry::InlineCompletionHint(
 3992                        InlineCompletionMenuHint::Loading,
 3993                    )) => return Some(Task::ready(Ok(()))),
 3994                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3995                        drop(entries);
 3996                        drop(context_menu);
 3997                        self.context_menu_next(&Default::default(), window, cx);
 3998                        return Some(Task::ready(Ok(())));
 3999                    }
 4000                    Some(CompletionEntry::InlineCompletionHint(
 4001                        InlineCompletionMenuHint::PendingTermsAcceptance,
 4002                    )) => {
 4003                        drop(entries);
 4004                        drop(context_menu);
 4005                        self.toggle_zed_predict_onboarding(window, cx);
 4006                        return Some(Task::ready(Ok(())));
 4007                    }
 4008                    _ => {}
 4009                }
 4010            }
 4011        }
 4012
 4013        let completions_menu =
 4014            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4015                menu
 4016            } else {
 4017                return None;
 4018            };
 4019
 4020        let entries = completions_menu.entries.borrow();
 4021        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4022        let mat = match mat {
 4023            CompletionEntry::InlineCompletionHint(_) => {
 4024                self.accept_inline_completion(&AcceptInlineCompletion, window, cx);
 4025                cx.stop_propagation();
 4026                return Some(Task::ready(Ok(())));
 4027            }
 4028            CompletionEntry::Match(mat) => {
 4029                if self.show_inline_completions_in_menu(cx) {
 4030                    self.discard_inline_completion(true, cx);
 4031                }
 4032                mat
 4033            }
 4034        };
 4035        let candidate_id = mat.candidate_id;
 4036        drop(entries);
 4037
 4038        let buffer_handle = completions_menu.buffer;
 4039        let completion = completions_menu
 4040            .completions
 4041            .borrow()
 4042            .get(candidate_id)?
 4043            .clone();
 4044        cx.stop_propagation();
 4045
 4046        let snippet;
 4047        let text;
 4048
 4049        if completion.is_snippet() {
 4050            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4051            text = snippet.as_ref().unwrap().text.clone();
 4052        } else {
 4053            snippet = None;
 4054            text = completion.new_text.clone();
 4055        };
 4056        let selections = self.selections.all::<usize>(cx);
 4057        let buffer = buffer_handle.read(cx);
 4058        let old_range = completion.old_range.to_offset(buffer);
 4059        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4060
 4061        let newest_selection = self.selections.newest_anchor();
 4062        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4063            return None;
 4064        }
 4065
 4066        let lookbehind = newest_selection
 4067            .start
 4068            .text_anchor
 4069            .to_offset(buffer)
 4070            .saturating_sub(old_range.start);
 4071        let lookahead = old_range
 4072            .end
 4073            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4074        let mut common_prefix_len = old_text
 4075            .bytes()
 4076            .zip(text.bytes())
 4077            .take_while(|(a, b)| a == b)
 4078            .count();
 4079
 4080        let snapshot = self.buffer.read(cx).snapshot(cx);
 4081        let mut range_to_replace: Option<Range<isize>> = None;
 4082        let mut ranges = Vec::new();
 4083        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4084        for selection in &selections {
 4085            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4086                let start = selection.start.saturating_sub(lookbehind);
 4087                let end = selection.end + lookahead;
 4088                if selection.id == newest_selection.id {
 4089                    range_to_replace = Some(
 4090                        ((start + common_prefix_len) as isize - selection.start as isize)
 4091                            ..(end as isize - selection.start as isize),
 4092                    );
 4093                }
 4094                ranges.push(start + common_prefix_len..end);
 4095            } else {
 4096                common_prefix_len = 0;
 4097                ranges.clear();
 4098                ranges.extend(selections.iter().map(|s| {
 4099                    if s.id == newest_selection.id {
 4100                        range_to_replace = Some(
 4101                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4102                                - selection.start as isize
 4103                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4104                                    - selection.start as isize,
 4105                        );
 4106                        old_range.clone()
 4107                    } else {
 4108                        s.start..s.end
 4109                    }
 4110                }));
 4111                break;
 4112            }
 4113            if !self.linked_edit_ranges.is_empty() {
 4114                let start_anchor = snapshot.anchor_before(selection.head());
 4115                let end_anchor = snapshot.anchor_after(selection.tail());
 4116                if let Some(ranges) = self
 4117                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4118                {
 4119                    for (buffer, edits) in ranges {
 4120                        linked_edits.entry(buffer.clone()).or_default().extend(
 4121                            edits
 4122                                .into_iter()
 4123                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4124                        );
 4125                    }
 4126                }
 4127            }
 4128        }
 4129        let text = &text[common_prefix_len..];
 4130
 4131        cx.emit(EditorEvent::InputHandled {
 4132            utf16_range_to_replace: range_to_replace,
 4133            text: text.into(),
 4134        });
 4135
 4136        self.transact(window, cx, |this, window, cx| {
 4137            if let Some(mut snippet) = snippet {
 4138                snippet.text = text.to_string();
 4139                for tabstop in snippet
 4140                    .tabstops
 4141                    .iter_mut()
 4142                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4143                {
 4144                    tabstop.start -= common_prefix_len as isize;
 4145                    tabstop.end -= common_prefix_len as isize;
 4146                }
 4147
 4148                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4149            } else {
 4150                this.buffer.update(cx, |buffer, cx| {
 4151                    buffer.edit(
 4152                        ranges.iter().map(|range| (range.clone(), text)),
 4153                        this.autoindent_mode.clone(),
 4154                        cx,
 4155                    );
 4156                });
 4157            }
 4158            for (buffer, edits) in linked_edits {
 4159                buffer.update(cx, |buffer, cx| {
 4160                    let snapshot = buffer.snapshot();
 4161                    let edits = edits
 4162                        .into_iter()
 4163                        .map(|(range, text)| {
 4164                            use text::ToPoint as TP;
 4165                            let end_point = TP::to_point(&range.end, &snapshot);
 4166                            let start_point = TP::to_point(&range.start, &snapshot);
 4167                            (start_point..end_point, text)
 4168                        })
 4169                        .sorted_by_key(|(range, _)| range.start)
 4170                        .collect::<Vec<_>>();
 4171                    buffer.edit(edits, None, cx);
 4172                })
 4173            }
 4174
 4175            this.refresh_inline_completion(true, false, window, cx);
 4176        });
 4177
 4178        let show_new_completions_on_confirm = completion
 4179            .confirm
 4180            .as_ref()
 4181            .map_or(false, |confirm| confirm(intent, window, cx));
 4182        if show_new_completions_on_confirm {
 4183            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4184        }
 4185
 4186        let provider = self.completion_provider.as_ref()?;
 4187        drop(completion);
 4188        let apply_edits = provider.apply_additional_edits_for_completion(
 4189            buffer_handle,
 4190            completions_menu.completions.clone(),
 4191            candidate_id,
 4192            true,
 4193            cx,
 4194        );
 4195
 4196        let editor_settings = EditorSettings::get_global(cx);
 4197        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4198            // After the code completion is finished, users often want to know what signatures are needed.
 4199            // so we should automatically call signature_help
 4200            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4201        }
 4202
 4203        Some(cx.foreground_executor().spawn(async move {
 4204            apply_edits.await?;
 4205            Ok(())
 4206        }))
 4207    }
 4208
 4209    pub fn toggle_code_actions(
 4210        &mut self,
 4211        action: &ToggleCodeActions,
 4212        window: &mut Window,
 4213        cx: &mut Context<Self>,
 4214    ) {
 4215        let mut context_menu = self.context_menu.borrow_mut();
 4216        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4217            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4218                // Toggle if we're selecting the same one
 4219                *context_menu = None;
 4220                cx.notify();
 4221                return;
 4222            } else {
 4223                // Otherwise, clear it and start a new one
 4224                *context_menu = None;
 4225                cx.notify();
 4226            }
 4227        }
 4228        drop(context_menu);
 4229        let snapshot = self.snapshot(window, cx);
 4230        let deployed_from_indicator = action.deployed_from_indicator;
 4231        let mut task = self.code_actions_task.take();
 4232        let action = action.clone();
 4233        cx.spawn_in(window, |editor, mut cx| async move {
 4234            while let Some(prev_task) = task {
 4235                prev_task.await.log_err();
 4236                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4237            }
 4238
 4239            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4240                if editor.focus_handle.is_focused(window) {
 4241                    let multibuffer_point = action
 4242                        .deployed_from_indicator
 4243                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4244                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4245                    let (buffer, buffer_row) = snapshot
 4246                        .buffer_snapshot
 4247                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4248                        .and_then(|(buffer_snapshot, range)| {
 4249                            editor
 4250                                .buffer
 4251                                .read(cx)
 4252                                .buffer(buffer_snapshot.remote_id())
 4253                                .map(|buffer| (buffer, range.start.row))
 4254                        })?;
 4255                    let (_, code_actions) = editor
 4256                        .available_code_actions
 4257                        .clone()
 4258                        .and_then(|(location, code_actions)| {
 4259                            let snapshot = location.buffer.read(cx).snapshot();
 4260                            let point_range = location.range.to_point(&snapshot);
 4261                            let point_range = point_range.start.row..=point_range.end.row;
 4262                            if point_range.contains(&buffer_row) {
 4263                                Some((location, code_actions))
 4264                            } else {
 4265                                None
 4266                            }
 4267                        })
 4268                        .unzip();
 4269                    let buffer_id = buffer.read(cx).remote_id();
 4270                    let tasks = editor
 4271                        .tasks
 4272                        .get(&(buffer_id, buffer_row))
 4273                        .map(|t| Arc::new(t.to_owned()));
 4274                    if tasks.is_none() && code_actions.is_none() {
 4275                        return None;
 4276                    }
 4277
 4278                    editor.completion_tasks.clear();
 4279                    editor.discard_inline_completion(false, cx);
 4280                    let task_context =
 4281                        tasks
 4282                            .as_ref()
 4283                            .zip(editor.project.clone())
 4284                            .map(|(tasks, project)| {
 4285                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4286                            });
 4287
 4288                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4289                        let task_context = match task_context {
 4290                            Some(task_context) => task_context.await,
 4291                            None => None,
 4292                        };
 4293                        let resolved_tasks =
 4294                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4295                                Rc::new(ResolvedTasks {
 4296                                    templates: tasks.resolve(&task_context).collect(),
 4297                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4298                                        multibuffer_point.row,
 4299                                        tasks.column,
 4300                                    )),
 4301                                })
 4302                            });
 4303                        let spawn_straight_away = resolved_tasks
 4304                            .as_ref()
 4305                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4306                            && code_actions
 4307                                .as_ref()
 4308                                .map_or(true, |actions| actions.is_empty());
 4309                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4310                            *editor.context_menu.borrow_mut() =
 4311                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4312                                    buffer,
 4313                                    actions: CodeActionContents {
 4314                                        tasks: resolved_tasks,
 4315                                        actions: code_actions,
 4316                                    },
 4317                                    selected_item: Default::default(),
 4318                                    scroll_handle: UniformListScrollHandle::default(),
 4319                                    deployed_from_indicator,
 4320                                }));
 4321                            if spawn_straight_away {
 4322                                if let Some(task) = editor.confirm_code_action(
 4323                                    &ConfirmCodeAction { item_ix: Some(0) },
 4324                                    window,
 4325                                    cx,
 4326                                ) {
 4327                                    cx.notify();
 4328                                    return task;
 4329                                }
 4330                            }
 4331                            cx.notify();
 4332                            Task::ready(Ok(()))
 4333                        }) {
 4334                            task.await
 4335                        } else {
 4336                            Ok(())
 4337                        }
 4338                    }))
 4339                } else {
 4340                    Some(Task::ready(Ok(())))
 4341                }
 4342            })?;
 4343            if let Some(task) = spawned_test_task {
 4344                task.await?;
 4345            }
 4346
 4347            Ok::<_, anyhow::Error>(())
 4348        })
 4349        .detach_and_log_err(cx);
 4350    }
 4351
 4352    pub fn confirm_code_action(
 4353        &mut self,
 4354        action: &ConfirmCodeAction,
 4355        window: &mut Window,
 4356        cx: &mut Context<Self>,
 4357    ) -> Option<Task<Result<()>>> {
 4358        let actions_menu =
 4359            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4360                menu
 4361            } else {
 4362                return None;
 4363            };
 4364        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4365        let action = actions_menu.actions.get(action_ix)?;
 4366        let title = action.label();
 4367        let buffer = actions_menu.buffer;
 4368        let workspace = self.workspace()?;
 4369
 4370        match action {
 4371            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4372                workspace.update(cx, |workspace, cx| {
 4373                    workspace::tasks::schedule_resolved_task(
 4374                        workspace,
 4375                        task_source_kind,
 4376                        resolved_task,
 4377                        false,
 4378                        cx,
 4379                    );
 4380
 4381                    Some(Task::ready(Ok(())))
 4382                })
 4383            }
 4384            CodeActionsItem::CodeAction {
 4385                excerpt_id,
 4386                action,
 4387                provider,
 4388            } => {
 4389                let apply_code_action =
 4390                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4391                let workspace = workspace.downgrade();
 4392                Some(cx.spawn_in(window, |editor, cx| async move {
 4393                    let project_transaction = apply_code_action.await?;
 4394                    Self::open_project_transaction(
 4395                        &editor,
 4396                        workspace,
 4397                        project_transaction,
 4398                        title,
 4399                        cx,
 4400                    )
 4401                    .await
 4402                }))
 4403            }
 4404        }
 4405    }
 4406
 4407    pub async fn open_project_transaction(
 4408        this: &WeakEntity<Editor>,
 4409        workspace: WeakEntity<Workspace>,
 4410        transaction: ProjectTransaction,
 4411        title: String,
 4412        mut cx: AsyncWindowContext,
 4413    ) -> Result<()> {
 4414        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4415        cx.update(|_, cx| {
 4416            entries.sort_unstable_by_key(|(buffer, _)| {
 4417                buffer.read(cx).file().map(|f| f.path().clone())
 4418            });
 4419        })?;
 4420
 4421        // If the project transaction's edits are all contained within this editor, then
 4422        // avoid opening a new editor to display them.
 4423
 4424        if let Some((buffer, transaction)) = entries.first() {
 4425            if entries.len() == 1 {
 4426                let excerpt = this.update(&mut cx, |editor, cx| {
 4427                    editor
 4428                        .buffer()
 4429                        .read(cx)
 4430                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4431                })?;
 4432                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4433                    if excerpted_buffer == *buffer {
 4434                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4435                            let excerpt_range = excerpt_range.to_offset(buffer);
 4436                            buffer
 4437                                .edited_ranges_for_transaction::<usize>(transaction)
 4438                                .all(|range| {
 4439                                    excerpt_range.start <= range.start
 4440                                        && excerpt_range.end >= range.end
 4441                                })
 4442                        })?;
 4443
 4444                        if all_edits_within_excerpt {
 4445                            return Ok(());
 4446                        }
 4447                    }
 4448                }
 4449            }
 4450        } else {
 4451            return Ok(());
 4452        }
 4453
 4454        let mut ranges_to_highlight = Vec::new();
 4455        let excerpt_buffer = cx.new(|cx| {
 4456            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4457            for (buffer_handle, transaction) in &entries {
 4458                let buffer = buffer_handle.read(cx);
 4459                ranges_to_highlight.extend(
 4460                    multibuffer.push_excerpts_with_context_lines(
 4461                        buffer_handle.clone(),
 4462                        buffer
 4463                            .edited_ranges_for_transaction::<usize>(transaction)
 4464                            .collect(),
 4465                        DEFAULT_MULTIBUFFER_CONTEXT,
 4466                        cx,
 4467                    ),
 4468                );
 4469            }
 4470            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4471            multibuffer
 4472        })?;
 4473
 4474        workspace.update_in(&mut cx, |workspace, window, cx| {
 4475            let project = workspace.project().clone();
 4476            let editor = cx
 4477                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4478            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4479            editor.update(cx, |editor, cx| {
 4480                editor.highlight_background::<Self>(
 4481                    &ranges_to_highlight,
 4482                    |theme| theme.editor_highlighted_line_background,
 4483                    cx,
 4484                );
 4485            });
 4486        })?;
 4487
 4488        Ok(())
 4489    }
 4490
 4491    pub fn clear_code_action_providers(&mut self) {
 4492        self.code_action_providers.clear();
 4493        self.available_code_actions.take();
 4494    }
 4495
 4496    pub fn add_code_action_provider(
 4497        &mut self,
 4498        provider: Rc<dyn CodeActionProvider>,
 4499        window: &mut Window,
 4500        cx: &mut Context<Self>,
 4501    ) {
 4502        if self
 4503            .code_action_providers
 4504            .iter()
 4505            .any(|existing_provider| existing_provider.id() == provider.id())
 4506        {
 4507            return;
 4508        }
 4509
 4510        self.code_action_providers.push(provider);
 4511        self.refresh_code_actions(window, cx);
 4512    }
 4513
 4514    pub fn remove_code_action_provider(
 4515        &mut self,
 4516        id: Arc<str>,
 4517        window: &mut Window,
 4518        cx: &mut Context<Self>,
 4519    ) {
 4520        self.code_action_providers
 4521            .retain(|provider| provider.id() != id);
 4522        self.refresh_code_actions(window, cx);
 4523    }
 4524
 4525    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4526        let buffer = self.buffer.read(cx);
 4527        let newest_selection = self.selections.newest_anchor().clone();
 4528        if newest_selection.head().diff_base_anchor.is_some() {
 4529            return None;
 4530        }
 4531        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4532        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4533        if start_buffer != end_buffer {
 4534            return None;
 4535        }
 4536
 4537        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4538            cx.background_executor()
 4539                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4540                .await;
 4541
 4542            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4543                let providers = this.code_action_providers.clone();
 4544                let tasks = this
 4545                    .code_action_providers
 4546                    .iter()
 4547                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4548                    .collect::<Vec<_>>();
 4549                (providers, tasks)
 4550            })?;
 4551
 4552            let mut actions = Vec::new();
 4553            for (provider, provider_actions) in
 4554                providers.into_iter().zip(future::join_all(tasks).await)
 4555            {
 4556                if let Some(provider_actions) = provider_actions.log_err() {
 4557                    actions.extend(provider_actions.into_iter().map(|action| {
 4558                        AvailableCodeAction {
 4559                            excerpt_id: newest_selection.start.excerpt_id,
 4560                            action,
 4561                            provider: provider.clone(),
 4562                        }
 4563                    }));
 4564                }
 4565            }
 4566
 4567            this.update(&mut cx, |this, cx| {
 4568                this.available_code_actions = if actions.is_empty() {
 4569                    None
 4570                } else {
 4571                    Some((
 4572                        Location {
 4573                            buffer: start_buffer,
 4574                            range: start..end,
 4575                        },
 4576                        actions.into(),
 4577                    ))
 4578                };
 4579                cx.notify();
 4580            })
 4581        }));
 4582        None
 4583    }
 4584
 4585    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4586        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4587            self.show_git_blame_inline = false;
 4588
 4589            self.show_git_blame_inline_delay_task =
 4590                Some(cx.spawn_in(window, |this, mut cx| async move {
 4591                    cx.background_executor().timer(delay).await;
 4592
 4593                    this.update(&mut cx, |this, cx| {
 4594                        this.show_git_blame_inline = true;
 4595                        cx.notify();
 4596                    })
 4597                    .log_err();
 4598                }));
 4599        }
 4600    }
 4601
 4602    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4603        if self.pending_rename.is_some() {
 4604            return None;
 4605        }
 4606
 4607        let provider = self.semantics_provider.clone()?;
 4608        let buffer = self.buffer.read(cx);
 4609        let newest_selection = self.selections.newest_anchor().clone();
 4610        let cursor_position = newest_selection.head();
 4611        let (cursor_buffer, cursor_buffer_position) =
 4612            buffer.text_anchor_for_position(cursor_position, cx)?;
 4613        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4614        if cursor_buffer != tail_buffer {
 4615            return None;
 4616        }
 4617        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4618        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4619            cx.background_executor()
 4620                .timer(Duration::from_millis(debounce))
 4621                .await;
 4622
 4623            let highlights = if let Some(highlights) = cx
 4624                .update(|cx| {
 4625                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4626                })
 4627                .ok()
 4628                .flatten()
 4629            {
 4630                highlights.await.log_err()
 4631            } else {
 4632                None
 4633            };
 4634
 4635            if let Some(highlights) = highlights {
 4636                this.update(&mut cx, |this, cx| {
 4637                    if this.pending_rename.is_some() {
 4638                        return;
 4639                    }
 4640
 4641                    let buffer_id = cursor_position.buffer_id;
 4642                    let buffer = this.buffer.read(cx);
 4643                    if !buffer
 4644                        .text_anchor_for_position(cursor_position, cx)
 4645                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4646                    {
 4647                        return;
 4648                    }
 4649
 4650                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4651                    let mut write_ranges = Vec::new();
 4652                    let mut read_ranges = Vec::new();
 4653                    for highlight in highlights {
 4654                        for (excerpt_id, excerpt_range) in
 4655                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4656                        {
 4657                            let start = highlight
 4658                                .range
 4659                                .start
 4660                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4661                            let end = highlight
 4662                                .range
 4663                                .end
 4664                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4665                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4666                                continue;
 4667                            }
 4668
 4669                            let range = Anchor {
 4670                                buffer_id,
 4671                                excerpt_id,
 4672                                text_anchor: start,
 4673                                diff_base_anchor: None,
 4674                            }..Anchor {
 4675                                buffer_id,
 4676                                excerpt_id,
 4677                                text_anchor: end,
 4678                                diff_base_anchor: None,
 4679                            };
 4680                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4681                                write_ranges.push(range);
 4682                            } else {
 4683                                read_ranges.push(range);
 4684                            }
 4685                        }
 4686                    }
 4687
 4688                    this.highlight_background::<DocumentHighlightRead>(
 4689                        &read_ranges,
 4690                        |theme| theme.editor_document_highlight_read_background,
 4691                        cx,
 4692                    );
 4693                    this.highlight_background::<DocumentHighlightWrite>(
 4694                        &write_ranges,
 4695                        |theme| theme.editor_document_highlight_write_background,
 4696                        cx,
 4697                    );
 4698                    cx.notify();
 4699                })
 4700                .log_err();
 4701            }
 4702        }));
 4703        None
 4704    }
 4705
 4706    pub fn refresh_inline_completion(
 4707        &mut self,
 4708        debounce: bool,
 4709        user_requested: bool,
 4710        window: &mut Window,
 4711        cx: &mut Context<Self>,
 4712    ) -> Option<()> {
 4713        let provider = self.inline_completion_provider()?;
 4714        let cursor = self.selections.newest_anchor().head();
 4715        let (buffer, cursor_buffer_position) =
 4716            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4717
 4718        if !user_requested
 4719            && (!self.enable_inline_completions
 4720                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4721                || !self.is_focused(window)
 4722                || buffer.read(cx).is_empty())
 4723        {
 4724            self.discard_inline_completion(false, cx);
 4725            return None;
 4726        }
 4727
 4728        self.update_visible_inline_completion(window, cx);
 4729        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4730        Some(())
 4731    }
 4732
 4733    fn cycle_inline_completion(
 4734        &mut self,
 4735        direction: Direction,
 4736        window: &mut Window,
 4737        cx: &mut Context<Self>,
 4738    ) -> Option<()> {
 4739        let provider = self.inline_completion_provider()?;
 4740        let cursor = self.selections.newest_anchor().head();
 4741        let (buffer, cursor_buffer_position) =
 4742            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4743        if !self.enable_inline_completions
 4744            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4745        {
 4746            return None;
 4747        }
 4748
 4749        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4750        self.update_visible_inline_completion(window, cx);
 4751
 4752        Some(())
 4753    }
 4754
 4755    pub fn show_inline_completion(
 4756        &mut self,
 4757        _: &ShowInlineCompletion,
 4758        window: &mut Window,
 4759        cx: &mut Context<Self>,
 4760    ) {
 4761        if !self.has_active_inline_completion() {
 4762            self.refresh_inline_completion(false, true, window, cx);
 4763            return;
 4764        }
 4765
 4766        self.update_visible_inline_completion(window, cx);
 4767    }
 4768
 4769    pub fn display_cursor_names(
 4770        &mut self,
 4771        _: &DisplayCursorNames,
 4772        window: &mut Window,
 4773        cx: &mut Context<Self>,
 4774    ) {
 4775        self.show_cursor_names(window, cx);
 4776    }
 4777
 4778    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4779        self.show_cursor_names = true;
 4780        cx.notify();
 4781        cx.spawn_in(window, |this, mut cx| async move {
 4782            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4783            this.update(&mut cx, |this, cx| {
 4784                this.show_cursor_names = false;
 4785                cx.notify()
 4786            })
 4787            .ok()
 4788        })
 4789        .detach();
 4790    }
 4791
 4792    pub fn next_inline_completion(
 4793        &mut self,
 4794        _: &NextInlineCompletion,
 4795        window: &mut Window,
 4796        cx: &mut Context<Self>,
 4797    ) {
 4798        if self.has_active_inline_completion() {
 4799            self.cycle_inline_completion(Direction::Next, window, cx);
 4800        } else {
 4801            let is_copilot_disabled = self
 4802                .refresh_inline_completion(false, true, window, cx)
 4803                .is_none();
 4804            if is_copilot_disabled {
 4805                cx.propagate();
 4806            }
 4807        }
 4808    }
 4809
 4810    pub fn previous_inline_completion(
 4811        &mut self,
 4812        _: &PreviousInlineCompletion,
 4813        window: &mut Window,
 4814        cx: &mut Context<Self>,
 4815    ) {
 4816        if self.has_active_inline_completion() {
 4817            self.cycle_inline_completion(Direction::Prev, window, cx);
 4818        } else {
 4819            let is_copilot_disabled = self
 4820                .refresh_inline_completion(false, true, window, cx)
 4821                .is_none();
 4822            if is_copilot_disabled {
 4823                cx.propagate();
 4824            }
 4825        }
 4826    }
 4827
 4828    pub fn accept_inline_completion(
 4829        &mut self,
 4830        _: &AcceptInlineCompletion,
 4831        window: &mut Window,
 4832        cx: &mut Context<Self>,
 4833    ) {
 4834        let buffer = self.buffer.read(cx);
 4835        let snapshot = buffer.snapshot(cx);
 4836        let selection = self.selections.newest_adjusted(cx);
 4837        let cursor = selection.head();
 4838        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4839        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4840        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4841        {
 4842            if cursor.column < suggested_indent.len
 4843                && cursor.column <= current_indent.len
 4844                && current_indent.len <= suggested_indent.len
 4845            {
 4846                self.tab(&Default::default(), window, cx);
 4847                return;
 4848            }
 4849        }
 4850
 4851        if self.show_inline_completions_in_menu(cx) {
 4852            self.hide_context_menu(window, cx);
 4853        }
 4854
 4855        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4856            return;
 4857        };
 4858
 4859        self.report_inline_completion_event(true, cx);
 4860
 4861        match &active_inline_completion.completion {
 4862            InlineCompletion::Move(position) => {
 4863                let position = *position;
 4864                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4865                    selections.select_anchor_ranges([position..position]);
 4866                });
 4867            }
 4868            InlineCompletion::Edit { edits, .. } => {
 4869                if let Some(provider) = self.inline_completion_provider() {
 4870                    provider.accept(cx);
 4871                }
 4872
 4873                let snapshot = self.buffer.read(cx).snapshot(cx);
 4874                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4875
 4876                self.buffer.update(cx, |buffer, cx| {
 4877                    buffer.edit(edits.iter().cloned(), None, cx)
 4878                });
 4879
 4880                self.change_selections(None, window, cx, |s| {
 4881                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4882                });
 4883
 4884                self.update_visible_inline_completion(window, cx);
 4885                if self.active_inline_completion.is_none() {
 4886                    self.refresh_inline_completion(true, true, window, cx);
 4887                }
 4888
 4889                cx.notify();
 4890            }
 4891        }
 4892    }
 4893
 4894    pub fn accept_partial_inline_completion(
 4895        &mut self,
 4896        _: &AcceptPartialInlineCompletion,
 4897        window: &mut Window,
 4898        cx: &mut Context<Self>,
 4899    ) {
 4900        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4901            return;
 4902        };
 4903        if self.selections.count() != 1 {
 4904            return;
 4905        }
 4906
 4907        self.report_inline_completion_event(true, cx);
 4908
 4909        match &active_inline_completion.completion {
 4910            InlineCompletion::Move(position) => {
 4911                let position = *position;
 4912                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4913                    selections.select_anchor_ranges([position..position]);
 4914                });
 4915            }
 4916            InlineCompletion::Edit { edits, .. } => {
 4917                // Find an insertion that starts at the cursor position.
 4918                let snapshot = self.buffer.read(cx).snapshot(cx);
 4919                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4920                let insertion = edits.iter().find_map(|(range, text)| {
 4921                    let range = range.to_offset(&snapshot);
 4922                    if range.is_empty() && range.start == cursor_offset {
 4923                        Some(text)
 4924                    } else {
 4925                        None
 4926                    }
 4927                });
 4928
 4929                if let Some(text) = insertion {
 4930                    let mut partial_completion = text
 4931                        .chars()
 4932                        .by_ref()
 4933                        .take_while(|c| c.is_alphabetic())
 4934                        .collect::<String>();
 4935                    if partial_completion.is_empty() {
 4936                        partial_completion = text
 4937                            .chars()
 4938                            .by_ref()
 4939                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4940                            .collect::<String>();
 4941                    }
 4942
 4943                    cx.emit(EditorEvent::InputHandled {
 4944                        utf16_range_to_replace: None,
 4945                        text: partial_completion.clone().into(),
 4946                    });
 4947
 4948                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4949
 4950                    self.refresh_inline_completion(true, true, window, cx);
 4951                    cx.notify();
 4952                } else {
 4953                    self.accept_inline_completion(&Default::default(), window, cx);
 4954                }
 4955            }
 4956        }
 4957    }
 4958
 4959    fn discard_inline_completion(
 4960        &mut self,
 4961        should_report_inline_completion_event: bool,
 4962        cx: &mut Context<Self>,
 4963    ) -> bool {
 4964        if should_report_inline_completion_event {
 4965            self.report_inline_completion_event(false, cx);
 4966        }
 4967
 4968        if let Some(provider) = self.inline_completion_provider() {
 4969            provider.discard(cx);
 4970        }
 4971
 4972        self.take_active_inline_completion(cx).is_some()
 4973    }
 4974
 4975    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4976        let Some(provider) = self.inline_completion_provider() else {
 4977            return;
 4978        };
 4979
 4980        let Some((_, buffer, _)) = self
 4981            .buffer
 4982            .read(cx)
 4983            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4984        else {
 4985            return;
 4986        };
 4987
 4988        let extension = buffer
 4989            .read(cx)
 4990            .file()
 4991            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4992
 4993        let event_type = match accepted {
 4994            true => "Inline Completion Accepted",
 4995            false => "Inline Completion Discarded",
 4996        };
 4997        telemetry::event!(
 4998            event_type,
 4999            provider = provider.name(),
 5000            suggestion_accepted = accepted,
 5001            file_extension = extension,
 5002        );
 5003    }
 5004
 5005    pub fn has_active_inline_completion(&self) -> bool {
 5006        self.active_inline_completion.is_some()
 5007    }
 5008
 5009    fn take_active_inline_completion(
 5010        &mut self,
 5011        cx: &mut Context<Self>,
 5012    ) -> Option<InlineCompletion> {
 5013        let active_inline_completion = self.active_inline_completion.take()?;
 5014        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 5015        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5016        Some(active_inline_completion.completion)
 5017    }
 5018
 5019    fn update_visible_inline_completion(
 5020        &mut self,
 5021        window: &mut Window,
 5022        cx: &mut Context<Self>,
 5023    ) -> Option<()> {
 5024        let selection = self.selections.newest_anchor();
 5025        let cursor = selection.head();
 5026        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5027        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5028        let excerpt_id = cursor.excerpt_id;
 5029
 5030        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 5031            && (self.context_menu.borrow().is_some()
 5032                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5033        if completions_menu_has_precedence
 5034            || !offset_selection.is_empty()
 5035            || !self.enable_inline_completions
 5036            || self
 5037                .active_inline_completion
 5038                .as_ref()
 5039                .map_or(false, |completion| {
 5040                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5041                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5042                    !invalidation_range.contains(&offset_selection.head())
 5043                })
 5044        {
 5045            self.discard_inline_completion(false, cx);
 5046            return None;
 5047        }
 5048
 5049        self.take_active_inline_completion(cx);
 5050        let provider = self.inline_completion_provider()?;
 5051
 5052        let (buffer, cursor_buffer_position) =
 5053            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5054
 5055        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5056        let edits = inline_completion
 5057            .edits
 5058            .into_iter()
 5059            .flat_map(|(range, new_text)| {
 5060                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5061                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5062                Some((start..end, new_text))
 5063            })
 5064            .collect::<Vec<_>>();
 5065        if edits.is_empty() {
 5066            return None;
 5067        }
 5068
 5069        let first_edit_start = edits.first().unwrap().0.start;
 5070        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5071        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5072
 5073        let last_edit_end = edits.last().unwrap().0.end;
 5074        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5075        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5076
 5077        let cursor_row = cursor.to_point(&multibuffer).row;
 5078
 5079        let mut inlay_ids = Vec::new();
 5080        let invalidation_row_range;
 5081        let completion = if cursor_row < edit_start_row {
 5082            invalidation_row_range = cursor_row..edit_end_row;
 5083            InlineCompletion::Move(first_edit_start)
 5084        } else if cursor_row > edit_end_row {
 5085            invalidation_row_range = edit_start_row..cursor_row;
 5086            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            let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5132
 5133            InlineCompletion::Edit {
 5134                edits,
 5135                edit_preview: inline_completion.edit_preview,
 5136                display_mode,
 5137                snapshot,
 5138            }
 5139        };
 5140
 5141        let invalidation_range = multibuffer
 5142            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5143            ..multibuffer.anchor_after(Point::new(
 5144                invalidation_row_range.end,
 5145                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5146            ));
 5147
 5148        self.active_inline_completion = Some(InlineCompletionState {
 5149            inlay_ids,
 5150            completion,
 5151            invalidation_range,
 5152        });
 5153
 5154        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 5155            if let Some(hint) = self.inline_completion_menu_hint(window, cx) {
 5156                match self.context_menu.borrow_mut().as_mut() {
 5157                    Some(CodeContextMenu::Completions(menu)) => {
 5158                        menu.show_inline_completion_hint(hint);
 5159                    }
 5160                    _ => {}
 5161                }
 5162            }
 5163        }
 5164
 5165        cx.notify();
 5166
 5167        Some(())
 5168    }
 5169
 5170    fn inline_completion_menu_hint(
 5171        &self,
 5172        window: &mut Window,
 5173        cx: &mut Context<Self>,
 5174    ) -> Option<InlineCompletionMenuHint> {
 5175        let provider = self.inline_completion_provider()?;
 5176        if self.has_active_inline_completion() {
 5177            let editor_snapshot = self.snapshot(window, cx);
 5178
 5179            let text = match &self.active_inline_completion.as_ref()?.completion {
 5180                InlineCompletion::Edit {
 5181                    edits,
 5182                    edit_preview,
 5183                    display_mode: _,
 5184                    snapshot,
 5185                } => edit_preview
 5186                    .as_ref()
 5187                    .and_then(|edit_preview| {
 5188                        inline_completion_edit_text(&snapshot, &edits, edit_preview, true, cx)
 5189                    })
 5190                    .map(InlineCompletionText::Edit),
 5191                InlineCompletion::Move(target) => {
 5192                    let target_point =
 5193                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 5194                    let target_line = target_point.row + 1;
 5195                    Some(InlineCompletionText::Move(
 5196                        format!("Jump to edit in line {}", target_line).into(),
 5197                    ))
 5198                }
 5199            };
 5200
 5201            Some(InlineCompletionMenuHint::Loaded { text: text? })
 5202        } else if provider.is_refreshing(cx) {
 5203            Some(InlineCompletionMenuHint::Loading)
 5204        } else if provider.needs_terms_acceptance(cx) {
 5205            Some(InlineCompletionMenuHint::PendingTermsAcceptance)
 5206        } else {
 5207            Some(InlineCompletionMenuHint::None)
 5208        }
 5209    }
 5210
 5211    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5212        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5213    }
 5214
 5215    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5216        let by_provider = matches!(
 5217            self.menu_inline_completions_policy,
 5218            MenuInlineCompletionsPolicy::ByProvider
 5219        );
 5220
 5221        by_provider
 5222            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5223            && self
 5224                .inline_completion_provider()
 5225                .map_or(false, |provider| provider.show_completions_in_menu())
 5226    }
 5227
 5228    fn render_code_actions_indicator(
 5229        &self,
 5230        _style: &EditorStyle,
 5231        row: DisplayRow,
 5232        is_active: bool,
 5233        cx: &mut Context<Self>,
 5234    ) -> Option<IconButton> {
 5235        if self.available_code_actions.is_some() {
 5236            Some(
 5237                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5238                    .shape(ui::IconButtonShape::Square)
 5239                    .icon_size(IconSize::XSmall)
 5240                    .icon_color(Color::Muted)
 5241                    .toggle_state(is_active)
 5242                    .tooltip({
 5243                        let focus_handle = self.focus_handle.clone();
 5244                        move |window, cx| {
 5245                            Tooltip::for_action_in(
 5246                                "Toggle Code Actions",
 5247                                &ToggleCodeActions {
 5248                                    deployed_from_indicator: None,
 5249                                },
 5250                                &focus_handle,
 5251                                window,
 5252                                cx,
 5253                            )
 5254                        }
 5255                    })
 5256                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5257                        window.focus(&editor.focus_handle(cx));
 5258                        editor.toggle_code_actions(
 5259                            &ToggleCodeActions {
 5260                                deployed_from_indicator: Some(row),
 5261                            },
 5262                            window,
 5263                            cx,
 5264                        );
 5265                    })),
 5266            )
 5267        } else {
 5268            None
 5269        }
 5270    }
 5271
 5272    fn clear_tasks(&mut self) {
 5273        self.tasks.clear()
 5274    }
 5275
 5276    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5277        if self.tasks.insert(key, value).is_some() {
 5278            // This case should hopefully be rare, but just in case...
 5279            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5280        }
 5281    }
 5282
 5283    fn build_tasks_context(
 5284        project: &Entity<Project>,
 5285        buffer: &Entity<Buffer>,
 5286        buffer_row: u32,
 5287        tasks: &Arc<RunnableTasks>,
 5288        cx: &mut Context<Self>,
 5289    ) -> Task<Option<task::TaskContext>> {
 5290        let position = Point::new(buffer_row, tasks.column);
 5291        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5292        let location = Location {
 5293            buffer: buffer.clone(),
 5294            range: range_start..range_start,
 5295        };
 5296        // Fill in the environmental variables from the tree-sitter captures
 5297        let mut captured_task_variables = TaskVariables::default();
 5298        for (capture_name, value) in tasks.extra_variables.clone() {
 5299            captured_task_variables.insert(
 5300                task::VariableName::Custom(capture_name.into()),
 5301                value.clone(),
 5302            );
 5303        }
 5304        project.update(cx, |project, cx| {
 5305            project.task_store().update(cx, |task_store, cx| {
 5306                task_store.task_context_for_location(captured_task_variables, location, cx)
 5307            })
 5308        })
 5309    }
 5310
 5311    pub fn spawn_nearest_task(
 5312        &mut self,
 5313        action: &SpawnNearestTask,
 5314        window: &mut Window,
 5315        cx: &mut Context<Self>,
 5316    ) {
 5317        let Some((workspace, _)) = self.workspace.clone() else {
 5318            return;
 5319        };
 5320        let Some(project) = self.project.clone() else {
 5321            return;
 5322        };
 5323
 5324        // Try to find a closest, enclosing node using tree-sitter that has a
 5325        // task
 5326        let Some((buffer, buffer_row, tasks)) = self
 5327            .find_enclosing_node_task(cx)
 5328            // Or find the task that's closest in row-distance.
 5329            .or_else(|| self.find_closest_task(cx))
 5330        else {
 5331            return;
 5332        };
 5333
 5334        let reveal_strategy = action.reveal;
 5335        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5336        cx.spawn_in(window, |_, mut cx| async move {
 5337            let context = task_context.await?;
 5338            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5339
 5340            let resolved = resolved_task.resolved.as_mut()?;
 5341            resolved.reveal = reveal_strategy;
 5342
 5343            workspace
 5344                .update(&mut cx, |workspace, cx| {
 5345                    workspace::tasks::schedule_resolved_task(
 5346                        workspace,
 5347                        task_source_kind,
 5348                        resolved_task,
 5349                        false,
 5350                        cx,
 5351                    );
 5352                })
 5353                .ok()
 5354        })
 5355        .detach();
 5356    }
 5357
 5358    fn find_closest_task(
 5359        &mut self,
 5360        cx: &mut Context<Self>,
 5361    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5362        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5363
 5364        let ((buffer_id, row), tasks) = self
 5365            .tasks
 5366            .iter()
 5367            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5368
 5369        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5370        let tasks = Arc::new(tasks.to_owned());
 5371        Some((buffer, *row, tasks))
 5372    }
 5373
 5374    fn find_enclosing_node_task(
 5375        &mut self,
 5376        cx: &mut Context<Self>,
 5377    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5378        let snapshot = self.buffer.read(cx).snapshot(cx);
 5379        let offset = self.selections.newest::<usize>(cx).head();
 5380        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5381        let buffer_id = excerpt.buffer().remote_id();
 5382
 5383        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5384        let mut cursor = layer.node().walk();
 5385
 5386        while cursor.goto_first_child_for_byte(offset).is_some() {
 5387            if cursor.node().end_byte() == offset {
 5388                cursor.goto_next_sibling();
 5389            }
 5390        }
 5391
 5392        // Ascend to the smallest ancestor that contains the range and has a task.
 5393        loop {
 5394            let node = cursor.node();
 5395            let node_range = node.byte_range();
 5396            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5397
 5398            // Check if this node contains our offset
 5399            if node_range.start <= offset && node_range.end >= offset {
 5400                // If it contains offset, check for task
 5401                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5402                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5403                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5404                }
 5405            }
 5406
 5407            if !cursor.goto_parent() {
 5408                break;
 5409            }
 5410        }
 5411        None
 5412    }
 5413
 5414    fn render_run_indicator(
 5415        &self,
 5416        _style: &EditorStyle,
 5417        is_active: bool,
 5418        row: DisplayRow,
 5419        cx: &mut Context<Self>,
 5420    ) -> IconButton {
 5421        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5422            .shape(ui::IconButtonShape::Square)
 5423            .icon_size(IconSize::XSmall)
 5424            .icon_color(Color::Muted)
 5425            .toggle_state(is_active)
 5426            .on_click(cx.listener(move |editor, _e, window, cx| {
 5427                window.focus(&editor.focus_handle(cx));
 5428                editor.toggle_code_actions(
 5429                    &ToggleCodeActions {
 5430                        deployed_from_indicator: Some(row),
 5431                    },
 5432                    window,
 5433                    cx,
 5434                );
 5435            }))
 5436    }
 5437
 5438    #[cfg(any(test, feature = "test-support"))]
 5439    pub fn context_menu_visible(&self) -> bool {
 5440        self.context_menu
 5441            .borrow()
 5442            .as_ref()
 5443            .map_or(false, |menu| menu.visible())
 5444    }
 5445
 5446    #[cfg(feature = "test-support")]
 5447    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5448        self.context_menu
 5449            .borrow()
 5450            .as_ref()
 5451            .map_or(false, |menu| match menu {
 5452                CodeContextMenu::Completions(menu) => {
 5453                    menu.entries.borrow().first().map_or(false, |entry| {
 5454                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5455                    })
 5456                }
 5457                CodeContextMenu::CodeActions(_) => false,
 5458            })
 5459    }
 5460
 5461    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5462        self.context_menu
 5463            .borrow()
 5464            .as_ref()
 5465            .map(|menu| menu.origin(cursor_position))
 5466    }
 5467
 5468    fn render_context_menu(
 5469        &self,
 5470        style: &EditorStyle,
 5471        max_height_in_lines: u32,
 5472        y_flipped: bool,
 5473        window: &mut Window,
 5474        cx: &mut Context<Editor>,
 5475    ) -> Option<AnyElement> {
 5476        self.context_menu.borrow().as_ref().and_then(|menu| {
 5477            if menu.visible() {
 5478                Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5479            } else {
 5480                None
 5481            }
 5482        })
 5483    }
 5484
 5485    fn render_context_menu_aside(
 5486        &self,
 5487        style: &EditorStyle,
 5488        max_size: Size<Pixels>,
 5489        cx: &mut Context<Editor>,
 5490    ) -> Option<AnyElement> {
 5491        self.context_menu.borrow().as_ref().and_then(|menu| {
 5492            if menu.visible() {
 5493                menu.render_aside(
 5494                    style,
 5495                    max_size,
 5496                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5497                    cx,
 5498                )
 5499            } else {
 5500                None
 5501            }
 5502        })
 5503    }
 5504
 5505    fn hide_context_menu(
 5506        &mut self,
 5507        window: &mut Window,
 5508        cx: &mut Context<Self>,
 5509    ) -> Option<CodeContextMenu> {
 5510        cx.notify();
 5511        self.completion_tasks.clear();
 5512        let context_menu = self.context_menu.borrow_mut().take();
 5513        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5514            self.update_visible_inline_completion(window, cx);
 5515        }
 5516        context_menu
 5517    }
 5518
 5519    fn show_snippet_choices(
 5520        &mut self,
 5521        choices: &Vec<String>,
 5522        selection: Range<Anchor>,
 5523        cx: &mut Context<Self>,
 5524    ) {
 5525        if selection.start.buffer_id.is_none() {
 5526            return;
 5527        }
 5528        let buffer_id = selection.start.buffer_id.unwrap();
 5529        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5530        let id = post_inc(&mut self.next_completion_id);
 5531
 5532        if let Some(buffer) = buffer {
 5533            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5534                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5535            ));
 5536        }
 5537    }
 5538
 5539    pub fn insert_snippet(
 5540        &mut self,
 5541        insertion_ranges: &[Range<usize>],
 5542        snippet: Snippet,
 5543        window: &mut Window,
 5544        cx: &mut Context<Self>,
 5545    ) -> Result<()> {
 5546        struct Tabstop<T> {
 5547            is_end_tabstop: bool,
 5548            ranges: Vec<Range<T>>,
 5549            choices: Option<Vec<String>>,
 5550        }
 5551
 5552        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5553            let snippet_text: Arc<str> = snippet.text.clone().into();
 5554            buffer.edit(
 5555                insertion_ranges
 5556                    .iter()
 5557                    .cloned()
 5558                    .map(|range| (range, snippet_text.clone())),
 5559                Some(AutoindentMode::EachLine),
 5560                cx,
 5561            );
 5562
 5563            let snapshot = &*buffer.read(cx);
 5564            let snippet = &snippet;
 5565            snippet
 5566                .tabstops
 5567                .iter()
 5568                .map(|tabstop| {
 5569                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5570                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5571                    });
 5572                    let mut tabstop_ranges = tabstop
 5573                        .ranges
 5574                        .iter()
 5575                        .flat_map(|tabstop_range| {
 5576                            let mut delta = 0_isize;
 5577                            insertion_ranges.iter().map(move |insertion_range| {
 5578                                let insertion_start = insertion_range.start as isize + delta;
 5579                                delta +=
 5580                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5581
 5582                                let start = ((insertion_start + tabstop_range.start) as usize)
 5583                                    .min(snapshot.len());
 5584                                let end = ((insertion_start + tabstop_range.end) as usize)
 5585                                    .min(snapshot.len());
 5586                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5587                            })
 5588                        })
 5589                        .collect::<Vec<_>>();
 5590                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5591
 5592                    Tabstop {
 5593                        is_end_tabstop,
 5594                        ranges: tabstop_ranges,
 5595                        choices: tabstop.choices.clone(),
 5596                    }
 5597                })
 5598                .collect::<Vec<_>>()
 5599        });
 5600        if let Some(tabstop) = tabstops.first() {
 5601            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5602                s.select_ranges(tabstop.ranges.iter().cloned());
 5603            });
 5604
 5605            if let Some(choices) = &tabstop.choices {
 5606                if let Some(selection) = tabstop.ranges.first() {
 5607                    self.show_snippet_choices(choices, selection.clone(), cx)
 5608                }
 5609            }
 5610
 5611            // If we're already at the last tabstop and it's at the end of the snippet,
 5612            // we're done, we don't need to keep the state around.
 5613            if !tabstop.is_end_tabstop {
 5614                let choices = tabstops
 5615                    .iter()
 5616                    .map(|tabstop| tabstop.choices.clone())
 5617                    .collect();
 5618
 5619                let ranges = tabstops
 5620                    .into_iter()
 5621                    .map(|tabstop| tabstop.ranges)
 5622                    .collect::<Vec<_>>();
 5623
 5624                self.snippet_stack.push(SnippetState {
 5625                    active_index: 0,
 5626                    ranges,
 5627                    choices,
 5628                });
 5629            }
 5630
 5631            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5632            if self.autoclose_regions.is_empty() {
 5633                let snapshot = self.buffer.read(cx).snapshot(cx);
 5634                for selection in &mut self.selections.all::<Point>(cx) {
 5635                    let selection_head = selection.head();
 5636                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5637                        continue;
 5638                    };
 5639
 5640                    let mut bracket_pair = None;
 5641                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5642                    let prev_chars = snapshot
 5643                        .reversed_chars_at(selection_head)
 5644                        .collect::<String>();
 5645                    for (pair, enabled) in scope.brackets() {
 5646                        if enabled
 5647                            && pair.close
 5648                            && prev_chars.starts_with(pair.start.as_str())
 5649                            && next_chars.starts_with(pair.end.as_str())
 5650                        {
 5651                            bracket_pair = Some(pair.clone());
 5652                            break;
 5653                        }
 5654                    }
 5655                    if let Some(pair) = bracket_pair {
 5656                        let start = snapshot.anchor_after(selection_head);
 5657                        let end = snapshot.anchor_after(selection_head);
 5658                        self.autoclose_regions.push(AutocloseRegion {
 5659                            selection_id: selection.id,
 5660                            range: start..end,
 5661                            pair,
 5662                        });
 5663                    }
 5664                }
 5665            }
 5666        }
 5667        Ok(())
 5668    }
 5669
 5670    pub fn move_to_next_snippet_tabstop(
 5671        &mut self,
 5672        window: &mut Window,
 5673        cx: &mut Context<Self>,
 5674    ) -> bool {
 5675        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5676    }
 5677
 5678    pub fn move_to_prev_snippet_tabstop(
 5679        &mut self,
 5680        window: &mut Window,
 5681        cx: &mut Context<Self>,
 5682    ) -> bool {
 5683        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5684    }
 5685
 5686    pub fn move_to_snippet_tabstop(
 5687        &mut self,
 5688        bias: Bias,
 5689        window: &mut Window,
 5690        cx: &mut Context<Self>,
 5691    ) -> bool {
 5692        if let Some(mut snippet) = self.snippet_stack.pop() {
 5693            match bias {
 5694                Bias::Left => {
 5695                    if snippet.active_index > 0 {
 5696                        snippet.active_index -= 1;
 5697                    } else {
 5698                        self.snippet_stack.push(snippet);
 5699                        return false;
 5700                    }
 5701                }
 5702                Bias::Right => {
 5703                    if snippet.active_index + 1 < snippet.ranges.len() {
 5704                        snippet.active_index += 1;
 5705                    } else {
 5706                        self.snippet_stack.push(snippet);
 5707                        return false;
 5708                    }
 5709                }
 5710            }
 5711            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5712                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5713                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5714                });
 5715
 5716                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5717                    if let Some(selection) = current_ranges.first() {
 5718                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5719                    }
 5720                }
 5721
 5722                // If snippet state is not at the last tabstop, push it back on the stack
 5723                if snippet.active_index + 1 < snippet.ranges.len() {
 5724                    self.snippet_stack.push(snippet);
 5725                }
 5726                return true;
 5727            }
 5728        }
 5729
 5730        false
 5731    }
 5732
 5733    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5734        self.transact(window, cx, |this, window, cx| {
 5735            this.select_all(&SelectAll, window, cx);
 5736            this.insert("", window, cx);
 5737        });
 5738    }
 5739
 5740    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 5741        self.transact(window, cx, |this, window, cx| {
 5742            this.select_autoclose_pair(window, cx);
 5743            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5744            if !this.linked_edit_ranges.is_empty() {
 5745                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5746                let snapshot = this.buffer.read(cx).snapshot(cx);
 5747
 5748                for selection in selections.iter() {
 5749                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5750                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5751                    if selection_start.buffer_id != selection_end.buffer_id {
 5752                        continue;
 5753                    }
 5754                    if let Some(ranges) =
 5755                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5756                    {
 5757                        for (buffer, entries) in ranges {
 5758                            linked_ranges.entry(buffer).or_default().extend(entries);
 5759                        }
 5760                    }
 5761                }
 5762            }
 5763
 5764            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5765            if !this.selections.line_mode {
 5766                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5767                for selection in &mut selections {
 5768                    if selection.is_empty() {
 5769                        let old_head = selection.head();
 5770                        let mut new_head =
 5771                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5772                                .to_point(&display_map);
 5773                        if let Some((buffer, line_buffer_range)) = display_map
 5774                            .buffer_snapshot
 5775                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5776                        {
 5777                            let indent_size =
 5778                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5779                            let indent_len = match indent_size.kind {
 5780                                IndentKind::Space => {
 5781                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5782                                }
 5783                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5784                            };
 5785                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5786                                let indent_len = indent_len.get();
 5787                                new_head = cmp::min(
 5788                                    new_head,
 5789                                    MultiBufferPoint::new(
 5790                                        old_head.row,
 5791                                        ((old_head.column - 1) / indent_len) * indent_len,
 5792                                    ),
 5793                                );
 5794                            }
 5795                        }
 5796
 5797                        selection.set_head(new_head, SelectionGoal::None);
 5798                    }
 5799                }
 5800            }
 5801
 5802            this.signature_help_state.set_backspace_pressed(true);
 5803            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5804                s.select(selections)
 5805            });
 5806            this.insert("", window, cx);
 5807            let empty_str: Arc<str> = Arc::from("");
 5808            for (buffer, edits) in linked_ranges {
 5809                let snapshot = buffer.read(cx).snapshot();
 5810                use text::ToPoint as TP;
 5811
 5812                let edits = edits
 5813                    .into_iter()
 5814                    .map(|range| {
 5815                        let end_point = TP::to_point(&range.end, &snapshot);
 5816                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5817
 5818                        if end_point == start_point {
 5819                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5820                                .saturating_sub(1);
 5821                            start_point =
 5822                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5823                        };
 5824
 5825                        (start_point..end_point, empty_str.clone())
 5826                    })
 5827                    .sorted_by_key(|(range, _)| range.start)
 5828                    .collect::<Vec<_>>();
 5829                buffer.update(cx, |this, cx| {
 5830                    this.edit(edits, None, cx);
 5831                })
 5832            }
 5833            this.refresh_inline_completion(true, false, window, cx);
 5834            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 5835        });
 5836    }
 5837
 5838    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 5839        self.transact(window, cx, |this, window, cx| {
 5840            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5841                let line_mode = s.line_mode;
 5842                s.move_with(|map, selection| {
 5843                    if selection.is_empty() && !line_mode {
 5844                        let cursor = movement::right(map, selection.head());
 5845                        selection.end = cursor;
 5846                        selection.reversed = true;
 5847                        selection.goal = SelectionGoal::None;
 5848                    }
 5849                })
 5850            });
 5851            this.insert("", window, cx);
 5852            this.refresh_inline_completion(true, false, window, cx);
 5853        });
 5854    }
 5855
 5856    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 5857        if self.move_to_prev_snippet_tabstop(window, cx) {
 5858            return;
 5859        }
 5860
 5861        self.outdent(&Outdent, window, cx);
 5862    }
 5863
 5864    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 5865        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 5866            return;
 5867        }
 5868
 5869        let mut selections = self.selections.all_adjusted(cx);
 5870        let buffer = self.buffer.read(cx);
 5871        let snapshot = buffer.snapshot(cx);
 5872        let rows_iter = selections.iter().map(|s| s.head().row);
 5873        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5874
 5875        let mut edits = Vec::new();
 5876        let mut prev_edited_row = 0;
 5877        let mut row_delta = 0;
 5878        for selection in &mut selections {
 5879            if selection.start.row != prev_edited_row {
 5880                row_delta = 0;
 5881            }
 5882            prev_edited_row = selection.end.row;
 5883
 5884            // If the selection is non-empty, then increase the indentation of the selected lines.
 5885            if !selection.is_empty() {
 5886                row_delta =
 5887                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5888                continue;
 5889            }
 5890
 5891            // If the selection is empty and the cursor is in the leading whitespace before the
 5892            // suggested indentation, then auto-indent the line.
 5893            let cursor = selection.head();
 5894            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5895            if let Some(suggested_indent) =
 5896                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5897            {
 5898                if cursor.column < suggested_indent.len
 5899                    && cursor.column <= current_indent.len
 5900                    && current_indent.len <= suggested_indent.len
 5901                {
 5902                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5903                    selection.end = selection.start;
 5904                    if row_delta == 0 {
 5905                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5906                            cursor.row,
 5907                            current_indent,
 5908                            suggested_indent,
 5909                        ));
 5910                        row_delta = suggested_indent.len - current_indent.len;
 5911                    }
 5912                    continue;
 5913                }
 5914            }
 5915
 5916            // Otherwise, insert a hard or soft tab.
 5917            let settings = buffer.settings_at(cursor, cx);
 5918            let tab_size = if settings.hard_tabs {
 5919                IndentSize::tab()
 5920            } else {
 5921                let tab_size = settings.tab_size.get();
 5922                let char_column = snapshot
 5923                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5924                    .flat_map(str::chars)
 5925                    .count()
 5926                    + row_delta as usize;
 5927                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5928                IndentSize::spaces(chars_to_next_tab_stop)
 5929            };
 5930            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5931            selection.end = selection.start;
 5932            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5933            row_delta += tab_size.len;
 5934        }
 5935
 5936        self.transact(window, cx, |this, window, cx| {
 5937            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5938            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5939                s.select(selections)
 5940            });
 5941            this.refresh_inline_completion(true, false, window, cx);
 5942        });
 5943    }
 5944
 5945    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 5946        if self.read_only(cx) {
 5947            return;
 5948        }
 5949        let mut selections = self.selections.all::<Point>(cx);
 5950        let mut prev_edited_row = 0;
 5951        let mut row_delta = 0;
 5952        let mut edits = Vec::new();
 5953        let buffer = self.buffer.read(cx);
 5954        let snapshot = buffer.snapshot(cx);
 5955        for selection in &mut selections {
 5956            if selection.start.row != prev_edited_row {
 5957                row_delta = 0;
 5958            }
 5959            prev_edited_row = selection.end.row;
 5960
 5961            row_delta =
 5962                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5963        }
 5964
 5965        self.transact(window, cx, |this, window, cx| {
 5966            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5967            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5968                s.select(selections)
 5969            });
 5970        });
 5971    }
 5972
 5973    fn indent_selection(
 5974        buffer: &MultiBuffer,
 5975        snapshot: &MultiBufferSnapshot,
 5976        selection: &mut Selection<Point>,
 5977        edits: &mut Vec<(Range<Point>, String)>,
 5978        delta_for_start_row: u32,
 5979        cx: &App,
 5980    ) -> u32 {
 5981        let settings = buffer.settings_at(selection.start, cx);
 5982        let tab_size = settings.tab_size.get();
 5983        let indent_kind = if settings.hard_tabs {
 5984            IndentKind::Tab
 5985        } else {
 5986            IndentKind::Space
 5987        };
 5988        let mut start_row = selection.start.row;
 5989        let mut end_row = selection.end.row + 1;
 5990
 5991        // If a selection ends at the beginning of a line, don't indent
 5992        // that last line.
 5993        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5994            end_row -= 1;
 5995        }
 5996
 5997        // Avoid re-indenting a row that has already been indented by a
 5998        // previous selection, but still update this selection's column
 5999        // to reflect that indentation.
 6000        if delta_for_start_row > 0 {
 6001            start_row += 1;
 6002            selection.start.column += delta_for_start_row;
 6003            if selection.end.row == selection.start.row {
 6004                selection.end.column += delta_for_start_row;
 6005            }
 6006        }
 6007
 6008        let mut delta_for_end_row = 0;
 6009        let has_multiple_rows = start_row + 1 != end_row;
 6010        for row in start_row..end_row {
 6011            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6012            let indent_delta = match (current_indent.kind, indent_kind) {
 6013                (IndentKind::Space, IndentKind::Space) => {
 6014                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6015                    IndentSize::spaces(columns_to_next_tab_stop)
 6016                }
 6017                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6018                (_, IndentKind::Tab) => IndentSize::tab(),
 6019            };
 6020
 6021            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6022                0
 6023            } else {
 6024                selection.start.column
 6025            };
 6026            let row_start = Point::new(row, start);
 6027            edits.push((
 6028                row_start..row_start,
 6029                indent_delta.chars().collect::<String>(),
 6030            ));
 6031
 6032            // Update this selection's endpoints to reflect the indentation.
 6033            if row == selection.start.row {
 6034                selection.start.column += indent_delta.len;
 6035            }
 6036            if row == selection.end.row {
 6037                selection.end.column += indent_delta.len;
 6038                delta_for_end_row = indent_delta.len;
 6039            }
 6040        }
 6041
 6042        if selection.start.row == selection.end.row {
 6043            delta_for_start_row + delta_for_end_row
 6044        } else {
 6045            delta_for_end_row
 6046        }
 6047    }
 6048
 6049    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6050        if self.read_only(cx) {
 6051            return;
 6052        }
 6053        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6054        let selections = self.selections.all::<Point>(cx);
 6055        let mut deletion_ranges = Vec::new();
 6056        let mut last_outdent = None;
 6057        {
 6058            let buffer = self.buffer.read(cx);
 6059            let snapshot = buffer.snapshot(cx);
 6060            for selection in &selections {
 6061                let settings = buffer.settings_at(selection.start, cx);
 6062                let tab_size = settings.tab_size.get();
 6063                let mut rows = selection.spanned_rows(false, &display_map);
 6064
 6065                // Avoid re-outdenting a row that has already been outdented by a
 6066                // previous selection.
 6067                if let Some(last_row) = last_outdent {
 6068                    if last_row == rows.start {
 6069                        rows.start = rows.start.next_row();
 6070                    }
 6071                }
 6072                let has_multiple_rows = rows.len() > 1;
 6073                for row in rows.iter_rows() {
 6074                    let indent_size = snapshot.indent_size_for_line(row);
 6075                    if indent_size.len > 0 {
 6076                        let deletion_len = match indent_size.kind {
 6077                            IndentKind::Space => {
 6078                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6079                                if columns_to_prev_tab_stop == 0 {
 6080                                    tab_size
 6081                                } else {
 6082                                    columns_to_prev_tab_stop
 6083                                }
 6084                            }
 6085                            IndentKind::Tab => 1,
 6086                        };
 6087                        let start = if has_multiple_rows
 6088                            || deletion_len > selection.start.column
 6089                            || indent_size.len < selection.start.column
 6090                        {
 6091                            0
 6092                        } else {
 6093                            selection.start.column - deletion_len
 6094                        };
 6095                        deletion_ranges.push(
 6096                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6097                        );
 6098                        last_outdent = Some(row);
 6099                    }
 6100                }
 6101            }
 6102        }
 6103
 6104        self.transact(window, cx, |this, window, cx| {
 6105            this.buffer.update(cx, |buffer, cx| {
 6106                let empty_str: Arc<str> = Arc::default();
 6107                buffer.edit(
 6108                    deletion_ranges
 6109                        .into_iter()
 6110                        .map(|range| (range, empty_str.clone())),
 6111                    None,
 6112                    cx,
 6113                );
 6114            });
 6115            let selections = this.selections.all::<usize>(cx);
 6116            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6117                s.select(selections)
 6118            });
 6119        });
 6120    }
 6121
 6122    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6123        if self.read_only(cx) {
 6124            return;
 6125        }
 6126        let selections = self
 6127            .selections
 6128            .all::<usize>(cx)
 6129            .into_iter()
 6130            .map(|s| s.range());
 6131
 6132        self.transact(window, cx, |this, window, cx| {
 6133            this.buffer.update(cx, |buffer, cx| {
 6134                buffer.autoindent_ranges(selections, cx);
 6135            });
 6136            let selections = this.selections.all::<usize>(cx);
 6137            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6138                s.select(selections)
 6139            });
 6140        });
 6141    }
 6142
 6143    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6145        let selections = self.selections.all::<Point>(cx);
 6146
 6147        let mut new_cursors = Vec::new();
 6148        let mut edit_ranges = Vec::new();
 6149        let mut selections = selections.iter().peekable();
 6150        while let Some(selection) = selections.next() {
 6151            let mut rows = selection.spanned_rows(false, &display_map);
 6152            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6153
 6154            // Accumulate contiguous regions of rows that we want to delete.
 6155            while let Some(next_selection) = selections.peek() {
 6156                let next_rows = next_selection.spanned_rows(false, &display_map);
 6157                if next_rows.start <= rows.end {
 6158                    rows.end = next_rows.end;
 6159                    selections.next().unwrap();
 6160                } else {
 6161                    break;
 6162                }
 6163            }
 6164
 6165            let buffer = &display_map.buffer_snapshot;
 6166            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6167            let edit_end;
 6168            let cursor_buffer_row;
 6169            if buffer.max_point().row >= rows.end.0 {
 6170                // If there's a line after the range, delete the \n from the end of the row range
 6171                // and position the cursor on the next line.
 6172                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6173                cursor_buffer_row = rows.end;
 6174            } else {
 6175                // If there isn't a line after the range, delete the \n from the line before the
 6176                // start of the row range and position the cursor there.
 6177                edit_start = edit_start.saturating_sub(1);
 6178                edit_end = buffer.len();
 6179                cursor_buffer_row = rows.start.previous_row();
 6180            }
 6181
 6182            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6183            *cursor.column_mut() =
 6184                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6185
 6186            new_cursors.push((
 6187                selection.id,
 6188                buffer.anchor_after(cursor.to_point(&display_map)),
 6189            ));
 6190            edit_ranges.push(edit_start..edit_end);
 6191        }
 6192
 6193        self.transact(window, cx, |this, window, cx| {
 6194            let buffer = this.buffer.update(cx, |buffer, cx| {
 6195                let empty_str: Arc<str> = Arc::default();
 6196                buffer.edit(
 6197                    edit_ranges
 6198                        .into_iter()
 6199                        .map(|range| (range, empty_str.clone())),
 6200                    None,
 6201                    cx,
 6202                );
 6203                buffer.snapshot(cx)
 6204            });
 6205            let new_selections = new_cursors
 6206                .into_iter()
 6207                .map(|(id, cursor)| {
 6208                    let cursor = cursor.to_point(&buffer);
 6209                    Selection {
 6210                        id,
 6211                        start: cursor,
 6212                        end: cursor,
 6213                        reversed: false,
 6214                        goal: SelectionGoal::None,
 6215                    }
 6216                })
 6217                .collect();
 6218
 6219            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6220                s.select(new_selections);
 6221            });
 6222        });
 6223    }
 6224
 6225    pub fn join_lines_impl(
 6226        &mut self,
 6227        insert_whitespace: bool,
 6228        window: &mut Window,
 6229        cx: &mut Context<Self>,
 6230    ) {
 6231        if self.read_only(cx) {
 6232            return;
 6233        }
 6234        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6235        for selection in self.selections.all::<Point>(cx) {
 6236            let start = MultiBufferRow(selection.start.row);
 6237            // Treat single line selections as if they include the next line. Otherwise this action
 6238            // would do nothing for single line selections individual cursors.
 6239            let end = if selection.start.row == selection.end.row {
 6240                MultiBufferRow(selection.start.row + 1)
 6241            } else {
 6242                MultiBufferRow(selection.end.row)
 6243            };
 6244
 6245            if let Some(last_row_range) = row_ranges.last_mut() {
 6246                if start <= last_row_range.end {
 6247                    last_row_range.end = end;
 6248                    continue;
 6249                }
 6250            }
 6251            row_ranges.push(start..end);
 6252        }
 6253
 6254        let snapshot = self.buffer.read(cx).snapshot(cx);
 6255        let mut cursor_positions = Vec::new();
 6256        for row_range in &row_ranges {
 6257            let anchor = snapshot.anchor_before(Point::new(
 6258                row_range.end.previous_row().0,
 6259                snapshot.line_len(row_range.end.previous_row()),
 6260            ));
 6261            cursor_positions.push(anchor..anchor);
 6262        }
 6263
 6264        self.transact(window, cx, |this, window, cx| {
 6265            for row_range in row_ranges.into_iter().rev() {
 6266                for row in row_range.iter_rows().rev() {
 6267                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6268                    let next_line_row = row.next_row();
 6269                    let indent = snapshot.indent_size_for_line(next_line_row);
 6270                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6271
 6272                    let replace =
 6273                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6274                            " "
 6275                        } else {
 6276                            ""
 6277                        };
 6278
 6279                    this.buffer.update(cx, |buffer, cx| {
 6280                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6281                    });
 6282                }
 6283            }
 6284
 6285            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6286                s.select_anchor_ranges(cursor_positions)
 6287            });
 6288        });
 6289    }
 6290
 6291    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6292        self.join_lines_impl(true, window, cx);
 6293    }
 6294
 6295    pub fn sort_lines_case_sensitive(
 6296        &mut self,
 6297        _: &SortLinesCaseSensitive,
 6298        window: &mut Window,
 6299        cx: &mut Context<Self>,
 6300    ) {
 6301        self.manipulate_lines(window, cx, |lines| lines.sort())
 6302    }
 6303
 6304    pub fn sort_lines_case_insensitive(
 6305        &mut self,
 6306        _: &SortLinesCaseInsensitive,
 6307        window: &mut Window,
 6308        cx: &mut Context<Self>,
 6309    ) {
 6310        self.manipulate_lines(window, cx, |lines| {
 6311            lines.sort_by_key(|line| line.to_lowercase())
 6312        })
 6313    }
 6314
 6315    pub fn unique_lines_case_insensitive(
 6316        &mut self,
 6317        _: &UniqueLinesCaseInsensitive,
 6318        window: &mut Window,
 6319        cx: &mut Context<Self>,
 6320    ) {
 6321        self.manipulate_lines(window, cx, |lines| {
 6322            let mut seen = HashSet::default();
 6323            lines.retain(|line| seen.insert(line.to_lowercase()));
 6324        })
 6325    }
 6326
 6327    pub fn unique_lines_case_sensitive(
 6328        &mut self,
 6329        _: &UniqueLinesCaseSensitive,
 6330        window: &mut Window,
 6331        cx: &mut Context<Self>,
 6332    ) {
 6333        self.manipulate_lines(window, cx, |lines| {
 6334            let mut seen = HashSet::default();
 6335            lines.retain(|line| seen.insert(*line));
 6336        })
 6337    }
 6338
 6339    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6340        let mut revert_changes = HashMap::default();
 6341        let snapshot = self.snapshot(window, cx);
 6342        for hunk in snapshot
 6343            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6344        {
 6345            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6346        }
 6347        if !revert_changes.is_empty() {
 6348            self.transact(window, cx, |editor, window, cx| {
 6349                editor.revert(revert_changes, window, cx);
 6350            });
 6351        }
 6352    }
 6353
 6354    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6355        let Some(project) = self.project.clone() else {
 6356            return;
 6357        };
 6358        self.reload(project, window, cx)
 6359            .detach_and_notify_err(window, cx);
 6360    }
 6361
 6362    pub fn revert_selected_hunks(
 6363        &mut self,
 6364        _: &RevertSelectedHunks,
 6365        window: &mut Window,
 6366        cx: &mut Context<Self>,
 6367    ) {
 6368        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6369        self.revert_hunks_in_ranges(selections, window, cx);
 6370    }
 6371
 6372    fn revert_hunks_in_ranges(
 6373        &mut self,
 6374        ranges: impl Iterator<Item = Range<Point>>,
 6375        window: &mut Window,
 6376        cx: &mut Context<Editor>,
 6377    ) {
 6378        let mut revert_changes = HashMap::default();
 6379        let snapshot = self.snapshot(window, cx);
 6380        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6381            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6382        }
 6383        if !revert_changes.is_empty() {
 6384            self.transact(window, cx, |editor, window, cx| {
 6385                editor.revert(revert_changes, window, cx);
 6386            });
 6387        }
 6388    }
 6389
 6390    pub fn open_active_item_in_terminal(
 6391        &mut self,
 6392        _: &OpenInTerminal,
 6393        window: &mut Window,
 6394        cx: &mut Context<Self>,
 6395    ) {
 6396        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6397            let project_path = buffer.read(cx).project_path(cx)?;
 6398            let project = self.project.as_ref()?.read(cx);
 6399            let entry = project.entry_for_path(&project_path, cx)?;
 6400            let parent = match &entry.canonical_path {
 6401                Some(canonical_path) => canonical_path.to_path_buf(),
 6402                None => project.absolute_path(&project_path, cx)?,
 6403            }
 6404            .parent()?
 6405            .to_path_buf();
 6406            Some(parent)
 6407        }) {
 6408            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6409        }
 6410    }
 6411
 6412    pub fn prepare_revert_change(
 6413        &self,
 6414        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6415        hunk: &MultiBufferDiffHunk,
 6416        cx: &mut App,
 6417    ) -> Option<()> {
 6418        let buffer = self.buffer.read(cx);
 6419        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6420        let buffer = buffer.buffer(hunk.buffer_id)?;
 6421        let buffer = buffer.read(cx);
 6422        let original_text = change_set
 6423            .read(cx)
 6424            .base_text
 6425            .as_ref()?
 6426            .as_rope()
 6427            .slice(hunk.diff_base_byte_range.clone());
 6428        let buffer_snapshot = buffer.snapshot();
 6429        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6430        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6431            probe
 6432                .0
 6433                .start
 6434                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6435                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6436        }) {
 6437            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6438            Some(())
 6439        } else {
 6440            None
 6441        }
 6442    }
 6443
 6444    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6445        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6446    }
 6447
 6448    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6449        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6450    }
 6451
 6452    fn manipulate_lines<Fn>(
 6453        &mut self,
 6454        window: &mut Window,
 6455        cx: &mut Context<Self>,
 6456        mut callback: Fn,
 6457    ) where
 6458        Fn: FnMut(&mut Vec<&str>),
 6459    {
 6460        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6461        let buffer = self.buffer.read(cx).snapshot(cx);
 6462
 6463        let mut edits = Vec::new();
 6464
 6465        let selections = self.selections.all::<Point>(cx);
 6466        let mut selections = selections.iter().peekable();
 6467        let mut contiguous_row_selections = Vec::new();
 6468        let mut new_selections = Vec::new();
 6469        let mut added_lines = 0;
 6470        let mut removed_lines = 0;
 6471
 6472        while let Some(selection) = selections.next() {
 6473            let (start_row, end_row) = consume_contiguous_rows(
 6474                &mut contiguous_row_selections,
 6475                selection,
 6476                &display_map,
 6477                &mut selections,
 6478            );
 6479
 6480            let start_point = Point::new(start_row.0, 0);
 6481            let end_point = Point::new(
 6482                end_row.previous_row().0,
 6483                buffer.line_len(end_row.previous_row()),
 6484            );
 6485            let text = buffer
 6486                .text_for_range(start_point..end_point)
 6487                .collect::<String>();
 6488
 6489            let mut lines = text.split('\n').collect_vec();
 6490
 6491            let lines_before = lines.len();
 6492            callback(&mut lines);
 6493            let lines_after = lines.len();
 6494
 6495            edits.push((start_point..end_point, lines.join("\n")));
 6496
 6497            // Selections must change based on added and removed line count
 6498            let start_row =
 6499                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6500            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6501            new_selections.push(Selection {
 6502                id: selection.id,
 6503                start: start_row,
 6504                end: end_row,
 6505                goal: SelectionGoal::None,
 6506                reversed: selection.reversed,
 6507            });
 6508
 6509            if lines_after > lines_before {
 6510                added_lines += lines_after - lines_before;
 6511            } else if lines_before > lines_after {
 6512                removed_lines += lines_before - lines_after;
 6513            }
 6514        }
 6515
 6516        self.transact(window, cx, |this, window, cx| {
 6517            let buffer = this.buffer.update(cx, |buffer, cx| {
 6518                buffer.edit(edits, None, cx);
 6519                buffer.snapshot(cx)
 6520            });
 6521
 6522            // Recalculate offsets on newly edited buffer
 6523            let new_selections = new_selections
 6524                .iter()
 6525                .map(|s| {
 6526                    let start_point = Point::new(s.start.0, 0);
 6527                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6528                    Selection {
 6529                        id: s.id,
 6530                        start: buffer.point_to_offset(start_point),
 6531                        end: buffer.point_to_offset(end_point),
 6532                        goal: s.goal,
 6533                        reversed: s.reversed,
 6534                    }
 6535                })
 6536                .collect();
 6537
 6538            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6539                s.select(new_selections);
 6540            });
 6541
 6542            this.request_autoscroll(Autoscroll::fit(), cx);
 6543        });
 6544    }
 6545
 6546    pub fn convert_to_upper_case(
 6547        &mut self,
 6548        _: &ConvertToUpperCase,
 6549        window: &mut Window,
 6550        cx: &mut Context<Self>,
 6551    ) {
 6552        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6553    }
 6554
 6555    pub fn convert_to_lower_case(
 6556        &mut self,
 6557        _: &ConvertToLowerCase,
 6558        window: &mut Window,
 6559        cx: &mut Context<Self>,
 6560    ) {
 6561        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6562    }
 6563
 6564    pub fn convert_to_title_case(
 6565        &mut self,
 6566        _: &ConvertToTitleCase,
 6567        window: &mut Window,
 6568        cx: &mut Context<Self>,
 6569    ) {
 6570        self.manipulate_text(window, cx, |text| {
 6571            text.split('\n')
 6572                .map(|line| line.to_case(Case::Title))
 6573                .join("\n")
 6574        })
 6575    }
 6576
 6577    pub fn convert_to_snake_case(
 6578        &mut self,
 6579        _: &ConvertToSnakeCase,
 6580        window: &mut Window,
 6581        cx: &mut Context<Self>,
 6582    ) {
 6583        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6584    }
 6585
 6586    pub fn convert_to_kebab_case(
 6587        &mut self,
 6588        _: &ConvertToKebabCase,
 6589        window: &mut Window,
 6590        cx: &mut Context<Self>,
 6591    ) {
 6592        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6593    }
 6594
 6595    pub fn convert_to_upper_camel_case(
 6596        &mut self,
 6597        _: &ConvertToUpperCamelCase,
 6598        window: &mut Window,
 6599        cx: &mut Context<Self>,
 6600    ) {
 6601        self.manipulate_text(window, cx, |text| {
 6602            text.split('\n')
 6603                .map(|line| line.to_case(Case::UpperCamel))
 6604                .join("\n")
 6605        })
 6606    }
 6607
 6608    pub fn convert_to_lower_camel_case(
 6609        &mut self,
 6610        _: &ConvertToLowerCamelCase,
 6611        window: &mut Window,
 6612        cx: &mut Context<Self>,
 6613    ) {
 6614        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6615    }
 6616
 6617    pub fn convert_to_opposite_case(
 6618        &mut self,
 6619        _: &ConvertToOppositeCase,
 6620        window: &mut Window,
 6621        cx: &mut Context<Self>,
 6622    ) {
 6623        self.manipulate_text(window, cx, |text| {
 6624            text.chars()
 6625                .fold(String::with_capacity(text.len()), |mut t, c| {
 6626                    if c.is_uppercase() {
 6627                        t.extend(c.to_lowercase());
 6628                    } else {
 6629                        t.extend(c.to_uppercase());
 6630                    }
 6631                    t
 6632                })
 6633        })
 6634    }
 6635
 6636    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6637    where
 6638        Fn: FnMut(&str) -> String,
 6639    {
 6640        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6641        let buffer = self.buffer.read(cx).snapshot(cx);
 6642
 6643        let mut new_selections = Vec::new();
 6644        let mut edits = Vec::new();
 6645        let mut selection_adjustment = 0i32;
 6646
 6647        for selection in self.selections.all::<usize>(cx) {
 6648            let selection_is_empty = selection.is_empty();
 6649
 6650            let (start, end) = if selection_is_empty {
 6651                let word_range = movement::surrounding_word(
 6652                    &display_map,
 6653                    selection.start.to_display_point(&display_map),
 6654                );
 6655                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6656                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6657                (start, end)
 6658            } else {
 6659                (selection.start, selection.end)
 6660            };
 6661
 6662            let text = buffer.text_for_range(start..end).collect::<String>();
 6663            let old_length = text.len() as i32;
 6664            let text = callback(&text);
 6665
 6666            new_selections.push(Selection {
 6667                start: (start as i32 - selection_adjustment) as usize,
 6668                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6669                goal: SelectionGoal::None,
 6670                ..selection
 6671            });
 6672
 6673            selection_adjustment += old_length - text.len() as i32;
 6674
 6675            edits.push((start..end, text));
 6676        }
 6677
 6678        self.transact(window, cx, |this, window, cx| {
 6679            this.buffer.update(cx, |buffer, cx| {
 6680                buffer.edit(edits, None, cx);
 6681            });
 6682
 6683            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6684                s.select(new_selections);
 6685            });
 6686
 6687            this.request_autoscroll(Autoscroll::fit(), cx);
 6688        });
 6689    }
 6690
 6691    pub fn duplicate(
 6692        &mut self,
 6693        upwards: bool,
 6694        whole_lines: bool,
 6695        window: &mut Window,
 6696        cx: &mut Context<Self>,
 6697    ) {
 6698        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6699        let buffer = &display_map.buffer_snapshot;
 6700        let selections = self.selections.all::<Point>(cx);
 6701
 6702        let mut edits = Vec::new();
 6703        let mut selections_iter = selections.iter().peekable();
 6704        while let Some(selection) = selections_iter.next() {
 6705            let mut rows = selection.spanned_rows(false, &display_map);
 6706            // duplicate line-wise
 6707            if whole_lines || selection.start == selection.end {
 6708                // Avoid duplicating the same lines twice.
 6709                while let Some(next_selection) = selections_iter.peek() {
 6710                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6711                    if next_rows.start < rows.end {
 6712                        rows.end = next_rows.end;
 6713                        selections_iter.next().unwrap();
 6714                    } else {
 6715                        break;
 6716                    }
 6717                }
 6718
 6719                // Copy the text from the selected row region and splice it either at the start
 6720                // or end of the region.
 6721                let start = Point::new(rows.start.0, 0);
 6722                let end = Point::new(
 6723                    rows.end.previous_row().0,
 6724                    buffer.line_len(rows.end.previous_row()),
 6725                );
 6726                let text = buffer
 6727                    .text_for_range(start..end)
 6728                    .chain(Some("\n"))
 6729                    .collect::<String>();
 6730                let insert_location = if upwards {
 6731                    Point::new(rows.end.0, 0)
 6732                } else {
 6733                    start
 6734                };
 6735                edits.push((insert_location..insert_location, text));
 6736            } else {
 6737                // duplicate character-wise
 6738                let start = selection.start;
 6739                let end = selection.end;
 6740                let text = buffer.text_for_range(start..end).collect::<String>();
 6741                edits.push((selection.end..selection.end, text));
 6742            }
 6743        }
 6744
 6745        self.transact(window, cx, |this, _, cx| {
 6746            this.buffer.update(cx, |buffer, cx| {
 6747                buffer.edit(edits, None, cx);
 6748            });
 6749
 6750            this.request_autoscroll(Autoscroll::fit(), cx);
 6751        });
 6752    }
 6753
 6754    pub fn duplicate_line_up(
 6755        &mut self,
 6756        _: &DuplicateLineUp,
 6757        window: &mut Window,
 6758        cx: &mut Context<Self>,
 6759    ) {
 6760        self.duplicate(true, true, window, cx);
 6761    }
 6762
 6763    pub fn duplicate_line_down(
 6764        &mut self,
 6765        _: &DuplicateLineDown,
 6766        window: &mut Window,
 6767        cx: &mut Context<Self>,
 6768    ) {
 6769        self.duplicate(false, true, window, cx);
 6770    }
 6771
 6772    pub fn duplicate_selection(
 6773        &mut self,
 6774        _: &DuplicateSelection,
 6775        window: &mut Window,
 6776        cx: &mut Context<Self>,
 6777    ) {
 6778        self.duplicate(false, false, window, cx);
 6779    }
 6780
 6781    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 6782        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6783        let buffer = self.buffer.read(cx).snapshot(cx);
 6784
 6785        let mut edits = Vec::new();
 6786        let mut unfold_ranges = Vec::new();
 6787        let mut refold_creases = Vec::new();
 6788
 6789        let selections = self.selections.all::<Point>(cx);
 6790        let mut selections = selections.iter().peekable();
 6791        let mut contiguous_row_selections = Vec::new();
 6792        let mut new_selections = Vec::new();
 6793
 6794        while let Some(selection) = selections.next() {
 6795            // Find all the selections that span a contiguous row range
 6796            let (start_row, end_row) = consume_contiguous_rows(
 6797                &mut contiguous_row_selections,
 6798                selection,
 6799                &display_map,
 6800                &mut selections,
 6801            );
 6802
 6803            // Move the text spanned by the row range to be before the line preceding the row range
 6804            if start_row.0 > 0 {
 6805                let range_to_move = Point::new(
 6806                    start_row.previous_row().0,
 6807                    buffer.line_len(start_row.previous_row()),
 6808                )
 6809                    ..Point::new(
 6810                        end_row.previous_row().0,
 6811                        buffer.line_len(end_row.previous_row()),
 6812                    );
 6813                let insertion_point = display_map
 6814                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6815                    .0;
 6816
 6817                // Don't move lines across excerpts
 6818                if buffer
 6819                    .excerpt_containing(insertion_point..range_to_move.end)
 6820                    .is_some()
 6821                {
 6822                    let text = buffer
 6823                        .text_for_range(range_to_move.clone())
 6824                        .flat_map(|s| s.chars())
 6825                        .skip(1)
 6826                        .chain(['\n'])
 6827                        .collect::<String>();
 6828
 6829                    edits.push((
 6830                        buffer.anchor_after(range_to_move.start)
 6831                            ..buffer.anchor_before(range_to_move.end),
 6832                        String::new(),
 6833                    ));
 6834                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6835                    edits.push((insertion_anchor..insertion_anchor, text));
 6836
 6837                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6838
 6839                    // Move selections up
 6840                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6841                        |mut selection| {
 6842                            selection.start.row -= row_delta;
 6843                            selection.end.row -= row_delta;
 6844                            selection
 6845                        },
 6846                    ));
 6847
 6848                    // Move folds up
 6849                    unfold_ranges.push(range_to_move.clone());
 6850                    for fold in display_map.folds_in_range(
 6851                        buffer.anchor_before(range_to_move.start)
 6852                            ..buffer.anchor_after(range_to_move.end),
 6853                    ) {
 6854                        let mut start = fold.range.start.to_point(&buffer);
 6855                        let mut end = fold.range.end.to_point(&buffer);
 6856                        start.row -= row_delta;
 6857                        end.row -= row_delta;
 6858                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6859                    }
 6860                }
 6861            }
 6862
 6863            // If we didn't move line(s), preserve the existing selections
 6864            new_selections.append(&mut contiguous_row_selections);
 6865        }
 6866
 6867        self.transact(window, cx, |this, window, cx| {
 6868            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6869            this.buffer.update(cx, |buffer, cx| {
 6870                for (range, text) in edits {
 6871                    buffer.edit([(range, text)], None, cx);
 6872                }
 6873            });
 6874            this.fold_creases(refold_creases, true, window, cx);
 6875            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6876                s.select(new_selections);
 6877            })
 6878        });
 6879    }
 6880
 6881    pub fn move_line_down(
 6882        &mut self,
 6883        _: &MoveLineDown,
 6884        window: &mut Window,
 6885        cx: &mut Context<Self>,
 6886    ) {
 6887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6888        let buffer = self.buffer.read(cx).snapshot(cx);
 6889
 6890        let mut edits = Vec::new();
 6891        let mut unfold_ranges = Vec::new();
 6892        let mut refold_creases = Vec::new();
 6893
 6894        let selections = self.selections.all::<Point>(cx);
 6895        let mut selections = selections.iter().peekable();
 6896        let mut contiguous_row_selections = Vec::new();
 6897        let mut new_selections = Vec::new();
 6898
 6899        while let Some(selection) = selections.next() {
 6900            // Find all the selections that span a contiguous row range
 6901            let (start_row, end_row) = consume_contiguous_rows(
 6902                &mut contiguous_row_selections,
 6903                selection,
 6904                &display_map,
 6905                &mut selections,
 6906            );
 6907
 6908            // Move the text spanned by the row range to be after the last line of the row range
 6909            if end_row.0 <= buffer.max_point().row {
 6910                let range_to_move =
 6911                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6912                let insertion_point = display_map
 6913                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6914                    .0;
 6915
 6916                // Don't move lines across excerpt boundaries
 6917                if buffer
 6918                    .excerpt_containing(range_to_move.start..insertion_point)
 6919                    .is_some()
 6920                {
 6921                    let mut text = String::from("\n");
 6922                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6923                    text.pop(); // Drop trailing newline
 6924                    edits.push((
 6925                        buffer.anchor_after(range_to_move.start)
 6926                            ..buffer.anchor_before(range_to_move.end),
 6927                        String::new(),
 6928                    ));
 6929                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6930                    edits.push((insertion_anchor..insertion_anchor, text));
 6931
 6932                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6933
 6934                    // Move selections down
 6935                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6936                        |mut selection| {
 6937                            selection.start.row += row_delta;
 6938                            selection.end.row += row_delta;
 6939                            selection
 6940                        },
 6941                    ));
 6942
 6943                    // Move folds down
 6944                    unfold_ranges.push(range_to_move.clone());
 6945                    for fold in display_map.folds_in_range(
 6946                        buffer.anchor_before(range_to_move.start)
 6947                            ..buffer.anchor_after(range_to_move.end),
 6948                    ) {
 6949                        let mut start = fold.range.start.to_point(&buffer);
 6950                        let mut end = fold.range.end.to_point(&buffer);
 6951                        start.row += row_delta;
 6952                        end.row += row_delta;
 6953                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6954                    }
 6955                }
 6956            }
 6957
 6958            // If we didn't move line(s), preserve the existing selections
 6959            new_selections.append(&mut contiguous_row_selections);
 6960        }
 6961
 6962        self.transact(window, cx, |this, window, cx| {
 6963            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6964            this.buffer.update(cx, |buffer, cx| {
 6965                for (range, text) in edits {
 6966                    buffer.edit([(range, text)], None, cx);
 6967                }
 6968            });
 6969            this.fold_creases(refold_creases, true, window, cx);
 6970            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6971                s.select(new_selections)
 6972            });
 6973        });
 6974    }
 6975
 6976    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 6977        let text_layout_details = &self.text_layout_details(window);
 6978        self.transact(window, cx, |this, window, cx| {
 6979            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6980                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6981                let line_mode = s.line_mode;
 6982                s.move_with(|display_map, selection| {
 6983                    if !selection.is_empty() || line_mode {
 6984                        return;
 6985                    }
 6986
 6987                    let mut head = selection.head();
 6988                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6989                    if head.column() == display_map.line_len(head.row()) {
 6990                        transpose_offset = display_map
 6991                            .buffer_snapshot
 6992                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6993                    }
 6994
 6995                    if transpose_offset == 0 {
 6996                        return;
 6997                    }
 6998
 6999                    *head.column_mut() += 1;
 7000                    head = display_map.clip_point(head, Bias::Right);
 7001                    let goal = SelectionGoal::HorizontalPosition(
 7002                        display_map
 7003                            .x_for_display_point(head, text_layout_details)
 7004                            .into(),
 7005                    );
 7006                    selection.collapse_to(head, goal);
 7007
 7008                    let transpose_start = display_map
 7009                        .buffer_snapshot
 7010                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7011                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7012                        let transpose_end = display_map
 7013                            .buffer_snapshot
 7014                            .clip_offset(transpose_offset + 1, Bias::Right);
 7015                        if let Some(ch) =
 7016                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7017                        {
 7018                            edits.push((transpose_start..transpose_offset, String::new()));
 7019                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7020                        }
 7021                    }
 7022                });
 7023                edits
 7024            });
 7025            this.buffer
 7026                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7027            let selections = this.selections.all::<usize>(cx);
 7028            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7029                s.select(selections);
 7030            });
 7031        });
 7032    }
 7033
 7034    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7035        self.rewrap_impl(IsVimMode::No, cx)
 7036    }
 7037
 7038    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7039        let buffer = self.buffer.read(cx).snapshot(cx);
 7040        let selections = self.selections.all::<Point>(cx);
 7041        let mut selections = selections.iter().peekable();
 7042
 7043        let mut edits = Vec::new();
 7044        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7045
 7046        while let Some(selection) = selections.next() {
 7047            let mut start_row = selection.start.row;
 7048            let mut end_row = selection.end.row;
 7049
 7050            // Skip selections that overlap with a range that has already been rewrapped.
 7051            let selection_range = start_row..end_row;
 7052            if rewrapped_row_ranges
 7053                .iter()
 7054                .any(|range| range.overlaps(&selection_range))
 7055            {
 7056                continue;
 7057            }
 7058
 7059            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7060
 7061            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7062                match language_scope.language_name().as_ref() {
 7063                    "Markdown" | "Plain Text" => {
 7064                        should_rewrap = true;
 7065                    }
 7066                    _ => {}
 7067                }
 7068            }
 7069
 7070            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7071
 7072            // Since not all lines in the selection may be at the same indent
 7073            // level, choose the indent size that is the most common between all
 7074            // of the lines.
 7075            //
 7076            // If there is a tie, we use the deepest indent.
 7077            let (indent_size, indent_end) = {
 7078                let mut indent_size_occurrences = HashMap::default();
 7079                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7080
 7081                for row in start_row..=end_row {
 7082                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7083                    rows_by_indent_size.entry(indent).or_default().push(row);
 7084                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7085                }
 7086
 7087                let indent_size = indent_size_occurrences
 7088                    .into_iter()
 7089                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7090                    .map(|(indent, _)| indent)
 7091                    .unwrap_or_default();
 7092                let row = rows_by_indent_size[&indent_size][0];
 7093                let indent_end = Point::new(row, indent_size.len);
 7094
 7095                (indent_size, indent_end)
 7096            };
 7097
 7098            let mut line_prefix = indent_size.chars().collect::<String>();
 7099
 7100            if let Some(comment_prefix) =
 7101                buffer
 7102                    .language_scope_at(selection.head())
 7103                    .and_then(|language| {
 7104                        language
 7105                            .line_comment_prefixes()
 7106                            .iter()
 7107                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7108                            .cloned()
 7109                    })
 7110            {
 7111                line_prefix.push_str(&comment_prefix);
 7112                should_rewrap = true;
 7113            }
 7114
 7115            if !should_rewrap {
 7116                continue;
 7117            }
 7118
 7119            if selection.is_empty() {
 7120                'expand_upwards: while start_row > 0 {
 7121                    let prev_row = start_row - 1;
 7122                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7123                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7124                    {
 7125                        start_row = prev_row;
 7126                    } else {
 7127                        break 'expand_upwards;
 7128                    }
 7129                }
 7130
 7131                'expand_downwards: while end_row < buffer.max_point().row {
 7132                    let next_row = end_row + 1;
 7133                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7134                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7135                    {
 7136                        end_row = next_row;
 7137                    } else {
 7138                        break 'expand_downwards;
 7139                    }
 7140                }
 7141            }
 7142
 7143            let start = Point::new(start_row, 0);
 7144            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7145            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7146            let Some(lines_without_prefixes) = selection_text
 7147                .lines()
 7148                .map(|line| {
 7149                    line.strip_prefix(&line_prefix)
 7150                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7151                        .ok_or_else(|| {
 7152                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7153                        })
 7154                })
 7155                .collect::<Result<Vec<_>, _>>()
 7156                .log_err()
 7157            else {
 7158                continue;
 7159            };
 7160
 7161            let wrap_column = buffer
 7162                .settings_at(Point::new(start_row, 0), cx)
 7163                .preferred_line_length as usize;
 7164            let wrapped_text = wrap_with_prefix(
 7165                line_prefix,
 7166                lines_without_prefixes.join(" "),
 7167                wrap_column,
 7168                tab_size,
 7169            );
 7170
 7171            // TODO: should always use char-based diff while still supporting cursor behavior that
 7172            // matches vim.
 7173            let diff = match is_vim_mode {
 7174                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7175                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7176            };
 7177            let mut offset = start.to_offset(&buffer);
 7178            let mut moved_since_edit = true;
 7179
 7180            for change in diff.iter_all_changes() {
 7181                let value = change.value();
 7182                match change.tag() {
 7183                    ChangeTag::Equal => {
 7184                        offset += value.len();
 7185                        moved_since_edit = true;
 7186                    }
 7187                    ChangeTag::Delete => {
 7188                        let start = buffer.anchor_after(offset);
 7189                        let end = buffer.anchor_before(offset + value.len());
 7190
 7191                        if moved_since_edit {
 7192                            edits.push((start..end, String::new()));
 7193                        } else {
 7194                            edits.last_mut().unwrap().0.end = end;
 7195                        }
 7196
 7197                        offset += value.len();
 7198                        moved_since_edit = false;
 7199                    }
 7200                    ChangeTag::Insert => {
 7201                        if moved_since_edit {
 7202                            let anchor = buffer.anchor_after(offset);
 7203                            edits.push((anchor..anchor, value.to_string()));
 7204                        } else {
 7205                            edits.last_mut().unwrap().1.push_str(value);
 7206                        }
 7207
 7208                        moved_since_edit = false;
 7209                    }
 7210                }
 7211            }
 7212
 7213            rewrapped_row_ranges.push(start_row..=end_row);
 7214        }
 7215
 7216        self.buffer
 7217            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7218    }
 7219
 7220    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7221        let mut text = String::new();
 7222        let buffer = self.buffer.read(cx).snapshot(cx);
 7223        let mut selections = self.selections.all::<Point>(cx);
 7224        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7225        {
 7226            let max_point = buffer.max_point();
 7227            let mut is_first = true;
 7228            for selection in &mut selections {
 7229                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7230                if is_entire_line {
 7231                    selection.start = Point::new(selection.start.row, 0);
 7232                    if !selection.is_empty() && selection.end.column == 0 {
 7233                        selection.end = cmp::min(max_point, selection.end);
 7234                    } else {
 7235                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7236                    }
 7237                    selection.goal = SelectionGoal::None;
 7238                }
 7239                if is_first {
 7240                    is_first = false;
 7241                } else {
 7242                    text += "\n";
 7243                }
 7244                let mut len = 0;
 7245                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7246                    text.push_str(chunk);
 7247                    len += chunk.len();
 7248                }
 7249                clipboard_selections.push(ClipboardSelection {
 7250                    len,
 7251                    is_entire_line,
 7252                    first_line_indent: buffer
 7253                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7254                        .len,
 7255                });
 7256            }
 7257        }
 7258
 7259        self.transact(window, cx, |this, window, cx| {
 7260            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7261                s.select(selections);
 7262            });
 7263            this.insert("", window, cx);
 7264        });
 7265        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7266    }
 7267
 7268    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7269        let item = self.cut_common(window, cx);
 7270        cx.write_to_clipboard(item);
 7271    }
 7272
 7273    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7274        self.change_selections(None, window, cx, |s| {
 7275            s.move_with(|snapshot, sel| {
 7276                if sel.is_empty() {
 7277                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7278                }
 7279            });
 7280        });
 7281        let item = self.cut_common(window, cx);
 7282        cx.set_global(KillRing(item))
 7283    }
 7284
 7285    pub fn kill_ring_yank(
 7286        &mut self,
 7287        _: &KillRingYank,
 7288        window: &mut Window,
 7289        cx: &mut Context<Self>,
 7290    ) {
 7291        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7292            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7293                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7294            } else {
 7295                return;
 7296            }
 7297        } else {
 7298            return;
 7299        };
 7300        self.do_paste(&text, metadata, false, window, cx);
 7301    }
 7302
 7303    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7304        let selections = self.selections.all::<Point>(cx);
 7305        let buffer = self.buffer.read(cx).read(cx);
 7306        let mut text = String::new();
 7307
 7308        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7309        {
 7310            let max_point = buffer.max_point();
 7311            let mut is_first = true;
 7312            for selection in selections.iter() {
 7313                let mut start = selection.start;
 7314                let mut end = selection.end;
 7315                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7316                if is_entire_line {
 7317                    start = Point::new(start.row, 0);
 7318                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7319                }
 7320                if is_first {
 7321                    is_first = false;
 7322                } else {
 7323                    text += "\n";
 7324                }
 7325                let mut len = 0;
 7326                for chunk in buffer.text_for_range(start..end) {
 7327                    text.push_str(chunk);
 7328                    len += chunk.len();
 7329                }
 7330                clipboard_selections.push(ClipboardSelection {
 7331                    len,
 7332                    is_entire_line,
 7333                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7334                });
 7335            }
 7336        }
 7337
 7338        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7339            text,
 7340            clipboard_selections,
 7341        ));
 7342    }
 7343
 7344    pub fn do_paste(
 7345        &mut self,
 7346        text: &String,
 7347        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7348        handle_entire_lines: bool,
 7349        window: &mut Window,
 7350        cx: &mut Context<Self>,
 7351    ) {
 7352        if self.read_only(cx) {
 7353            return;
 7354        }
 7355
 7356        let clipboard_text = Cow::Borrowed(text);
 7357
 7358        self.transact(window, cx, |this, window, cx| {
 7359            if let Some(mut clipboard_selections) = clipboard_selections {
 7360                let old_selections = this.selections.all::<usize>(cx);
 7361                let all_selections_were_entire_line =
 7362                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7363                let first_selection_indent_column =
 7364                    clipboard_selections.first().map(|s| s.first_line_indent);
 7365                if clipboard_selections.len() != old_selections.len() {
 7366                    clipboard_selections.drain(..);
 7367                }
 7368                let cursor_offset = this.selections.last::<usize>(cx).head();
 7369                let mut auto_indent_on_paste = true;
 7370
 7371                this.buffer.update(cx, |buffer, cx| {
 7372                    let snapshot = buffer.read(cx);
 7373                    auto_indent_on_paste =
 7374                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7375
 7376                    let mut start_offset = 0;
 7377                    let mut edits = Vec::new();
 7378                    let mut original_indent_columns = Vec::new();
 7379                    for (ix, selection) in old_selections.iter().enumerate() {
 7380                        let to_insert;
 7381                        let entire_line;
 7382                        let original_indent_column;
 7383                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7384                            let end_offset = start_offset + clipboard_selection.len;
 7385                            to_insert = &clipboard_text[start_offset..end_offset];
 7386                            entire_line = clipboard_selection.is_entire_line;
 7387                            start_offset = end_offset + 1;
 7388                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7389                        } else {
 7390                            to_insert = clipboard_text.as_str();
 7391                            entire_line = all_selections_were_entire_line;
 7392                            original_indent_column = first_selection_indent_column
 7393                        }
 7394
 7395                        // If the corresponding selection was empty when this slice of the
 7396                        // clipboard text was written, then the entire line containing the
 7397                        // selection was copied. If this selection is also currently empty,
 7398                        // then paste the line before the current line of the buffer.
 7399                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7400                            let column = selection.start.to_point(&snapshot).column as usize;
 7401                            let line_start = selection.start - column;
 7402                            line_start..line_start
 7403                        } else {
 7404                            selection.range()
 7405                        };
 7406
 7407                        edits.push((range, to_insert));
 7408                        original_indent_columns.extend(original_indent_column);
 7409                    }
 7410                    drop(snapshot);
 7411
 7412                    buffer.edit(
 7413                        edits,
 7414                        if auto_indent_on_paste {
 7415                            Some(AutoindentMode::Block {
 7416                                original_indent_columns,
 7417                            })
 7418                        } else {
 7419                            None
 7420                        },
 7421                        cx,
 7422                    );
 7423                });
 7424
 7425                let selections = this.selections.all::<usize>(cx);
 7426                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7427                    s.select(selections)
 7428                });
 7429            } else {
 7430                this.insert(&clipboard_text, window, cx);
 7431            }
 7432        });
 7433    }
 7434
 7435    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7436        if let Some(item) = cx.read_from_clipboard() {
 7437            let entries = item.entries();
 7438
 7439            match entries.first() {
 7440                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7441                // of all the pasted entries.
 7442                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7443                    .do_paste(
 7444                        clipboard_string.text(),
 7445                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7446                        true,
 7447                        window,
 7448                        cx,
 7449                    ),
 7450                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7451            }
 7452        }
 7453    }
 7454
 7455    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7456        if self.read_only(cx) {
 7457            return;
 7458        }
 7459
 7460        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7461            if let Some((selections, _)) =
 7462                self.selection_history.transaction(transaction_id).cloned()
 7463            {
 7464                self.change_selections(None, window, cx, |s| {
 7465                    s.select_anchors(selections.to_vec());
 7466                });
 7467            }
 7468            self.request_autoscroll(Autoscroll::fit(), cx);
 7469            self.unmark_text(window, cx);
 7470            self.refresh_inline_completion(true, false, window, cx);
 7471            cx.emit(EditorEvent::Edited { transaction_id });
 7472            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7473        }
 7474    }
 7475
 7476    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7477        if self.read_only(cx) {
 7478            return;
 7479        }
 7480
 7481        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7482            if let Some((_, Some(selections))) =
 7483                self.selection_history.transaction(transaction_id).cloned()
 7484            {
 7485                self.change_selections(None, window, cx, |s| {
 7486                    s.select_anchors(selections.to_vec());
 7487                });
 7488            }
 7489            self.request_autoscroll(Autoscroll::fit(), cx);
 7490            self.unmark_text(window, cx);
 7491            self.refresh_inline_completion(true, false, window, cx);
 7492            cx.emit(EditorEvent::Edited { transaction_id });
 7493        }
 7494    }
 7495
 7496    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7497        self.buffer
 7498            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7499    }
 7500
 7501    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7502        self.buffer
 7503            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7504    }
 7505
 7506    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7507        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7508            let line_mode = s.line_mode;
 7509            s.move_with(|map, selection| {
 7510                let cursor = if selection.is_empty() && !line_mode {
 7511                    movement::left(map, selection.start)
 7512                } else {
 7513                    selection.start
 7514                };
 7515                selection.collapse_to(cursor, SelectionGoal::None);
 7516            });
 7517        })
 7518    }
 7519
 7520    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7521        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7522            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7523        })
 7524    }
 7525
 7526    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7527        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7528            let line_mode = s.line_mode;
 7529            s.move_with(|map, selection| {
 7530                let cursor = if selection.is_empty() && !line_mode {
 7531                    movement::right(map, selection.end)
 7532                } else {
 7533                    selection.end
 7534                };
 7535                selection.collapse_to(cursor, SelectionGoal::None)
 7536            });
 7537        })
 7538    }
 7539
 7540    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7541        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7542            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7543        })
 7544    }
 7545
 7546    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7547        if self.take_rename(true, window, cx).is_some() {
 7548            return;
 7549        }
 7550
 7551        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7552            cx.propagate();
 7553            return;
 7554        }
 7555
 7556        let text_layout_details = &self.text_layout_details(window);
 7557        let selection_count = self.selections.count();
 7558        let first_selection = self.selections.first_anchor();
 7559
 7560        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7561            let line_mode = s.line_mode;
 7562            s.move_with(|map, selection| {
 7563                if !selection.is_empty() && !line_mode {
 7564                    selection.goal = SelectionGoal::None;
 7565                }
 7566                let (cursor, goal) = movement::up(
 7567                    map,
 7568                    selection.start,
 7569                    selection.goal,
 7570                    false,
 7571                    text_layout_details,
 7572                );
 7573                selection.collapse_to(cursor, goal);
 7574            });
 7575        });
 7576
 7577        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7578        {
 7579            cx.propagate();
 7580        }
 7581    }
 7582
 7583    pub fn move_up_by_lines(
 7584        &mut self,
 7585        action: &MoveUpByLines,
 7586        window: &mut Window,
 7587        cx: &mut Context<Self>,
 7588    ) {
 7589        if self.take_rename(true, window, cx).is_some() {
 7590            return;
 7591        }
 7592
 7593        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7594            cx.propagate();
 7595            return;
 7596        }
 7597
 7598        let text_layout_details = &self.text_layout_details(window);
 7599
 7600        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7601            let line_mode = s.line_mode;
 7602            s.move_with(|map, selection| {
 7603                if !selection.is_empty() && !line_mode {
 7604                    selection.goal = SelectionGoal::None;
 7605                }
 7606                let (cursor, goal) = movement::up_by_rows(
 7607                    map,
 7608                    selection.start,
 7609                    action.lines,
 7610                    selection.goal,
 7611                    false,
 7612                    text_layout_details,
 7613                );
 7614                selection.collapse_to(cursor, goal);
 7615            });
 7616        })
 7617    }
 7618
 7619    pub fn move_down_by_lines(
 7620        &mut self,
 7621        action: &MoveDownByLines,
 7622        window: &mut Window,
 7623        cx: &mut Context<Self>,
 7624    ) {
 7625        if self.take_rename(true, window, cx).is_some() {
 7626            return;
 7627        }
 7628
 7629        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7630            cx.propagate();
 7631            return;
 7632        }
 7633
 7634        let text_layout_details = &self.text_layout_details(window);
 7635
 7636        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7637            let line_mode = s.line_mode;
 7638            s.move_with(|map, selection| {
 7639                if !selection.is_empty() && !line_mode {
 7640                    selection.goal = SelectionGoal::None;
 7641                }
 7642                let (cursor, goal) = movement::down_by_rows(
 7643                    map,
 7644                    selection.start,
 7645                    action.lines,
 7646                    selection.goal,
 7647                    false,
 7648                    text_layout_details,
 7649                );
 7650                selection.collapse_to(cursor, goal);
 7651            });
 7652        })
 7653    }
 7654
 7655    pub fn select_down_by_lines(
 7656        &mut self,
 7657        action: &SelectDownByLines,
 7658        window: &mut Window,
 7659        cx: &mut Context<Self>,
 7660    ) {
 7661        let text_layout_details = &self.text_layout_details(window);
 7662        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7663            s.move_heads_with(|map, head, goal| {
 7664                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7665            })
 7666        })
 7667    }
 7668
 7669    pub fn select_up_by_lines(
 7670        &mut self,
 7671        action: &SelectUpByLines,
 7672        window: &mut Window,
 7673        cx: &mut Context<Self>,
 7674    ) {
 7675        let text_layout_details = &self.text_layout_details(window);
 7676        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7677            s.move_heads_with(|map, head, goal| {
 7678                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7679            })
 7680        })
 7681    }
 7682
 7683    pub fn select_page_up(
 7684        &mut self,
 7685        _: &SelectPageUp,
 7686        window: &mut Window,
 7687        cx: &mut Context<Self>,
 7688    ) {
 7689        let Some(row_count) = self.visible_row_count() else {
 7690            return;
 7691        };
 7692
 7693        let text_layout_details = &self.text_layout_details(window);
 7694
 7695        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7696            s.move_heads_with(|map, head, goal| {
 7697                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7698            })
 7699        })
 7700    }
 7701
 7702    pub fn move_page_up(
 7703        &mut self,
 7704        action: &MovePageUp,
 7705        window: &mut Window,
 7706        cx: &mut Context<Self>,
 7707    ) {
 7708        if self.take_rename(true, window, cx).is_some() {
 7709            return;
 7710        }
 7711
 7712        if self
 7713            .context_menu
 7714            .borrow_mut()
 7715            .as_mut()
 7716            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7717            .unwrap_or(false)
 7718        {
 7719            return;
 7720        }
 7721
 7722        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7723            cx.propagate();
 7724            return;
 7725        }
 7726
 7727        let Some(row_count) = self.visible_row_count() else {
 7728            return;
 7729        };
 7730
 7731        let autoscroll = if action.center_cursor {
 7732            Autoscroll::center()
 7733        } else {
 7734            Autoscroll::fit()
 7735        };
 7736
 7737        let text_layout_details = &self.text_layout_details(window);
 7738
 7739        self.change_selections(Some(autoscroll), window, cx, |s| {
 7740            let line_mode = s.line_mode;
 7741            s.move_with(|map, selection| {
 7742                if !selection.is_empty() && !line_mode {
 7743                    selection.goal = SelectionGoal::None;
 7744                }
 7745                let (cursor, goal) = movement::up_by_rows(
 7746                    map,
 7747                    selection.end,
 7748                    row_count,
 7749                    selection.goal,
 7750                    false,
 7751                    text_layout_details,
 7752                );
 7753                selection.collapse_to(cursor, goal);
 7754            });
 7755        });
 7756    }
 7757
 7758    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 7759        let text_layout_details = &self.text_layout_details(window);
 7760        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7761            s.move_heads_with(|map, head, goal| {
 7762                movement::up(map, head, goal, false, text_layout_details)
 7763            })
 7764        })
 7765    }
 7766
 7767    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 7768        self.take_rename(true, window, cx);
 7769
 7770        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7771            cx.propagate();
 7772            return;
 7773        }
 7774
 7775        let text_layout_details = &self.text_layout_details(window);
 7776        let selection_count = self.selections.count();
 7777        let first_selection = self.selections.first_anchor();
 7778
 7779        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7780            let line_mode = s.line_mode;
 7781            s.move_with(|map, selection| {
 7782                if !selection.is_empty() && !line_mode {
 7783                    selection.goal = SelectionGoal::None;
 7784                }
 7785                let (cursor, goal) = movement::down(
 7786                    map,
 7787                    selection.end,
 7788                    selection.goal,
 7789                    false,
 7790                    text_layout_details,
 7791                );
 7792                selection.collapse_to(cursor, goal);
 7793            });
 7794        });
 7795
 7796        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7797        {
 7798            cx.propagate();
 7799        }
 7800    }
 7801
 7802    pub fn select_page_down(
 7803        &mut self,
 7804        _: &SelectPageDown,
 7805        window: &mut Window,
 7806        cx: &mut Context<Self>,
 7807    ) {
 7808        let Some(row_count) = self.visible_row_count() else {
 7809            return;
 7810        };
 7811
 7812        let text_layout_details = &self.text_layout_details(window);
 7813
 7814        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7815            s.move_heads_with(|map, head, goal| {
 7816                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7817            })
 7818        })
 7819    }
 7820
 7821    pub fn move_page_down(
 7822        &mut self,
 7823        action: &MovePageDown,
 7824        window: &mut Window,
 7825        cx: &mut Context<Self>,
 7826    ) {
 7827        if self.take_rename(true, window, cx).is_some() {
 7828            return;
 7829        }
 7830
 7831        if self
 7832            .context_menu
 7833            .borrow_mut()
 7834            .as_mut()
 7835            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7836            .unwrap_or(false)
 7837        {
 7838            return;
 7839        }
 7840
 7841        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7842            cx.propagate();
 7843            return;
 7844        }
 7845
 7846        let Some(row_count) = self.visible_row_count() else {
 7847            return;
 7848        };
 7849
 7850        let autoscroll = if action.center_cursor {
 7851            Autoscroll::center()
 7852        } else {
 7853            Autoscroll::fit()
 7854        };
 7855
 7856        let text_layout_details = &self.text_layout_details(window);
 7857        self.change_selections(Some(autoscroll), window, cx, |s| {
 7858            let line_mode = s.line_mode;
 7859            s.move_with(|map, selection| {
 7860                if !selection.is_empty() && !line_mode {
 7861                    selection.goal = SelectionGoal::None;
 7862                }
 7863                let (cursor, goal) = movement::down_by_rows(
 7864                    map,
 7865                    selection.end,
 7866                    row_count,
 7867                    selection.goal,
 7868                    false,
 7869                    text_layout_details,
 7870                );
 7871                selection.collapse_to(cursor, goal);
 7872            });
 7873        });
 7874    }
 7875
 7876    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 7877        let text_layout_details = &self.text_layout_details(window);
 7878        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7879            s.move_heads_with(|map, head, goal| {
 7880                movement::down(map, head, goal, false, text_layout_details)
 7881            })
 7882        });
 7883    }
 7884
 7885    pub fn context_menu_first(
 7886        &mut self,
 7887        _: &ContextMenuFirst,
 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_first(self.completion_provider.as_deref(), cx);
 7893        }
 7894    }
 7895
 7896    pub fn context_menu_prev(
 7897        &mut self,
 7898        _: &ContextMenuPrev,
 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_prev(self.completion_provider.as_deref(), cx);
 7904        }
 7905    }
 7906
 7907    pub fn context_menu_next(
 7908        &mut self,
 7909        _: &ContextMenuNext,
 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_next(self.completion_provider.as_deref(), cx);
 7915        }
 7916    }
 7917
 7918    pub fn context_menu_last(
 7919        &mut self,
 7920        _: &ContextMenuLast,
 7921        _window: &mut Window,
 7922        cx: &mut Context<Self>,
 7923    ) {
 7924        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7925            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7926        }
 7927    }
 7928
 7929    pub fn move_to_previous_word_start(
 7930        &mut self,
 7931        _: &MoveToPreviousWordStart,
 7932        window: &mut Window,
 7933        cx: &mut Context<Self>,
 7934    ) {
 7935        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7936            s.move_cursors_with(|map, head, _| {
 7937                (
 7938                    movement::previous_word_start(map, head),
 7939                    SelectionGoal::None,
 7940                )
 7941            });
 7942        })
 7943    }
 7944
 7945    pub fn move_to_previous_subword_start(
 7946        &mut self,
 7947        _: &MoveToPreviousSubwordStart,
 7948        window: &mut Window,
 7949        cx: &mut Context<Self>,
 7950    ) {
 7951        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7952            s.move_cursors_with(|map, head, _| {
 7953                (
 7954                    movement::previous_subword_start(map, head),
 7955                    SelectionGoal::None,
 7956                )
 7957            });
 7958        })
 7959    }
 7960
 7961    pub fn select_to_previous_word_start(
 7962        &mut self,
 7963        _: &SelectToPreviousWordStart,
 7964        window: &mut Window,
 7965        cx: &mut Context<Self>,
 7966    ) {
 7967        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7968            s.move_heads_with(|map, head, _| {
 7969                (
 7970                    movement::previous_word_start(map, head),
 7971                    SelectionGoal::None,
 7972                )
 7973            });
 7974        })
 7975    }
 7976
 7977    pub fn select_to_previous_subword_start(
 7978        &mut self,
 7979        _: &SelectToPreviousSubwordStart,
 7980        window: &mut Window,
 7981        cx: &mut Context<Self>,
 7982    ) {
 7983        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7984            s.move_heads_with(|map, head, _| {
 7985                (
 7986                    movement::previous_subword_start(map, head),
 7987                    SelectionGoal::None,
 7988                )
 7989            });
 7990        })
 7991    }
 7992
 7993    pub fn delete_to_previous_word_start(
 7994        &mut self,
 7995        action: &DeleteToPreviousWordStart,
 7996        window: &mut Window,
 7997        cx: &mut Context<Self>,
 7998    ) {
 7999        self.transact(window, cx, |this, window, cx| {
 8000            this.select_autoclose_pair(window, cx);
 8001            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8002                let line_mode = s.line_mode;
 8003                s.move_with(|map, selection| {
 8004                    if selection.is_empty() && !line_mode {
 8005                        let cursor = if action.ignore_newlines {
 8006                            movement::previous_word_start(map, selection.head())
 8007                        } else {
 8008                            movement::previous_word_start_or_newline(map, selection.head())
 8009                        };
 8010                        selection.set_head(cursor, SelectionGoal::None);
 8011                    }
 8012                });
 8013            });
 8014            this.insert("", window, cx);
 8015        });
 8016    }
 8017
 8018    pub fn delete_to_previous_subword_start(
 8019        &mut self,
 8020        _: &DeleteToPreviousSubwordStart,
 8021        window: &mut Window,
 8022        cx: &mut Context<Self>,
 8023    ) {
 8024        self.transact(window, cx, |this, window, cx| {
 8025            this.select_autoclose_pair(window, cx);
 8026            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8027                let line_mode = s.line_mode;
 8028                s.move_with(|map, selection| {
 8029                    if selection.is_empty() && !line_mode {
 8030                        let cursor = movement::previous_subword_start(map, selection.head());
 8031                        selection.set_head(cursor, SelectionGoal::None);
 8032                    }
 8033                });
 8034            });
 8035            this.insert("", window, cx);
 8036        });
 8037    }
 8038
 8039    pub fn move_to_next_word_end(
 8040        &mut self,
 8041        _: &MoveToNextWordEnd,
 8042        window: &mut Window,
 8043        cx: &mut Context<Self>,
 8044    ) {
 8045        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8046            s.move_cursors_with(|map, head, _| {
 8047                (movement::next_word_end(map, head), SelectionGoal::None)
 8048            });
 8049        })
 8050    }
 8051
 8052    pub fn move_to_next_subword_end(
 8053        &mut self,
 8054        _: &MoveToNextSubwordEnd,
 8055        window: &mut Window,
 8056        cx: &mut Context<Self>,
 8057    ) {
 8058        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8059            s.move_cursors_with(|map, head, _| {
 8060                (movement::next_subword_end(map, head), SelectionGoal::None)
 8061            });
 8062        })
 8063    }
 8064
 8065    pub fn select_to_next_word_end(
 8066        &mut self,
 8067        _: &SelectToNextWordEnd,
 8068        window: &mut Window,
 8069        cx: &mut Context<Self>,
 8070    ) {
 8071        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8072            s.move_heads_with(|map, head, _| {
 8073                (movement::next_word_end(map, head), SelectionGoal::None)
 8074            });
 8075        })
 8076    }
 8077
 8078    pub fn select_to_next_subword_end(
 8079        &mut self,
 8080        _: &SelectToNextSubwordEnd,
 8081        window: &mut Window,
 8082        cx: &mut Context<Self>,
 8083    ) {
 8084        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8085            s.move_heads_with(|map, head, _| {
 8086                (movement::next_subword_end(map, head), SelectionGoal::None)
 8087            });
 8088        })
 8089    }
 8090
 8091    pub fn delete_to_next_word_end(
 8092        &mut self,
 8093        action: &DeleteToNextWordEnd,
 8094        window: &mut Window,
 8095        cx: &mut Context<Self>,
 8096    ) {
 8097        self.transact(window, cx, |this, window, cx| {
 8098            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8099                let line_mode = s.line_mode;
 8100                s.move_with(|map, selection| {
 8101                    if selection.is_empty() && !line_mode {
 8102                        let cursor = if action.ignore_newlines {
 8103                            movement::next_word_end(map, selection.head())
 8104                        } else {
 8105                            movement::next_word_end_or_newline(map, selection.head())
 8106                        };
 8107                        selection.set_head(cursor, SelectionGoal::None);
 8108                    }
 8109                });
 8110            });
 8111            this.insert("", window, cx);
 8112        });
 8113    }
 8114
 8115    pub fn delete_to_next_subword_end(
 8116        &mut self,
 8117        _: &DeleteToNextSubwordEnd,
 8118        window: &mut Window,
 8119        cx: &mut Context<Self>,
 8120    ) {
 8121        self.transact(window, cx, |this, window, cx| {
 8122            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8123                s.move_with(|map, selection| {
 8124                    if selection.is_empty() {
 8125                        let cursor = movement::next_subword_end(map, selection.head());
 8126                        selection.set_head(cursor, SelectionGoal::None);
 8127                    }
 8128                });
 8129            });
 8130            this.insert("", window, cx);
 8131        });
 8132    }
 8133
 8134    pub fn move_to_beginning_of_line(
 8135        &mut self,
 8136        action: &MoveToBeginningOfLine,
 8137        window: &mut Window,
 8138        cx: &mut Context<Self>,
 8139    ) {
 8140        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8141            s.move_cursors_with(|map, head, _| {
 8142                (
 8143                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8144                    SelectionGoal::None,
 8145                )
 8146            });
 8147        })
 8148    }
 8149
 8150    pub fn select_to_beginning_of_line(
 8151        &mut self,
 8152        action: &SelectToBeginningOfLine,
 8153        window: &mut Window,
 8154        cx: &mut Context<Self>,
 8155    ) {
 8156        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8157            s.move_heads_with(|map, head, _| {
 8158                (
 8159                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8160                    SelectionGoal::None,
 8161                )
 8162            });
 8163        });
 8164    }
 8165
 8166    pub fn delete_to_beginning_of_line(
 8167        &mut self,
 8168        _: &DeleteToBeginningOfLine,
 8169        window: &mut Window,
 8170        cx: &mut Context<Self>,
 8171    ) {
 8172        self.transact(window, cx, |this, window, cx| {
 8173            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8174                s.move_with(|_, selection| {
 8175                    selection.reversed = true;
 8176                });
 8177            });
 8178
 8179            this.select_to_beginning_of_line(
 8180                &SelectToBeginningOfLine {
 8181                    stop_at_soft_wraps: false,
 8182                },
 8183                window,
 8184                cx,
 8185            );
 8186            this.backspace(&Backspace, window, cx);
 8187        });
 8188    }
 8189
 8190    pub fn move_to_end_of_line(
 8191        &mut self,
 8192        action: &MoveToEndOfLine,
 8193        window: &mut Window,
 8194        cx: &mut Context<Self>,
 8195    ) {
 8196        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8197            s.move_cursors_with(|map, head, _| {
 8198                (
 8199                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8200                    SelectionGoal::None,
 8201                )
 8202            });
 8203        })
 8204    }
 8205
 8206    pub fn select_to_end_of_line(
 8207        &mut self,
 8208        action: &SelectToEndOfLine,
 8209        window: &mut Window,
 8210        cx: &mut Context<Self>,
 8211    ) {
 8212        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8213            s.move_heads_with(|map, head, _| {
 8214                (
 8215                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8216                    SelectionGoal::None,
 8217                )
 8218            });
 8219        })
 8220    }
 8221
 8222    pub fn delete_to_end_of_line(
 8223        &mut self,
 8224        _: &DeleteToEndOfLine,
 8225        window: &mut Window,
 8226        cx: &mut Context<Self>,
 8227    ) {
 8228        self.transact(window, cx, |this, window, cx| {
 8229            this.select_to_end_of_line(
 8230                &SelectToEndOfLine {
 8231                    stop_at_soft_wraps: false,
 8232                },
 8233                window,
 8234                cx,
 8235            );
 8236            this.delete(&Delete, window, cx);
 8237        });
 8238    }
 8239
 8240    pub fn cut_to_end_of_line(
 8241        &mut self,
 8242        _: &CutToEndOfLine,
 8243        window: &mut Window,
 8244        cx: &mut Context<Self>,
 8245    ) {
 8246        self.transact(window, cx, |this, window, cx| {
 8247            this.select_to_end_of_line(
 8248                &SelectToEndOfLine {
 8249                    stop_at_soft_wraps: false,
 8250                },
 8251                window,
 8252                cx,
 8253            );
 8254            this.cut(&Cut, window, cx);
 8255        });
 8256    }
 8257
 8258    pub fn move_to_start_of_paragraph(
 8259        &mut self,
 8260        _: &MoveToStartOfParagraph,
 8261        window: &mut Window,
 8262        cx: &mut Context<Self>,
 8263    ) {
 8264        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8265            cx.propagate();
 8266            return;
 8267        }
 8268
 8269        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8270            s.move_with(|map, selection| {
 8271                selection.collapse_to(
 8272                    movement::start_of_paragraph(map, selection.head(), 1),
 8273                    SelectionGoal::None,
 8274                )
 8275            });
 8276        })
 8277    }
 8278
 8279    pub fn move_to_end_of_paragraph(
 8280        &mut self,
 8281        _: &MoveToEndOfParagraph,
 8282        window: &mut Window,
 8283        cx: &mut Context<Self>,
 8284    ) {
 8285        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8286            cx.propagate();
 8287            return;
 8288        }
 8289
 8290        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8291            s.move_with(|map, selection| {
 8292                selection.collapse_to(
 8293                    movement::end_of_paragraph(map, selection.head(), 1),
 8294                    SelectionGoal::None,
 8295                )
 8296            });
 8297        })
 8298    }
 8299
 8300    pub fn select_to_start_of_paragraph(
 8301        &mut self,
 8302        _: &SelectToStartOfParagraph,
 8303        window: &mut Window,
 8304        cx: &mut Context<Self>,
 8305    ) {
 8306        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8307            cx.propagate();
 8308            return;
 8309        }
 8310
 8311        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8312            s.move_heads_with(|map, head, _| {
 8313                (
 8314                    movement::start_of_paragraph(map, head, 1),
 8315                    SelectionGoal::None,
 8316                )
 8317            });
 8318        })
 8319    }
 8320
 8321    pub fn select_to_end_of_paragraph(
 8322        &mut self,
 8323        _: &SelectToEndOfParagraph,
 8324        window: &mut Window,
 8325        cx: &mut Context<Self>,
 8326    ) {
 8327        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8328            cx.propagate();
 8329            return;
 8330        }
 8331
 8332        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8333            s.move_heads_with(|map, head, _| {
 8334                (
 8335                    movement::end_of_paragraph(map, head, 1),
 8336                    SelectionGoal::None,
 8337                )
 8338            });
 8339        })
 8340    }
 8341
 8342    pub fn move_to_beginning(
 8343        &mut self,
 8344        _: &MoveToBeginning,
 8345        window: &mut Window,
 8346        cx: &mut Context<Self>,
 8347    ) {
 8348        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8349            cx.propagate();
 8350            return;
 8351        }
 8352
 8353        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8354            s.select_ranges(vec![0..0]);
 8355        });
 8356    }
 8357
 8358    pub fn select_to_beginning(
 8359        &mut self,
 8360        _: &SelectToBeginning,
 8361        window: &mut Window,
 8362        cx: &mut Context<Self>,
 8363    ) {
 8364        let mut selection = self.selections.last::<Point>(cx);
 8365        selection.set_head(Point::zero(), SelectionGoal::None);
 8366
 8367        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8368            s.select(vec![selection]);
 8369        });
 8370    }
 8371
 8372    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8373        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8374            cx.propagate();
 8375            return;
 8376        }
 8377
 8378        let cursor = self.buffer.read(cx).read(cx).len();
 8379        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8380            s.select_ranges(vec![cursor..cursor])
 8381        });
 8382    }
 8383
 8384    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8385        self.nav_history = nav_history;
 8386    }
 8387
 8388    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8389        self.nav_history.as_ref()
 8390    }
 8391
 8392    fn push_to_nav_history(
 8393        &mut self,
 8394        cursor_anchor: Anchor,
 8395        new_position: Option<Point>,
 8396        cx: &mut Context<Self>,
 8397    ) {
 8398        if let Some(nav_history) = self.nav_history.as_mut() {
 8399            let buffer = self.buffer.read(cx).read(cx);
 8400            let cursor_position = cursor_anchor.to_point(&buffer);
 8401            let scroll_state = self.scroll_manager.anchor();
 8402            let scroll_top_row = scroll_state.top_row(&buffer);
 8403            drop(buffer);
 8404
 8405            if let Some(new_position) = new_position {
 8406                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8407                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8408                    return;
 8409                }
 8410            }
 8411
 8412            nav_history.push(
 8413                Some(NavigationData {
 8414                    cursor_anchor,
 8415                    cursor_position,
 8416                    scroll_anchor: scroll_state,
 8417                    scroll_top_row,
 8418                }),
 8419                cx,
 8420            );
 8421        }
 8422    }
 8423
 8424    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8425        let buffer = self.buffer.read(cx).snapshot(cx);
 8426        let mut selection = self.selections.first::<usize>(cx);
 8427        selection.set_head(buffer.len(), SelectionGoal::None);
 8428        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8429            s.select(vec![selection]);
 8430        });
 8431    }
 8432
 8433    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8434        let end = self.buffer.read(cx).read(cx).len();
 8435        self.change_selections(None, window, cx, |s| {
 8436            s.select_ranges(vec![0..end]);
 8437        });
 8438    }
 8439
 8440    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8441        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8442        let mut selections = self.selections.all::<Point>(cx);
 8443        let max_point = display_map.buffer_snapshot.max_point();
 8444        for selection in &mut selections {
 8445            let rows = selection.spanned_rows(true, &display_map);
 8446            selection.start = Point::new(rows.start.0, 0);
 8447            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8448            selection.reversed = false;
 8449        }
 8450        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8451            s.select(selections);
 8452        });
 8453    }
 8454
 8455    pub fn split_selection_into_lines(
 8456        &mut self,
 8457        _: &SplitSelectionIntoLines,
 8458        window: &mut Window,
 8459        cx: &mut Context<Self>,
 8460    ) {
 8461        let mut to_unfold = Vec::new();
 8462        let mut new_selection_ranges = Vec::new();
 8463        {
 8464            let selections = self.selections.all::<Point>(cx);
 8465            let buffer = self.buffer.read(cx).read(cx);
 8466            for selection in selections {
 8467                for row in selection.start.row..selection.end.row {
 8468                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8469                    new_selection_ranges.push(cursor..cursor);
 8470                }
 8471                new_selection_ranges.push(selection.end..selection.end);
 8472                to_unfold.push(selection.start..selection.end);
 8473            }
 8474        }
 8475        self.unfold_ranges(&to_unfold, true, true, cx);
 8476        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8477            s.select_ranges(new_selection_ranges);
 8478        });
 8479    }
 8480
 8481    pub fn add_selection_above(
 8482        &mut self,
 8483        _: &AddSelectionAbove,
 8484        window: &mut Window,
 8485        cx: &mut Context<Self>,
 8486    ) {
 8487        self.add_selection(true, window, cx);
 8488    }
 8489
 8490    pub fn add_selection_below(
 8491        &mut self,
 8492        _: &AddSelectionBelow,
 8493        window: &mut Window,
 8494        cx: &mut Context<Self>,
 8495    ) {
 8496        self.add_selection(false, window, cx);
 8497    }
 8498
 8499    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8500        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8501        let mut selections = self.selections.all::<Point>(cx);
 8502        let text_layout_details = self.text_layout_details(window);
 8503        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8504            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8505            let range = oldest_selection.display_range(&display_map).sorted();
 8506
 8507            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8508            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8509            let positions = start_x.min(end_x)..start_x.max(end_x);
 8510
 8511            selections.clear();
 8512            let mut stack = Vec::new();
 8513            for row in range.start.row().0..=range.end.row().0 {
 8514                if let Some(selection) = self.selections.build_columnar_selection(
 8515                    &display_map,
 8516                    DisplayRow(row),
 8517                    &positions,
 8518                    oldest_selection.reversed,
 8519                    &text_layout_details,
 8520                ) {
 8521                    stack.push(selection.id);
 8522                    selections.push(selection);
 8523                }
 8524            }
 8525
 8526            if above {
 8527                stack.reverse();
 8528            }
 8529
 8530            AddSelectionsState { above, stack }
 8531        });
 8532
 8533        let last_added_selection = *state.stack.last().unwrap();
 8534        let mut new_selections = Vec::new();
 8535        if above == state.above {
 8536            let end_row = if above {
 8537                DisplayRow(0)
 8538            } else {
 8539                display_map.max_point().row()
 8540            };
 8541
 8542            'outer: for selection in selections {
 8543                if selection.id == last_added_selection {
 8544                    let range = selection.display_range(&display_map).sorted();
 8545                    debug_assert_eq!(range.start.row(), range.end.row());
 8546                    let mut row = range.start.row();
 8547                    let positions =
 8548                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8549                            px(start)..px(end)
 8550                        } else {
 8551                            let start_x =
 8552                                display_map.x_for_display_point(range.start, &text_layout_details);
 8553                            let end_x =
 8554                                display_map.x_for_display_point(range.end, &text_layout_details);
 8555                            start_x.min(end_x)..start_x.max(end_x)
 8556                        };
 8557
 8558                    while row != end_row {
 8559                        if above {
 8560                            row.0 -= 1;
 8561                        } else {
 8562                            row.0 += 1;
 8563                        }
 8564
 8565                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8566                            &display_map,
 8567                            row,
 8568                            &positions,
 8569                            selection.reversed,
 8570                            &text_layout_details,
 8571                        ) {
 8572                            state.stack.push(new_selection.id);
 8573                            if above {
 8574                                new_selections.push(new_selection);
 8575                                new_selections.push(selection);
 8576                            } else {
 8577                                new_selections.push(selection);
 8578                                new_selections.push(new_selection);
 8579                            }
 8580
 8581                            continue 'outer;
 8582                        }
 8583                    }
 8584                }
 8585
 8586                new_selections.push(selection);
 8587            }
 8588        } else {
 8589            new_selections = selections;
 8590            new_selections.retain(|s| s.id != last_added_selection);
 8591            state.stack.pop();
 8592        }
 8593
 8594        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8595            s.select(new_selections);
 8596        });
 8597        if state.stack.len() > 1 {
 8598            self.add_selections_state = Some(state);
 8599        }
 8600    }
 8601
 8602    pub fn select_next_match_internal(
 8603        &mut self,
 8604        display_map: &DisplaySnapshot,
 8605        replace_newest: bool,
 8606        autoscroll: Option<Autoscroll>,
 8607        window: &mut Window,
 8608        cx: &mut Context<Self>,
 8609    ) -> Result<()> {
 8610        fn select_next_match_ranges(
 8611            this: &mut Editor,
 8612            range: Range<usize>,
 8613            replace_newest: bool,
 8614            auto_scroll: Option<Autoscroll>,
 8615            window: &mut Window,
 8616            cx: &mut Context<Editor>,
 8617        ) {
 8618            this.unfold_ranges(&[range.clone()], false, true, cx);
 8619            this.change_selections(auto_scroll, window, cx, |s| {
 8620                if replace_newest {
 8621                    s.delete(s.newest_anchor().id);
 8622                }
 8623                s.insert_range(range.clone());
 8624            });
 8625        }
 8626
 8627        let buffer = &display_map.buffer_snapshot;
 8628        let mut selections = self.selections.all::<usize>(cx);
 8629        if let Some(mut select_next_state) = self.select_next_state.take() {
 8630            let query = &select_next_state.query;
 8631            if !select_next_state.done {
 8632                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8633                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8634                let mut next_selected_range = None;
 8635
 8636                let bytes_after_last_selection =
 8637                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8638                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8639                let query_matches = query
 8640                    .stream_find_iter(bytes_after_last_selection)
 8641                    .map(|result| (last_selection.end, result))
 8642                    .chain(
 8643                        query
 8644                            .stream_find_iter(bytes_before_first_selection)
 8645                            .map(|result| (0, result)),
 8646                    );
 8647
 8648                for (start_offset, query_match) in query_matches {
 8649                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8650                    let offset_range =
 8651                        start_offset + query_match.start()..start_offset + query_match.end();
 8652                    let display_range = offset_range.start.to_display_point(display_map)
 8653                        ..offset_range.end.to_display_point(display_map);
 8654
 8655                    if !select_next_state.wordwise
 8656                        || (!movement::is_inside_word(display_map, display_range.start)
 8657                            && !movement::is_inside_word(display_map, display_range.end))
 8658                    {
 8659                        // TODO: This is n^2, because we might check all the selections
 8660                        if !selections
 8661                            .iter()
 8662                            .any(|selection| selection.range().overlaps(&offset_range))
 8663                        {
 8664                            next_selected_range = Some(offset_range);
 8665                            break;
 8666                        }
 8667                    }
 8668                }
 8669
 8670                if let Some(next_selected_range) = next_selected_range {
 8671                    select_next_match_ranges(
 8672                        self,
 8673                        next_selected_range,
 8674                        replace_newest,
 8675                        autoscroll,
 8676                        window,
 8677                        cx,
 8678                    );
 8679                } else {
 8680                    select_next_state.done = true;
 8681                }
 8682            }
 8683
 8684            self.select_next_state = Some(select_next_state);
 8685        } else {
 8686            let mut only_carets = true;
 8687            let mut same_text_selected = true;
 8688            let mut selected_text = None;
 8689
 8690            let mut selections_iter = selections.iter().peekable();
 8691            while let Some(selection) = selections_iter.next() {
 8692                if selection.start != selection.end {
 8693                    only_carets = false;
 8694                }
 8695
 8696                if same_text_selected {
 8697                    if selected_text.is_none() {
 8698                        selected_text =
 8699                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8700                    }
 8701
 8702                    if let Some(next_selection) = selections_iter.peek() {
 8703                        if next_selection.range().len() == selection.range().len() {
 8704                            let next_selected_text = buffer
 8705                                .text_for_range(next_selection.range())
 8706                                .collect::<String>();
 8707                            if Some(next_selected_text) != selected_text {
 8708                                same_text_selected = false;
 8709                                selected_text = None;
 8710                            }
 8711                        } else {
 8712                            same_text_selected = false;
 8713                            selected_text = None;
 8714                        }
 8715                    }
 8716                }
 8717            }
 8718
 8719            if only_carets {
 8720                for selection in &mut selections {
 8721                    let word_range = movement::surrounding_word(
 8722                        display_map,
 8723                        selection.start.to_display_point(display_map),
 8724                    );
 8725                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8726                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8727                    selection.goal = SelectionGoal::None;
 8728                    selection.reversed = false;
 8729                    select_next_match_ranges(
 8730                        self,
 8731                        selection.start..selection.end,
 8732                        replace_newest,
 8733                        autoscroll,
 8734                        window,
 8735                        cx,
 8736                    );
 8737                }
 8738
 8739                if selections.len() == 1 {
 8740                    let selection = selections
 8741                        .last()
 8742                        .expect("ensured that there's only one selection");
 8743                    let query = buffer
 8744                        .text_for_range(selection.start..selection.end)
 8745                        .collect::<String>();
 8746                    let is_empty = query.is_empty();
 8747                    let select_state = SelectNextState {
 8748                        query: AhoCorasick::new(&[query])?,
 8749                        wordwise: true,
 8750                        done: is_empty,
 8751                    };
 8752                    self.select_next_state = Some(select_state);
 8753                } else {
 8754                    self.select_next_state = None;
 8755                }
 8756            } else if let Some(selected_text) = selected_text {
 8757                self.select_next_state = Some(SelectNextState {
 8758                    query: AhoCorasick::new(&[selected_text])?,
 8759                    wordwise: false,
 8760                    done: false,
 8761                });
 8762                self.select_next_match_internal(
 8763                    display_map,
 8764                    replace_newest,
 8765                    autoscroll,
 8766                    window,
 8767                    cx,
 8768                )?;
 8769            }
 8770        }
 8771        Ok(())
 8772    }
 8773
 8774    pub fn select_all_matches(
 8775        &mut self,
 8776        _action: &SelectAllMatches,
 8777        window: &mut Window,
 8778        cx: &mut Context<Self>,
 8779    ) -> Result<()> {
 8780        self.push_to_selection_history();
 8781        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8782
 8783        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 8784        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8785            return Ok(());
 8786        };
 8787        if select_next_state.done {
 8788            return Ok(());
 8789        }
 8790
 8791        let mut new_selections = self.selections.all::<usize>(cx);
 8792
 8793        let buffer = &display_map.buffer_snapshot;
 8794        let query_matches = select_next_state
 8795            .query
 8796            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8797
 8798        for query_match in query_matches {
 8799            let query_match = query_match.unwrap(); // can only fail due to I/O
 8800            let offset_range = query_match.start()..query_match.end();
 8801            let display_range = offset_range.start.to_display_point(&display_map)
 8802                ..offset_range.end.to_display_point(&display_map);
 8803
 8804            if !select_next_state.wordwise
 8805                || (!movement::is_inside_word(&display_map, display_range.start)
 8806                    && !movement::is_inside_word(&display_map, display_range.end))
 8807            {
 8808                self.selections.change_with(cx, |selections| {
 8809                    new_selections.push(Selection {
 8810                        id: selections.new_selection_id(),
 8811                        start: offset_range.start,
 8812                        end: offset_range.end,
 8813                        reversed: false,
 8814                        goal: SelectionGoal::None,
 8815                    });
 8816                });
 8817            }
 8818        }
 8819
 8820        new_selections.sort_by_key(|selection| selection.start);
 8821        let mut ix = 0;
 8822        while ix + 1 < new_selections.len() {
 8823            let current_selection = &new_selections[ix];
 8824            let next_selection = &new_selections[ix + 1];
 8825            if current_selection.range().overlaps(&next_selection.range()) {
 8826                if current_selection.id < next_selection.id {
 8827                    new_selections.remove(ix + 1);
 8828                } else {
 8829                    new_selections.remove(ix);
 8830                }
 8831            } else {
 8832                ix += 1;
 8833            }
 8834        }
 8835
 8836        let reversed = self.selections.oldest::<usize>(cx).reversed;
 8837
 8838        for selection in new_selections.iter_mut() {
 8839            selection.reversed = reversed;
 8840        }
 8841
 8842        select_next_state.done = true;
 8843        self.unfold_ranges(
 8844            &new_selections
 8845                .iter()
 8846                .map(|selection| selection.range())
 8847                .collect::<Vec<_>>(),
 8848            false,
 8849            false,
 8850            cx,
 8851        );
 8852        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 8853            selections.select(new_selections)
 8854        });
 8855
 8856        Ok(())
 8857    }
 8858
 8859    pub fn select_next(
 8860        &mut self,
 8861        action: &SelectNext,
 8862        window: &mut Window,
 8863        cx: &mut Context<Self>,
 8864    ) -> Result<()> {
 8865        self.push_to_selection_history();
 8866        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8867        self.select_next_match_internal(
 8868            &display_map,
 8869            action.replace_newest,
 8870            Some(Autoscroll::newest()),
 8871            window,
 8872            cx,
 8873        )?;
 8874        Ok(())
 8875    }
 8876
 8877    pub fn select_previous(
 8878        &mut self,
 8879        action: &SelectPrevious,
 8880        window: &mut Window,
 8881        cx: &mut Context<Self>,
 8882    ) -> Result<()> {
 8883        self.push_to_selection_history();
 8884        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8885        let buffer = &display_map.buffer_snapshot;
 8886        let mut selections = self.selections.all::<usize>(cx);
 8887        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8888            let query = &select_prev_state.query;
 8889            if !select_prev_state.done {
 8890                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8891                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8892                let mut next_selected_range = None;
 8893                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8894                let bytes_before_last_selection =
 8895                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8896                let bytes_after_first_selection =
 8897                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8898                let query_matches = query
 8899                    .stream_find_iter(bytes_before_last_selection)
 8900                    .map(|result| (last_selection.start, result))
 8901                    .chain(
 8902                        query
 8903                            .stream_find_iter(bytes_after_first_selection)
 8904                            .map(|result| (buffer.len(), result)),
 8905                    );
 8906                for (end_offset, query_match) in query_matches {
 8907                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8908                    let offset_range =
 8909                        end_offset - query_match.end()..end_offset - query_match.start();
 8910                    let display_range = offset_range.start.to_display_point(&display_map)
 8911                        ..offset_range.end.to_display_point(&display_map);
 8912
 8913                    if !select_prev_state.wordwise
 8914                        || (!movement::is_inside_word(&display_map, display_range.start)
 8915                            && !movement::is_inside_word(&display_map, display_range.end))
 8916                    {
 8917                        next_selected_range = Some(offset_range);
 8918                        break;
 8919                    }
 8920                }
 8921
 8922                if let Some(next_selected_range) = next_selected_range {
 8923                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8924                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8925                        if action.replace_newest {
 8926                            s.delete(s.newest_anchor().id);
 8927                        }
 8928                        s.insert_range(next_selected_range);
 8929                    });
 8930                } else {
 8931                    select_prev_state.done = true;
 8932                }
 8933            }
 8934
 8935            self.select_prev_state = Some(select_prev_state);
 8936        } else {
 8937            let mut only_carets = true;
 8938            let mut same_text_selected = true;
 8939            let mut selected_text = None;
 8940
 8941            let mut selections_iter = selections.iter().peekable();
 8942            while let Some(selection) = selections_iter.next() {
 8943                if selection.start != selection.end {
 8944                    only_carets = false;
 8945                }
 8946
 8947                if same_text_selected {
 8948                    if selected_text.is_none() {
 8949                        selected_text =
 8950                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8951                    }
 8952
 8953                    if let Some(next_selection) = selections_iter.peek() {
 8954                        if next_selection.range().len() == selection.range().len() {
 8955                            let next_selected_text = buffer
 8956                                .text_for_range(next_selection.range())
 8957                                .collect::<String>();
 8958                            if Some(next_selected_text) != selected_text {
 8959                                same_text_selected = false;
 8960                                selected_text = None;
 8961                            }
 8962                        } else {
 8963                            same_text_selected = false;
 8964                            selected_text = None;
 8965                        }
 8966                    }
 8967                }
 8968            }
 8969
 8970            if only_carets {
 8971                for selection in &mut selections {
 8972                    let word_range = movement::surrounding_word(
 8973                        &display_map,
 8974                        selection.start.to_display_point(&display_map),
 8975                    );
 8976                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8977                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8978                    selection.goal = SelectionGoal::None;
 8979                    selection.reversed = false;
 8980                }
 8981                if selections.len() == 1 {
 8982                    let selection = selections
 8983                        .last()
 8984                        .expect("ensured that there's only one selection");
 8985                    let query = buffer
 8986                        .text_for_range(selection.start..selection.end)
 8987                        .collect::<String>();
 8988                    let is_empty = query.is_empty();
 8989                    let select_state = SelectNextState {
 8990                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8991                        wordwise: true,
 8992                        done: is_empty,
 8993                    };
 8994                    self.select_prev_state = Some(select_state);
 8995                } else {
 8996                    self.select_prev_state = None;
 8997                }
 8998
 8999                self.unfold_ranges(
 9000                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9001                    false,
 9002                    true,
 9003                    cx,
 9004                );
 9005                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9006                    s.select(selections);
 9007                });
 9008            } else if let Some(selected_text) = selected_text {
 9009                self.select_prev_state = Some(SelectNextState {
 9010                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9011                    wordwise: false,
 9012                    done: false,
 9013                });
 9014                self.select_previous(action, window, cx)?;
 9015            }
 9016        }
 9017        Ok(())
 9018    }
 9019
 9020    pub fn toggle_comments(
 9021        &mut self,
 9022        action: &ToggleComments,
 9023        window: &mut Window,
 9024        cx: &mut Context<Self>,
 9025    ) {
 9026        if self.read_only(cx) {
 9027            return;
 9028        }
 9029        let text_layout_details = &self.text_layout_details(window);
 9030        self.transact(window, cx, |this, window, cx| {
 9031            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9032            let mut edits = Vec::new();
 9033            let mut selection_edit_ranges = Vec::new();
 9034            let mut last_toggled_row = None;
 9035            let snapshot = this.buffer.read(cx).read(cx);
 9036            let empty_str: Arc<str> = Arc::default();
 9037            let mut suffixes_inserted = Vec::new();
 9038            let ignore_indent = action.ignore_indent;
 9039
 9040            fn comment_prefix_range(
 9041                snapshot: &MultiBufferSnapshot,
 9042                row: MultiBufferRow,
 9043                comment_prefix: &str,
 9044                comment_prefix_whitespace: &str,
 9045                ignore_indent: bool,
 9046            ) -> Range<Point> {
 9047                let indent_size = if ignore_indent {
 9048                    0
 9049                } else {
 9050                    snapshot.indent_size_for_line(row).len
 9051                };
 9052
 9053                let start = Point::new(row.0, indent_size);
 9054
 9055                let mut line_bytes = snapshot
 9056                    .bytes_in_range(start..snapshot.max_point())
 9057                    .flatten()
 9058                    .copied();
 9059
 9060                // If this line currently begins with the line comment prefix, then record
 9061                // the range containing the prefix.
 9062                if line_bytes
 9063                    .by_ref()
 9064                    .take(comment_prefix.len())
 9065                    .eq(comment_prefix.bytes())
 9066                {
 9067                    // Include any whitespace that matches the comment prefix.
 9068                    let matching_whitespace_len = line_bytes
 9069                        .zip(comment_prefix_whitespace.bytes())
 9070                        .take_while(|(a, b)| a == b)
 9071                        .count() as u32;
 9072                    let end = Point::new(
 9073                        start.row,
 9074                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9075                    );
 9076                    start..end
 9077                } else {
 9078                    start..start
 9079                }
 9080            }
 9081
 9082            fn comment_suffix_range(
 9083                snapshot: &MultiBufferSnapshot,
 9084                row: MultiBufferRow,
 9085                comment_suffix: &str,
 9086                comment_suffix_has_leading_space: bool,
 9087            ) -> Range<Point> {
 9088                let end = Point::new(row.0, snapshot.line_len(row));
 9089                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9090
 9091                let mut line_end_bytes = snapshot
 9092                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9093                    .flatten()
 9094                    .copied();
 9095
 9096                let leading_space_len = if suffix_start_column > 0
 9097                    && line_end_bytes.next() == Some(b' ')
 9098                    && comment_suffix_has_leading_space
 9099                {
 9100                    1
 9101                } else {
 9102                    0
 9103                };
 9104
 9105                // If this line currently begins with the line comment prefix, then record
 9106                // the range containing the prefix.
 9107                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9108                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9109                    start..end
 9110                } else {
 9111                    end..end
 9112                }
 9113            }
 9114
 9115            // TODO: Handle selections that cross excerpts
 9116            for selection in &mut selections {
 9117                let start_column = snapshot
 9118                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9119                    .len;
 9120                let language = if let Some(language) =
 9121                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9122                {
 9123                    language
 9124                } else {
 9125                    continue;
 9126                };
 9127
 9128                selection_edit_ranges.clear();
 9129
 9130                // If multiple selections contain a given row, avoid processing that
 9131                // row more than once.
 9132                let mut start_row = MultiBufferRow(selection.start.row);
 9133                if last_toggled_row == Some(start_row) {
 9134                    start_row = start_row.next_row();
 9135                }
 9136                let end_row =
 9137                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9138                        MultiBufferRow(selection.end.row - 1)
 9139                    } else {
 9140                        MultiBufferRow(selection.end.row)
 9141                    };
 9142                last_toggled_row = Some(end_row);
 9143
 9144                if start_row > end_row {
 9145                    continue;
 9146                }
 9147
 9148                // If the language has line comments, toggle those.
 9149                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9150
 9151                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9152                if ignore_indent {
 9153                    full_comment_prefixes = full_comment_prefixes
 9154                        .into_iter()
 9155                        .map(|s| Arc::from(s.trim_end()))
 9156                        .collect();
 9157                }
 9158
 9159                if !full_comment_prefixes.is_empty() {
 9160                    let first_prefix = full_comment_prefixes
 9161                        .first()
 9162                        .expect("prefixes is non-empty");
 9163                    let prefix_trimmed_lengths = full_comment_prefixes
 9164                        .iter()
 9165                        .map(|p| p.trim_end_matches(' ').len())
 9166                        .collect::<SmallVec<[usize; 4]>>();
 9167
 9168                    let mut all_selection_lines_are_comments = true;
 9169
 9170                    for row in start_row.0..=end_row.0 {
 9171                        let row = MultiBufferRow(row);
 9172                        if start_row < end_row && snapshot.is_line_blank(row) {
 9173                            continue;
 9174                        }
 9175
 9176                        let prefix_range = full_comment_prefixes
 9177                            .iter()
 9178                            .zip(prefix_trimmed_lengths.iter().copied())
 9179                            .map(|(prefix, trimmed_prefix_len)| {
 9180                                comment_prefix_range(
 9181                                    snapshot.deref(),
 9182                                    row,
 9183                                    &prefix[..trimmed_prefix_len],
 9184                                    &prefix[trimmed_prefix_len..],
 9185                                    ignore_indent,
 9186                                )
 9187                            })
 9188                            .max_by_key(|range| range.end.column - range.start.column)
 9189                            .expect("prefixes is non-empty");
 9190
 9191                        if prefix_range.is_empty() {
 9192                            all_selection_lines_are_comments = false;
 9193                        }
 9194
 9195                        selection_edit_ranges.push(prefix_range);
 9196                    }
 9197
 9198                    if all_selection_lines_are_comments {
 9199                        edits.extend(
 9200                            selection_edit_ranges
 9201                                .iter()
 9202                                .cloned()
 9203                                .map(|range| (range, empty_str.clone())),
 9204                        );
 9205                    } else {
 9206                        let min_column = selection_edit_ranges
 9207                            .iter()
 9208                            .map(|range| range.start.column)
 9209                            .min()
 9210                            .unwrap_or(0);
 9211                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9212                            let position = Point::new(range.start.row, min_column);
 9213                            (position..position, first_prefix.clone())
 9214                        }));
 9215                    }
 9216                } else if let Some((full_comment_prefix, comment_suffix)) =
 9217                    language.block_comment_delimiters()
 9218                {
 9219                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9220                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9221                    let prefix_range = comment_prefix_range(
 9222                        snapshot.deref(),
 9223                        start_row,
 9224                        comment_prefix,
 9225                        comment_prefix_whitespace,
 9226                        ignore_indent,
 9227                    );
 9228                    let suffix_range = comment_suffix_range(
 9229                        snapshot.deref(),
 9230                        end_row,
 9231                        comment_suffix.trim_start_matches(' '),
 9232                        comment_suffix.starts_with(' '),
 9233                    );
 9234
 9235                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9236                        edits.push((
 9237                            prefix_range.start..prefix_range.start,
 9238                            full_comment_prefix.clone(),
 9239                        ));
 9240                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9241                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9242                    } else {
 9243                        edits.push((prefix_range, empty_str.clone()));
 9244                        edits.push((suffix_range, empty_str.clone()));
 9245                    }
 9246                } else {
 9247                    continue;
 9248                }
 9249            }
 9250
 9251            drop(snapshot);
 9252            this.buffer.update(cx, |buffer, cx| {
 9253                buffer.edit(edits, None, cx);
 9254            });
 9255
 9256            // Adjust selections so that they end before any comment suffixes that
 9257            // were inserted.
 9258            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9259            let mut selections = this.selections.all::<Point>(cx);
 9260            let snapshot = this.buffer.read(cx).read(cx);
 9261            for selection in &mut selections {
 9262                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9263                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9264                        Ordering::Less => {
 9265                            suffixes_inserted.next();
 9266                            continue;
 9267                        }
 9268                        Ordering::Greater => break,
 9269                        Ordering::Equal => {
 9270                            if selection.end.column == snapshot.line_len(row) {
 9271                                if selection.is_empty() {
 9272                                    selection.start.column -= suffix_len as u32;
 9273                                }
 9274                                selection.end.column -= suffix_len as u32;
 9275                            }
 9276                            break;
 9277                        }
 9278                    }
 9279                }
 9280            }
 9281
 9282            drop(snapshot);
 9283            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9284                s.select(selections)
 9285            });
 9286
 9287            let selections = this.selections.all::<Point>(cx);
 9288            let selections_on_single_row = selections.windows(2).all(|selections| {
 9289                selections[0].start.row == selections[1].start.row
 9290                    && selections[0].end.row == selections[1].end.row
 9291                    && selections[0].start.row == selections[0].end.row
 9292            });
 9293            let selections_selecting = selections
 9294                .iter()
 9295                .any(|selection| selection.start != selection.end);
 9296            let advance_downwards = action.advance_downwards
 9297                && selections_on_single_row
 9298                && !selections_selecting
 9299                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9300
 9301            if advance_downwards {
 9302                let snapshot = this.buffer.read(cx).snapshot(cx);
 9303
 9304                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9305                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9306                        let mut point = display_point.to_point(display_snapshot);
 9307                        point.row += 1;
 9308                        point = snapshot.clip_point(point, Bias::Left);
 9309                        let display_point = point.to_display_point(display_snapshot);
 9310                        let goal = SelectionGoal::HorizontalPosition(
 9311                            display_snapshot
 9312                                .x_for_display_point(display_point, text_layout_details)
 9313                                .into(),
 9314                        );
 9315                        (display_point, goal)
 9316                    })
 9317                });
 9318            }
 9319        });
 9320    }
 9321
 9322    pub fn select_enclosing_symbol(
 9323        &mut self,
 9324        _: &SelectEnclosingSymbol,
 9325        window: &mut Window,
 9326        cx: &mut Context<Self>,
 9327    ) {
 9328        let buffer = self.buffer.read(cx).snapshot(cx);
 9329        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9330
 9331        fn update_selection(
 9332            selection: &Selection<usize>,
 9333            buffer_snap: &MultiBufferSnapshot,
 9334        ) -> Option<Selection<usize>> {
 9335            let cursor = selection.head();
 9336            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9337            for symbol in symbols.iter().rev() {
 9338                let start = symbol.range.start.to_offset(buffer_snap);
 9339                let end = symbol.range.end.to_offset(buffer_snap);
 9340                let new_range = start..end;
 9341                if start < selection.start || end > selection.end {
 9342                    return Some(Selection {
 9343                        id: selection.id,
 9344                        start: new_range.start,
 9345                        end: new_range.end,
 9346                        goal: SelectionGoal::None,
 9347                        reversed: selection.reversed,
 9348                    });
 9349                }
 9350            }
 9351            None
 9352        }
 9353
 9354        let mut selected_larger_symbol = false;
 9355        let new_selections = old_selections
 9356            .iter()
 9357            .map(|selection| match update_selection(selection, &buffer) {
 9358                Some(new_selection) => {
 9359                    if new_selection.range() != selection.range() {
 9360                        selected_larger_symbol = true;
 9361                    }
 9362                    new_selection
 9363                }
 9364                None => selection.clone(),
 9365            })
 9366            .collect::<Vec<_>>();
 9367
 9368        if selected_larger_symbol {
 9369            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9370                s.select(new_selections);
 9371            });
 9372        }
 9373    }
 9374
 9375    pub fn select_larger_syntax_node(
 9376        &mut self,
 9377        _: &SelectLargerSyntaxNode,
 9378        window: &mut Window,
 9379        cx: &mut Context<Self>,
 9380    ) {
 9381        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9382        let buffer = self.buffer.read(cx).snapshot(cx);
 9383        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9384
 9385        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9386        let mut selected_larger_node = false;
 9387        let new_selections = old_selections
 9388            .iter()
 9389            .map(|selection| {
 9390                let old_range = selection.start..selection.end;
 9391                let mut new_range = old_range.clone();
 9392                let mut new_node = None;
 9393                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9394                {
 9395                    new_node = Some(node);
 9396                    new_range = containing_range;
 9397                    if !display_map.intersects_fold(new_range.start)
 9398                        && !display_map.intersects_fold(new_range.end)
 9399                    {
 9400                        break;
 9401                    }
 9402                }
 9403
 9404                if let Some(node) = new_node {
 9405                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9406                    // nodes. Parent and grandparent are also logged because this operation will not
 9407                    // visit nodes that have the same range as their parent.
 9408                    log::info!("Node: {node:?}");
 9409                    let parent = node.parent();
 9410                    log::info!("Parent: {parent:?}");
 9411                    let grandparent = parent.and_then(|x| x.parent());
 9412                    log::info!("Grandparent: {grandparent:?}");
 9413                }
 9414
 9415                selected_larger_node |= new_range != old_range;
 9416                Selection {
 9417                    id: selection.id,
 9418                    start: new_range.start,
 9419                    end: new_range.end,
 9420                    goal: SelectionGoal::None,
 9421                    reversed: selection.reversed,
 9422                }
 9423            })
 9424            .collect::<Vec<_>>();
 9425
 9426        if selected_larger_node {
 9427            stack.push(old_selections);
 9428            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9429                s.select(new_selections);
 9430            });
 9431        }
 9432        self.select_larger_syntax_node_stack = stack;
 9433    }
 9434
 9435    pub fn select_smaller_syntax_node(
 9436        &mut self,
 9437        _: &SelectSmallerSyntaxNode,
 9438        window: &mut Window,
 9439        cx: &mut Context<Self>,
 9440    ) {
 9441        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9442        if let Some(selections) = stack.pop() {
 9443            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9444                s.select(selections.to_vec());
 9445            });
 9446        }
 9447        self.select_larger_syntax_node_stack = stack;
 9448    }
 9449
 9450    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9451        if !EditorSettings::get_global(cx).gutter.runnables {
 9452            self.clear_tasks();
 9453            return Task::ready(());
 9454        }
 9455        let project = self.project.as_ref().map(Entity::downgrade);
 9456        cx.spawn_in(window, |this, mut cx| async move {
 9457            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9458            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9459                return;
 9460            };
 9461            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9462                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9463            }) else {
 9464                return;
 9465            };
 9466
 9467            let hide_runnables = project
 9468                .update(&mut cx, |project, cx| {
 9469                    // Do not display any test indicators in non-dev server remote projects.
 9470                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9471                })
 9472                .unwrap_or(true);
 9473            if hide_runnables {
 9474                return;
 9475            }
 9476            let new_rows =
 9477                cx.background_executor()
 9478                    .spawn({
 9479                        let snapshot = display_snapshot.clone();
 9480                        async move {
 9481                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9482                        }
 9483                    })
 9484                    .await;
 9485
 9486            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9487            this.update(&mut cx, |this, _| {
 9488                this.clear_tasks();
 9489                for (key, value) in rows {
 9490                    this.insert_tasks(key, value);
 9491                }
 9492            })
 9493            .ok();
 9494        })
 9495    }
 9496    fn fetch_runnable_ranges(
 9497        snapshot: &DisplaySnapshot,
 9498        range: Range<Anchor>,
 9499    ) -> Vec<language::RunnableRange> {
 9500        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9501    }
 9502
 9503    fn runnable_rows(
 9504        project: Entity<Project>,
 9505        snapshot: DisplaySnapshot,
 9506        runnable_ranges: Vec<RunnableRange>,
 9507        mut cx: AsyncWindowContext,
 9508    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9509        runnable_ranges
 9510            .into_iter()
 9511            .filter_map(|mut runnable| {
 9512                let tasks = cx
 9513                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9514                    .ok()?;
 9515                if tasks.is_empty() {
 9516                    return None;
 9517                }
 9518
 9519                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9520
 9521                let row = snapshot
 9522                    .buffer_snapshot
 9523                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9524                    .1
 9525                    .start
 9526                    .row;
 9527
 9528                let context_range =
 9529                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9530                Some((
 9531                    (runnable.buffer_id, row),
 9532                    RunnableTasks {
 9533                        templates: tasks,
 9534                        offset: MultiBufferOffset(runnable.run_range.start),
 9535                        context_range,
 9536                        column: point.column,
 9537                        extra_variables: runnable.extra_captures,
 9538                    },
 9539                ))
 9540            })
 9541            .collect()
 9542    }
 9543
 9544    fn templates_with_tags(
 9545        project: &Entity<Project>,
 9546        runnable: &mut Runnable,
 9547        cx: &mut App,
 9548    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9549        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9550            let (worktree_id, file) = project
 9551                .buffer_for_id(runnable.buffer, cx)
 9552                .and_then(|buffer| buffer.read(cx).file())
 9553                .map(|file| (file.worktree_id(cx), file.clone()))
 9554                .unzip();
 9555
 9556            (
 9557                project.task_store().read(cx).task_inventory().cloned(),
 9558                worktree_id,
 9559                file,
 9560            )
 9561        });
 9562
 9563        let tags = mem::take(&mut runnable.tags);
 9564        let mut tags: Vec<_> = tags
 9565            .into_iter()
 9566            .flat_map(|tag| {
 9567                let tag = tag.0.clone();
 9568                inventory
 9569                    .as_ref()
 9570                    .into_iter()
 9571                    .flat_map(|inventory| {
 9572                        inventory.read(cx).list_tasks(
 9573                            file.clone(),
 9574                            Some(runnable.language.clone()),
 9575                            worktree_id,
 9576                            cx,
 9577                        )
 9578                    })
 9579                    .filter(move |(_, template)| {
 9580                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9581                    })
 9582            })
 9583            .sorted_by_key(|(kind, _)| kind.to_owned())
 9584            .collect();
 9585        if let Some((leading_tag_source, _)) = tags.first() {
 9586            // Strongest source wins; if we have worktree tag binding, prefer that to
 9587            // global and language bindings;
 9588            // if we have a global binding, prefer that to language binding.
 9589            let first_mismatch = tags
 9590                .iter()
 9591                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9592            if let Some(index) = first_mismatch {
 9593                tags.truncate(index);
 9594            }
 9595        }
 9596
 9597        tags
 9598    }
 9599
 9600    pub fn move_to_enclosing_bracket(
 9601        &mut self,
 9602        _: &MoveToEnclosingBracket,
 9603        window: &mut Window,
 9604        cx: &mut Context<Self>,
 9605    ) {
 9606        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9607            s.move_offsets_with(|snapshot, selection| {
 9608                let Some(enclosing_bracket_ranges) =
 9609                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9610                else {
 9611                    return;
 9612                };
 9613
 9614                let mut best_length = usize::MAX;
 9615                let mut best_inside = false;
 9616                let mut best_in_bracket_range = false;
 9617                let mut best_destination = None;
 9618                for (open, close) in enclosing_bracket_ranges {
 9619                    let close = close.to_inclusive();
 9620                    let length = close.end() - open.start;
 9621                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9622                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9623                        || close.contains(&selection.head());
 9624
 9625                    // If best is next to a bracket and current isn't, skip
 9626                    if !in_bracket_range && best_in_bracket_range {
 9627                        continue;
 9628                    }
 9629
 9630                    // Prefer smaller lengths unless best is inside and current isn't
 9631                    if length > best_length && (best_inside || !inside) {
 9632                        continue;
 9633                    }
 9634
 9635                    best_length = length;
 9636                    best_inside = inside;
 9637                    best_in_bracket_range = in_bracket_range;
 9638                    best_destination = Some(
 9639                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9640                            if inside {
 9641                                open.end
 9642                            } else {
 9643                                open.start
 9644                            }
 9645                        } else if inside {
 9646                            *close.start()
 9647                        } else {
 9648                            *close.end()
 9649                        },
 9650                    );
 9651                }
 9652
 9653                if let Some(destination) = best_destination {
 9654                    selection.collapse_to(destination, SelectionGoal::None);
 9655                }
 9656            })
 9657        });
 9658    }
 9659
 9660    pub fn undo_selection(
 9661        &mut self,
 9662        _: &UndoSelection,
 9663        window: &mut Window,
 9664        cx: &mut Context<Self>,
 9665    ) {
 9666        self.end_selection(window, cx);
 9667        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9668        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9669            self.change_selections(None, window, cx, |s| {
 9670                s.select_anchors(entry.selections.to_vec())
 9671            });
 9672            self.select_next_state = entry.select_next_state;
 9673            self.select_prev_state = entry.select_prev_state;
 9674            self.add_selections_state = entry.add_selections_state;
 9675            self.request_autoscroll(Autoscroll::newest(), cx);
 9676        }
 9677        self.selection_history.mode = SelectionHistoryMode::Normal;
 9678    }
 9679
 9680    pub fn redo_selection(
 9681        &mut self,
 9682        _: &RedoSelection,
 9683        window: &mut Window,
 9684        cx: &mut Context<Self>,
 9685    ) {
 9686        self.end_selection(window, cx);
 9687        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9688        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9689            self.change_selections(None, window, cx, |s| {
 9690                s.select_anchors(entry.selections.to_vec())
 9691            });
 9692            self.select_next_state = entry.select_next_state;
 9693            self.select_prev_state = entry.select_prev_state;
 9694            self.add_selections_state = entry.add_selections_state;
 9695            self.request_autoscroll(Autoscroll::newest(), cx);
 9696        }
 9697        self.selection_history.mode = SelectionHistoryMode::Normal;
 9698    }
 9699
 9700    pub fn expand_excerpts(
 9701        &mut self,
 9702        action: &ExpandExcerpts,
 9703        _: &mut Window,
 9704        cx: &mut Context<Self>,
 9705    ) {
 9706        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9707    }
 9708
 9709    pub fn expand_excerpts_down(
 9710        &mut self,
 9711        action: &ExpandExcerptsDown,
 9712        _: &mut Window,
 9713        cx: &mut Context<Self>,
 9714    ) {
 9715        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9716    }
 9717
 9718    pub fn expand_excerpts_up(
 9719        &mut self,
 9720        action: &ExpandExcerptsUp,
 9721        _: &mut Window,
 9722        cx: &mut Context<Self>,
 9723    ) {
 9724        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9725    }
 9726
 9727    pub fn expand_excerpts_for_direction(
 9728        &mut self,
 9729        lines: u32,
 9730        direction: ExpandExcerptDirection,
 9731
 9732        cx: &mut Context<Self>,
 9733    ) {
 9734        let selections = self.selections.disjoint_anchors();
 9735
 9736        let lines = if lines == 0 {
 9737            EditorSettings::get_global(cx).expand_excerpt_lines
 9738        } else {
 9739            lines
 9740        };
 9741
 9742        self.buffer.update(cx, |buffer, cx| {
 9743            let snapshot = buffer.snapshot(cx);
 9744            let mut excerpt_ids = selections
 9745                .iter()
 9746                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
 9747                .collect::<Vec<_>>();
 9748            excerpt_ids.sort();
 9749            excerpt_ids.dedup();
 9750            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9751        })
 9752    }
 9753
 9754    pub fn expand_excerpt(
 9755        &mut self,
 9756        excerpt: ExcerptId,
 9757        direction: ExpandExcerptDirection,
 9758        cx: &mut Context<Self>,
 9759    ) {
 9760        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9761        self.buffer.update(cx, |buffer, cx| {
 9762            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9763        })
 9764    }
 9765
 9766    pub fn go_to_singleton_buffer_point(
 9767        &mut self,
 9768        point: Point,
 9769        window: &mut Window,
 9770        cx: &mut Context<Self>,
 9771    ) {
 9772        self.go_to_singleton_buffer_range(point..point, window, cx);
 9773    }
 9774
 9775    pub fn go_to_singleton_buffer_range(
 9776        &mut self,
 9777        range: Range<Point>,
 9778        window: &mut Window,
 9779        cx: &mut Context<Self>,
 9780    ) {
 9781        let multibuffer = self.buffer().read(cx);
 9782        let Some(buffer) = multibuffer.as_singleton() else {
 9783            return;
 9784        };
 9785        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
 9786            return;
 9787        };
 9788        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
 9789            return;
 9790        };
 9791        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
 9792            s.select_anchor_ranges([start..end])
 9793        });
 9794    }
 9795
 9796    fn go_to_diagnostic(
 9797        &mut self,
 9798        _: &GoToDiagnostic,
 9799        window: &mut Window,
 9800        cx: &mut Context<Self>,
 9801    ) {
 9802        self.go_to_diagnostic_impl(Direction::Next, window, cx)
 9803    }
 9804
 9805    fn go_to_prev_diagnostic(
 9806        &mut self,
 9807        _: &GoToPrevDiagnostic,
 9808        window: &mut Window,
 9809        cx: &mut Context<Self>,
 9810    ) {
 9811        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
 9812    }
 9813
 9814    pub fn go_to_diagnostic_impl(
 9815        &mut self,
 9816        direction: Direction,
 9817        window: &mut Window,
 9818        cx: &mut Context<Self>,
 9819    ) {
 9820        let buffer = self.buffer.read(cx).snapshot(cx);
 9821        let selection = self.selections.newest::<usize>(cx);
 9822
 9823        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9824        if direction == Direction::Next {
 9825            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9826                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
 9827                    return;
 9828                };
 9829                self.activate_diagnostics(
 9830                    buffer_id,
 9831                    popover.local_diagnostic.diagnostic.group_id,
 9832                    window,
 9833                    cx,
 9834                );
 9835                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9836                    let primary_range_start = active_diagnostics.primary_range.start;
 9837                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9838                        let mut new_selection = s.newest_anchor().clone();
 9839                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9840                        s.select_anchors(vec![new_selection.clone()]);
 9841                    });
 9842                    self.refresh_inline_completion(false, true, window, cx);
 9843                }
 9844                return;
 9845            }
 9846        }
 9847
 9848        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9849            active_diagnostics
 9850                .primary_range
 9851                .to_offset(&buffer)
 9852                .to_inclusive()
 9853        });
 9854        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9855            if active_primary_range.contains(&selection.head()) {
 9856                *active_primary_range.start()
 9857            } else {
 9858                selection.head()
 9859            }
 9860        } else {
 9861            selection.head()
 9862        };
 9863        let snapshot = self.snapshot(window, cx);
 9864        loop {
 9865            let mut diagnostics;
 9866            if direction == Direction::Prev {
 9867                diagnostics = buffer
 9868                    .diagnostics_in_range::<_, usize>(0..search_start)
 9869                    .collect::<Vec<_>>();
 9870                diagnostics.reverse();
 9871            } else {
 9872                diagnostics = buffer
 9873                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
 9874                    .collect::<Vec<_>>();
 9875            };
 9876            let group = diagnostics
 9877                .into_iter()
 9878                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
 9879                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9880                // be sorted in a stable way
 9881                // skip until we are at current active diagnostic, if it exists
 9882                .skip_while(|entry| {
 9883                    let is_in_range = match direction {
 9884                        Direction::Prev => entry.range.end > search_start,
 9885                        Direction::Next => entry.range.start < search_start,
 9886                    };
 9887                    is_in_range
 9888                        && self
 9889                            .active_diagnostics
 9890                            .as_ref()
 9891                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9892                })
 9893                .find_map(|entry| {
 9894                    if entry.diagnostic.is_primary
 9895                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9896                        && entry.range.start != entry.range.end
 9897                        // if we match with the active diagnostic, skip it
 9898                        && Some(entry.diagnostic.group_id)
 9899                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9900                    {
 9901                        Some((entry.range, entry.diagnostic.group_id))
 9902                    } else {
 9903                        None
 9904                    }
 9905                });
 9906
 9907            if let Some((primary_range, group_id)) = group {
 9908                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
 9909                    return;
 9910                };
 9911                self.activate_diagnostics(buffer_id, group_id, window, cx);
 9912                if self.active_diagnostics.is_some() {
 9913                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9914                        s.select(vec![Selection {
 9915                            id: selection.id,
 9916                            start: primary_range.start,
 9917                            end: primary_range.start,
 9918                            reversed: false,
 9919                            goal: SelectionGoal::None,
 9920                        }]);
 9921                    });
 9922                    self.refresh_inline_completion(false, true, window, cx);
 9923                }
 9924                break;
 9925            } else {
 9926                // Cycle around to the start of the buffer, potentially moving back to the start of
 9927                // the currently active diagnostic.
 9928                active_primary_range.take();
 9929                if direction == Direction::Prev {
 9930                    if search_start == buffer.len() {
 9931                        break;
 9932                    } else {
 9933                        search_start = buffer.len();
 9934                    }
 9935                } else if search_start == 0 {
 9936                    break;
 9937                } else {
 9938                    search_start = 0;
 9939                }
 9940            }
 9941        }
 9942    }
 9943
 9944    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
 9945        let snapshot = self.snapshot(window, cx);
 9946        let selection = self.selections.newest::<Point>(cx);
 9947        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
 9948    }
 9949
 9950    fn go_to_hunk_after_position(
 9951        &mut self,
 9952        snapshot: &EditorSnapshot,
 9953        position: Point,
 9954        window: &mut Window,
 9955        cx: &mut Context<Editor>,
 9956    ) -> Option<MultiBufferDiffHunk> {
 9957        let mut hunk = snapshot
 9958            .buffer_snapshot
 9959            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
 9960            .find(|hunk| hunk.row_range.start.0 > position.row);
 9961        if hunk.is_none() {
 9962            hunk = snapshot
 9963                .buffer_snapshot
 9964                .diff_hunks_in_range(Point::zero()..position)
 9965                .find(|hunk| hunk.row_range.end.0 < position.row)
 9966        }
 9967        if let Some(hunk) = &hunk {
 9968            let destination = Point::new(hunk.row_range.start.0, 0);
 9969            self.unfold_ranges(&[destination..destination], false, false, cx);
 9970            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9971                s.select_ranges(vec![destination..destination]);
 9972            });
 9973        }
 9974
 9975        hunk
 9976    }
 9977
 9978    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
 9979        let snapshot = self.snapshot(window, cx);
 9980        let selection = self.selections.newest::<Point>(cx);
 9981        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
 9982    }
 9983
 9984    fn go_to_hunk_before_position(
 9985        &mut self,
 9986        snapshot: &EditorSnapshot,
 9987        position: Point,
 9988        window: &mut Window,
 9989        cx: &mut Context<Editor>,
 9990    ) -> Option<MultiBufferDiffHunk> {
 9991        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
 9992        if hunk.is_none() {
 9993            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
 9994        }
 9995        if let Some(hunk) = &hunk {
 9996            let destination = Point::new(hunk.row_range.start.0, 0);
 9997            self.unfold_ranges(&[destination..destination], false, false, cx);
 9998            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9999                s.select_ranges(vec![destination..destination]);
10000            });
10001        }
10002
10003        hunk
10004    }
10005
10006    pub fn go_to_definition(
10007        &mut self,
10008        _: &GoToDefinition,
10009        window: &mut Window,
10010        cx: &mut Context<Self>,
10011    ) -> Task<Result<Navigated>> {
10012        let definition =
10013            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10014        cx.spawn_in(window, |editor, mut cx| async move {
10015            if definition.await? == Navigated::Yes {
10016                return Ok(Navigated::Yes);
10017            }
10018            match editor.update_in(&mut cx, |editor, window, cx| {
10019                editor.find_all_references(&FindAllReferences, window, cx)
10020            })? {
10021                Some(references) => references.await,
10022                None => Ok(Navigated::No),
10023            }
10024        })
10025    }
10026
10027    pub fn go_to_declaration(
10028        &mut self,
10029        _: &GoToDeclaration,
10030        window: &mut Window,
10031        cx: &mut Context<Self>,
10032    ) -> Task<Result<Navigated>> {
10033        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10034    }
10035
10036    pub fn go_to_declaration_split(
10037        &mut self,
10038        _: &GoToDeclaration,
10039        window: &mut Window,
10040        cx: &mut Context<Self>,
10041    ) -> Task<Result<Navigated>> {
10042        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10043    }
10044
10045    pub fn go_to_implementation(
10046        &mut self,
10047        _: &GoToImplementation,
10048        window: &mut Window,
10049        cx: &mut Context<Self>,
10050    ) -> Task<Result<Navigated>> {
10051        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10052    }
10053
10054    pub fn go_to_implementation_split(
10055        &mut self,
10056        _: &GoToImplementationSplit,
10057        window: &mut Window,
10058        cx: &mut Context<Self>,
10059    ) -> Task<Result<Navigated>> {
10060        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10061    }
10062
10063    pub fn go_to_type_definition(
10064        &mut self,
10065        _: &GoToTypeDefinition,
10066        window: &mut Window,
10067        cx: &mut Context<Self>,
10068    ) -> Task<Result<Navigated>> {
10069        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10070    }
10071
10072    pub fn go_to_definition_split(
10073        &mut self,
10074        _: &GoToDefinitionSplit,
10075        window: &mut Window,
10076        cx: &mut Context<Self>,
10077    ) -> Task<Result<Navigated>> {
10078        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10079    }
10080
10081    pub fn go_to_type_definition_split(
10082        &mut self,
10083        _: &GoToTypeDefinitionSplit,
10084        window: &mut Window,
10085        cx: &mut Context<Self>,
10086    ) -> Task<Result<Navigated>> {
10087        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10088    }
10089
10090    fn go_to_definition_of_kind(
10091        &mut self,
10092        kind: GotoDefinitionKind,
10093        split: bool,
10094        window: &mut Window,
10095        cx: &mut Context<Self>,
10096    ) -> Task<Result<Navigated>> {
10097        let Some(provider) = self.semantics_provider.clone() else {
10098            return Task::ready(Ok(Navigated::No));
10099        };
10100        let head = self.selections.newest::<usize>(cx).head();
10101        let buffer = self.buffer.read(cx);
10102        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10103            text_anchor
10104        } else {
10105            return Task::ready(Ok(Navigated::No));
10106        };
10107
10108        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10109            return Task::ready(Ok(Navigated::No));
10110        };
10111
10112        cx.spawn_in(window, |editor, mut cx| async move {
10113            let definitions = definitions.await?;
10114            let navigated = editor
10115                .update_in(&mut cx, |editor, window, cx| {
10116                    editor.navigate_to_hover_links(
10117                        Some(kind),
10118                        definitions
10119                            .into_iter()
10120                            .filter(|location| {
10121                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10122                            })
10123                            .map(HoverLink::Text)
10124                            .collect::<Vec<_>>(),
10125                        split,
10126                        window,
10127                        cx,
10128                    )
10129                })?
10130                .await?;
10131            anyhow::Ok(navigated)
10132        })
10133    }
10134
10135    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10136        let selection = self.selections.newest_anchor();
10137        let head = selection.head();
10138        let tail = selection.tail();
10139
10140        let Some((buffer, start_position)) =
10141            self.buffer.read(cx).text_anchor_for_position(head, cx)
10142        else {
10143            return;
10144        };
10145
10146        let end_position = if head != tail {
10147            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10148                return;
10149            };
10150            Some(pos)
10151        } else {
10152            None
10153        };
10154
10155        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10156            let url = if let Some(end_pos) = end_position {
10157                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10158            } else {
10159                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10160            };
10161
10162            if let Some(url) = url {
10163                editor.update(&mut cx, |_, cx| {
10164                    cx.open_url(&url);
10165                })
10166            } else {
10167                Ok(())
10168            }
10169        });
10170
10171        url_finder.detach();
10172    }
10173
10174    pub fn open_selected_filename(
10175        &mut self,
10176        _: &OpenSelectedFilename,
10177        window: &mut Window,
10178        cx: &mut Context<Self>,
10179    ) {
10180        let Some(workspace) = self.workspace() else {
10181            return;
10182        };
10183
10184        let position = self.selections.newest_anchor().head();
10185
10186        let Some((buffer, buffer_position)) =
10187            self.buffer.read(cx).text_anchor_for_position(position, cx)
10188        else {
10189            return;
10190        };
10191
10192        let project = self.project.clone();
10193
10194        cx.spawn_in(window, |_, mut cx| async move {
10195            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10196
10197            if let Some((_, path)) = result {
10198                workspace
10199                    .update_in(&mut cx, |workspace, window, cx| {
10200                        workspace.open_resolved_path(path, window, cx)
10201                    })?
10202                    .await?;
10203            }
10204            anyhow::Ok(())
10205        })
10206        .detach();
10207    }
10208
10209    pub(crate) fn navigate_to_hover_links(
10210        &mut self,
10211        kind: Option<GotoDefinitionKind>,
10212        mut definitions: Vec<HoverLink>,
10213        split: bool,
10214        window: &mut Window,
10215        cx: &mut Context<Editor>,
10216    ) -> Task<Result<Navigated>> {
10217        // If there is one definition, just open it directly
10218        if definitions.len() == 1 {
10219            let definition = definitions.pop().unwrap();
10220
10221            enum TargetTaskResult {
10222                Location(Option<Location>),
10223                AlreadyNavigated,
10224            }
10225
10226            let target_task = match definition {
10227                HoverLink::Text(link) => {
10228                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10229                }
10230                HoverLink::InlayHint(lsp_location, server_id) => {
10231                    let computation =
10232                        self.compute_target_location(lsp_location, server_id, window, cx);
10233                    cx.background_executor().spawn(async move {
10234                        let location = computation.await?;
10235                        Ok(TargetTaskResult::Location(location))
10236                    })
10237                }
10238                HoverLink::Url(url) => {
10239                    cx.open_url(&url);
10240                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10241                }
10242                HoverLink::File(path) => {
10243                    if let Some(workspace) = self.workspace() {
10244                        cx.spawn_in(window, |_, mut cx| async move {
10245                            workspace
10246                                .update_in(&mut cx, |workspace, window, cx| {
10247                                    workspace.open_resolved_path(path, window, cx)
10248                                })?
10249                                .await
10250                                .map(|_| TargetTaskResult::AlreadyNavigated)
10251                        })
10252                    } else {
10253                        Task::ready(Ok(TargetTaskResult::Location(None)))
10254                    }
10255                }
10256            };
10257            cx.spawn_in(window, |editor, mut cx| async move {
10258                let target = match target_task.await.context("target resolution task")? {
10259                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10260                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10261                    TargetTaskResult::Location(Some(target)) => target,
10262                };
10263
10264                editor.update_in(&mut cx, |editor, window, cx| {
10265                    let Some(workspace) = editor.workspace() else {
10266                        return Navigated::No;
10267                    };
10268                    let pane = workspace.read(cx).active_pane().clone();
10269
10270                    let range = target.range.to_point(target.buffer.read(cx));
10271                    let range = editor.range_for_match(&range);
10272                    let range = collapse_multiline_range(range);
10273
10274                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10275                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10276                    } else {
10277                        window.defer(cx, move |window, cx| {
10278                            let target_editor: Entity<Self> =
10279                                workspace.update(cx, |workspace, cx| {
10280                                    let pane = if split {
10281                                        workspace.adjacent_pane(window, cx)
10282                                    } else {
10283                                        workspace.active_pane().clone()
10284                                    };
10285
10286                                    workspace.open_project_item(
10287                                        pane,
10288                                        target.buffer.clone(),
10289                                        true,
10290                                        true,
10291                                        window,
10292                                        cx,
10293                                    )
10294                                });
10295                            target_editor.update(cx, |target_editor, cx| {
10296                                // When selecting a definition in a different buffer, disable the nav history
10297                                // to avoid creating a history entry at the previous cursor location.
10298                                pane.update(cx, |pane, _| pane.disable_history());
10299                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10300                                pane.update(cx, |pane, _| pane.enable_history());
10301                            });
10302                        });
10303                    }
10304                    Navigated::Yes
10305                })
10306            })
10307        } else if !definitions.is_empty() {
10308            cx.spawn_in(window, |editor, mut cx| async move {
10309                let (title, location_tasks, workspace) = editor
10310                    .update_in(&mut cx, |editor, window, cx| {
10311                        let tab_kind = match kind {
10312                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10313                            _ => "Definitions",
10314                        };
10315                        let title = definitions
10316                            .iter()
10317                            .find_map(|definition| match definition {
10318                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10319                                    let buffer = origin.buffer.read(cx);
10320                                    format!(
10321                                        "{} for {}",
10322                                        tab_kind,
10323                                        buffer
10324                                            .text_for_range(origin.range.clone())
10325                                            .collect::<String>()
10326                                    )
10327                                }),
10328                                HoverLink::InlayHint(_, _) => None,
10329                                HoverLink::Url(_) => None,
10330                                HoverLink::File(_) => None,
10331                            })
10332                            .unwrap_or(tab_kind.to_string());
10333                        let location_tasks = definitions
10334                            .into_iter()
10335                            .map(|definition| match definition {
10336                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10337                                HoverLink::InlayHint(lsp_location, server_id) => editor
10338                                    .compute_target_location(lsp_location, server_id, window, cx),
10339                                HoverLink::Url(_) => Task::ready(Ok(None)),
10340                                HoverLink::File(_) => Task::ready(Ok(None)),
10341                            })
10342                            .collect::<Vec<_>>();
10343                        (title, location_tasks, editor.workspace().clone())
10344                    })
10345                    .context("location tasks preparation")?;
10346
10347                let locations = future::join_all(location_tasks)
10348                    .await
10349                    .into_iter()
10350                    .filter_map(|location| location.transpose())
10351                    .collect::<Result<_>>()
10352                    .context("location tasks")?;
10353
10354                let Some(workspace) = workspace else {
10355                    return Ok(Navigated::No);
10356                };
10357                let opened = workspace
10358                    .update_in(&mut cx, |workspace, window, cx| {
10359                        Self::open_locations_in_multibuffer(
10360                            workspace,
10361                            locations,
10362                            title,
10363                            split,
10364                            MultibufferSelectionMode::First,
10365                            window,
10366                            cx,
10367                        )
10368                    })
10369                    .ok();
10370
10371                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10372            })
10373        } else {
10374            Task::ready(Ok(Navigated::No))
10375        }
10376    }
10377
10378    fn compute_target_location(
10379        &self,
10380        lsp_location: lsp::Location,
10381        server_id: LanguageServerId,
10382        window: &mut Window,
10383        cx: &mut Context<Self>,
10384    ) -> Task<anyhow::Result<Option<Location>>> {
10385        let Some(project) = self.project.clone() else {
10386            return Task::ready(Ok(None));
10387        };
10388
10389        cx.spawn_in(window, move |editor, mut cx| async move {
10390            let location_task = editor.update(&mut cx, |_, cx| {
10391                project.update(cx, |project, cx| {
10392                    let language_server_name = project
10393                        .language_server_statuses(cx)
10394                        .find(|(id, _)| server_id == *id)
10395                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10396                    language_server_name.map(|language_server_name| {
10397                        project.open_local_buffer_via_lsp(
10398                            lsp_location.uri.clone(),
10399                            server_id,
10400                            language_server_name,
10401                            cx,
10402                        )
10403                    })
10404                })
10405            })?;
10406            let location = match location_task {
10407                Some(task) => Some({
10408                    let target_buffer_handle = task.await.context("open local buffer")?;
10409                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10410                        let target_start = target_buffer
10411                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10412                        let target_end = target_buffer
10413                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10414                        target_buffer.anchor_after(target_start)
10415                            ..target_buffer.anchor_before(target_end)
10416                    })?;
10417                    Location {
10418                        buffer: target_buffer_handle,
10419                        range,
10420                    }
10421                }),
10422                None => None,
10423            };
10424            Ok(location)
10425        })
10426    }
10427
10428    pub fn find_all_references(
10429        &mut self,
10430        _: &FindAllReferences,
10431        window: &mut Window,
10432        cx: &mut Context<Self>,
10433    ) -> Option<Task<Result<Navigated>>> {
10434        let selection = self.selections.newest::<usize>(cx);
10435        let multi_buffer = self.buffer.read(cx);
10436        let head = selection.head();
10437
10438        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10439        let head_anchor = multi_buffer_snapshot.anchor_at(
10440            head,
10441            if head < selection.tail() {
10442                Bias::Right
10443            } else {
10444                Bias::Left
10445            },
10446        );
10447
10448        match self
10449            .find_all_references_task_sources
10450            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10451        {
10452            Ok(_) => {
10453                log::info!(
10454                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10455                );
10456                return None;
10457            }
10458            Err(i) => {
10459                self.find_all_references_task_sources.insert(i, head_anchor);
10460            }
10461        }
10462
10463        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10464        let workspace = self.workspace()?;
10465        let project = workspace.read(cx).project().clone();
10466        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10467        Some(cx.spawn_in(window, |editor, mut cx| async move {
10468            let _cleanup = defer({
10469                let mut cx = cx.clone();
10470                move || {
10471                    let _ = editor.update(&mut cx, |editor, _| {
10472                        if let Ok(i) =
10473                            editor
10474                                .find_all_references_task_sources
10475                                .binary_search_by(|anchor| {
10476                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10477                                })
10478                        {
10479                            editor.find_all_references_task_sources.remove(i);
10480                        }
10481                    });
10482                }
10483            });
10484
10485            let locations = references.await?;
10486            if locations.is_empty() {
10487                return anyhow::Ok(Navigated::No);
10488            }
10489
10490            workspace.update_in(&mut cx, |workspace, window, cx| {
10491                let title = locations
10492                    .first()
10493                    .as_ref()
10494                    .map(|location| {
10495                        let buffer = location.buffer.read(cx);
10496                        format!(
10497                            "References to `{}`",
10498                            buffer
10499                                .text_for_range(location.range.clone())
10500                                .collect::<String>()
10501                        )
10502                    })
10503                    .unwrap();
10504                Self::open_locations_in_multibuffer(
10505                    workspace,
10506                    locations,
10507                    title,
10508                    false,
10509                    MultibufferSelectionMode::First,
10510                    window,
10511                    cx,
10512                );
10513                Navigated::Yes
10514            })
10515        }))
10516    }
10517
10518    /// Opens a multibuffer with the given project locations in it
10519    pub fn open_locations_in_multibuffer(
10520        workspace: &mut Workspace,
10521        mut locations: Vec<Location>,
10522        title: String,
10523        split: bool,
10524        multibuffer_selection_mode: MultibufferSelectionMode,
10525        window: &mut Window,
10526        cx: &mut Context<Workspace>,
10527    ) {
10528        // If there are multiple definitions, open them in a multibuffer
10529        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10530        let mut locations = locations.into_iter().peekable();
10531        let mut ranges = Vec::new();
10532        let capability = workspace.project().read(cx).capability();
10533
10534        let excerpt_buffer = cx.new(|cx| {
10535            let mut multibuffer = MultiBuffer::new(capability);
10536            while let Some(location) = locations.next() {
10537                let buffer = location.buffer.read(cx);
10538                let mut ranges_for_buffer = Vec::new();
10539                let range = location.range.to_offset(buffer);
10540                ranges_for_buffer.push(range.clone());
10541
10542                while let Some(next_location) = locations.peek() {
10543                    if next_location.buffer == location.buffer {
10544                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10545                        locations.next();
10546                    } else {
10547                        break;
10548                    }
10549                }
10550
10551                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10552                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10553                    location.buffer.clone(),
10554                    ranges_for_buffer,
10555                    DEFAULT_MULTIBUFFER_CONTEXT,
10556                    cx,
10557                ))
10558            }
10559
10560            multibuffer.with_title(title)
10561        });
10562
10563        let editor = cx.new(|cx| {
10564            Editor::for_multibuffer(
10565                excerpt_buffer,
10566                Some(workspace.project().clone()),
10567                true,
10568                window,
10569                cx,
10570            )
10571        });
10572        editor.update(cx, |editor, cx| {
10573            match multibuffer_selection_mode {
10574                MultibufferSelectionMode::First => {
10575                    if let Some(first_range) = ranges.first() {
10576                        editor.change_selections(None, window, cx, |selections| {
10577                            selections.clear_disjoint();
10578                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10579                        });
10580                    }
10581                    editor.highlight_background::<Self>(
10582                        &ranges,
10583                        |theme| theme.editor_highlighted_line_background,
10584                        cx,
10585                    );
10586                }
10587                MultibufferSelectionMode::All => {
10588                    editor.change_selections(None, window, cx, |selections| {
10589                        selections.clear_disjoint();
10590                        selections.select_anchor_ranges(ranges);
10591                    });
10592                }
10593            }
10594            editor.register_buffers_with_language_servers(cx);
10595        });
10596
10597        let item = Box::new(editor);
10598        let item_id = item.item_id();
10599
10600        if split {
10601            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10602        } else {
10603            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10604                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10605                    pane.close_current_preview_item(window, cx)
10606                } else {
10607                    None
10608                }
10609            });
10610            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10611        }
10612        workspace.active_pane().update(cx, |pane, cx| {
10613            pane.set_preview_item_id(Some(item_id), cx);
10614        });
10615    }
10616
10617    pub fn rename(
10618        &mut self,
10619        _: &Rename,
10620        window: &mut Window,
10621        cx: &mut Context<Self>,
10622    ) -> Option<Task<Result<()>>> {
10623        use language::ToOffset as _;
10624
10625        let provider = self.semantics_provider.clone()?;
10626        let selection = self.selections.newest_anchor().clone();
10627        let (cursor_buffer, cursor_buffer_position) = self
10628            .buffer
10629            .read(cx)
10630            .text_anchor_for_position(selection.head(), cx)?;
10631        let (tail_buffer, cursor_buffer_position_end) = self
10632            .buffer
10633            .read(cx)
10634            .text_anchor_for_position(selection.tail(), cx)?;
10635        if tail_buffer != cursor_buffer {
10636            return None;
10637        }
10638
10639        let snapshot = cursor_buffer.read(cx).snapshot();
10640        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10641        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10642        let prepare_rename = provider
10643            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10644            .unwrap_or_else(|| Task::ready(Ok(None)));
10645        drop(snapshot);
10646
10647        Some(cx.spawn_in(window, |this, mut cx| async move {
10648            let rename_range = if let Some(range) = prepare_rename.await? {
10649                Some(range)
10650            } else {
10651                this.update(&mut cx, |this, cx| {
10652                    let buffer = this.buffer.read(cx).snapshot(cx);
10653                    let mut buffer_highlights = this
10654                        .document_highlights_for_position(selection.head(), &buffer)
10655                        .filter(|highlight| {
10656                            highlight.start.excerpt_id == selection.head().excerpt_id
10657                                && highlight.end.excerpt_id == selection.head().excerpt_id
10658                        });
10659                    buffer_highlights
10660                        .next()
10661                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10662                })?
10663            };
10664            if let Some(rename_range) = rename_range {
10665                this.update_in(&mut cx, |this, window, cx| {
10666                    let snapshot = cursor_buffer.read(cx).snapshot();
10667                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10668                    let cursor_offset_in_rename_range =
10669                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10670                    let cursor_offset_in_rename_range_end =
10671                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10672
10673                    this.take_rename(false, window, cx);
10674                    let buffer = this.buffer.read(cx).read(cx);
10675                    let cursor_offset = selection.head().to_offset(&buffer);
10676                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10677                    let rename_end = rename_start + rename_buffer_range.len();
10678                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10679                    let mut old_highlight_id = None;
10680                    let old_name: Arc<str> = buffer
10681                        .chunks(rename_start..rename_end, true)
10682                        .map(|chunk| {
10683                            if old_highlight_id.is_none() {
10684                                old_highlight_id = chunk.syntax_highlight_id;
10685                            }
10686                            chunk.text
10687                        })
10688                        .collect::<String>()
10689                        .into();
10690
10691                    drop(buffer);
10692
10693                    // Position the selection in the rename editor so that it matches the current selection.
10694                    this.show_local_selections = false;
10695                    let rename_editor = cx.new(|cx| {
10696                        let mut editor = Editor::single_line(window, cx);
10697                        editor.buffer.update(cx, |buffer, cx| {
10698                            buffer.edit([(0..0, old_name.clone())], None, cx)
10699                        });
10700                        let rename_selection_range = match cursor_offset_in_rename_range
10701                            .cmp(&cursor_offset_in_rename_range_end)
10702                        {
10703                            Ordering::Equal => {
10704                                editor.select_all(&SelectAll, window, cx);
10705                                return editor;
10706                            }
10707                            Ordering::Less => {
10708                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10709                            }
10710                            Ordering::Greater => {
10711                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10712                            }
10713                        };
10714                        if rename_selection_range.end > old_name.len() {
10715                            editor.select_all(&SelectAll, window, cx);
10716                        } else {
10717                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10718                                s.select_ranges([rename_selection_range]);
10719                            });
10720                        }
10721                        editor
10722                    });
10723                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10724                        if e == &EditorEvent::Focused {
10725                            cx.emit(EditorEvent::FocusedIn)
10726                        }
10727                    })
10728                    .detach();
10729
10730                    let write_highlights =
10731                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10732                    let read_highlights =
10733                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10734                    let ranges = write_highlights
10735                        .iter()
10736                        .flat_map(|(_, ranges)| ranges.iter())
10737                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10738                        .cloned()
10739                        .collect();
10740
10741                    this.highlight_text::<Rename>(
10742                        ranges,
10743                        HighlightStyle {
10744                            fade_out: Some(0.6),
10745                            ..Default::default()
10746                        },
10747                        cx,
10748                    );
10749                    let rename_focus_handle = rename_editor.focus_handle(cx);
10750                    window.focus(&rename_focus_handle);
10751                    let block_id = this.insert_blocks(
10752                        [BlockProperties {
10753                            style: BlockStyle::Flex,
10754                            placement: BlockPlacement::Below(range.start),
10755                            height: 1,
10756                            render: Arc::new({
10757                                let rename_editor = rename_editor.clone();
10758                                move |cx: &mut BlockContext| {
10759                                    let mut text_style = cx.editor_style.text.clone();
10760                                    if let Some(highlight_style) = old_highlight_id
10761                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10762                                    {
10763                                        text_style = text_style.highlight(highlight_style);
10764                                    }
10765                                    div()
10766                                        .block_mouse_down()
10767                                        .pl(cx.anchor_x)
10768                                        .child(EditorElement::new(
10769                                            &rename_editor,
10770                                            EditorStyle {
10771                                                background: cx.theme().system().transparent,
10772                                                local_player: cx.editor_style.local_player,
10773                                                text: text_style,
10774                                                scrollbar_width: cx.editor_style.scrollbar_width,
10775                                                syntax: cx.editor_style.syntax.clone(),
10776                                                status: cx.editor_style.status.clone(),
10777                                                inlay_hints_style: HighlightStyle {
10778                                                    font_weight: Some(FontWeight::BOLD),
10779                                                    ..make_inlay_hints_style(cx.app)
10780                                                },
10781                                                inline_completion_styles: make_suggestion_styles(
10782                                                    cx.app,
10783                                                ),
10784                                                ..EditorStyle::default()
10785                                            },
10786                                        ))
10787                                        .into_any_element()
10788                                }
10789                            }),
10790                            priority: 0,
10791                        }],
10792                        Some(Autoscroll::fit()),
10793                        cx,
10794                    )[0];
10795                    this.pending_rename = Some(RenameState {
10796                        range,
10797                        old_name,
10798                        editor: rename_editor,
10799                        block_id,
10800                    });
10801                })?;
10802            }
10803
10804            Ok(())
10805        }))
10806    }
10807
10808    pub fn confirm_rename(
10809        &mut self,
10810        _: &ConfirmRename,
10811        window: &mut Window,
10812        cx: &mut Context<Self>,
10813    ) -> Option<Task<Result<()>>> {
10814        let rename = self.take_rename(false, window, cx)?;
10815        let workspace = self.workspace()?.downgrade();
10816        let (buffer, start) = self
10817            .buffer
10818            .read(cx)
10819            .text_anchor_for_position(rename.range.start, cx)?;
10820        let (end_buffer, _) = self
10821            .buffer
10822            .read(cx)
10823            .text_anchor_for_position(rename.range.end, cx)?;
10824        if buffer != end_buffer {
10825            return None;
10826        }
10827
10828        let old_name = rename.old_name;
10829        let new_name = rename.editor.read(cx).text(cx);
10830
10831        let rename = self.semantics_provider.as_ref()?.perform_rename(
10832            &buffer,
10833            start,
10834            new_name.clone(),
10835            cx,
10836        )?;
10837
10838        Some(cx.spawn_in(window, |editor, mut cx| async move {
10839            let project_transaction = rename.await?;
10840            Self::open_project_transaction(
10841                &editor,
10842                workspace,
10843                project_transaction,
10844                format!("Rename: {}{}", old_name, new_name),
10845                cx.clone(),
10846            )
10847            .await?;
10848
10849            editor.update(&mut cx, |editor, cx| {
10850                editor.refresh_document_highlights(cx);
10851            })?;
10852            Ok(())
10853        }))
10854    }
10855
10856    fn take_rename(
10857        &mut self,
10858        moving_cursor: bool,
10859        window: &mut Window,
10860        cx: &mut Context<Self>,
10861    ) -> Option<RenameState> {
10862        let rename = self.pending_rename.take()?;
10863        if rename.editor.focus_handle(cx).is_focused(window) {
10864            window.focus(&self.focus_handle);
10865        }
10866
10867        self.remove_blocks(
10868            [rename.block_id].into_iter().collect(),
10869            Some(Autoscroll::fit()),
10870            cx,
10871        );
10872        self.clear_highlights::<Rename>(cx);
10873        self.show_local_selections = true;
10874
10875        if moving_cursor {
10876            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10877                editor.selections.newest::<usize>(cx).head()
10878            });
10879
10880            // Update the selection to match the position of the selection inside
10881            // the rename editor.
10882            let snapshot = self.buffer.read(cx).read(cx);
10883            let rename_range = rename.range.to_offset(&snapshot);
10884            let cursor_in_editor = snapshot
10885                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10886                .min(rename_range.end);
10887            drop(snapshot);
10888
10889            self.change_selections(None, window, cx, |s| {
10890                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10891            });
10892        } else {
10893            self.refresh_document_highlights(cx);
10894        }
10895
10896        Some(rename)
10897    }
10898
10899    pub fn pending_rename(&self) -> Option<&RenameState> {
10900        self.pending_rename.as_ref()
10901    }
10902
10903    fn format(
10904        &mut self,
10905        _: &Format,
10906        window: &mut Window,
10907        cx: &mut Context<Self>,
10908    ) -> Option<Task<Result<()>>> {
10909        let project = match &self.project {
10910            Some(project) => project.clone(),
10911            None => return None,
10912        };
10913
10914        Some(self.perform_format(
10915            project,
10916            FormatTrigger::Manual,
10917            FormatTarget::Buffers,
10918            window,
10919            cx,
10920        ))
10921    }
10922
10923    fn format_selections(
10924        &mut self,
10925        _: &FormatSelections,
10926        window: &mut Window,
10927        cx: &mut Context<Self>,
10928    ) -> Option<Task<Result<()>>> {
10929        let project = match &self.project {
10930            Some(project) => project.clone(),
10931            None => return None,
10932        };
10933
10934        let ranges = self
10935            .selections
10936            .all_adjusted(cx)
10937            .into_iter()
10938            .map(|selection| selection.range())
10939            .collect_vec();
10940
10941        Some(self.perform_format(
10942            project,
10943            FormatTrigger::Manual,
10944            FormatTarget::Ranges(ranges),
10945            window,
10946            cx,
10947        ))
10948    }
10949
10950    fn perform_format(
10951        &mut self,
10952        project: Entity<Project>,
10953        trigger: FormatTrigger,
10954        target: FormatTarget,
10955        window: &mut Window,
10956        cx: &mut Context<Self>,
10957    ) -> Task<Result<()>> {
10958        let buffer = self.buffer.clone();
10959        let (buffers, target) = match target {
10960            FormatTarget::Buffers => {
10961                let mut buffers = buffer.read(cx).all_buffers();
10962                if trigger == FormatTrigger::Save {
10963                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10964                }
10965                (buffers, LspFormatTarget::Buffers)
10966            }
10967            FormatTarget::Ranges(selection_ranges) => {
10968                let multi_buffer = buffer.read(cx);
10969                let snapshot = multi_buffer.read(cx);
10970                let mut buffers = HashSet::default();
10971                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10972                    BTreeMap::new();
10973                for selection_range in selection_ranges {
10974                    for (buffer, buffer_range, _) in
10975                        snapshot.range_to_buffer_ranges(selection_range)
10976                    {
10977                        let buffer_id = buffer.remote_id();
10978                        let start = buffer.anchor_before(buffer_range.start);
10979                        let end = buffer.anchor_after(buffer_range.end);
10980                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10981                        buffer_id_to_ranges
10982                            .entry(buffer_id)
10983                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10984                            .or_insert_with(|| vec![start..end]);
10985                    }
10986                }
10987                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10988            }
10989        };
10990
10991        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10992        let format = project.update(cx, |project, cx| {
10993            project.format(buffers, target, true, trigger, cx)
10994        });
10995
10996        cx.spawn_in(window, |_, mut cx| async move {
10997            let transaction = futures::select_biased! {
10998                () = timeout => {
10999                    log::warn!("timed out waiting for formatting");
11000                    None
11001                }
11002                transaction = format.log_err().fuse() => transaction,
11003            };
11004
11005            buffer
11006                .update(&mut cx, |buffer, cx| {
11007                    if let Some(transaction) = transaction {
11008                        if !buffer.is_singleton() {
11009                            buffer.push_transaction(&transaction.0, cx);
11010                        }
11011                    }
11012
11013                    cx.notify();
11014                })
11015                .ok();
11016
11017            Ok(())
11018        })
11019    }
11020
11021    fn restart_language_server(
11022        &mut self,
11023        _: &RestartLanguageServer,
11024        _: &mut Window,
11025        cx: &mut Context<Self>,
11026    ) {
11027        if let Some(project) = self.project.clone() {
11028            self.buffer.update(cx, |multi_buffer, cx| {
11029                project.update(cx, |project, cx| {
11030                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11031                });
11032            })
11033        }
11034    }
11035
11036    fn cancel_language_server_work(
11037        &mut self,
11038        _: &actions::CancelLanguageServerWork,
11039        _: &mut Window,
11040        cx: &mut Context<Self>,
11041    ) {
11042        if let Some(project) = self.project.clone() {
11043            self.buffer.update(cx, |multi_buffer, cx| {
11044                project.update(cx, |project, cx| {
11045                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11046                });
11047            })
11048        }
11049    }
11050
11051    fn show_character_palette(
11052        &mut self,
11053        _: &ShowCharacterPalette,
11054        window: &mut Window,
11055        _: &mut Context<Self>,
11056    ) {
11057        window.show_character_palette();
11058    }
11059
11060    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11061        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11062            let buffer = self.buffer.read(cx).snapshot(cx);
11063            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11064            let is_valid = buffer
11065                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11066                .any(|entry| {
11067                    entry.diagnostic.is_primary
11068                        && !entry.range.is_empty()
11069                        && entry.range.start == primary_range_start
11070                        && entry.diagnostic.message == active_diagnostics.primary_message
11071                });
11072
11073            if is_valid != active_diagnostics.is_valid {
11074                active_diagnostics.is_valid = is_valid;
11075                let mut new_styles = HashMap::default();
11076                for (block_id, diagnostic) in &active_diagnostics.blocks {
11077                    new_styles.insert(
11078                        *block_id,
11079                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11080                    );
11081                }
11082                self.display_map.update(cx, |display_map, _cx| {
11083                    display_map.replace_blocks(new_styles)
11084                });
11085            }
11086        }
11087    }
11088
11089    fn activate_diagnostics(
11090        &mut self,
11091        buffer_id: BufferId,
11092        group_id: usize,
11093        window: &mut Window,
11094        cx: &mut Context<Self>,
11095    ) {
11096        self.dismiss_diagnostics(cx);
11097        let snapshot = self.snapshot(window, cx);
11098        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11099            let buffer = self.buffer.read(cx).snapshot(cx);
11100
11101            let mut primary_range = None;
11102            let mut primary_message = None;
11103            let diagnostic_group = buffer
11104                .diagnostic_group(buffer_id, group_id)
11105                .filter_map(|entry| {
11106                    let start = entry.range.start;
11107                    let end = entry.range.end;
11108                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11109                        && (start.row == end.row
11110                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11111                    {
11112                        return None;
11113                    }
11114                    if entry.diagnostic.is_primary {
11115                        primary_range = Some(entry.range.clone());
11116                        primary_message = Some(entry.diagnostic.message.clone());
11117                    }
11118                    Some(entry)
11119                })
11120                .collect::<Vec<_>>();
11121            let primary_range = primary_range?;
11122            let primary_message = primary_message?;
11123
11124            let blocks = display_map
11125                .insert_blocks(
11126                    diagnostic_group.iter().map(|entry| {
11127                        let diagnostic = entry.diagnostic.clone();
11128                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11129                        BlockProperties {
11130                            style: BlockStyle::Fixed,
11131                            placement: BlockPlacement::Below(
11132                                buffer.anchor_after(entry.range.start),
11133                            ),
11134                            height: message_height,
11135                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11136                            priority: 0,
11137                        }
11138                    }),
11139                    cx,
11140                )
11141                .into_iter()
11142                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11143                .collect();
11144
11145            Some(ActiveDiagnosticGroup {
11146                primary_range: buffer.anchor_before(primary_range.start)
11147                    ..buffer.anchor_after(primary_range.end),
11148                primary_message,
11149                group_id,
11150                blocks,
11151                is_valid: true,
11152            })
11153        });
11154    }
11155
11156    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11157        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11158            self.display_map.update(cx, |display_map, cx| {
11159                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11160            });
11161            cx.notify();
11162        }
11163    }
11164
11165    pub fn set_selections_from_remote(
11166        &mut self,
11167        selections: Vec<Selection<Anchor>>,
11168        pending_selection: Option<Selection<Anchor>>,
11169        window: &mut Window,
11170        cx: &mut Context<Self>,
11171    ) {
11172        let old_cursor_position = self.selections.newest_anchor().head();
11173        self.selections.change_with(cx, |s| {
11174            s.select_anchors(selections);
11175            if let Some(pending_selection) = pending_selection {
11176                s.set_pending(pending_selection, SelectMode::Character);
11177            } else {
11178                s.clear_pending();
11179            }
11180        });
11181        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11182    }
11183
11184    fn push_to_selection_history(&mut self) {
11185        self.selection_history.push(SelectionHistoryEntry {
11186            selections: self.selections.disjoint_anchors(),
11187            select_next_state: self.select_next_state.clone(),
11188            select_prev_state: self.select_prev_state.clone(),
11189            add_selections_state: self.add_selections_state.clone(),
11190        });
11191    }
11192
11193    pub fn transact(
11194        &mut self,
11195        window: &mut Window,
11196        cx: &mut Context<Self>,
11197        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11198    ) -> Option<TransactionId> {
11199        self.start_transaction_at(Instant::now(), window, cx);
11200        update(self, window, cx);
11201        self.end_transaction_at(Instant::now(), cx)
11202    }
11203
11204    pub fn start_transaction_at(
11205        &mut self,
11206        now: Instant,
11207        window: &mut Window,
11208        cx: &mut Context<Self>,
11209    ) {
11210        self.end_selection(window, cx);
11211        if let Some(tx_id) = self
11212            .buffer
11213            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11214        {
11215            self.selection_history
11216                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11217            cx.emit(EditorEvent::TransactionBegun {
11218                transaction_id: tx_id,
11219            })
11220        }
11221    }
11222
11223    pub fn end_transaction_at(
11224        &mut self,
11225        now: Instant,
11226        cx: &mut Context<Self>,
11227    ) -> Option<TransactionId> {
11228        if let Some(transaction_id) = self
11229            .buffer
11230            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11231        {
11232            if let Some((_, end_selections)) =
11233                self.selection_history.transaction_mut(transaction_id)
11234            {
11235                *end_selections = Some(self.selections.disjoint_anchors());
11236            } else {
11237                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11238            }
11239
11240            cx.emit(EditorEvent::Edited { transaction_id });
11241            Some(transaction_id)
11242        } else {
11243            None
11244        }
11245    }
11246
11247    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11248        if self.selection_mark_mode {
11249            self.change_selections(None, window, cx, |s| {
11250                s.move_with(|_, sel| {
11251                    sel.collapse_to(sel.head(), SelectionGoal::None);
11252                });
11253            })
11254        }
11255        self.selection_mark_mode = true;
11256        cx.notify();
11257    }
11258
11259    pub fn swap_selection_ends(
11260        &mut self,
11261        _: &actions::SwapSelectionEnds,
11262        window: &mut Window,
11263        cx: &mut Context<Self>,
11264    ) {
11265        self.change_selections(None, window, cx, |s| {
11266            s.move_with(|_, sel| {
11267                if sel.start != sel.end {
11268                    sel.reversed = !sel.reversed
11269                }
11270            });
11271        });
11272        self.request_autoscroll(Autoscroll::newest(), cx);
11273        cx.notify();
11274    }
11275
11276    pub fn toggle_fold(
11277        &mut self,
11278        _: &actions::ToggleFold,
11279        window: &mut Window,
11280        cx: &mut Context<Self>,
11281    ) {
11282        if self.is_singleton(cx) {
11283            let selection = self.selections.newest::<Point>(cx);
11284
11285            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11286            let range = if selection.is_empty() {
11287                let point = selection.head().to_display_point(&display_map);
11288                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11289                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11290                    .to_point(&display_map);
11291                start..end
11292            } else {
11293                selection.range()
11294            };
11295            if display_map.folds_in_range(range).next().is_some() {
11296                self.unfold_lines(&Default::default(), window, cx)
11297            } else {
11298                self.fold(&Default::default(), window, cx)
11299            }
11300        } else {
11301            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11302            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11303                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11304                .map(|(snapshot, _, _)| snapshot.remote_id())
11305                .collect();
11306
11307            for buffer_id in buffer_ids {
11308                if self.is_buffer_folded(buffer_id, cx) {
11309                    self.unfold_buffer(buffer_id, cx);
11310                } else {
11311                    self.fold_buffer(buffer_id, cx);
11312                }
11313            }
11314        }
11315    }
11316
11317    pub fn toggle_fold_recursive(
11318        &mut self,
11319        _: &actions::ToggleFoldRecursive,
11320        window: &mut Window,
11321        cx: &mut Context<Self>,
11322    ) {
11323        let selection = self.selections.newest::<Point>(cx);
11324
11325        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11326        let range = if selection.is_empty() {
11327            let point = selection.head().to_display_point(&display_map);
11328            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11329            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11330                .to_point(&display_map);
11331            start..end
11332        } else {
11333            selection.range()
11334        };
11335        if display_map.folds_in_range(range).next().is_some() {
11336            self.unfold_recursive(&Default::default(), window, cx)
11337        } else {
11338            self.fold_recursive(&Default::default(), window, cx)
11339        }
11340    }
11341
11342    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11343        if self.is_singleton(cx) {
11344            let mut to_fold = Vec::new();
11345            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11346            let selections = self.selections.all_adjusted(cx);
11347
11348            for selection in selections {
11349                let range = selection.range().sorted();
11350                let buffer_start_row = range.start.row;
11351
11352                if range.start.row != range.end.row {
11353                    let mut found = false;
11354                    let mut row = range.start.row;
11355                    while row <= range.end.row {
11356                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11357                        {
11358                            found = true;
11359                            row = crease.range().end.row + 1;
11360                            to_fold.push(crease);
11361                        } else {
11362                            row += 1
11363                        }
11364                    }
11365                    if found {
11366                        continue;
11367                    }
11368                }
11369
11370                for row in (0..=range.start.row).rev() {
11371                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11372                        if crease.range().end.row >= buffer_start_row {
11373                            to_fold.push(crease);
11374                            if row <= range.start.row {
11375                                break;
11376                            }
11377                        }
11378                    }
11379                }
11380            }
11381
11382            self.fold_creases(to_fold, true, window, cx);
11383        } else {
11384            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11385
11386            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11387                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11388                .map(|(snapshot, _, _)| snapshot.remote_id())
11389                .collect();
11390            for buffer_id in buffer_ids {
11391                self.fold_buffer(buffer_id, cx);
11392            }
11393        }
11394    }
11395
11396    fn fold_at_level(
11397        &mut self,
11398        fold_at: &FoldAtLevel,
11399        window: &mut Window,
11400        cx: &mut Context<Self>,
11401    ) {
11402        if !self.buffer.read(cx).is_singleton() {
11403            return;
11404        }
11405
11406        let fold_at_level = fold_at.level;
11407        let snapshot = self.buffer.read(cx).snapshot(cx);
11408        let mut to_fold = Vec::new();
11409        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11410
11411        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11412            while start_row < end_row {
11413                match self
11414                    .snapshot(window, cx)
11415                    .crease_for_buffer_row(MultiBufferRow(start_row))
11416                {
11417                    Some(crease) => {
11418                        let nested_start_row = crease.range().start.row + 1;
11419                        let nested_end_row = crease.range().end.row;
11420
11421                        if current_level < fold_at_level {
11422                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11423                        } else if current_level == fold_at_level {
11424                            to_fold.push(crease);
11425                        }
11426
11427                        start_row = nested_end_row + 1;
11428                    }
11429                    None => start_row += 1,
11430                }
11431            }
11432        }
11433
11434        self.fold_creases(to_fold, true, window, cx);
11435    }
11436
11437    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11438        if self.buffer.read(cx).is_singleton() {
11439            let mut fold_ranges = Vec::new();
11440            let snapshot = self.buffer.read(cx).snapshot(cx);
11441
11442            for row in 0..snapshot.max_row().0 {
11443                if let Some(foldable_range) = self
11444                    .snapshot(window, cx)
11445                    .crease_for_buffer_row(MultiBufferRow(row))
11446                {
11447                    fold_ranges.push(foldable_range);
11448                }
11449            }
11450
11451            self.fold_creases(fold_ranges, true, window, cx);
11452        } else {
11453            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11454                editor
11455                    .update_in(&mut cx, |editor, _, cx| {
11456                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11457                            editor.fold_buffer(buffer_id, cx);
11458                        }
11459                    })
11460                    .ok();
11461            });
11462        }
11463    }
11464
11465    pub fn fold_function_bodies(
11466        &mut self,
11467        _: &actions::FoldFunctionBodies,
11468        window: &mut Window,
11469        cx: &mut Context<Self>,
11470    ) {
11471        let snapshot = self.buffer.read(cx).snapshot(cx);
11472
11473        let ranges = snapshot
11474            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11475            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11476            .collect::<Vec<_>>();
11477
11478        let creases = ranges
11479            .into_iter()
11480            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11481            .collect();
11482
11483        self.fold_creases(creases, true, window, cx);
11484    }
11485
11486    pub fn fold_recursive(
11487        &mut self,
11488        _: &actions::FoldRecursive,
11489        window: &mut Window,
11490        cx: &mut Context<Self>,
11491    ) {
11492        let mut to_fold = Vec::new();
11493        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11494        let selections = self.selections.all_adjusted(cx);
11495
11496        for selection in selections {
11497            let range = selection.range().sorted();
11498            let buffer_start_row = range.start.row;
11499
11500            if range.start.row != range.end.row {
11501                let mut found = false;
11502                for row in range.start.row..=range.end.row {
11503                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11504                        found = true;
11505                        to_fold.push(crease);
11506                    }
11507                }
11508                if found {
11509                    continue;
11510                }
11511            }
11512
11513            for row in (0..=range.start.row).rev() {
11514                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11515                    if crease.range().end.row >= buffer_start_row {
11516                        to_fold.push(crease);
11517                    } else {
11518                        break;
11519                    }
11520                }
11521            }
11522        }
11523
11524        self.fold_creases(to_fold, true, window, cx);
11525    }
11526
11527    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11528        let buffer_row = fold_at.buffer_row;
11529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11530
11531        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11532            let autoscroll = self
11533                .selections
11534                .all::<Point>(cx)
11535                .iter()
11536                .any(|selection| crease.range().overlaps(&selection.range()));
11537
11538            self.fold_creases(vec![crease], autoscroll, window, cx);
11539        }
11540    }
11541
11542    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11543        if self.is_singleton(cx) {
11544            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11545            let buffer = &display_map.buffer_snapshot;
11546            let selections = self.selections.all::<Point>(cx);
11547            let ranges = selections
11548                .iter()
11549                .map(|s| {
11550                    let range = s.display_range(&display_map).sorted();
11551                    let mut start = range.start.to_point(&display_map);
11552                    let mut end = range.end.to_point(&display_map);
11553                    start.column = 0;
11554                    end.column = buffer.line_len(MultiBufferRow(end.row));
11555                    start..end
11556                })
11557                .collect::<Vec<_>>();
11558
11559            self.unfold_ranges(&ranges, true, true, cx);
11560        } else {
11561            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11562            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11563                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11564                .map(|(snapshot, _, _)| snapshot.remote_id())
11565                .collect();
11566            for buffer_id in buffer_ids {
11567                self.unfold_buffer(buffer_id, cx);
11568            }
11569        }
11570    }
11571
11572    pub fn unfold_recursive(
11573        &mut self,
11574        _: &UnfoldRecursive,
11575        _window: &mut Window,
11576        cx: &mut Context<Self>,
11577    ) {
11578        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11579        let selections = self.selections.all::<Point>(cx);
11580        let ranges = selections
11581            .iter()
11582            .map(|s| {
11583                let mut range = s.display_range(&display_map).sorted();
11584                *range.start.column_mut() = 0;
11585                *range.end.column_mut() = display_map.line_len(range.end.row());
11586                let start = range.start.to_point(&display_map);
11587                let end = range.end.to_point(&display_map);
11588                start..end
11589            })
11590            .collect::<Vec<_>>();
11591
11592        self.unfold_ranges(&ranges, true, true, cx);
11593    }
11594
11595    pub fn unfold_at(
11596        &mut self,
11597        unfold_at: &UnfoldAt,
11598        _window: &mut Window,
11599        cx: &mut Context<Self>,
11600    ) {
11601        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11602
11603        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11604            ..Point::new(
11605                unfold_at.buffer_row.0,
11606                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11607            );
11608
11609        let autoscroll = self
11610            .selections
11611            .all::<Point>(cx)
11612            .iter()
11613            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11614
11615        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11616    }
11617
11618    pub fn unfold_all(
11619        &mut self,
11620        _: &actions::UnfoldAll,
11621        _window: &mut Window,
11622        cx: &mut Context<Self>,
11623    ) {
11624        if self.buffer.read(cx).is_singleton() {
11625            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11626            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11627        } else {
11628            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11629                editor
11630                    .update(&mut cx, |editor, cx| {
11631                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11632                            editor.unfold_buffer(buffer_id, cx);
11633                        }
11634                    })
11635                    .ok();
11636            });
11637        }
11638    }
11639
11640    pub fn fold_selected_ranges(
11641        &mut self,
11642        _: &FoldSelectedRanges,
11643        window: &mut Window,
11644        cx: &mut Context<Self>,
11645    ) {
11646        let selections = self.selections.all::<Point>(cx);
11647        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11648        let line_mode = self.selections.line_mode;
11649        let ranges = selections
11650            .into_iter()
11651            .map(|s| {
11652                if line_mode {
11653                    let start = Point::new(s.start.row, 0);
11654                    let end = Point::new(
11655                        s.end.row,
11656                        display_map
11657                            .buffer_snapshot
11658                            .line_len(MultiBufferRow(s.end.row)),
11659                    );
11660                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11661                } else {
11662                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11663                }
11664            })
11665            .collect::<Vec<_>>();
11666        self.fold_creases(ranges, true, window, cx);
11667    }
11668
11669    pub fn fold_ranges<T: ToOffset + Clone>(
11670        &mut self,
11671        ranges: Vec<Range<T>>,
11672        auto_scroll: bool,
11673        window: &mut Window,
11674        cx: &mut Context<Self>,
11675    ) {
11676        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11677        let ranges = ranges
11678            .into_iter()
11679            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11680            .collect::<Vec<_>>();
11681        self.fold_creases(ranges, auto_scroll, window, cx);
11682    }
11683
11684    pub fn fold_creases<T: ToOffset + Clone>(
11685        &mut self,
11686        creases: Vec<Crease<T>>,
11687        auto_scroll: bool,
11688        window: &mut Window,
11689        cx: &mut Context<Self>,
11690    ) {
11691        if creases.is_empty() {
11692            return;
11693        }
11694
11695        let mut buffers_affected = HashSet::default();
11696        let multi_buffer = self.buffer().read(cx);
11697        for crease in &creases {
11698            if let Some((_, buffer, _)) =
11699                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11700            {
11701                buffers_affected.insert(buffer.read(cx).remote_id());
11702            };
11703        }
11704
11705        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11706
11707        if auto_scroll {
11708            self.request_autoscroll(Autoscroll::fit(), cx);
11709        }
11710
11711        cx.notify();
11712
11713        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11714            // Clear diagnostics block when folding a range that contains it.
11715            let snapshot = self.snapshot(window, cx);
11716            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11717                drop(snapshot);
11718                self.active_diagnostics = Some(active_diagnostics);
11719                self.dismiss_diagnostics(cx);
11720            } else {
11721                self.active_diagnostics = Some(active_diagnostics);
11722            }
11723        }
11724
11725        self.scrollbar_marker_state.dirty = true;
11726    }
11727
11728    /// Removes any folds whose ranges intersect any of the given ranges.
11729    pub fn unfold_ranges<T: ToOffset + Clone>(
11730        &mut self,
11731        ranges: &[Range<T>],
11732        inclusive: bool,
11733        auto_scroll: bool,
11734        cx: &mut Context<Self>,
11735    ) {
11736        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11737            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11738        });
11739    }
11740
11741    pub fn fold_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 folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11749        self.display_map
11750            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11751        cx.emit(EditorEvent::BufferFoldToggled {
11752            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11753            folded: true,
11754        });
11755        cx.notify();
11756    }
11757
11758    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11759        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11760            return;
11761        }
11762        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11763            return;
11764        };
11765        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11766        self.display_map.update(cx, |display_map, cx| {
11767            display_map.unfold_buffer(buffer_id, cx);
11768        });
11769        cx.emit(EditorEvent::BufferFoldToggled {
11770            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11771            folded: false,
11772        });
11773        cx.notify();
11774    }
11775
11776    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11777        self.display_map.read(cx).is_buffer_folded(buffer)
11778    }
11779
11780    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
11781        self.display_map.read(cx).folded_buffers()
11782    }
11783
11784    /// Removes any folds with the given ranges.
11785    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11786        &mut self,
11787        ranges: &[Range<T>],
11788        type_id: TypeId,
11789        auto_scroll: bool,
11790        cx: &mut Context<Self>,
11791    ) {
11792        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11793            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11794        });
11795    }
11796
11797    fn remove_folds_with<T: ToOffset + Clone>(
11798        &mut self,
11799        ranges: &[Range<T>],
11800        auto_scroll: bool,
11801        cx: &mut Context<Self>,
11802        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
11803    ) {
11804        if ranges.is_empty() {
11805            return;
11806        }
11807
11808        let mut buffers_affected = HashSet::default();
11809        let multi_buffer = self.buffer().read(cx);
11810        for range in ranges {
11811            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11812                buffers_affected.insert(buffer.read(cx).remote_id());
11813            };
11814        }
11815
11816        self.display_map.update(cx, update);
11817
11818        if auto_scroll {
11819            self.request_autoscroll(Autoscroll::fit(), cx);
11820        }
11821
11822        cx.notify();
11823        self.scrollbar_marker_state.dirty = true;
11824        self.active_indent_guides_state.dirty = true;
11825    }
11826
11827    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
11828        self.display_map.read(cx).fold_placeholder.clone()
11829    }
11830
11831    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
11832        self.buffer.update(cx, |buffer, cx| {
11833            buffer.set_all_diff_hunks_expanded(cx);
11834        });
11835    }
11836
11837    pub fn expand_all_diff_hunks(
11838        &mut self,
11839        _: &ExpandAllHunkDiffs,
11840        _window: &mut Window,
11841        cx: &mut Context<Self>,
11842    ) {
11843        self.buffer.update(cx, |buffer, cx| {
11844            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11845        });
11846    }
11847
11848    pub fn toggle_selected_diff_hunks(
11849        &mut self,
11850        _: &ToggleSelectedDiffHunks,
11851        _window: &mut Window,
11852        cx: &mut Context<Self>,
11853    ) {
11854        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11855        self.toggle_diff_hunks_in_ranges(ranges, cx);
11856    }
11857
11858    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
11859        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11860        self.buffer
11861            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11862    }
11863
11864    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
11865        self.buffer.update(cx, |buffer, cx| {
11866            let ranges = vec![Anchor::min()..Anchor::max()];
11867            if !buffer.all_diff_hunks_expanded()
11868                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11869            {
11870                buffer.collapse_diff_hunks(ranges, cx);
11871                true
11872            } else {
11873                false
11874            }
11875        })
11876    }
11877
11878    fn toggle_diff_hunks_in_ranges(
11879        &mut self,
11880        ranges: Vec<Range<Anchor>>,
11881        cx: &mut Context<'_, Editor>,
11882    ) {
11883        self.buffer.update(cx, |buffer, cx| {
11884            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11885                buffer.collapse_diff_hunks(ranges, cx)
11886            } else {
11887                buffer.expand_diff_hunks(ranges, cx)
11888            }
11889        })
11890    }
11891
11892    pub(crate) fn apply_all_diff_hunks(
11893        &mut self,
11894        _: &ApplyAllDiffHunks,
11895        window: &mut Window,
11896        cx: &mut Context<Self>,
11897    ) {
11898        let buffers = self.buffer.read(cx).all_buffers();
11899        for branch_buffer in buffers {
11900            branch_buffer.update(cx, |branch_buffer, cx| {
11901                branch_buffer.merge_into_base(Vec::new(), cx);
11902            });
11903        }
11904
11905        if let Some(project) = self.project.clone() {
11906            self.save(true, project, window, cx).detach_and_log_err(cx);
11907        }
11908    }
11909
11910    pub(crate) fn apply_selected_diff_hunks(
11911        &mut self,
11912        _: &ApplyDiffHunk,
11913        window: &mut Window,
11914        cx: &mut Context<Self>,
11915    ) {
11916        let snapshot = self.snapshot(window, cx);
11917        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11918        let mut ranges_by_buffer = HashMap::default();
11919        self.transact(window, cx, |editor, _window, cx| {
11920            for hunk in hunks {
11921                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11922                    ranges_by_buffer
11923                        .entry(buffer.clone())
11924                        .or_insert_with(Vec::new)
11925                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11926                }
11927            }
11928
11929            for (buffer, ranges) in ranges_by_buffer {
11930                buffer.update(cx, |buffer, cx| {
11931                    buffer.merge_into_base(ranges, cx);
11932                });
11933            }
11934        });
11935
11936        if let Some(project) = self.project.clone() {
11937            self.save(true, project, window, cx).detach_and_log_err(cx);
11938        }
11939    }
11940
11941    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
11942        if hovered != self.gutter_hovered {
11943            self.gutter_hovered = hovered;
11944            cx.notify();
11945        }
11946    }
11947
11948    pub fn insert_blocks(
11949        &mut self,
11950        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11951        autoscroll: Option<Autoscroll>,
11952        cx: &mut Context<Self>,
11953    ) -> Vec<CustomBlockId> {
11954        let blocks = self
11955            .display_map
11956            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11957        if let Some(autoscroll) = autoscroll {
11958            self.request_autoscroll(autoscroll, cx);
11959        }
11960        cx.notify();
11961        blocks
11962    }
11963
11964    pub fn resize_blocks(
11965        &mut self,
11966        heights: HashMap<CustomBlockId, u32>,
11967        autoscroll: Option<Autoscroll>,
11968        cx: &mut Context<Self>,
11969    ) {
11970        self.display_map
11971            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11972        if let Some(autoscroll) = autoscroll {
11973            self.request_autoscroll(autoscroll, cx);
11974        }
11975        cx.notify();
11976    }
11977
11978    pub fn replace_blocks(
11979        &mut self,
11980        renderers: HashMap<CustomBlockId, RenderBlock>,
11981        autoscroll: Option<Autoscroll>,
11982        cx: &mut Context<Self>,
11983    ) {
11984        self.display_map
11985            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11986        if let Some(autoscroll) = autoscroll {
11987            self.request_autoscroll(autoscroll, cx);
11988        }
11989        cx.notify();
11990    }
11991
11992    pub fn remove_blocks(
11993        &mut self,
11994        block_ids: HashSet<CustomBlockId>,
11995        autoscroll: Option<Autoscroll>,
11996        cx: &mut Context<Self>,
11997    ) {
11998        self.display_map.update(cx, |display_map, cx| {
11999            display_map.remove_blocks(block_ids, cx)
12000        });
12001        if let Some(autoscroll) = autoscroll {
12002            self.request_autoscroll(autoscroll, cx);
12003        }
12004        cx.notify();
12005    }
12006
12007    pub fn row_for_block(
12008        &self,
12009        block_id: CustomBlockId,
12010        cx: &mut Context<Self>,
12011    ) -> Option<DisplayRow> {
12012        self.display_map
12013            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12014    }
12015
12016    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12017        self.focused_block = Some(focused_block);
12018    }
12019
12020    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12021        self.focused_block.take()
12022    }
12023
12024    pub fn insert_creases(
12025        &mut self,
12026        creases: impl IntoIterator<Item = Crease<Anchor>>,
12027        cx: &mut Context<Self>,
12028    ) -> Vec<CreaseId> {
12029        self.display_map
12030            .update(cx, |map, cx| map.insert_creases(creases, cx))
12031    }
12032
12033    pub fn remove_creases(
12034        &mut self,
12035        ids: impl IntoIterator<Item = CreaseId>,
12036        cx: &mut Context<Self>,
12037    ) {
12038        self.display_map
12039            .update(cx, |map, cx| map.remove_creases(ids, cx));
12040    }
12041
12042    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12043        self.display_map
12044            .update(cx, |map, cx| map.snapshot(cx))
12045            .longest_row()
12046    }
12047
12048    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12049        self.display_map
12050            .update(cx, |map, cx| map.snapshot(cx))
12051            .max_point()
12052    }
12053
12054    pub fn text(&self, cx: &App) -> String {
12055        self.buffer.read(cx).read(cx).text()
12056    }
12057
12058    pub fn text_option(&self, cx: &App) -> Option<String> {
12059        let text = self.text(cx);
12060        let text = text.trim();
12061
12062        if text.is_empty() {
12063            return None;
12064        }
12065
12066        Some(text.to_string())
12067    }
12068
12069    pub fn set_text(
12070        &mut self,
12071        text: impl Into<Arc<str>>,
12072        window: &mut Window,
12073        cx: &mut Context<Self>,
12074    ) {
12075        self.transact(window, cx, |this, _, cx| {
12076            this.buffer
12077                .read(cx)
12078                .as_singleton()
12079                .expect("you can only call set_text on editors for singleton buffers")
12080                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12081        });
12082    }
12083
12084    pub fn display_text(&self, cx: &mut App) -> String {
12085        self.display_map
12086            .update(cx, |map, cx| map.snapshot(cx))
12087            .text()
12088    }
12089
12090    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12091        let mut wrap_guides = smallvec::smallvec![];
12092
12093        if self.show_wrap_guides == Some(false) {
12094            return wrap_guides;
12095        }
12096
12097        let settings = self.buffer.read(cx).settings_at(0, cx);
12098        if settings.show_wrap_guides {
12099            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12100                wrap_guides.push((soft_wrap as usize, true));
12101            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12102                wrap_guides.push((soft_wrap as usize, true));
12103            }
12104            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12105        }
12106
12107        wrap_guides
12108    }
12109
12110    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12111        let settings = self.buffer.read(cx).settings_at(0, cx);
12112        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12113        match mode {
12114            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12115                SoftWrap::None
12116            }
12117            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12118            language_settings::SoftWrap::PreferredLineLength => {
12119                SoftWrap::Column(settings.preferred_line_length)
12120            }
12121            language_settings::SoftWrap::Bounded => {
12122                SoftWrap::Bounded(settings.preferred_line_length)
12123            }
12124        }
12125    }
12126
12127    pub fn set_soft_wrap_mode(
12128        &mut self,
12129        mode: language_settings::SoftWrap,
12130
12131        cx: &mut Context<Self>,
12132    ) {
12133        self.soft_wrap_mode_override = Some(mode);
12134        cx.notify();
12135    }
12136
12137    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12138        self.text_style_refinement = Some(style);
12139    }
12140
12141    /// called by the Element so we know what style we were most recently rendered with.
12142    pub(crate) fn set_style(
12143        &mut self,
12144        style: EditorStyle,
12145        window: &mut Window,
12146        cx: &mut Context<Self>,
12147    ) {
12148        let rem_size = window.rem_size();
12149        self.display_map.update(cx, |map, cx| {
12150            map.set_font(
12151                style.text.font(),
12152                style.text.font_size.to_pixels(rem_size),
12153                cx,
12154            )
12155        });
12156        self.style = Some(style);
12157    }
12158
12159    pub fn style(&self) -> Option<&EditorStyle> {
12160        self.style.as_ref()
12161    }
12162
12163    // Called by the element. This method is not designed to be called outside of the editor
12164    // element's layout code because it does not notify when rewrapping is computed synchronously.
12165    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12166        self.display_map
12167            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12168    }
12169
12170    pub fn set_soft_wrap(&mut self) {
12171        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12172    }
12173
12174    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12175        if self.soft_wrap_mode_override.is_some() {
12176            self.soft_wrap_mode_override.take();
12177        } else {
12178            let soft_wrap = match self.soft_wrap_mode(cx) {
12179                SoftWrap::GitDiff => return,
12180                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12181                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12182                    language_settings::SoftWrap::None
12183                }
12184            };
12185            self.soft_wrap_mode_override = Some(soft_wrap);
12186        }
12187        cx.notify();
12188    }
12189
12190    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12191        let Some(workspace) = self.workspace() else {
12192            return;
12193        };
12194        let fs = workspace.read(cx).app_state().fs.clone();
12195        let current_show = TabBarSettings::get_global(cx).show;
12196        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12197            setting.show = Some(!current_show);
12198        });
12199    }
12200
12201    pub fn toggle_indent_guides(
12202        &mut self,
12203        _: &ToggleIndentGuides,
12204        _: &mut Window,
12205        cx: &mut Context<Self>,
12206    ) {
12207        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12208            self.buffer
12209                .read(cx)
12210                .settings_at(0, cx)
12211                .indent_guides
12212                .enabled
12213        });
12214        self.show_indent_guides = Some(!currently_enabled);
12215        cx.notify();
12216    }
12217
12218    fn should_show_indent_guides(&self) -> Option<bool> {
12219        self.show_indent_guides
12220    }
12221
12222    pub fn toggle_line_numbers(
12223        &mut self,
12224        _: &ToggleLineNumbers,
12225        _: &mut Window,
12226        cx: &mut Context<Self>,
12227    ) {
12228        let mut editor_settings = EditorSettings::get_global(cx).clone();
12229        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12230        EditorSettings::override_global(editor_settings, cx);
12231    }
12232
12233    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12234        self.use_relative_line_numbers
12235            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12236    }
12237
12238    pub fn toggle_relative_line_numbers(
12239        &mut self,
12240        _: &ToggleRelativeLineNumbers,
12241        _: &mut Window,
12242        cx: &mut Context<Self>,
12243    ) {
12244        let is_relative = self.should_use_relative_line_numbers(cx);
12245        self.set_relative_line_number(Some(!is_relative), cx)
12246    }
12247
12248    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12249        self.use_relative_line_numbers = is_relative;
12250        cx.notify();
12251    }
12252
12253    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12254        self.show_gutter = show_gutter;
12255        cx.notify();
12256    }
12257
12258    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12259        self.show_scrollbars = show_scrollbars;
12260        cx.notify();
12261    }
12262
12263    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12264        self.show_line_numbers = Some(show_line_numbers);
12265        cx.notify();
12266    }
12267
12268    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12269        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12270        cx.notify();
12271    }
12272
12273    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12274        self.show_code_actions = Some(show_code_actions);
12275        cx.notify();
12276    }
12277
12278    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12279        self.show_runnables = Some(show_runnables);
12280        cx.notify();
12281    }
12282
12283    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12284        if self.display_map.read(cx).masked != masked {
12285            self.display_map.update(cx, |map, _| map.masked = masked);
12286        }
12287        cx.notify()
12288    }
12289
12290    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12291        self.show_wrap_guides = Some(show_wrap_guides);
12292        cx.notify();
12293    }
12294
12295    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12296        self.show_indent_guides = Some(show_indent_guides);
12297        cx.notify();
12298    }
12299
12300    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12301        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12302            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12303                if let Some(dir) = file.abs_path(cx).parent() {
12304                    return Some(dir.to_owned());
12305                }
12306            }
12307
12308            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12309                return Some(project_path.path.to_path_buf());
12310            }
12311        }
12312
12313        None
12314    }
12315
12316    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12317        self.active_excerpt(cx)?
12318            .1
12319            .read(cx)
12320            .file()
12321            .and_then(|f| f.as_local())
12322    }
12323
12324    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12325        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12326            let project_path = buffer.read(cx).project_path(cx)?;
12327            let project = self.project.as_ref()?.read(cx);
12328            project.absolute_path(&project_path, cx)
12329        })
12330    }
12331
12332    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12333        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12334            let project_path = buffer.read(cx).project_path(cx)?;
12335            let project = self.project.as_ref()?.read(cx);
12336            let entry = project.entry_for_path(&project_path, cx)?;
12337            let path = entry.path.to_path_buf();
12338            Some(path)
12339        })
12340    }
12341
12342    pub fn reveal_in_finder(
12343        &mut self,
12344        _: &RevealInFileManager,
12345        _window: &mut Window,
12346        cx: &mut Context<Self>,
12347    ) {
12348        if let Some(target) = self.target_file(cx) {
12349            cx.reveal_path(&target.abs_path(cx));
12350        }
12351    }
12352
12353    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12354        if let Some(path) = self.target_file_abs_path(cx) {
12355            if let Some(path) = path.to_str() {
12356                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12357            }
12358        }
12359    }
12360
12361    pub fn copy_relative_path(
12362        &mut self,
12363        _: &CopyRelativePath,
12364        _window: &mut Window,
12365        cx: &mut Context<Self>,
12366    ) {
12367        if let Some(path) = self.target_file_path(cx) {
12368            if let Some(path) = path.to_str() {
12369                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12370            }
12371        }
12372    }
12373
12374    pub fn toggle_git_blame(
12375        &mut self,
12376        _: &ToggleGitBlame,
12377        window: &mut Window,
12378        cx: &mut Context<Self>,
12379    ) {
12380        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12381
12382        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12383            self.start_git_blame(true, window, cx);
12384        }
12385
12386        cx.notify();
12387    }
12388
12389    pub fn toggle_git_blame_inline(
12390        &mut self,
12391        _: &ToggleGitBlameInline,
12392        window: &mut Window,
12393        cx: &mut Context<Self>,
12394    ) {
12395        self.toggle_git_blame_inline_internal(true, window, cx);
12396        cx.notify();
12397    }
12398
12399    pub fn git_blame_inline_enabled(&self) -> bool {
12400        self.git_blame_inline_enabled
12401    }
12402
12403    pub fn toggle_selection_menu(
12404        &mut self,
12405        _: &ToggleSelectionMenu,
12406        _: &mut Window,
12407        cx: &mut Context<Self>,
12408    ) {
12409        self.show_selection_menu = self
12410            .show_selection_menu
12411            .map(|show_selections_menu| !show_selections_menu)
12412            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12413
12414        cx.notify();
12415    }
12416
12417    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12418        self.show_selection_menu
12419            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12420    }
12421
12422    fn start_git_blame(
12423        &mut self,
12424        user_triggered: bool,
12425        window: &mut Window,
12426        cx: &mut Context<Self>,
12427    ) {
12428        if let Some(project) = self.project.as_ref() {
12429            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12430                return;
12431            };
12432
12433            if buffer.read(cx).file().is_none() {
12434                return;
12435            }
12436
12437            let focused = self.focus_handle(cx).contains_focused(window, cx);
12438
12439            let project = project.clone();
12440            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12441            self.blame_subscription =
12442                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12443            self.blame = Some(blame);
12444        }
12445    }
12446
12447    fn toggle_git_blame_inline_internal(
12448        &mut self,
12449        user_triggered: bool,
12450        window: &mut Window,
12451        cx: &mut Context<Self>,
12452    ) {
12453        if self.git_blame_inline_enabled {
12454            self.git_blame_inline_enabled = false;
12455            self.show_git_blame_inline = false;
12456            self.show_git_blame_inline_delay_task.take();
12457        } else {
12458            self.git_blame_inline_enabled = true;
12459            self.start_git_blame_inline(user_triggered, window, cx);
12460        }
12461
12462        cx.notify();
12463    }
12464
12465    fn start_git_blame_inline(
12466        &mut self,
12467        user_triggered: bool,
12468        window: &mut Window,
12469        cx: &mut Context<Self>,
12470    ) {
12471        self.start_git_blame(user_triggered, window, cx);
12472
12473        if ProjectSettings::get_global(cx)
12474            .git
12475            .inline_blame_delay()
12476            .is_some()
12477        {
12478            self.start_inline_blame_timer(window, cx);
12479        } else {
12480            self.show_git_blame_inline = true
12481        }
12482    }
12483
12484    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12485        self.blame.as_ref()
12486    }
12487
12488    pub fn show_git_blame_gutter(&self) -> bool {
12489        self.show_git_blame_gutter
12490    }
12491
12492    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12493        self.show_git_blame_gutter && self.has_blame_entries(cx)
12494    }
12495
12496    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12497        self.show_git_blame_inline
12498            && self.focus_handle.is_focused(window)
12499            && !self.newest_selection_head_on_empty_line(cx)
12500            && self.has_blame_entries(cx)
12501    }
12502
12503    fn has_blame_entries(&self, cx: &App) -> bool {
12504        self.blame()
12505            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12506    }
12507
12508    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12509        let cursor_anchor = self.selections.newest_anchor().head();
12510
12511        let snapshot = self.buffer.read(cx).snapshot(cx);
12512        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12513
12514        snapshot.line_len(buffer_row) == 0
12515    }
12516
12517    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12518        let buffer_and_selection = maybe!({
12519            let selection = self.selections.newest::<Point>(cx);
12520            let selection_range = selection.range();
12521
12522            let multi_buffer = self.buffer().read(cx);
12523            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12524            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12525
12526            let (buffer, range, _) = if selection.reversed {
12527                buffer_ranges.first()
12528            } else {
12529                buffer_ranges.last()
12530            }?;
12531
12532            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12533                ..text::ToPoint::to_point(&range.end, &buffer).row;
12534            Some((
12535                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12536                selection,
12537            ))
12538        });
12539
12540        let Some((buffer, selection)) = buffer_and_selection else {
12541            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12542        };
12543
12544        let Some(project) = self.project.as_ref() else {
12545            return Task::ready(Err(anyhow!("editor does not have project")));
12546        };
12547
12548        project.update(cx, |project, cx| {
12549            project.get_permalink_to_line(&buffer, selection, cx)
12550        })
12551    }
12552
12553    pub fn copy_permalink_to_line(
12554        &mut self,
12555        _: &CopyPermalinkToLine,
12556        window: &mut Window,
12557        cx: &mut Context<Self>,
12558    ) {
12559        let permalink_task = self.get_permalink_to_line(cx);
12560        let workspace = self.workspace();
12561
12562        cx.spawn_in(window, |_, mut cx| async move {
12563            match permalink_task.await {
12564                Ok(permalink) => {
12565                    cx.update(|_, cx| {
12566                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12567                    })
12568                    .ok();
12569                }
12570                Err(err) => {
12571                    let message = format!("Failed to copy permalink: {err}");
12572
12573                    Err::<(), anyhow::Error>(err).log_err();
12574
12575                    if let Some(workspace) = workspace {
12576                        workspace
12577                            .update_in(&mut cx, |workspace, _, cx| {
12578                                struct CopyPermalinkToLine;
12579
12580                                workspace.show_toast(
12581                                    Toast::new(
12582                                        NotificationId::unique::<CopyPermalinkToLine>(),
12583                                        message,
12584                                    ),
12585                                    cx,
12586                                )
12587                            })
12588                            .ok();
12589                    }
12590                }
12591            }
12592        })
12593        .detach();
12594    }
12595
12596    pub fn copy_file_location(
12597        &mut self,
12598        _: &CopyFileLocation,
12599        _: &mut Window,
12600        cx: &mut Context<Self>,
12601    ) {
12602        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12603        if let Some(file) = self.target_file(cx) {
12604            if let Some(path) = file.path().to_str() {
12605                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12606            }
12607        }
12608    }
12609
12610    pub fn open_permalink_to_line(
12611        &mut self,
12612        _: &OpenPermalinkToLine,
12613        window: &mut Window,
12614        cx: &mut Context<Self>,
12615    ) {
12616        let permalink_task = self.get_permalink_to_line(cx);
12617        let workspace = self.workspace();
12618
12619        cx.spawn_in(window, |_, mut cx| async move {
12620            match permalink_task.await {
12621                Ok(permalink) => {
12622                    cx.update(|_, cx| {
12623                        cx.open_url(permalink.as_ref());
12624                    })
12625                    .ok();
12626                }
12627                Err(err) => {
12628                    let message = format!("Failed to open permalink: {err}");
12629
12630                    Err::<(), anyhow::Error>(err).log_err();
12631
12632                    if let Some(workspace) = workspace {
12633                        workspace
12634                            .update(&mut cx, |workspace, cx| {
12635                                struct OpenPermalinkToLine;
12636
12637                                workspace.show_toast(
12638                                    Toast::new(
12639                                        NotificationId::unique::<OpenPermalinkToLine>(),
12640                                        message,
12641                                    ),
12642                                    cx,
12643                                )
12644                            })
12645                            .ok();
12646                    }
12647                }
12648            }
12649        })
12650        .detach();
12651    }
12652
12653    pub fn insert_uuid_v4(
12654        &mut self,
12655        _: &InsertUuidV4,
12656        window: &mut Window,
12657        cx: &mut Context<Self>,
12658    ) {
12659        self.insert_uuid(UuidVersion::V4, window, cx);
12660    }
12661
12662    pub fn insert_uuid_v7(
12663        &mut self,
12664        _: &InsertUuidV7,
12665        window: &mut Window,
12666        cx: &mut Context<Self>,
12667    ) {
12668        self.insert_uuid(UuidVersion::V7, window, cx);
12669    }
12670
12671    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12672        self.transact(window, cx, |this, window, cx| {
12673            let edits = this
12674                .selections
12675                .all::<Point>(cx)
12676                .into_iter()
12677                .map(|selection| {
12678                    let uuid = match version {
12679                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12680                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12681                    };
12682
12683                    (selection.range(), uuid.to_string())
12684                });
12685            this.edit(edits, cx);
12686            this.refresh_inline_completion(true, false, window, cx);
12687        });
12688    }
12689
12690    pub fn open_selections_in_multibuffer(
12691        &mut self,
12692        _: &OpenSelectionsInMultibuffer,
12693        window: &mut Window,
12694        cx: &mut Context<Self>,
12695    ) {
12696        let multibuffer = self.buffer.read(cx);
12697
12698        let Some(buffer) = multibuffer.as_singleton() else {
12699            return;
12700        };
12701
12702        let Some(workspace) = self.workspace() else {
12703            return;
12704        };
12705
12706        let locations = self
12707            .selections
12708            .disjoint_anchors()
12709            .iter()
12710            .map(|range| Location {
12711                buffer: buffer.clone(),
12712                range: range.start.text_anchor..range.end.text_anchor,
12713            })
12714            .collect::<Vec<_>>();
12715
12716        let title = multibuffer.title(cx).to_string();
12717
12718        cx.spawn_in(window, |_, mut cx| async move {
12719            workspace.update_in(&mut cx, |workspace, window, cx| {
12720                Self::open_locations_in_multibuffer(
12721                    workspace,
12722                    locations,
12723                    format!("Selections for '{title}'"),
12724                    false,
12725                    MultibufferSelectionMode::All,
12726                    window,
12727                    cx,
12728                );
12729            })
12730        })
12731        .detach();
12732    }
12733
12734    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12735    /// last highlight added will be used.
12736    ///
12737    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12738    pub fn highlight_rows<T: 'static>(
12739        &mut self,
12740        range: Range<Anchor>,
12741        color: Hsla,
12742        should_autoscroll: bool,
12743        cx: &mut Context<Self>,
12744    ) {
12745        let snapshot = self.buffer().read(cx).snapshot(cx);
12746        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12747        let ix = row_highlights.binary_search_by(|highlight| {
12748            Ordering::Equal
12749                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12750                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12751        });
12752
12753        if let Err(mut ix) = ix {
12754            let index = post_inc(&mut self.highlight_order);
12755
12756            // If this range intersects with the preceding highlight, then merge it with
12757            // the preceding highlight. Otherwise insert a new highlight.
12758            let mut merged = false;
12759            if ix > 0 {
12760                let prev_highlight = &mut row_highlights[ix - 1];
12761                if prev_highlight
12762                    .range
12763                    .end
12764                    .cmp(&range.start, &snapshot)
12765                    .is_ge()
12766                {
12767                    ix -= 1;
12768                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12769                        prev_highlight.range.end = range.end;
12770                    }
12771                    merged = true;
12772                    prev_highlight.index = index;
12773                    prev_highlight.color = color;
12774                    prev_highlight.should_autoscroll = should_autoscroll;
12775                }
12776            }
12777
12778            if !merged {
12779                row_highlights.insert(
12780                    ix,
12781                    RowHighlight {
12782                        range: range.clone(),
12783                        index,
12784                        color,
12785                        should_autoscroll,
12786                    },
12787                );
12788            }
12789
12790            // If any of the following highlights intersect with this one, merge them.
12791            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12792                let highlight = &row_highlights[ix];
12793                if next_highlight
12794                    .range
12795                    .start
12796                    .cmp(&highlight.range.end, &snapshot)
12797                    .is_le()
12798                {
12799                    if next_highlight
12800                        .range
12801                        .end
12802                        .cmp(&highlight.range.end, &snapshot)
12803                        .is_gt()
12804                    {
12805                        row_highlights[ix].range.end = next_highlight.range.end;
12806                    }
12807                    row_highlights.remove(ix + 1);
12808                } else {
12809                    break;
12810                }
12811            }
12812        }
12813    }
12814
12815    /// Remove any highlighted row ranges of the given type that intersect the
12816    /// given ranges.
12817    pub fn remove_highlighted_rows<T: 'static>(
12818        &mut self,
12819        ranges_to_remove: Vec<Range<Anchor>>,
12820        cx: &mut Context<Self>,
12821    ) {
12822        let snapshot = self.buffer().read(cx).snapshot(cx);
12823        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12824        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12825        row_highlights.retain(|highlight| {
12826            while let Some(range_to_remove) = ranges_to_remove.peek() {
12827                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12828                    Ordering::Less | Ordering::Equal => {
12829                        ranges_to_remove.next();
12830                    }
12831                    Ordering::Greater => {
12832                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12833                            Ordering::Less | Ordering::Equal => {
12834                                return false;
12835                            }
12836                            Ordering::Greater => break,
12837                        }
12838                    }
12839                }
12840            }
12841
12842            true
12843        })
12844    }
12845
12846    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12847    pub fn clear_row_highlights<T: 'static>(&mut self) {
12848        self.highlighted_rows.remove(&TypeId::of::<T>());
12849    }
12850
12851    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12852    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12853        self.highlighted_rows
12854            .get(&TypeId::of::<T>())
12855            .map_or(&[] as &[_], |vec| vec.as_slice())
12856            .iter()
12857            .map(|highlight| (highlight.range.clone(), highlight.color))
12858    }
12859
12860    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12861    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12862    /// Allows to ignore certain kinds of highlights.
12863    pub fn highlighted_display_rows(
12864        &self,
12865        window: &mut Window,
12866        cx: &mut App,
12867    ) -> BTreeMap<DisplayRow, Hsla> {
12868        let snapshot = self.snapshot(window, cx);
12869        let mut used_highlight_orders = HashMap::default();
12870        self.highlighted_rows
12871            .iter()
12872            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12873            .fold(
12874                BTreeMap::<DisplayRow, Hsla>::new(),
12875                |mut unique_rows, highlight| {
12876                    let start = highlight.range.start.to_display_point(&snapshot);
12877                    let end = highlight.range.end.to_display_point(&snapshot);
12878                    let start_row = start.row().0;
12879                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12880                        && end.column() == 0
12881                    {
12882                        end.row().0.saturating_sub(1)
12883                    } else {
12884                        end.row().0
12885                    };
12886                    for row in start_row..=end_row {
12887                        let used_index =
12888                            used_highlight_orders.entry(row).or_insert(highlight.index);
12889                        if highlight.index >= *used_index {
12890                            *used_index = highlight.index;
12891                            unique_rows.insert(DisplayRow(row), highlight.color);
12892                        }
12893                    }
12894                    unique_rows
12895                },
12896            )
12897    }
12898
12899    pub fn highlighted_display_row_for_autoscroll(
12900        &self,
12901        snapshot: &DisplaySnapshot,
12902    ) -> Option<DisplayRow> {
12903        self.highlighted_rows
12904            .values()
12905            .flat_map(|highlighted_rows| highlighted_rows.iter())
12906            .filter_map(|highlight| {
12907                if highlight.should_autoscroll {
12908                    Some(highlight.range.start.to_display_point(snapshot).row())
12909                } else {
12910                    None
12911                }
12912            })
12913            .min()
12914    }
12915
12916    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
12917        self.highlight_background::<SearchWithinRange>(
12918            ranges,
12919            |colors| colors.editor_document_highlight_read_background,
12920            cx,
12921        )
12922    }
12923
12924    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12925        self.breadcrumb_header = Some(new_header);
12926    }
12927
12928    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
12929        self.clear_background_highlights::<SearchWithinRange>(cx);
12930    }
12931
12932    pub fn highlight_background<T: 'static>(
12933        &mut self,
12934        ranges: &[Range<Anchor>],
12935        color_fetcher: fn(&ThemeColors) -> Hsla,
12936        cx: &mut Context<Self>,
12937    ) {
12938        self.background_highlights
12939            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12940        self.scrollbar_marker_state.dirty = true;
12941        cx.notify();
12942    }
12943
12944    pub fn clear_background_highlights<T: 'static>(
12945        &mut self,
12946        cx: &mut Context<Self>,
12947    ) -> Option<BackgroundHighlight> {
12948        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12949        if !text_highlights.1.is_empty() {
12950            self.scrollbar_marker_state.dirty = true;
12951            cx.notify();
12952        }
12953        Some(text_highlights)
12954    }
12955
12956    pub fn highlight_gutter<T: 'static>(
12957        &mut self,
12958        ranges: &[Range<Anchor>],
12959        color_fetcher: fn(&App) -> Hsla,
12960        cx: &mut Context<Self>,
12961    ) {
12962        self.gutter_highlights
12963            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12964        cx.notify();
12965    }
12966
12967    pub fn clear_gutter_highlights<T: 'static>(
12968        &mut self,
12969        cx: &mut Context<Self>,
12970    ) -> Option<GutterHighlight> {
12971        cx.notify();
12972        self.gutter_highlights.remove(&TypeId::of::<T>())
12973    }
12974
12975    #[cfg(feature = "test-support")]
12976    pub fn all_text_background_highlights(
12977        &self,
12978        window: &mut Window,
12979        cx: &mut Context<Self>,
12980    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12981        let snapshot = self.snapshot(window, cx);
12982        let buffer = &snapshot.buffer_snapshot;
12983        let start = buffer.anchor_before(0);
12984        let end = buffer.anchor_after(buffer.len());
12985        let theme = cx.theme().colors();
12986        self.background_highlights_in_range(start..end, &snapshot, theme)
12987    }
12988
12989    #[cfg(feature = "test-support")]
12990    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
12991        let snapshot = self.buffer().read(cx).snapshot(cx);
12992
12993        let highlights = self
12994            .background_highlights
12995            .get(&TypeId::of::<items::BufferSearchHighlights>());
12996
12997        if let Some((_color, ranges)) = highlights {
12998            ranges
12999                .iter()
13000                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13001                .collect_vec()
13002        } else {
13003            vec![]
13004        }
13005    }
13006
13007    fn document_highlights_for_position<'a>(
13008        &'a self,
13009        position: Anchor,
13010        buffer: &'a MultiBufferSnapshot,
13011    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13012        let read_highlights = self
13013            .background_highlights
13014            .get(&TypeId::of::<DocumentHighlightRead>())
13015            .map(|h| &h.1);
13016        let write_highlights = self
13017            .background_highlights
13018            .get(&TypeId::of::<DocumentHighlightWrite>())
13019            .map(|h| &h.1);
13020        let left_position = position.bias_left(buffer);
13021        let right_position = position.bias_right(buffer);
13022        read_highlights
13023            .into_iter()
13024            .chain(write_highlights)
13025            .flat_map(move |ranges| {
13026                let start_ix = match ranges.binary_search_by(|probe| {
13027                    let cmp = probe.end.cmp(&left_position, buffer);
13028                    if cmp.is_ge() {
13029                        Ordering::Greater
13030                    } else {
13031                        Ordering::Less
13032                    }
13033                }) {
13034                    Ok(i) | Err(i) => i,
13035                };
13036
13037                ranges[start_ix..]
13038                    .iter()
13039                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13040            })
13041    }
13042
13043    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13044        self.background_highlights
13045            .get(&TypeId::of::<T>())
13046            .map_or(false, |(_, highlights)| !highlights.is_empty())
13047    }
13048
13049    pub fn background_highlights_in_range(
13050        &self,
13051        search_range: Range<Anchor>,
13052        display_snapshot: &DisplaySnapshot,
13053        theme: &ThemeColors,
13054    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13055        let mut results = Vec::new();
13056        for (color_fetcher, ranges) in self.background_highlights.values() {
13057            let color = color_fetcher(theme);
13058            let start_ix = match ranges.binary_search_by(|probe| {
13059                let cmp = probe
13060                    .end
13061                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13062                if cmp.is_gt() {
13063                    Ordering::Greater
13064                } else {
13065                    Ordering::Less
13066                }
13067            }) {
13068                Ok(i) | Err(i) => i,
13069            };
13070            for range in &ranges[start_ix..] {
13071                if range
13072                    .start
13073                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13074                    .is_ge()
13075                {
13076                    break;
13077                }
13078
13079                let start = range.start.to_display_point(display_snapshot);
13080                let end = range.end.to_display_point(display_snapshot);
13081                results.push((start..end, color))
13082            }
13083        }
13084        results
13085    }
13086
13087    pub fn background_highlight_row_ranges<T: 'static>(
13088        &self,
13089        search_range: Range<Anchor>,
13090        display_snapshot: &DisplaySnapshot,
13091        count: usize,
13092    ) -> Vec<RangeInclusive<DisplayPoint>> {
13093        let mut results = Vec::new();
13094        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13095            return vec![];
13096        };
13097
13098        let start_ix = match ranges.binary_search_by(|probe| {
13099            let cmp = probe
13100                .end
13101                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13102            if cmp.is_gt() {
13103                Ordering::Greater
13104            } else {
13105                Ordering::Less
13106            }
13107        }) {
13108            Ok(i) | Err(i) => i,
13109        };
13110        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13111            if let (Some(start_display), Some(end_display)) = (start, end) {
13112                results.push(
13113                    start_display.to_display_point(display_snapshot)
13114                        ..=end_display.to_display_point(display_snapshot),
13115                );
13116            }
13117        };
13118        let mut start_row: Option<Point> = None;
13119        let mut end_row: Option<Point> = None;
13120        if ranges.len() > count {
13121            return Vec::new();
13122        }
13123        for range in &ranges[start_ix..] {
13124            if range
13125                .start
13126                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13127                .is_ge()
13128            {
13129                break;
13130            }
13131            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13132            if let Some(current_row) = &end_row {
13133                if end.row == current_row.row {
13134                    continue;
13135                }
13136            }
13137            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13138            if start_row.is_none() {
13139                assert_eq!(end_row, None);
13140                start_row = Some(start);
13141                end_row = Some(end);
13142                continue;
13143            }
13144            if let Some(current_end) = end_row.as_mut() {
13145                if start.row > current_end.row + 1 {
13146                    push_region(start_row, end_row);
13147                    start_row = Some(start);
13148                    end_row = Some(end);
13149                } else {
13150                    // Merge two hunks.
13151                    *current_end = end;
13152                }
13153            } else {
13154                unreachable!();
13155            }
13156        }
13157        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13158        push_region(start_row, end_row);
13159        results
13160    }
13161
13162    pub fn gutter_highlights_in_range(
13163        &self,
13164        search_range: Range<Anchor>,
13165        display_snapshot: &DisplaySnapshot,
13166        cx: &App,
13167    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13168        let mut results = Vec::new();
13169        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13170            let color = color_fetcher(cx);
13171            let start_ix = match ranges.binary_search_by(|probe| {
13172                let cmp = probe
13173                    .end
13174                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13175                if cmp.is_gt() {
13176                    Ordering::Greater
13177                } else {
13178                    Ordering::Less
13179                }
13180            }) {
13181                Ok(i) | Err(i) => i,
13182            };
13183            for range in &ranges[start_ix..] {
13184                if range
13185                    .start
13186                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13187                    .is_ge()
13188                {
13189                    break;
13190                }
13191
13192                let start = range.start.to_display_point(display_snapshot);
13193                let end = range.end.to_display_point(display_snapshot);
13194                results.push((start..end, color))
13195            }
13196        }
13197        results
13198    }
13199
13200    /// Get the text ranges corresponding to the redaction query
13201    pub fn redacted_ranges(
13202        &self,
13203        search_range: Range<Anchor>,
13204        display_snapshot: &DisplaySnapshot,
13205        cx: &App,
13206    ) -> Vec<Range<DisplayPoint>> {
13207        display_snapshot
13208            .buffer_snapshot
13209            .redacted_ranges(search_range, |file| {
13210                if let Some(file) = file {
13211                    file.is_private()
13212                        && EditorSettings::get(
13213                            Some(SettingsLocation {
13214                                worktree_id: file.worktree_id(cx),
13215                                path: file.path().as_ref(),
13216                            }),
13217                            cx,
13218                        )
13219                        .redact_private_values
13220                } else {
13221                    false
13222                }
13223            })
13224            .map(|range| {
13225                range.start.to_display_point(display_snapshot)
13226                    ..range.end.to_display_point(display_snapshot)
13227            })
13228            .collect()
13229    }
13230
13231    pub fn highlight_text<T: 'static>(
13232        &mut self,
13233        ranges: Vec<Range<Anchor>>,
13234        style: HighlightStyle,
13235        cx: &mut Context<Self>,
13236    ) {
13237        self.display_map.update(cx, |map, _| {
13238            map.highlight_text(TypeId::of::<T>(), ranges, style)
13239        });
13240        cx.notify();
13241    }
13242
13243    pub(crate) fn highlight_inlays<T: 'static>(
13244        &mut self,
13245        highlights: Vec<InlayHighlight>,
13246        style: HighlightStyle,
13247        cx: &mut Context<Self>,
13248    ) {
13249        self.display_map.update(cx, |map, _| {
13250            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13251        });
13252        cx.notify();
13253    }
13254
13255    pub fn text_highlights<'a, T: 'static>(
13256        &'a self,
13257        cx: &'a App,
13258    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13259        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13260    }
13261
13262    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13263        let cleared = self
13264            .display_map
13265            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13266        if cleared {
13267            cx.notify();
13268        }
13269    }
13270
13271    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13272        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13273            && self.focus_handle.is_focused(window)
13274    }
13275
13276    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13277        self.show_cursor_when_unfocused = is_enabled;
13278        cx.notify();
13279    }
13280
13281    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13282        self.project
13283            .as_ref()
13284            .map(|project| project.read(cx).lsp_store())
13285    }
13286
13287    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13288        cx.notify();
13289    }
13290
13291    fn on_buffer_event(
13292        &mut self,
13293        multibuffer: &Entity<MultiBuffer>,
13294        event: &multi_buffer::Event,
13295        window: &mut Window,
13296        cx: &mut Context<Self>,
13297    ) {
13298        match event {
13299            multi_buffer::Event::Edited {
13300                singleton_buffer_edited,
13301                edited_buffer: buffer_edited,
13302            } => {
13303                self.scrollbar_marker_state.dirty = true;
13304                self.active_indent_guides_state.dirty = true;
13305                self.refresh_active_diagnostics(cx);
13306                self.refresh_code_actions(window, cx);
13307                if self.has_active_inline_completion() {
13308                    self.update_visible_inline_completion(window, cx);
13309                }
13310                if let Some(buffer) = buffer_edited {
13311                    let buffer_id = buffer.read(cx).remote_id();
13312                    if !self.registered_buffers.contains_key(&buffer_id) {
13313                        if let Some(lsp_store) = self.lsp_store(cx) {
13314                            lsp_store.update(cx, |lsp_store, cx| {
13315                                self.registered_buffers.insert(
13316                                    buffer_id,
13317                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13318                                );
13319                            })
13320                        }
13321                    }
13322                }
13323                cx.emit(EditorEvent::BufferEdited);
13324                cx.emit(SearchEvent::MatchesInvalidated);
13325                if *singleton_buffer_edited {
13326                    if let Some(project) = &self.project {
13327                        let project = project.read(cx);
13328                        #[allow(clippy::mutable_key_type)]
13329                        let languages_affected = multibuffer
13330                            .read(cx)
13331                            .all_buffers()
13332                            .into_iter()
13333                            .filter_map(|buffer| {
13334                                let buffer = buffer.read(cx);
13335                                let language = buffer.language()?;
13336                                if project.is_local()
13337                                    && project
13338                                        .language_servers_for_local_buffer(buffer, cx)
13339                                        .count()
13340                                        == 0
13341                                {
13342                                    None
13343                                } else {
13344                                    Some(language)
13345                                }
13346                            })
13347                            .cloned()
13348                            .collect::<HashSet<_>>();
13349                        if !languages_affected.is_empty() {
13350                            self.refresh_inlay_hints(
13351                                InlayHintRefreshReason::BufferEdited(languages_affected),
13352                                cx,
13353                            );
13354                        }
13355                    }
13356                }
13357
13358                let Some(project) = &self.project else { return };
13359                let (telemetry, is_via_ssh) = {
13360                    let project = project.read(cx);
13361                    let telemetry = project.client().telemetry().clone();
13362                    let is_via_ssh = project.is_via_ssh();
13363                    (telemetry, is_via_ssh)
13364                };
13365                refresh_linked_ranges(self, window, cx);
13366                telemetry.log_edit_event("editor", is_via_ssh);
13367            }
13368            multi_buffer::Event::ExcerptsAdded {
13369                buffer,
13370                predecessor,
13371                excerpts,
13372            } => {
13373                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13374                let buffer_id = buffer.read(cx).remote_id();
13375                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13376                    if let Some(project) = &self.project {
13377                        get_unstaged_changes_for_buffers(
13378                            project,
13379                            [buffer.clone()],
13380                            self.buffer.clone(),
13381                            cx,
13382                        );
13383                    }
13384                }
13385                cx.emit(EditorEvent::ExcerptsAdded {
13386                    buffer: buffer.clone(),
13387                    predecessor: *predecessor,
13388                    excerpts: excerpts.clone(),
13389                });
13390                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13391            }
13392            multi_buffer::Event::ExcerptsRemoved { ids } => {
13393                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13394                let buffer = self.buffer.read(cx);
13395                self.registered_buffers
13396                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13397                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13398            }
13399            multi_buffer::Event::ExcerptsEdited { ids } => {
13400                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13401            }
13402            multi_buffer::Event::ExcerptsExpanded { ids } => {
13403                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13404                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13405            }
13406            multi_buffer::Event::Reparsed(buffer_id) => {
13407                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13408
13409                cx.emit(EditorEvent::Reparsed(*buffer_id));
13410            }
13411            multi_buffer::Event::DiffHunksToggled => {
13412                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13413            }
13414            multi_buffer::Event::LanguageChanged(buffer_id) => {
13415                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13416                cx.emit(EditorEvent::Reparsed(*buffer_id));
13417                cx.notify();
13418            }
13419            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13420            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13421            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13422                cx.emit(EditorEvent::TitleChanged)
13423            }
13424            // multi_buffer::Event::DiffBaseChanged => {
13425            //     self.scrollbar_marker_state.dirty = true;
13426            //     cx.emit(EditorEvent::DiffBaseChanged);
13427            //     cx.notify();
13428            // }
13429            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13430            multi_buffer::Event::DiagnosticsUpdated => {
13431                self.refresh_active_diagnostics(cx);
13432                self.scrollbar_marker_state.dirty = true;
13433                cx.notify();
13434            }
13435            _ => {}
13436        };
13437    }
13438
13439    fn on_display_map_changed(
13440        &mut self,
13441        _: Entity<DisplayMap>,
13442        _: &mut Window,
13443        cx: &mut Context<Self>,
13444    ) {
13445        cx.notify();
13446    }
13447
13448    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13449        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13450        self.refresh_inline_completion(true, false, window, cx);
13451        self.refresh_inlay_hints(
13452            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13453                self.selections.newest_anchor().head(),
13454                &self.buffer.read(cx).snapshot(cx),
13455                cx,
13456            )),
13457            cx,
13458        );
13459
13460        let old_cursor_shape = self.cursor_shape;
13461
13462        {
13463            let editor_settings = EditorSettings::get_global(cx);
13464            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13465            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13466            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13467        }
13468
13469        if old_cursor_shape != self.cursor_shape {
13470            cx.emit(EditorEvent::CursorShapeChanged);
13471        }
13472
13473        let project_settings = ProjectSettings::get_global(cx);
13474        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13475
13476        if self.mode == EditorMode::Full {
13477            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13478            if self.git_blame_inline_enabled != inline_blame_enabled {
13479                self.toggle_git_blame_inline_internal(false, window, cx);
13480            }
13481        }
13482
13483        cx.notify();
13484    }
13485
13486    pub fn set_searchable(&mut self, searchable: bool) {
13487        self.searchable = searchable;
13488    }
13489
13490    pub fn searchable(&self) -> bool {
13491        self.searchable
13492    }
13493
13494    fn open_proposed_changes_editor(
13495        &mut self,
13496        _: &OpenProposedChangesEditor,
13497        window: &mut Window,
13498        cx: &mut Context<Self>,
13499    ) {
13500        let Some(workspace) = self.workspace() else {
13501            cx.propagate();
13502            return;
13503        };
13504
13505        let selections = self.selections.all::<usize>(cx);
13506        let multi_buffer = self.buffer.read(cx);
13507        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13508        let mut new_selections_by_buffer = HashMap::default();
13509        for selection in selections {
13510            for (buffer, range, _) in
13511                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13512            {
13513                let mut range = range.to_point(buffer);
13514                range.start.column = 0;
13515                range.end.column = buffer.line_len(range.end.row);
13516                new_selections_by_buffer
13517                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13518                    .or_insert(Vec::new())
13519                    .push(range)
13520            }
13521        }
13522
13523        let proposed_changes_buffers = new_selections_by_buffer
13524            .into_iter()
13525            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13526            .collect::<Vec<_>>();
13527        let proposed_changes_editor = cx.new(|cx| {
13528            ProposedChangesEditor::new(
13529                "Proposed changes",
13530                proposed_changes_buffers,
13531                self.project.clone(),
13532                window,
13533                cx,
13534            )
13535        });
13536
13537        window.defer(cx, move |window, cx| {
13538            workspace.update(cx, |workspace, cx| {
13539                workspace.active_pane().update(cx, |pane, cx| {
13540                    pane.add_item(
13541                        Box::new(proposed_changes_editor),
13542                        true,
13543                        true,
13544                        None,
13545                        window,
13546                        cx,
13547                    );
13548                });
13549            });
13550        });
13551    }
13552
13553    pub fn open_excerpts_in_split(
13554        &mut self,
13555        _: &OpenExcerptsSplit,
13556        window: &mut Window,
13557        cx: &mut Context<Self>,
13558    ) {
13559        self.open_excerpts_common(None, true, window, cx)
13560    }
13561
13562    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13563        self.open_excerpts_common(None, false, window, cx)
13564    }
13565
13566    fn open_excerpts_common(
13567        &mut self,
13568        jump_data: Option<JumpData>,
13569        split: bool,
13570        window: &mut Window,
13571        cx: &mut Context<Self>,
13572    ) {
13573        let Some(workspace) = self.workspace() else {
13574            cx.propagate();
13575            return;
13576        };
13577
13578        if self.buffer.read(cx).is_singleton() {
13579            cx.propagate();
13580            return;
13581        }
13582
13583        let mut new_selections_by_buffer = HashMap::default();
13584        match &jump_data {
13585            Some(JumpData::MultiBufferPoint {
13586                excerpt_id,
13587                position,
13588                anchor,
13589                line_offset_from_top,
13590            }) => {
13591                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13592                if let Some(buffer) = multi_buffer_snapshot
13593                    .buffer_id_for_excerpt(*excerpt_id)
13594                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13595                {
13596                    let buffer_snapshot = buffer.read(cx).snapshot();
13597                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13598                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13599                    } else {
13600                        buffer_snapshot.clip_point(*position, Bias::Left)
13601                    };
13602                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13603                    new_selections_by_buffer.insert(
13604                        buffer,
13605                        (
13606                            vec![jump_to_offset..jump_to_offset],
13607                            Some(*line_offset_from_top),
13608                        ),
13609                    );
13610                }
13611            }
13612            Some(JumpData::MultiBufferRow {
13613                row,
13614                line_offset_from_top,
13615            }) => {
13616                let point = MultiBufferPoint::new(row.0, 0);
13617                if let Some((buffer, buffer_point, _)) =
13618                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13619                {
13620                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13621                    new_selections_by_buffer
13622                        .entry(buffer)
13623                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13624                        .0
13625                        .push(buffer_offset..buffer_offset)
13626                }
13627            }
13628            None => {
13629                let selections = self.selections.all::<usize>(cx);
13630                let multi_buffer = self.buffer.read(cx);
13631                for selection in selections {
13632                    for (buffer, mut range, _) in multi_buffer
13633                        .snapshot(cx)
13634                        .range_to_buffer_ranges(selection.range())
13635                    {
13636                        // When editing branch buffers, jump to the corresponding location
13637                        // in their base buffer.
13638                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13639                        let buffer = buffer_handle.read(cx);
13640                        if let Some(base_buffer) = buffer.base_buffer() {
13641                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13642                            buffer_handle = base_buffer;
13643                        }
13644
13645                        if selection.reversed {
13646                            mem::swap(&mut range.start, &mut range.end);
13647                        }
13648                        new_selections_by_buffer
13649                            .entry(buffer_handle)
13650                            .or_insert((Vec::new(), None))
13651                            .0
13652                            .push(range)
13653                    }
13654                }
13655            }
13656        }
13657
13658        if new_selections_by_buffer.is_empty() {
13659            return;
13660        }
13661
13662        // We defer the pane interaction because we ourselves are a workspace item
13663        // and activating a new item causes the pane to call a method on us reentrantly,
13664        // which panics if we're on the stack.
13665        window.defer(cx, move |window, cx| {
13666            workspace.update(cx, |workspace, cx| {
13667                let pane = if split {
13668                    workspace.adjacent_pane(window, cx)
13669                } else {
13670                    workspace.active_pane().clone()
13671                };
13672
13673                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13674                    let editor = buffer
13675                        .read(cx)
13676                        .file()
13677                        .is_none()
13678                        .then(|| {
13679                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13680                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13681                            // Instead, we try to activate the existing editor in the pane first.
13682                            let (editor, pane_item_index) =
13683                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13684                                    let editor = item.downcast::<Editor>()?;
13685                                    let singleton_buffer =
13686                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13687                                    if singleton_buffer == buffer {
13688                                        Some((editor, i))
13689                                    } else {
13690                                        None
13691                                    }
13692                                })?;
13693                            pane.update(cx, |pane, cx| {
13694                                pane.activate_item(pane_item_index, true, true, window, cx)
13695                            });
13696                            Some(editor)
13697                        })
13698                        .flatten()
13699                        .unwrap_or_else(|| {
13700                            workspace.open_project_item::<Self>(
13701                                pane.clone(),
13702                                buffer,
13703                                true,
13704                                true,
13705                                window,
13706                                cx,
13707                            )
13708                        });
13709
13710                    editor.update(cx, |editor, cx| {
13711                        let autoscroll = match scroll_offset {
13712                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13713                            None => Autoscroll::newest(),
13714                        };
13715                        let nav_history = editor.nav_history.take();
13716                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13717                            s.select_ranges(ranges);
13718                        });
13719                        editor.nav_history = nav_history;
13720                    });
13721                }
13722            })
13723        });
13724    }
13725
13726    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13727        let snapshot = self.buffer.read(cx).read(cx);
13728        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13729        Some(
13730            ranges
13731                .iter()
13732                .map(move |range| {
13733                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13734                })
13735                .collect(),
13736        )
13737    }
13738
13739    fn selection_replacement_ranges(
13740        &self,
13741        range: Range<OffsetUtf16>,
13742        cx: &mut App,
13743    ) -> Vec<Range<OffsetUtf16>> {
13744        let selections = self.selections.all::<OffsetUtf16>(cx);
13745        let newest_selection = selections
13746            .iter()
13747            .max_by_key(|selection| selection.id)
13748            .unwrap();
13749        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13750        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13751        let snapshot = self.buffer.read(cx).read(cx);
13752        selections
13753            .into_iter()
13754            .map(|mut selection| {
13755                selection.start.0 =
13756                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
13757                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13758                snapshot.clip_offset_utf16(selection.start, Bias::Left)
13759                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13760            })
13761            .collect()
13762    }
13763
13764    fn report_editor_event(
13765        &self,
13766        event_type: &'static str,
13767        file_extension: Option<String>,
13768        cx: &App,
13769    ) {
13770        if cfg!(any(test, feature = "test-support")) {
13771            return;
13772        }
13773
13774        let Some(project) = &self.project else { return };
13775
13776        // If None, we are in a file without an extension
13777        let file = self
13778            .buffer
13779            .read(cx)
13780            .as_singleton()
13781            .and_then(|b| b.read(cx).file());
13782        let file_extension = file_extension.or(file
13783            .as_ref()
13784            .and_then(|file| Path::new(file.file_name(cx)).extension())
13785            .and_then(|e| e.to_str())
13786            .map(|a| a.to_string()));
13787
13788        let vim_mode = cx
13789            .global::<SettingsStore>()
13790            .raw_user_settings()
13791            .get("vim_mode")
13792            == Some(&serde_json::Value::Bool(true));
13793
13794        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13795            == language::language_settings::InlineCompletionProvider::Copilot;
13796        let copilot_enabled_for_language = self
13797            .buffer
13798            .read(cx)
13799            .settings_at(0, cx)
13800            .show_inline_completions;
13801
13802        let project = project.read(cx);
13803        telemetry::event!(
13804            event_type,
13805            file_extension,
13806            vim_mode,
13807            copilot_enabled,
13808            copilot_enabled_for_language,
13809            is_via_ssh = project.is_via_ssh(),
13810        );
13811    }
13812
13813    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13814    /// with each line being an array of {text, highlight} objects.
13815    fn copy_highlight_json(
13816        &mut self,
13817        _: &CopyHighlightJson,
13818        window: &mut Window,
13819        cx: &mut Context<Self>,
13820    ) {
13821        #[derive(Serialize)]
13822        struct Chunk<'a> {
13823            text: String,
13824            highlight: Option<&'a str>,
13825        }
13826
13827        let snapshot = self.buffer.read(cx).snapshot(cx);
13828        let range = self
13829            .selected_text_range(false, window, cx)
13830            .and_then(|selection| {
13831                if selection.range.is_empty() {
13832                    None
13833                } else {
13834                    Some(selection.range)
13835                }
13836            })
13837            .unwrap_or_else(|| 0..snapshot.len());
13838
13839        let chunks = snapshot.chunks(range, true);
13840        let mut lines = Vec::new();
13841        let mut line: VecDeque<Chunk> = VecDeque::new();
13842
13843        let Some(style) = self.style.as_ref() else {
13844            return;
13845        };
13846
13847        for chunk in chunks {
13848            let highlight = chunk
13849                .syntax_highlight_id
13850                .and_then(|id| id.name(&style.syntax));
13851            let mut chunk_lines = chunk.text.split('\n').peekable();
13852            while let Some(text) = chunk_lines.next() {
13853                let mut merged_with_last_token = false;
13854                if let Some(last_token) = line.back_mut() {
13855                    if last_token.highlight == highlight {
13856                        last_token.text.push_str(text);
13857                        merged_with_last_token = true;
13858                    }
13859                }
13860
13861                if !merged_with_last_token {
13862                    line.push_back(Chunk {
13863                        text: text.into(),
13864                        highlight,
13865                    });
13866                }
13867
13868                if chunk_lines.peek().is_some() {
13869                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13870                        line.pop_front();
13871                    }
13872                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13873                        line.pop_back();
13874                    }
13875
13876                    lines.push(mem::take(&mut line));
13877                }
13878            }
13879        }
13880
13881        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13882            return;
13883        };
13884        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13885    }
13886
13887    pub fn open_context_menu(
13888        &mut self,
13889        _: &OpenContextMenu,
13890        window: &mut Window,
13891        cx: &mut Context<Self>,
13892    ) {
13893        self.request_autoscroll(Autoscroll::newest(), cx);
13894        let position = self.selections.newest_display(cx).start;
13895        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
13896    }
13897
13898    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13899        &self.inlay_hint_cache
13900    }
13901
13902    pub fn replay_insert_event(
13903        &mut self,
13904        text: &str,
13905        relative_utf16_range: Option<Range<isize>>,
13906        window: &mut Window,
13907        cx: &mut Context<Self>,
13908    ) {
13909        if !self.input_enabled {
13910            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13911            return;
13912        }
13913        if let Some(relative_utf16_range) = relative_utf16_range {
13914            let selections = self.selections.all::<OffsetUtf16>(cx);
13915            self.change_selections(None, window, cx, |s| {
13916                let new_ranges = selections.into_iter().map(|range| {
13917                    let start = OffsetUtf16(
13918                        range
13919                            .head()
13920                            .0
13921                            .saturating_add_signed(relative_utf16_range.start),
13922                    );
13923                    let end = OffsetUtf16(
13924                        range
13925                            .head()
13926                            .0
13927                            .saturating_add_signed(relative_utf16_range.end),
13928                    );
13929                    start..end
13930                });
13931                s.select_ranges(new_ranges);
13932            });
13933        }
13934
13935        self.handle_input(text, window, cx);
13936    }
13937
13938    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
13939        let Some(provider) = self.semantics_provider.as_ref() else {
13940            return false;
13941        };
13942
13943        let mut supports = false;
13944        self.buffer().read(cx).for_each_buffer(|buffer| {
13945            supports |= provider.supports_inlay_hints(buffer, cx);
13946        });
13947        supports
13948    }
13949    pub fn is_focused(&self, window: &mut Window) -> bool {
13950        self.focus_handle.is_focused(window)
13951    }
13952
13953    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13954        cx.emit(EditorEvent::Focused);
13955
13956        if let Some(descendant) = self
13957            .last_focused_descendant
13958            .take()
13959            .and_then(|descendant| descendant.upgrade())
13960        {
13961            window.focus(&descendant);
13962        } else {
13963            if let Some(blame) = self.blame.as_ref() {
13964                blame.update(cx, GitBlame::focus)
13965            }
13966
13967            self.blink_manager.update(cx, BlinkManager::enable);
13968            self.show_cursor_names(window, cx);
13969            self.buffer.update(cx, |buffer, cx| {
13970                buffer.finalize_last_transaction(cx);
13971                if self.leader_peer_id.is_none() {
13972                    buffer.set_active_selections(
13973                        &self.selections.disjoint_anchors(),
13974                        self.selections.line_mode,
13975                        self.cursor_shape,
13976                        cx,
13977                    );
13978                }
13979            });
13980        }
13981    }
13982
13983    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
13984        cx.emit(EditorEvent::FocusedIn)
13985    }
13986
13987    fn handle_focus_out(
13988        &mut self,
13989        event: FocusOutEvent,
13990        _window: &mut Window,
13991        _cx: &mut Context<Self>,
13992    ) {
13993        if event.blurred != self.focus_handle {
13994            self.last_focused_descendant = Some(event.blurred);
13995        }
13996    }
13997
13998    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13999        self.blink_manager.update(cx, BlinkManager::disable);
14000        self.buffer
14001            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14002
14003        if let Some(blame) = self.blame.as_ref() {
14004            blame.update(cx, GitBlame::blur)
14005        }
14006        if !self.hover_state.focused(window, cx) {
14007            hide_hover(self, cx);
14008        }
14009
14010        self.hide_context_menu(window, cx);
14011        cx.emit(EditorEvent::Blurred);
14012        cx.notify();
14013    }
14014
14015    pub fn register_action<A: Action>(
14016        &mut self,
14017        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14018    ) -> Subscription {
14019        let id = self.next_editor_action_id.post_inc();
14020        let listener = Arc::new(listener);
14021        self.editor_actions.borrow_mut().insert(
14022            id,
14023            Box::new(move |window, _| {
14024                let listener = listener.clone();
14025                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14026                    let action = action.downcast_ref().unwrap();
14027                    if phase == DispatchPhase::Bubble {
14028                        listener(action, window, cx)
14029                    }
14030                })
14031            }),
14032        );
14033
14034        let editor_actions = self.editor_actions.clone();
14035        Subscription::new(move || {
14036            editor_actions.borrow_mut().remove(&id);
14037        })
14038    }
14039
14040    pub fn file_header_size(&self) -> u32 {
14041        FILE_HEADER_HEIGHT
14042    }
14043
14044    pub fn revert(
14045        &mut self,
14046        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14047        window: &mut Window,
14048        cx: &mut Context<Self>,
14049    ) {
14050        self.buffer().update(cx, |multi_buffer, cx| {
14051            for (buffer_id, changes) in revert_changes {
14052                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14053                    buffer.update(cx, |buffer, cx| {
14054                        buffer.edit(
14055                            changes.into_iter().map(|(range, text)| {
14056                                (range, text.to_string().map(Arc::<str>::from))
14057                            }),
14058                            None,
14059                            cx,
14060                        );
14061                    });
14062                }
14063            }
14064        });
14065        self.change_selections(None, window, cx, |selections| selections.refresh());
14066    }
14067
14068    pub fn to_pixel_point(
14069        &self,
14070        source: multi_buffer::Anchor,
14071        editor_snapshot: &EditorSnapshot,
14072        window: &mut Window,
14073    ) -> Option<gpui::Point<Pixels>> {
14074        let source_point = source.to_display_point(editor_snapshot);
14075        self.display_to_pixel_point(source_point, editor_snapshot, window)
14076    }
14077
14078    pub fn display_to_pixel_point(
14079        &self,
14080        source: DisplayPoint,
14081        editor_snapshot: &EditorSnapshot,
14082        window: &mut Window,
14083    ) -> Option<gpui::Point<Pixels>> {
14084        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14085        let text_layout_details = self.text_layout_details(window);
14086        let scroll_top = text_layout_details
14087            .scroll_anchor
14088            .scroll_position(editor_snapshot)
14089            .y;
14090
14091        if source.row().as_f32() < scroll_top.floor() {
14092            return None;
14093        }
14094        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14095        let source_y = line_height * (source.row().as_f32() - scroll_top);
14096        Some(gpui::Point::new(source_x, source_y))
14097    }
14098
14099    pub fn has_active_completions_menu(&self) -> bool {
14100        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14101            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14102        })
14103    }
14104
14105    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14106        self.addons
14107            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14108    }
14109
14110    pub fn unregister_addon<T: Addon>(&mut self) {
14111        self.addons.remove(&std::any::TypeId::of::<T>());
14112    }
14113
14114    pub fn addon<T: Addon>(&self) -> Option<&T> {
14115        let type_id = std::any::TypeId::of::<T>();
14116        self.addons
14117            .get(&type_id)
14118            .and_then(|item| item.to_any().downcast_ref::<T>())
14119    }
14120
14121    fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14122        let text_layout_details = self.text_layout_details(window);
14123        let style = &text_layout_details.editor_style;
14124        let font_id = window.text_system().resolve_font(&style.text.font());
14125        let font_size = style.text.font_size.to_pixels(window.rem_size());
14126        let line_height = style.text.line_height_in_pixels(window.rem_size());
14127        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14128
14129        gpui::Point::new(em_width, line_height)
14130    }
14131}
14132
14133fn get_unstaged_changes_for_buffers(
14134    project: &Entity<Project>,
14135    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14136    buffer: Entity<MultiBuffer>,
14137    cx: &mut App,
14138) {
14139    let mut tasks = Vec::new();
14140    project.update(cx, |project, cx| {
14141        for buffer in buffers {
14142            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14143        }
14144    });
14145    cx.spawn(|mut cx| async move {
14146        let change_sets = futures::future::join_all(tasks).await;
14147        buffer
14148            .update(&mut cx, |buffer, cx| {
14149                for change_set in change_sets {
14150                    if let Some(change_set) = change_set.log_err() {
14151                        buffer.add_change_set(change_set, cx);
14152                    }
14153                }
14154            })
14155            .ok();
14156    })
14157    .detach();
14158}
14159
14160fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14161    let tab_size = tab_size.get() as usize;
14162    let mut width = offset;
14163
14164    for ch in text.chars() {
14165        width += if ch == '\t' {
14166            tab_size - (width % tab_size)
14167        } else {
14168            1
14169        };
14170    }
14171
14172    width - offset
14173}
14174
14175#[cfg(test)]
14176mod tests {
14177    use super::*;
14178
14179    #[test]
14180    fn test_string_size_with_expanded_tabs() {
14181        let nz = |val| NonZeroU32::new(val).unwrap();
14182        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14183        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14184        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14185        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14186        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14187        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14188        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14189        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14190    }
14191}
14192
14193/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14194struct WordBreakingTokenizer<'a> {
14195    input: &'a str,
14196}
14197
14198impl<'a> WordBreakingTokenizer<'a> {
14199    fn new(input: &'a str) -> Self {
14200        Self { input }
14201    }
14202}
14203
14204fn is_char_ideographic(ch: char) -> bool {
14205    use unicode_script::Script::*;
14206    use unicode_script::UnicodeScript;
14207    matches!(ch.script(), Han | Tangut | Yi)
14208}
14209
14210fn is_grapheme_ideographic(text: &str) -> bool {
14211    text.chars().any(is_char_ideographic)
14212}
14213
14214fn is_grapheme_whitespace(text: &str) -> bool {
14215    text.chars().any(|x| x.is_whitespace())
14216}
14217
14218fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14219    text.chars().next().map_or(false, |ch| {
14220        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14221    })
14222}
14223
14224#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14225struct WordBreakToken<'a> {
14226    token: &'a str,
14227    grapheme_len: usize,
14228    is_whitespace: bool,
14229}
14230
14231impl<'a> Iterator for WordBreakingTokenizer<'a> {
14232    /// Yields a span, the count of graphemes in the token, and whether it was
14233    /// whitespace. Note that it also breaks at word boundaries.
14234    type Item = WordBreakToken<'a>;
14235
14236    fn next(&mut self) -> Option<Self::Item> {
14237        use unicode_segmentation::UnicodeSegmentation;
14238        if self.input.is_empty() {
14239            return None;
14240        }
14241
14242        let mut iter = self.input.graphemes(true).peekable();
14243        let mut offset = 0;
14244        let mut graphemes = 0;
14245        if let Some(first_grapheme) = iter.next() {
14246            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14247            offset += first_grapheme.len();
14248            graphemes += 1;
14249            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14250                if let Some(grapheme) = iter.peek().copied() {
14251                    if should_stay_with_preceding_ideograph(grapheme) {
14252                        offset += grapheme.len();
14253                        graphemes += 1;
14254                    }
14255                }
14256            } else {
14257                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14258                let mut next_word_bound = words.peek().copied();
14259                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14260                    next_word_bound = words.next();
14261                }
14262                while let Some(grapheme) = iter.peek().copied() {
14263                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14264                        break;
14265                    };
14266                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14267                        break;
14268                    };
14269                    offset += grapheme.len();
14270                    graphemes += 1;
14271                    iter.next();
14272                }
14273            }
14274            let token = &self.input[..offset];
14275            self.input = &self.input[offset..];
14276            if is_whitespace {
14277                Some(WordBreakToken {
14278                    token: " ",
14279                    grapheme_len: 1,
14280                    is_whitespace: true,
14281                })
14282            } else {
14283                Some(WordBreakToken {
14284                    token,
14285                    grapheme_len: graphemes,
14286                    is_whitespace: false,
14287                })
14288            }
14289        } else {
14290            None
14291        }
14292    }
14293}
14294
14295#[test]
14296fn test_word_breaking_tokenizer() {
14297    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14298        ("", &[]),
14299        ("  ", &[(" ", 1, true)]),
14300        ("Ʒ", &[("Ʒ", 1, false)]),
14301        ("Ǽ", &[("Ǽ", 1, false)]),
14302        ("", &[("", 1, false)]),
14303        ("⋑⋑", &[("⋑⋑", 2, false)]),
14304        (
14305            "原理,进而",
14306            &[
14307                ("", 1, false),
14308                ("理,", 2, false),
14309                ("", 1, false),
14310                ("", 1, false),
14311            ],
14312        ),
14313        (
14314            "hello world",
14315            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14316        ),
14317        (
14318            "hello, world",
14319            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14320        ),
14321        (
14322            "  hello world",
14323            &[
14324                (" ", 1, true),
14325                ("hello", 5, false),
14326                (" ", 1, true),
14327                ("world", 5, false),
14328            ],
14329        ),
14330        (
14331            "这是什么 \n 钢笔",
14332            &[
14333                ("", 1, false),
14334                ("", 1, false),
14335                ("", 1, false),
14336                ("", 1, false),
14337                (" ", 1, true),
14338                ("", 1, false),
14339                ("", 1, false),
14340            ],
14341        ),
14342        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14343    ];
14344
14345    for (input, result) in tests {
14346        assert_eq!(
14347            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14348            result
14349                .iter()
14350                .copied()
14351                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14352                    token,
14353                    grapheme_len,
14354                    is_whitespace,
14355                })
14356                .collect::<Vec<_>>()
14357        );
14358    }
14359}
14360
14361fn wrap_with_prefix(
14362    line_prefix: String,
14363    unwrapped_text: String,
14364    wrap_column: usize,
14365    tab_size: NonZeroU32,
14366) -> String {
14367    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14368    let mut wrapped_text = String::new();
14369    let mut current_line = line_prefix.clone();
14370
14371    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14372    let mut current_line_len = line_prefix_len;
14373    for WordBreakToken {
14374        token,
14375        grapheme_len,
14376        is_whitespace,
14377    } in tokenizer
14378    {
14379        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14380            wrapped_text.push_str(current_line.trim_end());
14381            wrapped_text.push('\n');
14382            current_line.truncate(line_prefix.len());
14383            current_line_len = line_prefix_len;
14384            if !is_whitespace {
14385                current_line.push_str(token);
14386                current_line_len += grapheme_len;
14387            }
14388        } else if !is_whitespace {
14389            current_line.push_str(token);
14390            current_line_len += grapheme_len;
14391        } else if current_line_len != line_prefix_len {
14392            current_line.push(' ');
14393            current_line_len += 1;
14394        }
14395    }
14396
14397    if !current_line.is_empty() {
14398        wrapped_text.push_str(&current_line);
14399    }
14400    wrapped_text
14401}
14402
14403#[test]
14404fn test_wrap_with_prefix() {
14405    assert_eq!(
14406        wrap_with_prefix(
14407            "# ".to_string(),
14408            "abcdefg".to_string(),
14409            4,
14410            NonZeroU32::new(4).unwrap()
14411        ),
14412        "# abcdefg"
14413    );
14414    assert_eq!(
14415        wrap_with_prefix(
14416            "".to_string(),
14417            "\thello world".to_string(),
14418            8,
14419            NonZeroU32::new(4).unwrap()
14420        ),
14421        "hello\nworld"
14422    );
14423    assert_eq!(
14424        wrap_with_prefix(
14425            "// ".to_string(),
14426            "xx \nyy zz aa bb cc".to_string(),
14427            12,
14428            NonZeroU32::new(4).unwrap()
14429        ),
14430        "// xx yy zz\n// aa bb cc"
14431    );
14432    assert_eq!(
14433        wrap_with_prefix(
14434            String::new(),
14435            "这是什么 \n 钢笔".to_string(),
14436            3,
14437            NonZeroU32::new(4).unwrap()
14438        ),
14439        "这是什\n么 钢\n"
14440    );
14441}
14442
14443pub trait CollaborationHub {
14444    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14445    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14446    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14447}
14448
14449impl CollaborationHub for Entity<Project> {
14450    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14451        self.read(cx).collaborators()
14452    }
14453
14454    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14455        self.read(cx).user_store().read(cx).participant_indices()
14456    }
14457
14458    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14459        let this = self.read(cx);
14460        let user_ids = this.collaborators().values().map(|c| c.user_id);
14461        this.user_store().read_with(cx, |user_store, cx| {
14462            user_store.participant_names(user_ids, cx)
14463        })
14464    }
14465}
14466
14467pub trait SemanticsProvider {
14468    fn hover(
14469        &self,
14470        buffer: &Entity<Buffer>,
14471        position: text::Anchor,
14472        cx: &mut App,
14473    ) -> Option<Task<Vec<project::Hover>>>;
14474
14475    fn inlay_hints(
14476        &self,
14477        buffer_handle: Entity<Buffer>,
14478        range: Range<text::Anchor>,
14479        cx: &mut App,
14480    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14481
14482    fn resolve_inlay_hint(
14483        &self,
14484        hint: InlayHint,
14485        buffer_handle: Entity<Buffer>,
14486        server_id: LanguageServerId,
14487        cx: &mut App,
14488    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14489
14490    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14491
14492    fn document_highlights(
14493        &self,
14494        buffer: &Entity<Buffer>,
14495        position: text::Anchor,
14496        cx: &mut App,
14497    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14498
14499    fn definitions(
14500        &self,
14501        buffer: &Entity<Buffer>,
14502        position: text::Anchor,
14503        kind: GotoDefinitionKind,
14504        cx: &mut App,
14505    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14506
14507    fn range_for_rename(
14508        &self,
14509        buffer: &Entity<Buffer>,
14510        position: text::Anchor,
14511        cx: &mut App,
14512    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14513
14514    fn perform_rename(
14515        &self,
14516        buffer: &Entity<Buffer>,
14517        position: text::Anchor,
14518        new_name: String,
14519        cx: &mut App,
14520    ) -> Option<Task<Result<ProjectTransaction>>>;
14521}
14522
14523pub trait CompletionProvider {
14524    fn completions(
14525        &self,
14526        buffer: &Entity<Buffer>,
14527        buffer_position: text::Anchor,
14528        trigger: CompletionContext,
14529        window: &mut Window,
14530        cx: &mut Context<Editor>,
14531    ) -> Task<Result<Vec<Completion>>>;
14532
14533    fn resolve_completions(
14534        &self,
14535        buffer: Entity<Buffer>,
14536        completion_indices: Vec<usize>,
14537        completions: Rc<RefCell<Box<[Completion]>>>,
14538        cx: &mut Context<Editor>,
14539    ) -> Task<Result<bool>>;
14540
14541    fn apply_additional_edits_for_completion(
14542        &self,
14543        _buffer: Entity<Buffer>,
14544        _completions: Rc<RefCell<Box<[Completion]>>>,
14545        _completion_index: usize,
14546        _push_to_history: bool,
14547        _cx: &mut Context<Editor>,
14548    ) -> Task<Result<Option<language::Transaction>>> {
14549        Task::ready(Ok(None))
14550    }
14551
14552    fn is_completion_trigger(
14553        &self,
14554        buffer: &Entity<Buffer>,
14555        position: language::Anchor,
14556        text: &str,
14557        trigger_in_words: bool,
14558        cx: &mut Context<Editor>,
14559    ) -> bool;
14560
14561    fn sort_completions(&self) -> bool {
14562        true
14563    }
14564}
14565
14566pub trait CodeActionProvider {
14567    fn id(&self) -> Arc<str>;
14568
14569    fn code_actions(
14570        &self,
14571        buffer: &Entity<Buffer>,
14572        range: Range<text::Anchor>,
14573        window: &mut Window,
14574        cx: &mut App,
14575    ) -> Task<Result<Vec<CodeAction>>>;
14576
14577    fn apply_code_action(
14578        &self,
14579        buffer_handle: Entity<Buffer>,
14580        action: CodeAction,
14581        excerpt_id: ExcerptId,
14582        push_to_history: bool,
14583        window: &mut Window,
14584        cx: &mut App,
14585    ) -> Task<Result<ProjectTransaction>>;
14586}
14587
14588impl CodeActionProvider for Entity<Project> {
14589    fn id(&self) -> Arc<str> {
14590        "project".into()
14591    }
14592
14593    fn code_actions(
14594        &self,
14595        buffer: &Entity<Buffer>,
14596        range: Range<text::Anchor>,
14597        _window: &mut Window,
14598        cx: &mut App,
14599    ) -> Task<Result<Vec<CodeAction>>> {
14600        self.update(cx, |project, cx| {
14601            project.code_actions(buffer, range, None, cx)
14602        })
14603    }
14604
14605    fn apply_code_action(
14606        &self,
14607        buffer_handle: Entity<Buffer>,
14608        action: CodeAction,
14609        _excerpt_id: ExcerptId,
14610        push_to_history: bool,
14611        _window: &mut Window,
14612        cx: &mut App,
14613    ) -> Task<Result<ProjectTransaction>> {
14614        self.update(cx, |project, cx| {
14615            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14616        })
14617    }
14618}
14619
14620fn snippet_completions(
14621    project: &Project,
14622    buffer: &Entity<Buffer>,
14623    buffer_position: text::Anchor,
14624    cx: &mut App,
14625) -> Task<Result<Vec<Completion>>> {
14626    let language = buffer.read(cx).language_at(buffer_position);
14627    let language_name = language.as_ref().map(|language| language.lsp_id());
14628    let snippet_store = project.snippets().read(cx);
14629    let snippets = snippet_store.snippets_for(language_name, cx);
14630
14631    if snippets.is_empty() {
14632        return Task::ready(Ok(vec![]));
14633    }
14634    let snapshot = buffer.read(cx).text_snapshot();
14635    let chars: String = snapshot
14636        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14637        .collect();
14638
14639    let scope = language.map(|language| language.default_scope());
14640    let executor = cx.background_executor().clone();
14641
14642    cx.background_executor().spawn(async move {
14643        let classifier = CharClassifier::new(scope).for_completion(true);
14644        let mut last_word = chars
14645            .chars()
14646            .take_while(|c| classifier.is_word(*c))
14647            .collect::<String>();
14648        last_word = last_word.chars().rev().collect();
14649
14650        if last_word.is_empty() {
14651            return Ok(vec![]);
14652        }
14653
14654        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14655        let to_lsp = |point: &text::Anchor| {
14656            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14657            point_to_lsp(end)
14658        };
14659        let lsp_end = to_lsp(&buffer_position);
14660
14661        let candidates = snippets
14662            .iter()
14663            .enumerate()
14664            .flat_map(|(ix, snippet)| {
14665                snippet
14666                    .prefix
14667                    .iter()
14668                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14669            })
14670            .collect::<Vec<StringMatchCandidate>>();
14671
14672        let mut matches = fuzzy::match_strings(
14673            &candidates,
14674            &last_word,
14675            last_word.chars().any(|c| c.is_uppercase()),
14676            100,
14677            &Default::default(),
14678            executor,
14679        )
14680        .await;
14681
14682        // Remove all candidates where the query's start does not match the start of any word in the candidate
14683        if let Some(query_start) = last_word.chars().next() {
14684            matches.retain(|string_match| {
14685                split_words(&string_match.string).any(|word| {
14686                    // Check that the first codepoint of the word as lowercase matches the first
14687                    // codepoint of the query as lowercase
14688                    word.chars()
14689                        .flat_map(|codepoint| codepoint.to_lowercase())
14690                        .zip(query_start.to_lowercase())
14691                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14692                })
14693            });
14694        }
14695
14696        let matched_strings = matches
14697            .into_iter()
14698            .map(|m| m.string)
14699            .collect::<HashSet<_>>();
14700
14701        let result: Vec<Completion> = snippets
14702            .into_iter()
14703            .filter_map(|snippet| {
14704                let matching_prefix = snippet
14705                    .prefix
14706                    .iter()
14707                    .find(|prefix| matched_strings.contains(*prefix))?;
14708                let start = as_offset - last_word.len();
14709                let start = snapshot.anchor_before(start);
14710                let range = start..buffer_position;
14711                let lsp_start = to_lsp(&start);
14712                let lsp_range = lsp::Range {
14713                    start: lsp_start,
14714                    end: lsp_end,
14715                };
14716                Some(Completion {
14717                    old_range: range,
14718                    new_text: snippet.body.clone(),
14719                    resolved: false,
14720                    label: CodeLabel {
14721                        text: matching_prefix.clone(),
14722                        runs: vec![],
14723                        filter_range: 0..matching_prefix.len(),
14724                    },
14725                    server_id: LanguageServerId(usize::MAX),
14726                    documentation: snippet
14727                        .description
14728                        .clone()
14729                        .map(CompletionDocumentation::SingleLine),
14730                    lsp_completion: lsp::CompletionItem {
14731                        label: snippet.prefix.first().unwrap().clone(),
14732                        kind: Some(CompletionItemKind::SNIPPET),
14733                        label_details: snippet.description.as_ref().map(|description| {
14734                            lsp::CompletionItemLabelDetails {
14735                                detail: Some(description.clone()),
14736                                description: None,
14737                            }
14738                        }),
14739                        insert_text_format: Some(InsertTextFormat::SNIPPET),
14740                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14741                            lsp::InsertReplaceEdit {
14742                                new_text: snippet.body.clone(),
14743                                insert: lsp_range,
14744                                replace: lsp_range,
14745                            },
14746                        )),
14747                        filter_text: Some(snippet.body.clone()),
14748                        sort_text: Some(char::MAX.to_string()),
14749                        ..Default::default()
14750                    },
14751                    confirm: None,
14752                })
14753            })
14754            .collect();
14755
14756        Ok(result)
14757    })
14758}
14759
14760impl CompletionProvider for Entity<Project> {
14761    fn completions(
14762        &self,
14763        buffer: &Entity<Buffer>,
14764        buffer_position: text::Anchor,
14765        options: CompletionContext,
14766        _window: &mut Window,
14767        cx: &mut Context<Editor>,
14768    ) -> Task<Result<Vec<Completion>>> {
14769        self.update(cx, |project, cx| {
14770            let snippets = snippet_completions(project, buffer, buffer_position, cx);
14771            let project_completions = project.completions(buffer, buffer_position, options, cx);
14772            cx.background_executor().spawn(async move {
14773                let mut completions = project_completions.await?;
14774                let snippets_completions = snippets.await?;
14775                completions.extend(snippets_completions);
14776                Ok(completions)
14777            })
14778        })
14779    }
14780
14781    fn resolve_completions(
14782        &self,
14783        buffer: Entity<Buffer>,
14784        completion_indices: Vec<usize>,
14785        completions: Rc<RefCell<Box<[Completion]>>>,
14786        cx: &mut Context<Editor>,
14787    ) -> Task<Result<bool>> {
14788        self.update(cx, |project, cx| {
14789            project.lsp_store().update(cx, |lsp_store, cx| {
14790                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
14791            })
14792        })
14793    }
14794
14795    fn apply_additional_edits_for_completion(
14796        &self,
14797        buffer: Entity<Buffer>,
14798        completions: Rc<RefCell<Box<[Completion]>>>,
14799        completion_index: usize,
14800        push_to_history: bool,
14801        cx: &mut Context<Editor>,
14802    ) -> Task<Result<Option<language::Transaction>>> {
14803        self.update(cx, |project, cx| {
14804            project.lsp_store().update(cx, |lsp_store, cx| {
14805                lsp_store.apply_additional_edits_for_completion(
14806                    buffer,
14807                    completions,
14808                    completion_index,
14809                    push_to_history,
14810                    cx,
14811                )
14812            })
14813        })
14814    }
14815
14816    fn is_completion_trigger(
14817        &self,
14818        buffer: &Entity<Buffer>,
14819        position: language::Anchor,
14820        text: &str,
14821        trigger_in_words: bool,
14822        cx: &mut Context<Editor>,
14823    ) -> bool {
14824        let mut chars = text.chars();
14825        let char = if let Some(char) = chars.next() {
14826            char
14827        } else {
14828            return false;
14829        };
14830        if chars.next().is_some() {
14831            return false;
14832        }
14833
14834        let buffer = buffer.read(cx);
14835        let snapshot = buffer.snapshot();
14836        if !snapshot.settings_at(position, cx).show_completions_on_input {
14837            return false;
14838        }
14839        let classifier = snapshot.char_classifier_at(position).for_completion(true);
14840        if trigger_in_words && classifier.is_word(char) {
14841            return true;
14842        }
14843
14844        buffer.completion_triggers().contains(text)
14845    }
14846}
14847
14848impl SemanticsProvider for Entity<Project> {
14849    fn hover(
14850        &self,
14851        buffer: &Entity<Buffer>,
14852        position: text::Anchor,
14853        cx: &mut App,
14854    ) -> Option<Task<Vec<project::Hover>>> {
14855        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14856    }
14857
14858    fn document_highlights(
14859        &self,
14860        buffer: &Entity<Buffer>,
14861        position: text::Anchor,
14862        cx: &mut App,
14863    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14864        Some(self.update(cx, |project, cx| {
14865            project.document_highlights(buffer, position, cx)
14866        }))
14867    }
14868
14869    fn definitions(
14870        &self,
14871        buffer: &Entity<Buffer>,
14872        position: text::Anchor,
14873        kind: GotoDefinitionKind,
14874        cx: &mut App,
14875    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14876        Some(self.update(cx, |project, cx| match kind {
14877            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14878            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14879            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14880            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14881        }))
14882    }
14883
14884    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
14885        // TODO: make this work for remote projects
14886        self.read(cx)
14887            .language_servers_for_local_buffer(buffer.read(cx), cx)
14888            .any(
14889                |(_, server)| match server.capabilities().inlay_hint_provider {
14890                    Some(lsp::OneOf::Left(enabled)) => enabled,
14891                    Some(lsp::OneOf::Right(_)) => true,
14892                    None => false,
14893                },
14894            )
14895    }
14896
14897    fn inlay_hints(
14898        &self,
14899        buffer_handle: Entity<Buffer>,
14900        range: Range<text::Anchor>,
14901        cx: &mut App,
14902    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14903        Some(self.update(cx, |project, cx| {
14904            project.inlay_hints(buffer_handle, range, cx)
14905        }))
14906    }
14907
14908    fn resolve_inlay_hint(
14909        &self,
14910        hint: InlayHint,
14911        buffer_handle: Entity<Buffer>,
14912        server_id: LanguageServerId,
14913        cx: &mut App,
14914    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14915        Some(self.update(cx, |project, cx| {
14916            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14917        }))
14918    }
14919
14920    fn range_for_rename(
14921        &self,
14922        buffer: &Entity<Buffer>,
14923        position: text::Anchor,
14924        cx: &mut App,
14925    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14926        Some(self.update(cx, |project, cx| {
14927            let buffer = buffer.clone();
14928            let task = project.prepare_rename(buffer.clone(), position, cx);
14929            cx.spawn(|_, mut cx| async move {
14930                Ok(match task.await? {
14931                    PrepareRenameResponse::Success(range) => Some(range),
14932                    PrepareRenameResponse::InvalidPosition => None,
14933                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14934                        // Fallback on using TreeSitter info to determine identifier range
14935                        buffer.update(&mut cx, |buffer, _| {
14936                            let snapshot = buffer.snapshot();
14937                            let (range, kind) = snapshot.surrounding_word(position);
14938                            if kind != Some(CharKind::Word) {
14939                                return None;
14940                            }
14941                            Some(
14942                                snapshot.anchor_before(range.start)
14943                                    ..snapshot.anchor_after(range.end),
14944                            )
14945                        })?
14946                    }
14947                })
14948            })
14949        }))
14950    }
14951
14952    fn perform_rename(
14953        &self,
14954        buffer: &Entity<Buffer>,
14955        position: text::Anchor,
14956        new_name: String,
14957        cx: &mut App,
14958    ) -> Option<Task<Result<ProjectTransaction>>> {
14959        Some(self.update(cx, |project, cx| {
14960            project.perform_rename(buffer.clone(), position, new_name, cx)
14961        }))
14962    }
14963}
14964
14965fn inlay_hint_settings(
14966    location: Anchor,
14967    snapshot: &MultiBufferSnapshot,
14968    cx: &mut Context<Editor>,
14969) -> InlayHintSettings {
14970    let file = snapshot.file_at(location);
14971    let language = snapshot.language_at(location).map(|l| l.name());
14972    language_settings(language, file, cx).inlay_hints
14973}
14974
14975fn consume_contiguous_rows(
14976    contiguous_row_selections: &mut Vec<Selection<Point>>,
14977    selection: &Selection<Point>,
14978    display_map: &DisplaySnapshot,
14979    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14980) -> (MultiBufferRow, MultiBufferRow) {
14981    contiguous_row_selections.push(selection.clone());
14982    let start_row = MultiBufferRow(selection.start.row);
14983    let mut end_row = ending_row(selection, display_map);
14984
14985    while let Some(next_selection) = selections.peek() {
14986        if next_selection.start.row <= end_row.0 {
14987            end_row = ending_row(next_selection, display_map);
14988            contiguous_row_selections.push(selections.next().unwrap().clone());
14989        } else {
14990            break;
14991        }
14992    }
14993    (start_row, end_row)
14994}
14995
14996fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14997    if next_selection.end.column > 0 || next_selection.is_empty() {
14998        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14999    } else {
15000        MultiBufferRow(next_selection.end.row)
15001    }
15002}
15003
15004impl EditorSnapshot {
15005    pub fn remote_selections_in_range<'a>(
15006        &'a self,
15007        range: &'a Range<Anchor>,
15008        collaboration_hub: &dyn CollaborationHub,
15009        cx: &'a App,
15010    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15011        let participant_names = collaboration_hub.user_names(cx);
15012        let participant_indices = collaboration_hub.user_participant_indices(cx);
15013        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15014        let collaborators_by_replica_id = collaborators_by_peer_id
15015            .iter()
15016            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15017            .collect::<HashMap<_, _>>();
15018        self.buffer_snapshot
15019            .selections_in_range(range, false)
15020            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15021                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15022                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15023                let user_name = participant_names.get(&collaborator.user_id).cloned();
15024                Some(RemoteSelection {
15025                    replica_id,
15026                    selection,
15027                    cursor_shape,
15028                    line_mode,
15029                    participant_index,
15030                    peer_id: collaborator.peer_id,
15031                    user_name,
15032                })
15033            })
15034    }
15035
15036    pub fn hunks_for_ranges(
15037        &self,
15038        ranges: impl Iterator<Item = Range<Point>>,
15039    ) -> Vec<MultiBufferDiffHunk> {
15040        let mut hunks = Vec::new();
15041        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15042            HashMap::default();
15043        for query_range in ranges {
15044            let query_rows =
15045                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15046            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15047                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15048            ) {
15049                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15050                // when the caret is just above or just below the deleted hunk.
15051                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15052                let related_to_selection = if allow_adjacent {
15053                    hunk.row_range.overlaps(&query_rows)
15054                        || hunk.row_range.start == query_rows.end
15055                        || hunk.row_range.end == query_rows.start
15056                } else {
15057                    hunk.row_range.overlaps(&query_rows)
15058                };
15059                if related_to_selection {
15060                    if !processed_buffer_rows
15061                        .entry(hunk.buffer_id)
15062                        .or_default()
15063                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15064                    {
15065                        continue;
15066                    }
15067                    hunks.push(hunk);
15068                }
15069            }
15070        }
15071
15072        hunks
15073    }
15074
15075    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15076        self.display_snapshot.buffer_snapshot.language_at(position)
15077    }
15078
15079    pub fn is_focused(&self) -> bool {
15080        self.is_focused
15081    }
15082
15083    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15084        self.placeholder_text.as_ref()
15085    }
15086
15087    pub fn scroll_position(&self) -> gpui::Point<f32> {
15088        self.scroll_anchor.scroll_position(&self.display_snapshot)
15089    }
15090
15091    fn gutter_dimensions(
15092        &self,
15093        font_id: FontId,
15094        font_size: Pixels,
15095        max_line_number_width: Pixels,
15096        cx: &App,
15097    ) -> Option<GutterDimensions> {
15098        if !self.show_gutter {
15099            return None;
15100        }
15101
15102        let descent = cx.text_system().descent(font_id, font_size);
15103        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15104        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15105
15106        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15107            matches!(
15108                ProjectSettings::get_global(cx).git.git_gutter,
15109                Some(GitGutterSetting::TrackedFiles)
15110            )
15111        });
15112        let gutter_settings = EditorSettings::get_global(cx).gutter;
15113        let show_line_numbers = self
15114            .show_line_numbers
15115            .unwrap_or(gutter_settings.line_numbers);
15116        let line_gutter_width = if show_line_numbers {
15117            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15118            let min_width_for_number_on_gutter = em_advance * 4.0;
15119            max_line_number_width.max(min_width_for_number_on_gutter)
15120        } else {
15121            0.0.into()
15122        };
15123
15124        let show_code_actions = self
15125            .show_code_actions
15126            .unwrap_or(gutter_settings.code_actions);
15127
15128        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15129
15130        let git_blame_entries_width =
15131            self.git_blame_gutter_max_author_length
15132                .map(|max_author_length| {
15133                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15134
15135                    /// The number of characters to dedicate to gaps and margins.
15136                    const SPACING_WIDTH: usize = 4;
15137
15138                    let max_char_count = max_author_length
15139                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15140                        + ::git::SHORT_SHA_LENGTH
15141                        + MAX_RELATIVE_TIMESTAMP.len()
15142                        + SPACING_WIDTH;
15143
15144                    em_advance * max_char_count
15145                });
15146
15147        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15148        left_padding += if show_code_actions || show_runnables {
15149            em_width * 3.0
15150        } else if show_git_gutter && show_line_numbers {
15151            em_width * 2.0
15152        } else if show_git_gutter || show_line_numbers {
15153            em_width
15154        } else {
15155            px(0.)
15156        };
15157
15158        let right_padding = if gutter_settings.folds && show_line_numbers {
15159            em_width * 4.0
15160        } else if gutter_settings.folds {
15161            em_width * 3.0
15162        } else if show_line_numbers {
15163            em_width
15164        } else {
15165            px(0.)
15166        };
15167
15168        Some(GutterDimensions {
15169            left_padding,
15170            right_padding,
15171            width: line_gutter_width + left_padding + right_padding,
15172            margin: -descent,
15173            git_blame_entries_width,
15174        })
15175    }
15176
15177    pub fn render_crease_toggle(
15178        &self,
15179        buffer_row: MultiBufferRow,
15180        row_contains_cursor: bool,
15181        editor: Entity<Editor>,
15182        window: &mut Window,
15183        cx: &mut App,
15184    ) -> Option<AnyElement> {
15185        let folded = self.is_line_folded(buffer_row);
15186        let mut is_foldable = false;
15187
15188        if let Some(crease) = self
15189            .crease_snapshot
15190            .query_row(buffer_row, &self.buffer_snapshot)
15191        {
15192            is_foldable = true;
15193            match crease {
15194                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15195                    if let Some(render_toggle) = render_toggle {
15196                        let toggle_callback =
15197                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15198                                if folded {
15199                                    editor.update(cx, |editor, cx| {
15200                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15201                                    });
15202                                } else {
15203                                    editor.update(cx, |editor, cx| {
15204                                        editor.unfold_at(
15205                                            &crate::UnfoldAt { buffer_row },
15206                                            window,
15207                                            cx,
15208                                        )
15209                                    });
15210                                }
15211                            });
15212                        return Some((render_toggle)(
15213                            buffer_row,
15214                            folded,
15215                            toggle_callback,
15216                            window,
15217                            cx,
15218                        ));
15219                    }
15220                }
15221            }
15222        }
15223
15224        is_foldable |= self.starts_indent(buffer_row);
15225
15226        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15227            Some(
15228                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15229                    .toggle_state(folded)
15230                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15231                        if folded {
15232                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15233                        } else {
15234                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15235                        }
15236                    }))
15237                    .into_any_element(),
15238            )
15239        } else {
15240            None
15241        }
15242    }
15243
15244    pub fn render_crease_trailer(
15245        &self,
15246        buffer_row: MultiBufferRow,
15247        window: &mut Window,
15248        cx: &mut App,
15249    ) -> Option<AnyElement> {
15250        let folded = self.is_line_folded(buffer_row);
15251        if let Crease::Inline { render_trailer, .. } = self
15252            .crease_snapshot
15253            .query_row(buffer_row, &self.buffer_snapshot)?
15254        {
15255            let render_trailer = render_trailer.as_ref()?;
15256            Some(render_trailer(buffer_row, folded, window, cx))
15257        } else {
15258            None
15259        }
15260    }
15261}
15262
15263impl Deref for EditorSnapshot {
15264    type Target = DisplaySnapshot;
15265
15266    fn deref(&self) -> &Self::Target {
15267        &self.display_snapshot
15268    }
15269}
15270
15271#[derive(Clone, Debug, PartialEq, Eq)]
15272pub enum EditorEvent {
15273    InputIgnored {
15274        text: Arc<str>,
15275    },
15276    InputHandled {
15277        utf16_range_to_replace: Option<Range<isize>>,
15278        text: Arc<str>,
15279    },
15280    ExcerptsAdded {
15281        buffer: Entity<Buffer>,
15282        predecessor: ExcerptId,
15283        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15284    },
15285    ExcerptsRemoved {
15286        ids: Vec<ExcerptId>,
15287    },
15288    BufferFoldToggled {
15289        ids: Vec<ExcerptId>,
15290        folded: bool,
15291    },
15292    ExcerptsEdited {
15293        ids: Vec<ExcerptId>,
15294    },
15295    ExcerptsExpanded {
15296        ids: Vec<ExcerptId>,
15297    },
15298    BufferEdited,
15299    Edited {
15300        transaction_id: clock::Lamport,
15301    },
15302    Reparsed(BufferId),
15303    Focused,
15304    FocusedIn,
15305    Blurred,
15306    DirtyChanged,
15307    Saved,
15308    TitleChanged,
15309    DiffBaseChanged,
15310    SelectionsChanged {
15311        local: bool,
15312    },
15313    ScrollPositionChanged {
15314        local: bool,
15315        autoscroll: bool,
15316    },
15317    Closed,
15318    TransactionUndone {
15319        transaction_id: clock::Lamport,
15320    },
15321    TransactionBegun {
15322        transaction_id: clock::Lamport,
15323    },
15324    Reloaded,
15325    CursorShapeChanged,
15326}
15327
15328impl EventEmitter<EditorEvent> for Editor {}
15329
15330impl Focusable for Editor {
15331    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15332        self.focus_handle.clone()
15333    }
15334}
15335
15336impl Render for Editor {
15337    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15338        let settings = ThemeSettings::get_global(cx);
15339
15340        let mut text_style = match self.mode {
15341            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15342                color: cx.theme().colors().editor_foreground,
15343                font_family: settings.ui_font.family.clone(),
15344                font_features: settings.ui_font.features.clone(),
15345                font_fallbacks: settings.ui_font.fallbacks.clone(),
15346                font_size: rems(0.875).into(),
15347                font_weight: settings.ui_font.weight,
15348                line_height: relative(settings.buffer_line_height.value()),
15349                ..Default::default()
15350            },
15351            EditorMode::Full => TextStyle {
15352                color: cx.theme().colors().editor_foreground,
15353                font_family: settings.buffer_font.family.clone(),
15354                font_features: settings.buffer_font.features.clone(),
15355                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15356                font_size: settings.buffer_font_size().into(),
15357                font_weight: settings.buffer_font.weight,
15358                line_height: relative(settings.buffer_line_height.value()),
15359                ..Default::default()
15360            },
15361        };
15362        if let Some(text_style_refinement) = &self.text_style_refinement {
15363            text_style.refine(text_style_refinement)
15364        }
15365
15366        let background = match self.mode {
15367            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15368            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15369            EditorMode::Full => cx.theme().colors().editor_background,
15370        };
15371
15372        EditorElement::new(
15373            &cx.entity(),
15374            EditorStyle {
15375                background,
15376                local_player: cx.theme().players().local(),
15377                text: text_style,
15378                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15379                syntax: cx.theme().syntax().clone(),
15380                status: cx.theme().status().clone(),
15381                inlay_hints_style: make_inlay_hints_style(cx),
15382                inline_completion_styles: make_suggestion_styles(cx),
15383                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15384            },
15385        )
15386    }
15387}
15388
15389impl EntityInputHandler for Editor {
15390    fn text_for_range(
15391        &mut self,
15392        range_utf16: Range<usize>,
15393        adjusted_range: &mut Option<Range<usize>>,
15394        _: &mut Window,
15395        cx: &mut Context<Self>,
15396    ) -> Option<String> {
15397        let snapshot = self.buffer.read(cx).read(cx);
15398        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15399        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15400        if (start.0..end.0) != range_utf16 {
15401            adjusted_range.replace(start.0..end.0);
15402        }
15403        Some(snapshot.text_for_range(start..end).collect())
15404    }
15405
15406    fn selected_text_range(
15407        &mut self,
15408        ignore_disabled_input: bool,
15409        _: &mut Window,
15410        cx: &mut Context<Self>,
15411    ) -> Option<UTF16Selection> {
15412        // Prevent the IME menu from appearing when holding down an alphabetic key
15413        // while input is disabled.
15414        if !ignore_disabled_input && !self.input_enabled {
15415            return None;
15416        }
15417
15418        let selection = self.selections.newest::<OffsetUtf16>(cx);
15419        let range = selection.range();
15420
15421        Some(UTF16Selection {
15422            range: range.start.0..range.end.0,
15423            reversed: selection.reversed,
15424        })
15425    }
15426
15427    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15428        let snapshot = self.buffer.read(cx).read(cx);
15429        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15430        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15431    }
15432
15433    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15434        self.clear_highlights::<InputComposition>(cx);
15435        self.ime_transaction.take();
15436    }
15437
15438    fn replace_text_in_range(
15439        &mut self,
15440        range_utf16: Option<Range<usize>>,
15441        text: &str,
15442        window: &mut Window,
15443        cx: &mut Context<Self>,
15444    ) {
15445        if !self.input_enabled {
15446            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15447            return;
15448        }
15449
15450        self.transact(window, cx, |this, window, cx| {
15451            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15452                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15453                Some(this.selection_replacement_ranges(range_utf16, cx))
15454            } else {
15455                this.marked_text_ranges(cx)
15456            };
15457
15458            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15459                let newest_selection_id = this.selections.newest_anchor().id;
15460                this.selections
15461                    .all::<OffsetUtf16>(cx)
15462                    .iter()
15463                    .zip(ranges_to_replace.iter())
15464                    .find_map(|(selection, range)| {
15465                        if selection.id == newest_selection_id {
15466                            Some(
15467                                (range.start.0 as isize - selection.head().0 as isize)
15468                                    ..(range.end.0 as isize - selection.head().0 as isize),
15469                            )
15470                        } else {
15471                            None
15472                        }
15473                    })
15474            });
15475
15476            cx.emit(EditorEvent::InputHandled {
15477                utf16_range_to_replace: range_to_replace,
15478                text: text.into(),
15479            });
15480
15481            if let Some(new_selected_ranges) = new_selected_ranges {
15482                this.change_selections(None, window, cx, |selections| {
15483                    selections.select_ranges(new_selected_ranges)
15484                });
15485                this.backspace(&Default::default(), window, cx);
15486            }
15487
15488            this.handle_input(text, window, cx);
15489        });
15490
15491        if let Some(transaction) = self.ime_transaction {
15492            self.buffer.update(cx, |buffer, cx| {
15493                buffer.group_until_transaction(transaction, cx);
15494            });
15495        }
15496
15497        self.unmark_text(window, cx);
15498    }
15499
15500    fn replace_and_mark_text_in_range(
15501        &mut self,
15502        range_utf16: Option<Range<usize>>,
15503        text: &str,
15504        new_selected_range_utf16: Option<Range<usize>>,
15505        window: &mut Window,
15506        cx: &mut Context<Self>,
15507    ) {
15508        if !self.input_enabled {
15509            return;
15510        }
15511
15512        let transaction = self.transact(window, cx, |this, window, cx| {
15513            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15514                let snapshot = this.buffer.read(cx).read(cx);
15515                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15516                    for marked_range in &mut marked_ranges {
15517                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15518                        marked_range.start.0 += relative_range_utf16.start;
15519                        marked_range.start =
15520                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15521                        marked_range.end =
15522                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15523                    }
15524                }
15525                Some(marked_ranges)
15526            } else if let Some(range_utf16) = range_utf16 {
15527                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15528                Some(this.selection_replacement_ranges(range_utf16, cx))
15529            } else {
15530                None
15531            };
15532
15533            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15534                let newest_selection_id = this.selections.newest_anchor().id;
15535                this.selections
15536                    .all::<OffsetUtf16>(cx)
15537                    .iter()
15538                    .zip(ranges_to_replace.iter())
15539                    .find_map(|(selection, range)| {
15540                        if selection.id == newest_selection_id {
15541                            Some(
15542                                (range.start.0 as isize - selection.head().0 as isize)
15543                                    ..(range.end.0 as isize - selection.head().0 as isize),
15544                            )
15545                        } else {
15546                            None
15547                        }
15548                    })
15549            });
15550
15551            cx.emit(EditorEvent::InputHandled {
15552                utf16_range_to_replace: range_to_replace,
15553                text: text.into(),
15554            });
15555
15556            if let Some(ranges) = ranges_to_replace {
15557                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15558            }
15559
15560            let marked_ranges = {
15561                let snapshot = this.buffer.read(cx).read(cx);
15562                this.selections
15563                    .disjoint_anchors()
15564                    .iter()
15565                    .map(|selection| {
15566                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15567                    })
15568                    .collect::<Vec<_>>()
15569            };
15570
15571            if text.is_empty() {
15572                this.unmark_text(window, cx);
15573            } else {
15574                this.highlight_text::<InputComposition>(
15575                    marked_ranges.clone(),
15576                    HighlightStyle {
15577                        underline: Some(UnderlineStyle {
15578                            thickness: px(1.),
15579                            color: None,
15580                            wavy: false,
15581                        }),
15582                        ..Default::default()
15583                    },
15584                    cx,
15585                );
15586            }
15587
15588            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15589            let use_autoclose = this.use_autoclose;
15590            let use_auto_surround = this.use_auto_surround;
15591            this.set_use_autoclose(false);
15592            this.set_use_auto_surround(false);
15593            this.handle_input(text, window, cx);
15594            this.set_use_autoclose(use_autoclose);
15595            this.set_use_auto_surround(use_auto_surround);
15596
15597            if let Some(new_selected_range) = new_selected_range_utf16 {
15598                let snapshot = this.buffer.read(cx).read(cx);
15599                let new_selected_ranges = marked_ranges
15600                    .into_iter()
15601                    .map(|marked_range| {
15602                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15603                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15604                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15605                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15606                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15607                    })
15608                    .collect::<Vec<_>>();
15609
15610                drop(snapshot);
15611                this.change_selections(None, window, cx, |selections| {
15612                    selections.select_ranges(new_selected_ranges)
15613                });
15614            }
15615        });
15616
15617        self.ime_transaction = self.ime_transaction.or(transaction);
15618        if let Some(transaction) = self.ime_transaction {
15619            self.buffer.update(cx, |buffer, cx| {
15620                buffer.group_until_transaction(transaction, cx);
15621            });
15622        }
15623
15624        if self.text_highlights::<InputComposition>(cx).is_none() {
15625            self.ime_transaction.take();
15626        }
15627    }
15628
15629    fn bounds_for_range(
15630        &mut self,
15631        range_utf16: Range<usize>,
15632        element_bounds: gpui::Bounds<Pixels>,
15633        window: &mut Window,
15634        cx: &mut Context<Self>,
15635    ) -> Option<gpui::Bounds<Pixels>> {
15636        let text_layout_details = self.text_layout_details(window);
15637        let gpui::Point {
15638            x: em_width,
15639            y: line_height,
15640        } = self.character_size(window);
15641
15642        let snapshot = self.snapshot(window, cx);
15643        let scroll_position = snapshot.scroll_position();
15644        let scroll_left = scroll_position.x * em_width;
15645
15646        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15647        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15648            + self.gutter_dimensions.width
15649            + self.gutter_dimensions.margin;
15650        let y = line_height * (start.row().as_f32() - scroll_position.y);
15651
15652        Some(Bounds {
15653            origin: element_bounds.origin + point(x, y),
15654            size: size(em_width, line_height),
15655        })
15656    }
15657}
15658
15659trait SelectionExt {
15660    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15661    fn spanned_rows(
15662        &self,
15663        include_end_if_at_line_start: bool,
15664        map: &DisplaySnapshot,
15665    ) -> Range<MultiBufferRow>;
15666}
15667
15668impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15669    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15670        let start = self
15671            .start
15672            .to_point(&map.buffer_snapshot)
15673            .to_display_point(map);
15674        let end = self
15675            .end
15676            .to_point(&map.buffer_snapshot)
15677            .to_display_point(map);
15678        if self.reversed {
15679            end..start
15680        } else {
15681            start..end
15682        }
15683    }
15684
15685    fn spanned_rows(
15686        &self,
15687        include_end_if_at_line_start: bool,
15688        map: &DisplaySnapshot,
15689    ) -> Range<MultiBufferRow> {
15690        let start = self.start.to_point(&map.buffer_snapshot);
15691        let mut end = self.end.to_point(&map.buffer_snapshot);
15692        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15693            end.row -= 1;
15694        }
15695
15696        let buffer_start = map.prev_line_boundary(start).0;
15697        let buffer_end = map.next_line_boundary(end).0;
15698        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15699    }
15700}
15701
15702impl<T: InvalidationRegion> InvalidationStack<T> {
15703    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15704    where
15705        S: Clone + ToOffset,
15706    {
15707        while let Some(region) = self.last() {
15708            let all_selections_inside_invalidation_ranges =
15709                if selections.len() == region.ranges().len() {
15710                    selections
15711                        .iter()
15712                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15713                        .all(|(selection, invalidation_range)| {
15714                            let head = selection.head().to_offset(buffer);
15715                            invalidation_range.start <= head && invalidation_range.end >= head
15716                        })
15717                } else {
15718                    false
15719                };
15720
15721            if all_selections_inside_invalidation_ranges {
15722                break;
15723            } else {
15724                self.pop();
15725            }
15726        }
15727    }
15728}
15729
15730impl<T> Default for InvalidationStack<T> {
15731    fn default() -> Self {
15732        Self(Default::default())
15733    }
15734}
15735
15736impl<T> Deref for InvalidationStack<T> {
15737    type Target = Vec<T>;
15738
15739    fn deref(&self) -> &Self::Target {
15740        &self.0
15741    }
15742}
15743
15744impl<T> DerefMut for InvalidationStack<T> {
15745    fn deref_mut(&mut self) -> &mut Self::Target {
15746        &mut self.0
15747    }
15748}
15749
15750impl InvalidationRegion for SnippetState {
15751    fn ranges(&self) -> &[Range<Anchor>] {
15752        &self.ranges[self.active_index]
15753    }
15754}
15755
15756pub fn diagnostic_block_renderer(
15757    diagnostic: Diagnostic,
15758    max_message_rows: Option<u8>,
15759    allow_closing: bool,
15760    _is_valid: bool,
15761) -> RenderBlock {
15762    let (text_without_backticks, code_ranges) =
15763        highlight_diagnostic_message(&diagnostic, max_message_rows);
15764
15765    Arc::new(move |cx: &mut BlockContext| {
15766        let group_id: SharedString = cx.block_id.to_string().into();
15767
15768        let mut text_style = cx.window.text_style().clone();
15769        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15770        let theme_settings = ThemeSettings::get_global(cx);
15771        text_style.font_family = theme_settings.buffer_font.family.clone();
15772        text_style.font_style = theme_settings.buffer_font.style;
15773        text_style.font_features = theme_settings.buffer_font.features.clone();
15774        text_style.font_weight = theme_settings.buffer_font.weight;
15775
15776        let multi_line_diagnostic = diagnostic.message.contains('\n');
15777
15778        let buttons = |diagnostic: &Diagnostic| {
15779            if multi_line_diagnostic {
15780                v_flex()
15781            } else {
15782                h_flex()
15783            }
15784            .when(allow_closing, |div| {
15785                div.children(diagnostic.is_primary.then(|| {
15786                    IconButton::new("close-block", IconName::XCircle)
15787                        .icon_color(Color::Muted)
15788                        .size(ButtonSize::Compact)
15789                        .style(ButtonStyle::Transparent)
15790                        .visible_on_hover(group_id.clone())
15791                        .on_click(move |_click, window, cx| {
15792                            window.dispatch_action(Box::new(Cancel), cx)
15793                        })
15794                        .tooltip(|window, cx| {
15795                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
15796                        })
15797                }))
15798            })
15799            .child(
15800                IconButton::new("copy-block", IconName::Copy)
15801                    .icon_color(Color::Muted)
15802                    .size(ButtonSize::Compact)
15803                    .style(ButtonStyle::Transparent)
15804                    .visible_on_hover(group_id.clone())
15805                    .on_click({
15806                        let message = diagnostic.message.clone();
15807                        move |_click, _, cx| {
15808                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15809                        }
15810                    })
15811                    .tooltip(Tooltip::text("Copy diagnostic message")),
15812            )
15813        };
15814
15815        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
15816            AvailableSpace::min_size(),
15817            cx.window,
15818            cx.app,
15819        );
15820
15821        h_flex()
15822            .id(cx.block_id)
15823            .group(group_id.clone())
15824            .relative()
15825            .size_full()
15826            .block_mouse_down()
15827            .pl(cx.gutter_dimensions.width)
15828            .w(cx.max_width - cx.gutter_dimensions.full_width())
15829            .child(
15830                div()
15831                    .flex()
15832                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15833                    .flex_shrink(),
15834            )
15835            .child(buttons(&diagnostic))
15836            .child(div().flex().flex_shrink_0().child(
15837                StyledText::new(text_without_backticks.clone()).with_highlights(
15838                    &text_style,
15839                    code_ranges.iter().map(|range| {
15840                        (
15841                            range.clone(),
15842                            HighlightStyle {
15843                                font_weight: Some(FontWeight::BOLD),
15844                                ..Default::default()
15845                            },
15846                        )
15847                    }),
15848                ),
15849            ))
15850            .into_any_element()
15851    })
15852}
15853
15854fn inline_completion_edit_text(
15855    current_snapshot: &BufferSnapshot,
15856    edits: &[(Range<Anchor>, String)],
15857    edit_preview: &EditPreview,
15858    include_deletions: bool,
15859    cx: &App,
15860) -> Option<HighlightedText> {
15861    let edits = edits
15862        .iter()
15863        .map(|(anchor, text)| {
15864            (
15865                anchor.start.text_anchor..anchor.end.text_anchor,
15866                text.clone(),
15867            )
15868        })
15869        .collect::<Vec<_>>();
15870
15871    Some(edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx))
15872}
15873
15874pub fn highlight_diagnostic_message(
15875    diagnostic: &Diagnostic,
15876    mut max_message_rows: Option<u8>,
15877) -> (SharedString, Vec<Range<usize>>) {
15878    let mut text_without_backticks = String::new();
15879    let mut code_ranges = Vec::new();
15880
15881    if let Some(source) = &diagnostic.source {
15882        text_without_backticks.push_str(source);
15883        code_ranges.push(0..source.len());
15884        text_without_backticks.push_str(": ");
15885    }
15886
15887    let mut prev_offset = 0;
15888    let mut in_code_block = false;
15889    let has_row_limit = max_message_rows.is_some();
15890    let mut newline_indices = diagnostic
15891        .message
15892        .match_indices('\n')
15893        .filter(|_| has_row_limit)
15894        .map(|(ix, _)| ix)
15895        .fuse()
15896        .peekable();
15897
15898    for (quote_ix, _) in diagnostic
15899        .message
15900        .match_indices('`')
15901        .chain([(diagnostic.message.len(), "")])
15902    {
15903        let mut first_newline_ix = None;
15904        let mut last_newline_ix = None;
15905        while let Some(newline_ix) = newline_indices.peek() {
15906            if *newline_ix < quote_ix {
15907                if first_newline_ix.is_none() {
15908                    first_newline_ix = Some(*newline_ix);
15909                }
15910                last_newline_ix = Some(*newline_ix);
15911
15912                if let Some(rows_left) = &mut max_message_rows {
15913                    if *rows_left == 0 {
15914                        break;
15915                    } else {
15916                        *rows_left -= 1;
15917                    }
15918                }
15919                let _ = newline_indices.next();
15920            } else {
15921                break;
15922            }
15923        }
15924        let prev_len = text_without_backticks.len();
15925        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15926        text_without_backticks.push_str(new_text);
15927        if in_code_block {
15928            code_ranges.push(prev_len..text_without_backticks.len());
15929        }
15930        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15931        in_code_block = !in_code_block;
15932        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15933            text_without_backticks.push_str("...");
15934            break;
15935        }
15936    }
15937
15938    (text_without_backticks.into(), code_ranges)
15939}
15940
15941fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15942    match severity {
15943        DiagnosticSeverity::ERROR => colors.error,
15944        DiagnosticSeverity::WARNING => colors.warning,
15945        DiagnosticSeverity::INFORMATION => colors.info,
15946        DiagnosticSeverity::HINT => colors.info,
15947        _ => colors.ignored,
15948    }
15949}
15950
15951pub fn styled_runs_for_code_label<'a>(
15952    label: &'a CodeLabel,
15953    syntax_theme: &'a theme::SyntaxTheme,
15954) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15955    let fade_out = HighlightStyle {
15956        fade_out: Some(0.35),
15957        ..Default::default()
15958    };
15959
15960    let mut prev_end = label.filter_range.end;
15961    label
15962        .runs
15963        .iter()
15964        .enumerate()
15965        .flat_map(move |(ix, (range, highlight_id))| {
15966            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15967                style
15968            } else {
15969                return Default::default();
15970            };
15971            let mut muted_style = style;
15972            muted_style.highlight(fade_out);
15973
15974            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15975            if range.start >= label.filter_range.end {
15976                if range.start > prev_end {
15977                    runs.push((prev_end..range.start, fade_out));
15978                }
15979                runs.push((range.clone(), muted_style));
15980            } else if range.end <= label.filter_range.end {
15981                runs.push((range.clone(), style));
15982            } else {
15983                runs.push((range.start..label.filter_range.end, style));
15984                runs.push((label.filter_range.end..range.end, muted_style));
15985            }
15986            prev_end = cmp::max(prev_end, range.end);
15987
15988            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15989                runs.push((prev_end..label.text.len(), fade_out));
15990            }
15991
15992            runs
15993        })
15994}
15995
15996pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15997    let mut prev_index = 0;
15998    let mut prev_codepoint: Option<char> = None;
15999    text.char_indices()
16000        .chain([(text.len(), '\0')])
16001        .filter_map(move |(index, codepoint)| {
16002            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16003            let is_boundary = index == text.len()
16004                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16005                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16006            if is_boundary {
16007                let chunk = &text[prev_index..index];
16008                prev_index = index;
16009                Some(chunk)
16010            } else {
16011                None
16012            }
16013        })
16014}
16015
16016pub trait RangeToAnchorExt: Sized {
16017    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16018
16019    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16020        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16021        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16022    }
16023}
16024
16025impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16026    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16027        let start_offset = self.start.to_offset(snapshot);
16028        let end_offset = self.end.to_offset(snapshot);
16029        if start_offset == end_offset {
16030            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16031        } else {
16032            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16033        }
16034    }
16035}
16036
16037pub trait RowExt {
16038    fn as_f32(&self) -> f32;
16039
16040    fn next_row(&self) -> Self;
16041
16042    fn previous_row(&self) -> Self;
16043
16044    fn minus(&self, other: Self) -> u32;
16045}
16046
16047impl RowExt for DisplayRow {
16048    fn as_f32(&self) -> f32 {
16049        self.0 as f32
16050    }
16051
16052    fn next_row(&self) -> Self {
16053        Self(self.0 + 1)
16054    }
16055
16056    fn previous_row(&self) -> Self {
16057        Self(self.0.saturating_sub(1))
16058    }
16059
16060    fn minus(&self, other: Self) -> u32 {
16061        self.0 - other.0
16062    }
16063}
16064
16065impl RowExt for MultiBufferRow {
16066    fn as_f32(&self) -> f32 {
16067        self.0 as f32
16068    }
16069
16070    fn next_row(&self) -> Self {
16071        Self(self.0 + 1)
16072    }
16073
16074    fn previous_row(&self) -> Self {
16075        Self(self.0.saturating_sub(1))
16076    }
16077
16078    fn minus(&self, other: Self) -> u32 {
16079        self.0 - other.0
16080    }
16081}
16082
16083trait RowRangeExt {
16084    type Row;
16085
16086    fn len(&self) -> usize;
16087
16088    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16089}
16090
16091impl RowRangeExt for Range<MultiBufferRow> {
16092    type Row = MultiBufferRow;
16093
16094    fn len(&self) -> usize {
16095        (self.end.0 - self.start.0) as usize
16096    }
16097
16098    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16099        (self.start.0..self.end.0).map(MultiBufferRow)
16100    }
16101}
16102
16103impl RowRangeExt for Range<DisplayRow> {
16104    type Row = DisplayRow;
16105
16106    fn len(&self) -> usize {
16107        (self.end.0 - self.start.0) as usize
16108    }
16109
16110    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16111        (self.start.0..self.end.0).map(DisplayRow)
16112    }
16113}
16114
16115/// If select range has more than one line, we
16116/// just point the cursor to range.start.
16117fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16118    if range.start.row == range.end.row {
16119        range
16120    } else {
16121        range.start..range.start
16122    }
16123}
16124pub struct KillRing(ClipboardItem);
16125impl Global for KillRing {}
16126
16127const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16128
16129fn all_edits_insertions_or_deletions(
16130    edits: &Vec<(Range<Anchor>, String)>,
16131    snapshot: &MultiBufferSnapshot,
16132) -> bool {
16133    let mut all_insertions = true;
16134    let mut all_deletions = true;
16135
16136    for (range, new_text) in edits.iter() {
16137        let range_is_empty = range.to_offset(&snapshot).is_empty();
16138        let text_is_empty = new_text.is_empty();
16139
16140        if range_is_empty != text_is_empty {
16141            if range_is_empty {
16142                all_deletions = false;
16143            } else {
16144                all_insertions = false;
16145            }
16146        } else {
16147            return false;
16148        }
16149
16150        if !all_insertions && !all_deletions {
16151            return false;
16152        }
16153    }
16154    all_insertions || all_deletions
16155}