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                    cx.activate(true);
  336                    Editor::new_file(workspace, &Default::default(), window, cx)
  337                },
  338            )
  339            .detach();
  340        }
  341    });
  342    git::project_diff::init(cx);
  343}
  344
  345pub struct SearchWithinRange;
  346
  347trait InvalidationRegion {
  348    fn ranges(&self) -> &[Range<Anchor>];
  349}
  350
  351#[derive(Clone, Debug, PartialEq)]
  352pub enum SelectPhase {
  353    Begin {
  354        position: DisplayPoint,
  355        add: bool,
  356        click_count: usize,
  357    },
  358    BeginColumnar {
  359        position: DisplayPoint,
  360        reset: bool,
  361        goal_column: u32,
  362    },
  363    Extend {
  364        position: DisplayPoint,
  365        click_count: usize,
  366    },
  367    Update {
  368        position: DisplayPoint,
  369        goal_column: u32,
  370        scroll_delta: gpui::Point<f32>,
  371    },
  372    End,
  373}
  374
  375#[derive(Clone, Debug)]
  376pub enum SelectMode {
  377    Character,
  378    Word(Range<Anchor>),
  379    Line(Range<Anchor>),
  380    All,
  381}
  382
  383#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  384pub enum EditorMode {
  385    SingleLine { auto_width: bool },
  386    AutoHeight { max_lines: usize },
  387    Full,
  388}
  389
  390#[derive(Copy, Clone, Debug)]
  391pub enum SoftWrap {
  392    /// Prefer not to wrap at all.
  393    ///
  394    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  395    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  396    GitDiff,
  397    /// Prefer a single line generally, unless an overly long line is encountered.
  398    None,
  399    /// Soft wrap lines that exceed the editor width.
  400    EditorWidth,
  401    /// Soft wrap lines at the preferred line length.
  402    Column(u32),
  403    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  404    Bounded(u32),
  405}
  406
  407#[derive(Clone)]
  408pub struct EditorStyle {
  409    pub background: Hsla,
  410    pub local_player: PlayerColor,
  411    pub text: TextStyle,
  412    pub scrollbar_width: Pixels,
  413    pub syntax: Arc<SyntaxTheme>,
  414    pub status: StatusColors,
  415    pub inlay_hints_style: HighlightStyle,
  416    pub inline_completion_styles: InlineCompletionStyles,
  417    pub unnecessary_code_fade: f32,
  418}
  419
  420impl Default for EditorStyle {
  421    fn default() -> Self {
  422        Self {
  423            background: Hsla::default(),
  424            local_player: PlayerColor::default(),
  425            text: TextStyle::default(),
  426            scrollbar_width: Pixels::default(),
  427            syntax: Default::default(),
  428            // HACK: Status colors don't have a real default.
  429            // We should look into removing the status colors from the editor
  430            // style and retrieve them directly from the theme.
  431            status: StatusColors::dark(),
  432            inlay_hints_style: HighlightStyle::default(),
  433            inline_completion_styles: InlineCompletionStyles {
  434                insertion: HighlightStyle::default(),
  435                whitespace: HighlightStyle::default(),
  436            },
  437            unnecessary_code_fade: Default::default(),
  438        }
  439    }
  440}
  441
  442pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  443    let show_background = language_settings::language_settings(None, None, cx)
  444        .inlay_hints
  445        .show_background;
  446
  447    HighlightStyle {
  448        color: Some(cx.theme().status().hint),
  449        background_color: show_background.then(|| cx.theme().status().hint_background),
  450        ..HighlightStyle::default()
  451    }
  452}
  453
  454pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  455    InlineCompletionStyles {
  456        insertion: HighlightStyle {
  457            color: Some(cx.theme().status().predictive),
  458            ..HighlightStyle::default()
  459        },
  460        whitespace: HighlightStyle {
  461            background_color: Some(cx.theme().status().created_background),
  462            ..HighlightStyle::default()
  463        },
  464    }
  465}
  466
  467type CompletionId = usize;
  468
  469#[derive(Debug, Clone)]
  470enum InlineCompletionMenuHint {
  471    Loading,
  472    Loaded { text: InlineCompletionText },
  473    PendingTermsAcceptance,
  474    None,
  475}
  476
  477impl InlineCompletionMenuHint {
  478    pub fn label(&self) -> &'static str {
  479        match self {
  480            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  481                "Edit Prediction"
  482            }
  483            InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
  484            InlineCompletionMenuHint::None => "No Prediction",
  485        }
  486    }
  487}
  488
  489#[derive(Clone, Debug)]
  490enum InlineCompletionText {
  491    Move(SharedString),
  492    Edit(HighlightedText),
  493}
  494
  495pub(crate) enum EditDisplayMode {
  496    TabAccept,
  497    DiffPopover,
  498    Inline,
  499}
  500
  501enum InlineCompletion {
  502    Edit {
  503        edits: Vec<(Range<Anchor>, String)>,
  504        edit_preview: Option<EditPreview>,
  505        display_mode: EditDisplayMode,
  506        snapshot: BufferSnapshot,
  507    },
  508    Move(Anchor),
  509}
  510
  511struct InlineCompletionState {
  512    inlay_ids: Vec<InlayId>,
  513    completion: InlineCompletion,
  514    invalidation_range: Range<Anchor>,
  515}
  516
  517enum InlineCompletionHighlight {}
  518
  519pub enum MenuInlineCompletionsPolicy {
  520    Never,
  521    ByProvider,
  522}
  523
  524#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  525struct EditorActionId(usize);
  526
  527impl EditorActionId {
  528    pub fn post_inc(&mut self) -> Self {
  529        let answer = self.0;
  530
  531        *self = Self(answer + 1);
  532
  533        Self(answer)
  534    }
  535}
  536
  537// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  538// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  539
  540type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  541type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  542
  543#[derive(Default)]
  544struct ScrollbarMarkerState {
  545    scrollbar_size: Size<Pixels>,
  546    dirty: bool,
  547    markers: Arc<[PaintQuad]>,
  548    pending_refresh: Option<Task<Result<()>>>,
  549}
  550
  551impl ScrollbarMarkerState {
  552    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  553        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  554    }
  555}
  556
  557#[derive(Clone, Debug)]
  558struct RunnableTasks {
  559    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  560    offset: MultiBufferOffset,
  561    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  562    column: u32,
  563    // Values of all named captures, including those starting with '_'
  564    extra_variables: HashMap<String, String>,
  565    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  566    context_range: Range<BufferOffset>,
  567}
  568
  569impl RunnableTasks {
  570    fn resolve<'a>(
  571        &'a self,
  572        cx: &'a task::TaskContext,
  573    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  574        self.templates.iter().filter_map(|(kind, template)| {
  575            template
  576                .resolve_task(&kind.to_id_base(), cx)
  577                .map(|task| (kind.clone(), task))
  578        })
  579    }
  580}
  581
  582#[derive(Clone)]
  583struct ResolvedTasks {
  584    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  585    position: Anchor,
  586}
  587#[derive(Copy, Clone, Debug)]
  588struct MultiBufferOffset(usize);
  589#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  590struct BufferOffset(usize);
  591
  592// Addons allow storing per-editor state in other crates (e.g. Vim)
  593pub trait Addon: 'static {
  594    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  595
  596    fn to_any(&self) -> &dyn std::any::Any;
  597}
  598
  599#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  600pub enum IsVimMode {
  601    Yes,
  602    No,
  603}
  604
  605/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  606///
  607/// See the [module level documentation](self) for more information.
  608pub struct Editor {
  609    focus_handle: FocusHandle,
  610    last_focused_descendant: Option<WeakFocusHandle>,
  611    /// The text buffer being edited
  612    buffer: Entity<MultiBuffer>,
  613    /// Map of how text in the buffer should be displayed.
  614    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  615    pub display_map: Entity<DisplayMap>,
  616    pub selections: SelectionsCollection,
  617    pub scroll_manager: ScrollManager,
  618    /// When inline assist editors are linked, they all render cursors because
  619    /// typing enters text into each of them, even the ones that aren't focused.
  620    pub(crate) show_cursor_when_unfocused: bool,
  621    columnar_selection_tail: Option<Anchor>,
  622    add_selections_state: Option<AddSelectionsState>,
  623    select_next_state: Option<SelectNextState>,
  624    select_prev_state: Option<SelectNextState>,
  625    selection_history: SelectionHistory,
  626    autoclose_regions: Vec<AutocloseRegion>,
  627    snippet_stack: InvalidationStack<SnippetState>,
  628    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  629    ime_transaction: Option<TransactionId>,
  630    active_diagnostics: Option<ActiveDiagnosticGroup>,
  631    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  632
  633    project: Option<Entity<Project>>,
  634    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  635    completion_provider: Option<Box<dyn CompletionProvider>>,
  636    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  637    blink_manager: Entity<BlinkManager>,
  638    show_cursor_names: bool,
  639    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  640    pub show_local_selections: bool,
  641    mode: EditorMode,
  642    show_breadcrumbs: bool,
  643    show_gutter: bool,
  644    show_scrollbars: bool,
  645    show_line_numbers: Option<bool>,
  646    use_relative_line_numbers: Option<bool>,
  647    show_git_diff_gutter: Option<bool>,
  648    show_code_actions: Option<bool>,
  649    show_runnables: Option<bool>,
  650    show_wrap_guides: Option<bool>,
  651    show_indent_guides: Option<bool>,
  652    placeholder_text: Option<Arc<str>>,
  653    highlight_order: usize,
  654    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  655    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  656    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  657    scrollbar_marker_state: ScrollbarMarkerState,
  658    active_indent_guides_state: ActiveIndentGuidesState,
  659    nav_history: Option<ItemNavHistory>,
  660    context_menu: RefCell<Option<CodeContextMenu>>,
  661    mouse_context_menu: Option<MouseContextMenu>,
  662    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  663    signature_help_state: SignatureHelpState,
  664    auto_signature_help: Option<bool>,
  665    find_all_references_task_sources: Vec<Anchor>,
  666    next_completion_id: CompletionId,
  667    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  668    code_actions_task: Option<Task<Result<()>>>,
  669    document_highlights_task: Option<Task<()>>,
  670    linked_editing_range_task: Option<Task<Option<()>>>,
  671    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  672    pending_rename: Option<RenameState>,
  673    searchable: bool,
  674    cursor_shape: CursorShape,
  675    current_line_highlight: Option<CurrentLineHighlight>,
  676    collapse_matches: bool,
  677    autoindent_mode: Option<AutoindentMode>,
  678    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  679    input_enabled: bool,
  680    use_modal_editing: bool,
  681    read_only: bool,
  682    leader_peer_id: Option<PeerId>,
  683    remote_id: Option<ViewId>,
  684    hover_state: HoverState,
  685    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  686    gutter_hovered: bool,
  687    hovered_link_state: Option<HoveredLinkState>,
  688    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  689    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  690    active_inline_completion: Option<InlineCompletionState>,
  691    // enable_inline_completions is a switch that Vim can use to disable
  692    // inline completions based on its mode.
  693    enable_inline_completions: bool,
  694    show_inline_completions_override: Option<bool>,
  695    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  696    inlay_hint_cache: InlayHintCache,
  697    next_inlay_id: usize,
  698    _subscriptions: Vec<Subscription>,
  699    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  700    gutter_dimensions: GutterDimensions,
  701    style: Option<EditorStyle>,
  702    text_style_refinement: Option<TextStyleRefinement>,
  703    next_editor_action_id: EditorActionId,
  704    editor_actions:
  705        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  706    use_autoclose: bool,
  707    use_auto_surround: bool,
  708    auto_replace_emoji_shortcode: bool,
  709    show_git_blame_gutter: bool,
  710    show_git_blame_inline: bool,
  711    show_git_blame_inline_delay_task: Option<Task<()>>,
  712    git_blame_inline_enabled: bool,
  713    serialize_dirty_buffers: bool,
  714    show_selection_menu: Option<bool>,
  715    blame: Option<Entity<GitBlame>>,
  716    blame_subscription: Option<Subscription>,
  717    custom_context_menu: Option<
  718        Box<
  719            dyn 'static
  720                + Fn(
  721                    &mut Self,
  722                    DisplayPoint,
  723                    &mut Window,
  724                    &mut Context<Self>,
  725                ) -> Option<Entity<ui::ContextMenu>>,
  726        >,
  727    >,
  728    last_bounds: Option<Bounds<Pixels>>,
  729    expect_bounds_change: Option<Bounds<Pixels>>,
  730    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  731    tasks_update_task: Option<Task<()>>,
  732    in_project_search: bool,
  733    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  734    breadcrumb_header: Option<String>,
  735    focused_block: Option<FocusedBlock>,
  736    next_scroll_position: NextScrollCursorCenterTopBottom,
  737    addons: HashMap<TypeId, Box<dyn Addon>>,
  738    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  739    selection_mark_mode: bool,
  740    toggle_fold_multiple_buffers: Task<()>,
  741    _scroll_cursor_center_top_bottom_task: Task<()>,
  742}
  743
  744#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  745enum NextScrollCursorCenterTopBottom {
  746    #[default]
  747    Center,
  748    Top,
  749    Bottom,
  750}
  751
  752impl NextScrollCursorCenterTopBottom {
  753    fn next(&self) -> Self {
  754        match self {
  755            Self::Center => Self::Top,
  756            Self::Top => Self::Bottom,
  757            Self::Bottom => Self::Center,
  758        }
  759    }
  760}
  761
  762#[derive(Clone)]
  763pub struct EditorSnapshot {
  764    pub mode: EditorMode,
  765    show_gutter: bool,
  766    show_line_numbers: Option<bool>,
  767    show_git_diff_gutter: Option<bool>,
  768    show_code_actions: Option<bool>,
  769    show_runnables: Option<bool>,
  770    git_blame_gutter_max_author_length: Option<usize>,
  771    pub display_snapshot: DisplaySnapshot,
  772    pub placeholder_text: Option<Arc<str>>,
  773    is_focused: bool,
  774    scroll_anchor: ScrollAnchor,
  775    ongoing_scroll: OngoingScroll,
  776    current_line_highlight: CurrentLineHighlight,
  777    gutter_hovered: bool,
  778}
  779
  780const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  781
  782#[derive(Default, Debug, Clone, Copy)]
  783pub struct GutterDimensions {
  784    pub left_padding: Pixels,
  785    pub right_padding: Pixels,
  786    pub width: Pixels,
  787    pub margin: Pixels,
  788    pub git_blame_entries_width: Option<Pixels>,
  789}
  790
  791impl GutterDimensions {
  792    /// The full width of the space taken up by the gutter.
  793    pub fn full_width(&self) -> Pixels {
  794        self.margin + self.width
  795    }
  796
  797    /// The width of the space reserved for the fold indicators,
  798    /// use alongside 'justify_end' and `gutter_width` to
  799    /// right align content with the line numbers
  800    pub fn fold_area_width(&self) -> Pixels {
  801        self.margin + self.right_padding
  802    }
  803}
  804
  805#[derive(Debug)]
  806pub struct RemoteSelection {
  807    pub replica_id: ReplicaId,
  808    pub selection: Selection<Anchor>,
  809    pub cursor_shape: CursorShape,
  810    pub peer_id: PeerId,
  811    pub line_mode: bool,
  812    pub participant_index: Option<ParticipantIndex>,
  813    pub user_name: Option<SharedString>,
  814}
  815
  816#[derive(Clone, Debug)]
  817struct SelectionHistoryEntry {
  818    selections: Arc<[Selection<Anchor>]>,
  819    select_next_state: Option<SelectNextState>,
  820    select_prev_state: Option<SelectNextState>,
  821    add_selections_state: Option<AddSelectionsState>,
  822}
  823
  824enum SelectionHistoryMode {
  825    Normal,
  826    Undoing,
  827    Redoing,
  828}
  829
  830#[derive(Clone, PartialEq, Eq, Hash)]
  831struct HoveredCursor {
  832    replica_id: u16,
  833    selection_id: usize,
  834}
  835
  836impl Default for SelectionHistoryMode {
  837    fn default() -> Self {
  838        Self::Normal
  839    }
  840}
  841
  842#[derive(Default)]
  843struct SelectionHistory {
  844    #[allow(clippy::type_complexity)]
  845    selections_by_transaction:
  846        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  847    mode: SelectionHistoryMode,
  848    undo_stack: VecDeque<SelectionHistoryEntry>,
  849    redo_stack: VecDeque<SelectionHistoryEntry>,
  850}
  851
  852impl SelectionHistory {
  853    fn insert_transaction(
  854        &mut self,
  855        transaction_id: TransactionId,
  856        selections: Arc<[Selection<Anchor>]>,
  857    ) {
  858        self.selections_by_transaction
  859            .insert(transaction_id, (selections, None));
  860    }
  861
  862    #[allow(clippy::type_complexity)]
  863    fn transaction(
  864        &self,
  865        transaction_id: TransactionId,
  866    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  867        self.selections_by_transaction.get(&transaction_id)
  868    }
  869
  870    #[allow(clippy::type_complexity)]
  871    fn transaction_mut(
  872        &mut self,
  873        transaction_id: TransactionId,
  874    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  875        self.selections_by_transaction.get_mut(&transaction_id)
  876    }
  877
  878    fn push(&mut self, entry: SelectionHistoryEntry) {
  879        if !entry.selections.is_empty() {
  880            match self.mode {
  881                SelectionHistoryMode::Normal => {
  882                    self.push_undo(entry);
  883                    self.redo_stack.clear();
  884                }
  885                SelectionHistoryMode::Undoing => self.push_redo(entry),
  886                SelectionHistoryMode::Redoing => self.push_undo(entry),
  887            }
  888        }
  889    }
  890
  891    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  892        if self
  893            .undo_stack
  894            .back()
  895            .map_or(true, |e| e.selections != entry.selections)
  896        {
  897            self.undo_stack.push_back(entry);
  898            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  899                self.undo_stack.pop_front();
  900            }
  901        }
  902    }
  903
  904    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  905        if self
  906            .redo_stack
  907            .back()
  908            .map_or(true, |e| e.selections != entry.selections)
  909        {
  910            self.redo_stack.push_back(entry);
  911            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  912                self.redo_stack.pop_front();
  913            }
  914        }
  915    }
  916}
  917
  918struct RowHighlight {
  919    index: usize,
  920    range: Range<Anchor>,
  921    color: Hsla,
  922    should_autoscroll: bool,
  923}
  924
  925#[derive(Clone, Debug)]
  926struct AddSelectionsState {
  927    above: bool,
  928    stack: Vec<usize>,
  929}
  930
  931#[derive(Clone)]
  932struct SelectNextState {
  933    query: AhoCorasick,
  934    wordwise: bool,
  935    done: bool,
  936}
  937
  938impl std::fmt::Debug for SelectNextState {
  939    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  940        f.debug_struct(std::any::type_name::<Self>())
  941            .field("wordwise", &self.wordwise)
  942            .field("done", &self.done)
  943            .finish()
  944    }
  945}
  946
  947#[derive(Debug)]
  948struct AutocloseRegion {
  949    selection_id: usize,
  950    range: Range<Anchor>,
  951    pair: BracketPair,
  952}
  953
  954#[derive(Debug)]
  955struct SnippetState {
  956    ranges: Vec<Vec<Range<Anchor>>>,
  957    active_index: usize,
  958    choices: Vec<Option<Vec<String>>>,
  959}
  960
  961#[doc(hidden)]
  962pub struct RenameState {
  963    pub range: Range<Anchor>,
  964    pub old_name: Arc<str>,
  965    pub editor: Entity<Editor>,
  966    block_id: CustomBlockId,
  967}
  968
  969struct InvalidationStack<T>(Vec<T>);
  970
  971struct RegisteredInlineCompletionProvider {
  972    provider: Arc<dyn InlineCompletionProviderHandle>,
  973    _subscription: Subscription,
  974}
  975
  976#[derive(Debug)]
  977struct ActiveDiagnosticGroup {
  978    primary_range: Range<Anchor>,
  979    primary_message: String,
  980    group_id: usize,
  981    blocks: HashMap<CustomBlockId, Diagnostic>,
  982    is_valid: bool,
  983}
  984
  985#[derive(Serialize, Deserialize, Clone, Debug)]
  986pub struct ClipboardSelection {
  987    pub len: usize,
  988    pub is_entire_line: bool,
  989    pub first_line_indent: u32,
  990}
  991
  992#[derive(Debug)]
  993pub(crate) struct NavigationData {
  994    cursor_anchor: Anchor,
  995    cursor_position: Point,
  996    scroll_anchor: ScrollAnchor,
  997    scroll_top_row: u32,
  998}
  999
 1000#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1001pub enum GotoDefinitionKind {
 1002    Symbol,
 1003    Declaration,
 1004    Type,
 1005    Implementation,
 1006}
 1007
 1008#[derive(Debug, Clone)]
 1009enum InlayHintRefreshReason {
 1010    Toggle(bool),
 1011    SettingsChange(InlayHintSettings),
 1012    NewLinesShown,
 1013    BufferEdited(HashSet<Arc<Language>>),
 1014    RefreshRequested,
 1015    ExcerptsRemoved(Vec<ExcerptId>),
 1016}
 1017
 1018impl InlayHintRefreshReason {
 1019    fn description(&self) -> &'static str {
 1020        match self {
 1021            Self::Toggle(_) => "toggle",
 1022            Self::SettingsChange(_) => "settings change",
 1023            Self::NewLinesShown => "new lines shown",
 1024            Self::BufferEdited(_) => "buffer edited",
 1025            Self::RefreshRequested => "refresh requested",
 1026            Self::ExcerptsRemoved(_) => "excerpts removed",
 1027        }
 1028    }
 1029}
 1030
 1031pub enum FormatTarget {
 1032    Buffers,
 1033    Ranges(Vec<Range<MultiBufferPoint>>),
 1034}
 1035
 1036pub(crate) struct FocusedBlock {
 1037    id: BlockId,
 1038    focus_handle: WeakFocusHandle,
 1039}
 1040
 1041#[derive(Clone)]
 1042enum JumpData {
 1043    MultiBufferRow {
 1044        row: MultiBufferRow,
 1045        line_offset_from_top: u32,
 1046    },
 1047    MultiBufferPoint {
 1048        excerpt_id: ExcerptId,
 1049        position: Point,
 1050        anchor: text::Anchor,
 1051        line_offset_from_top: u32,
 1052    },
 1053}
 1054
 1055pub enum MultibufferSelectionMode {
 1056    First,
 1057    All,
 1058}
 1059
 1060impl Editor {
 1061    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1062        let buffer = cx.new(|cx| Buffer::local("", cx));
 1063        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1064        Self::new(
 1065            EditorMode::SingleLine { auto_width: false },
 1066            buffer,
 1067            None,
 1068            false,
 1069            window,
 1070            cx,
 1071        )
 1072    }
 1073
 1074    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1075        let buffer = cx.new(|cx| Buffer::local("", cx));
 1076        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1077        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1078    }
 1079
 1080    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1081        let buffer = cx.new(|cx| Buffer::local("", cx));
 1082        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1083        Self::new(
 1084            EditorMode::SingleLine { auto_width: true },
 1085            buffer,
 1086            None,
 1087            false,
 1088            window,
 1089            cx,
 1090        )
 1091    }
 1092
 1093    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1094        let buffer = cx.new(|cx| Buffer::local("", cx));
 1095        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1096        Self::new(
 1097            EditorMode::AutoHeight { max_lines },
 1098            buffer,
 1099            None,
 1100            false,
 1101            window,
 1102            cx,
 1103        )
 1104    }
 1105
 1106    pub fn for_buffer(
 1107        buffer: Entity<Buffer>,
 1108        project: Option<Entity<Project>>,
 1109        window: &mut Window,
 1110        cx: &mut Context<Self>,
 1111    ) -> Self {
 1112        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1113        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1114    }
 1115
 1116    pub fn for_multibuffer(
 1117        buffer: Entity<MultiBuffer>,
 1118        project: Option<Entity<Project>>,
 1119        show_excerpt_controls: bool,
 1120        window: &mut Window,
 1121        cx: &mut Context<Self>,
 1122    ) -> Self {
 1123        Self::new(
 1124            EditorMode::Full,
 1125            buffer,
 1126            project,
 1127            show_excerpt_controls,
 1128            window,
 1129            cx,
 1130        )
 1131    }
 1132
 1133    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1134        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1135        let mut clone = Self::new(
 1136            self.mode,
 1137            self.buffer.clone(),
 1138            self.project.clone(),
 1139            show_excerpt_controls,
 1140            window,
 1141            cx,
 1142        );
 1143        self.display_map.update(cx, |display_map, cx| {
 1144            let snapshot = display_map.snapshot(cx);
 1145            clone.display_map.update(cx, |display_map, cx| {
 1146                display_map.set_state(&snapshot, cx);
 1147            });
 1148        });
 1149        clone.selections.clone_state(&self.selections);
 1150        clone.scroll_manager.clone_state(&self.scroll_manager);
 1151        clone.searchable = self.searchable;
 1152        clone
 1153    }
 1154
 1155    pub fn new(
 1156        mode: EditorMode,
 1157        buffer: Entity<MultiBuffer>,
 1158        project: Option<Entity<Project>>,
 1159        show_excerpt_controls: bool,
 1160        window: &mut Window,
 1161        cx: &mut Context<Self>,
 1162    ) -> Self {
 1163        let style = window.text_style();
 1164        let font_size = style.font_size.to_pixels(window.rem_size());
 1165        let editor = cx.entity().downgrade();
 1166        let fold_placeholder = FoldPlaceholder {
 1167            constrain_width: true,
 1168            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1169                let editor = editor.clone();
 1170                div()
 1171                    .id(fold_id)
 1172                    .bg(cx.theme().colors().ghost_element_background)
 1173                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1174                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1175                    .rounded_sm()
 1176                    .size_full()
 1177                    .cursor_pointer()
 1178                    .child("")
 1179                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1180                    .on_click(move |_, _window, cx| {
 1181                        editor
 1182                            .update(cx, |editor, cx| {
 1183                                editor.unfold_ranges(
 1184                                    &[fold_range.start..fold_range.end],
 1185                                    true,
 1186                                    false,
 1187                                    cx,
 1188                                );
 1189                                cx.stop_propagation();
 1190                            })
 1191                            .ok();
 1192                    })
 1193                    .into_any()
 1194            }),
 1195            merge_adjacent: true,
 1196            ..Default::default()
 1197        };
 1198        let display_map = cx.new(|cx| {
 1199            DisplayMap::new(
 1200                buffer.clone(),
 1201                style.font(),
 1202                font_size,
 1203                None,
 1204                show_excerpt_controls,
 1205                FILE_HEADER_HEIGHT,
 1206                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1207                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1208                fold_placeholder,
 1209                cx,
 1210            )
 1211        });
 1212
 1213        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1214
 1215        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1216
 1217        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1218            .then(|| language_settings::SoftWrap::None);
 1219
 1220        let mut project_subscriptions = Vec::new();
 1221        if mode == EditorMode::Full {
 1222            if let Some(project) = project.as_ref() {
 1223                if buffer.read(cx).is_singleton() {
 1224                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1225                        cx.emit(EditorEvent::TitleChanged);
 1226                    }));
 1227                }
 1228                project_subscriptions.push(cx.subscribe_in(
 1229                    project,
 1230                    window,
 1231                    |editor, _, event, window, cx| {
 1232                        if let project::Event::RefreshInlayHints = event {
 1233                            editor
 1234                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1235                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1236                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1237                                let focus_handle = editor.focus_handle(cx);
 1238                                if focus_handle.is_focused(window) {
 1239                                    let snapshot = buffer.read(cx).snapshot();
 1240                                    for (range, snippet) in snippet_edits {
 1241                                        let editor_range =
 1242                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1243                                        editor
 1244                                            .insert_snippet(
 1245                                                &[editor_range],
 1246                                                snippet.clone(),
 1247                                                window,
 1248                                                cx,
 1249                                            )
 1250                                            .ok();
 1251                                    }
 1252                                }
 1253                            }
 1254                        }
 1255                    },
 1256                ));
 1257                if let Some(task_inventory) = project
 1258                    .read(cx)
 1259                    .task_store()
 1260                    .read(cx)
 1261                    .task_inventory()
 1262                    .cloned()
 1263                {
 1264                    project_subscriptions.push(cx.observe_in(
 1265                        &task_inventory,
 1266                        window,
 1267                        |editor, _, window, cx| {
 1268                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1269                        },
 1270                    ));
 1271                }
 1272            }
 1273        }
 1274
 1275        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1276
 1277        let inlay_hint_settings =
 1278            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1279        let focus_handle = cx.focus_handle();
 1280        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1281            .detach();
 1282        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1283            .detach();
 1284        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1285            .detach();
 1286        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1287            .detach();
 1288
 1289        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1290            Some(false)
 1291        } else {
 1292            None
 1293        };
 1294
 1295        let mut code_action_providers = Vec::new();
 1296        if let Some(project) = project.clone() {
 1297            get_unstaged_changes_for_buffers(
 1298                &project,
 1299                buffer.read(cx).all_buffers(),
 1300                buffer.clone(),
 1301                cx,
 1302            );
 1303            code_action_providers.push(Rc::new(project) as Rc<_>);
 1304        }
 1305
 1306        let mut this = Self {
 1307            focus_handle,
 1308            show_cursor_when_unfocused: false,
 1309            last_focused_descendant: None,
 1310            buffer: buffer.clone(),
 1311            display_map: display_map.clone(),
 1312            selections,
 1313            scroll_manager: ScrollManager::new(cx),
 1314            columnar_selection_tail: None,
 1315            add_selections_state: None,
 1316            select_next_state: None,
 1317            select_prev_state: None,
 1318            selection_history: Default::default(),
 1319            autoclose_regions: Default::default(),
 1320            snippet_stack: Default::default(),
 1321            select_larger_syntax_node_stack: Vec::new(),
 1322            ime_transaction: Default::default(),
 1323            active_diagnostics: None,
 1324            soft_wrap_mode_override,
 1325            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1326            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1327            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1328            project,
 1329            blink_manager: blink_manager.clone(),
 1330            show_local_selections: true,
 1331            show_scrollbars: true,
 1332            mode,
 1333            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1334            show_gutter: mode == EditorMode::Full,
 1335            show_line_numbers: None,
 1336            use_relative_line_numbers: None,
 1337            show_git_diff_gutter: None,
 1338            show_code_actions: None,
 1339            show_runnables: None,
 1340            show_wrap_guides: None,
 1341            show_indent_guides,
 1342            placeholder_text: None,
 1343            highlight_order: 0,
 1344            highlighted_rows: HashMap::default(),
 1345            background_highlights: Default::default(),
 1346            gutter_highlights: TreeMap::default(),
 1347            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1348            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1349            nav_history: None,
 1350            context_menu: RefCell::new(None),
 1351            mouse_context_menu: None,
 1352            completion_tasks: Default::default(),
 1353            signature_help_state: SignatureHelpState::default(),
 1354            auto_signature_help: None,
 1355            find_all_references_task_sources: Vec::new(),
 1356            next_completion_id: 0,
 1357            next_inlay_id: 0,
 1358            code_action_providers,
 1359            available_code_actions: Default::default(),
 1360            code_actions_task: Default::default(),
 1361            document_highlights_task: Default::default(),
 1362            linked_editing_range_task: Default::default(),
 1363            pending_rename: Default::default(),
 1364            searchable: true,
 1365            cursor_shape: EditorSettings::get_global(cx)
 1366                .cursor_shape
 1367                .unwrap_or_default(),
 1368            current_line_highlight: None,
 1369            autoindent_mode: Some(AutoindentMode::EachLine),
 1370            collapse_matches: false,
 1371            workspace: None,
 1372            input_enabled: true,
 1373            use_modal_editing: mode == EditorMode::Full,
 1374            read_only: false,
 1375            use_autoclose: true,
 1376            use_auto_surround: true,
 1377            auto_replace_emoji_shortcode: false,
 1378            leader_peer_id: None,
 1379            remote_id: None,
 1380            hover_state: Default::default(),
 1381            pending_mouse_down: None,
 1382            hovered_link_state: Default::default(),
 1383            inline_completion_provider: None,
 1384            active_inline_completion: None,
 1385            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1386
 1387            gutter_hovered: false,
 1388            pixel_position_of_newest_cursor: None,
 1389            last_bounds: None,
 1390            expect_bounds_change: None,
 1391            gutter_dimensions: GutterDimensions::default(),
 1392            style: None,
 1393            show_cursor_names: false,
 1394            hovered_cursors: Default::default(),
 1395            next_editor_action_id: EditorActionId::default(),
 1396            editor_actions: Rc::default(),
 1397            show_inline_completions_override: None,
 1398            enable_inline_completions: true,
 1399            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1400            custom_context_menu: None,
 1401            show_git_blame_gutter: false,
 1402            show_git_blame_inline: false,
 1403            show_selection_menu: None,
 1404            show_git_blame_inline_delay_task: None,
 1405            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1406            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1407                .session
 1408                .restore_unsaved_buffers,
 1409            blame: None,
 1410            blame_subscription: None,
 1411            tasks: Default::default(),
 1412            _subscriptions: vec![
 1413                cx.observe(&buffer, Self::on_buffer_changed),
 1414                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1415                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1416                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1417                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1418                cx.observe_window_activation(window, |editor, window, cx| {
 1419                    let active = window.is_window_active();
 1420                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1421                        if active {
 1422                            blink_manager.enable(cx);
 1423                        } else {
 1424                            blink_manager.disable(cx);
 1425                        }
 1426                    });
 1427                }),
 1428            ],
 1429            tasks_update_task: None,
 1430            linked_edit_ranges: Default::default(),
 1431            in_project_search: false,
 1432            previous_search_ranges: None,
 1433            breadcrumb_header: None,
 1434            focused_block: None,
 1435            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1436            addons: HashMap::default(),
 1437            registered_buffers: HashMap::default(),
 1438            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1439            selection_mark_mode: false,
 1440            toggle_fold_multiple_buffers: Task::ready(()),
 1441            text_style_refinement: None,
 1442        };
 1443        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1444        this._subscriptions.extend(project_subscriptions);
 1445
 1446        this.end_selection(window, cx);
 1447        this.scroll_manager.show_scrollbar(window, cx);
 1448
 1449        if mode == EditorMode::Full {
 1450            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1451            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1452
 1453            if this.git_blame_inline_enabled {
 1454                this.git_blame_inline_enabled = true;
 1455                this.start_git_blame_inline(false, window, cx);
 1456            }
 1457
 1458            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1459                if let Some(project) = this.project.as_ref() {
 1460                    let lsp_store = project.read(cx).lsp_store();
 1461                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1462                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1463                    });
 1464                    this.registered_buffers
 1465                        .insert(buffer.read(cx).remote_id(), handle);
 1466                }
 1467            }
 1468        }
 1469
 1470        this.report_editor_event("Editor Opened", None, cx);
 1471        this
 1472    }
 1473
 1474    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1475        self.mouse_context_menu
 1476            .as_ref()
 1477            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1478    }
 1479
 1480    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1481        let mut key_context = KeyContext::new_with_defaults();
 1482        key_context.add("Editor");
 1483        let mode = match self.mode {
 1484            EditorMode::SingleLine { .. } => "single_line",
 1485            EditorMode::AutoHeight { .. } => "auto_height",
 1486            EditorMode::Full => "full",
 1487        };
 1488
 1489        if EditorSettings::jupyter_enabled(cx) {
 1490            key_context.add("jupyter");
 1491        }
 1492
 1493        key_context.set("mode", mode);
 1494        if self.pending_rename.is_some() {
 1495            key_context.add("renaming");
 1496        }
 1497        match self.context_menu.borrow().as_ref() {
 1498            Some(CodeContextMenu::Completions(_)) => {
 1499                key_context.add("menu");
 1500                key_context.add("showing_completions")
 1501            }
 1502            Some(CodeContextMenu::CodeActions(_)) => {
 1503                key_context.add("menu");
 1504                key_context.add("showing_code_actions")
 1505            }
 1506            None => {}
 1507        }
 1508
 1509        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1510        if !self.focus_handle(cx).contains_focused(window, cx)
 1511            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1512        {
 1513            for addon in self.addons.values() {
 1514                addon.extend_key_context(&mut key_context, cx)
 1515            }
 1516        }
 1517
 1518        if let Some(extension) = self
 1519            .buffer
 1520            .read(cx)
 1521            .as_singleton()
 1522            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1523        {
 1524            key_context.set("extension", extension.to_string());
 1525        }
 1526
 1527        if self.has_active_inline_completion() {
 1528            key_context.add("copilot_suggestion");
 1529            key_context.add("inline_completion");
 1530        }
 1531
 1532        if self.selection_mark_mode {
 1533            key_context.add("selection_mode");
 1534        }
 1535
 1536        key_context
 1537    }
 1538
 1539    pub fn new_file(
 1540        workspace: &mut Workspace,
 1541        _: &workspace::NewFile,
 1542        window: &mut Window,
 1543        cx: &mut Context<Workspace>,
 1544    ) {
 1545        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1546            "Failed to create buffer",
 1547            window,
 1548            cx,
 1549            |e, _, _| match e.error_code() {
 1550                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1551                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1552                e.error_tag("required").unwrap_or("the latest version")
 1553            )),
 1554                _ => None,
 1555            },
 1556        );
 1557    }
 1558
 1559    pub fn new_in_workspace(
 1560        workspace: &mut Workspace,
 1561        window: &mut Window,
 1562        cx: &mut Context<Workspace>,
 1563    ) -> Task<Result<Entity<Editor>>> {
 1564        let project = workspace.project().clone();
 1565        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1566
 1567        cx.spawn_in(window, |workspace, mut cx| async move {
 1568            let buffer = create.await?;
 1569            workspace.update_in(&mut cx, |workspace, window, cx| {
 1570                let editor =
 1571                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1572                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1573                editor
 1574            })
 1575        })
 1576    }
 1577
 1578    fn new_file_vertical(
 1579        workspace: &mut Workspace,
 1580        _: &workspace::NewFileSplitVertical,
 1581        window: &mut Window,
 1582        cx: &mut Context<Workspace>,
 1583    ) {
 1584        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1585    }
 1586
 1587    fn new_file_horizontal(
 1588        workspace: &mut Workspace,
 1589        _: &workspace::NewFileSplitHorizontal,
 1590        window: &mut Window,
 1591        cx: &mut Context<Workspace>,
 1592    ) {
 1593        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1594    }
 1595
 1596    fn new_file_in_direction(
 1597        workspace: &mut Workspace,
 1598        direction: SplitDirection,
 1599        window: &mut Window,
 1600        cx: &mut Context<Workspace>,
 1601    ) {
 1602        let project = workspace.project().clone();
 1603        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1604
 1605        cx.spawn_in(window, |workspace, mut cx| async move {
 1606            let buffer = create.await?;
 1607            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1608                workspace.split_item(
 1609                    direction,
 1610                    Box::new(
 1611                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1612                    ),
 1613                    window,
 1614                    cx,
 1615                )
 1616            })?;
 1617            anyhow::Ok(())
 1618        })
 1619        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1620            match e.error_code() {
 1621                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1622                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1623                e.error_tag("required").unwrap_or("the latest version")
 1624            )),
 1625                _ => None,
 1626            }
 1627        });
 1628    }
 1629
 1630    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1631        self.leader_peer_id
 1632    }
 1633
 1634    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1635        &self.buffer
 1636    }
 1637
 1638    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1639        self.workspace.as_ref()?.0.upgrade()
 1640    }
 1641
 1642    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1643        self.buffer().read(cx).title(cx)
 1644    }
 1645
 1646    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1647        let git_blame_gutter_max_author_length = self
 1648            .render_git_blame_gutter(cx)
 1649            .then(|| {
 1650                if let Some(blame) = self.blame.as_ref() {
 1651                    let max_author_length =
 1652                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1653                    Some(max_author_length)
 1654                } else {
 1655                    None
 1656                }
 1657            })
 1658            .flatten();
 1659
 1660        EditorSnapshot {
 1661            mode: self.mode,
 1662            show_gutter: self.show_gutter,
 1663            show_line_numbers: self.show_line_numbers,
 1664            show_git_diff_gutter: self.show_git_diff_gutter,
 1665            show_code_actions: self.show_code_actions,
 1666            show_runnables: self.show_runnables,
 1667            git_blame_gutter_max_author_length,
 1668            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1669            scroll_anchor: self.scroll_manager.anchor(),
 1670            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1671            placeholder_text: self.placeholder_text.clone(),
 1672            is_focused: self.focus_handle.is_focused(window),
 1673            current_line_highlight: self
 1674                .current_line_highlight
 1675                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1676            gutter_hovered: self.gutter_hovered,
 1677        }
 1678    }
 1679
 1680    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1681        self.buffer.read(cx).language_at(point, cx)
 1682    }
 1683
 1684    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1685        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1686    }
 1687
 1688    pub fn active_excerpt(
 1689        &self,
 1690        cx: &App,
 1691    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1692        self.buffer
 1693            .read(cx)
 1694            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1695    }
 1696
 1697    pub fn mode(&self) -> EditorMode {
 1698        self.mode
 1699    }
 1700
 1701    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1702        self.collaboration_hub.as_deref()
 1703    }
 1704
 1705    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1706        self.collaboration_hub = Some(hub);
 1707    }
 1708
 1709    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1710        self.in_project_search = in_project_search;
 1711    }
 1712
 1713    pub fn set_custom_context_menu(
 1714        &mut self,
 1715        f: impl 'static
 1716            + Fn(
 1717                &mut Self,
 1718                DisplayPoint,
 1719                &mut Window,
 1720                &mut Context<Self>,
 1721            ) -> Option<Entity<ui::ContextMenu>>,
 1722    ) {
 1723        self.custom_context_menu = Some(Box::new(f))
 1724    }
 1725
 1726    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1727        self.completion_provider = provider;
 1728    }
 1729
 1730    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1731        self.semantics_provider.clone()
 1732    }
 1733
 1734    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1735        self.semantics_provider = provider;
 1736    }
 1737
 1738    pub fn set_inline_completion_provider<T>(
 1739        &mut self,
 1740        provider: Option<Entity<T>>,
 1741        window: &mut Window,
 1742        cx: &mut Context<Self>,
 1743    ) where
 1744        T: InlineCompletionProvider,
 1745    {
 1746        self.inline_completion_provider =
 1747            provider.map(|provider| RegisteredInlineCompletionProvider {
 1748                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1749                    if this.focus_handle.is_focused(window) {
 1750                        this.update_visible_inline_completion(window, cx);
 1751                    }
 1752                }),
 1753                provider: Arc::new(provider),
 1754            });
 1755        self.refresh_inline_completion(false, false, window, cx);
 1756    }
 1757
 1758    pub fn placeholder_text(&self) -> Option<&str> {
 1759        self.placeholder_text.as_deref()
 1760    }
 1761
 1762    pub fn set_placeholder_text(
 1763        &mut self,
 1764        placeholder_text: impl Into<Arc<str>>,
 1765        cx: &mut Context<Self>,
 1766    ) {
 1767        let placeholder_text = Some(placeholder_text.into());
 1768        if self.placeholder_text != placeholder_text {
 1769            self.placeholder_text = placeholder_text;
 1770            cx.notify();
 1771        }
 1772    }
 1773
 1774    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1775        self.cursor_shape = cursor_shape;
 1776
 1777        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1778        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1779
 1780        cx.notify();
 1781    }
 1782
 1783    pub fn set_current_line_highlight(
 1784        &mut self,
 1785        current_line_highlight: Option<CurrentLineHighlight>,
 1786    ) {
 1787        self.current_line_highlight = current_line_highlight;
 1788    }
 1789
 1790    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1791        self.collapse_matches = collapse_matches;
 1792    }
 1793
 1794    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1795        let buffers = self.buffer.read(cx).all_buffers();
 1796        let Some(lsp_store) = self.lsp_store(cx) else {
 1797            return;
 1798        };
 1799        lsp_store.update(cx, |lsp_store, cx| {
 1800            for buffer in buffers {
 1801                self.registered_buffers
 1802                    .entry(buffer.read(cx).remote_id())
 1803                    .or_insert_with(|| {
 1804                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1805                    });
 1806            }
 1807        })
 1808    }
 1809
 1810    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1811        if self.collapse_matches {
 1812            return range.start..range.start;
 1813        }
 1814        range.clone()
 1815    }
 1816
 1817    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1818        if self.display_map.read(cx).clip_at_line_ends != clip {
 1819            self.display_map
 1820                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1821        }
 1822    }
 1823
 1824    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1825        self.input_enabled = input_enabled;
 1826    }
 1827
 1828    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1829        self.enable_inline_completions = enabled;
 1830        if !self.enable_inline_completions {
 1831            self.take_active_inline_completion(cx);
 1832            cx.notify();
 1833        }
 1834    }
 1835
 1836    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1837        self.menu_inline_completions_policy = value;
 1838    }
 1839
 1840    pub fn set_autoindent(&mut self, autoindent: bool) {
 1841        if autoindent {
 1842            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1843        } else {
 1844            self.autoindent_mode = None;
 1845        }
 1846    }
 1847
 1848    pub fn read_only(&self, cx: &App) -> bool {
 1849        self.read_only || self.buffer.read(cx).read_only()
 1850    }
 1851
 1852    pub fn set_read_only(&mut self, read_only: bool) {
 1853        self.read_only = read_only;
 1854    }
 1855
 1856    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1857        self.use_autoclose = autoclose;
 1858    }
 1859
 1860    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1861        self.use_auto_surround = auto_surround;
 1862    }
 1863
 1864    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1865        self.auto_replace_emoji_shortcode = auto_replace;
 1866    }
 1867
 1868    pub fn toggle_inline_completions(
 1869        &mut self,
 1870        _: &ToggleInlineCompletions,
 1871        window: &mut Window,
 1872        cx: &mut Context<Self>,
 1873    ) {
 1874        if self.show_inline_completions_override.is_some() {
 1875            self.set_show_inline_completions(None, window, cx);
 1876        } else {
 1877            let cursor = self.selections.newest_anchor().head();
 1878            if let Some((buffer, cursor_buffer_position)) =
 1879                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1880            {
 1881                let show_inline_completions =
 1882                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1883                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1884            }
 1885        }
 1886    }
 1887
 1888    pub fn set_show_inline_completions(
 1889        &mut self,
 1890        show_inline_completions: Option<bool>,
 1891        window: &mut Window,
 1892        cx: &mut Context<Self>,
 1893    ) {
 1894        self.show_inline_completions_override = show_inline_completions;
 1895        self.refresh_inline_completion(false, true, window, cx);
 1896    }
 1897
 1898    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1899        let cursor = self.selections.newest_anchor().head();
 1900        if let Some((buffer, buffer_position)) =
 1901            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1902        {
 1903            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1904        } else {
 1905            false
 1906        }
 1907    }
 1908
 1909    fn should_show_inline_completions(
 1910        &self,
 1911        buffer: &Entity<Buffer>,
 1912        buffer_position: language::Anchor,
 1913        cx: &App,
 1914    ) -> bool {
 1915        if !self.snippet_stack.is_empty() {
 1916            return false;
 1917        }
 1918
 1919        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1920            return false;
 1921        }
 1922
 1923        if let Some(provider) = self.inline_completion_provider() {
 1924            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1925                show_inline_completions
 1926            } else {
 1927                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1928            }
 1929        } else {
 1930            false
 1931        }
 1932    }
 1933
 1934    fn inline_completions_disabled_in_scope(
 1935        &self,
 1936        buffer: &Entity<Buffer>,
 1937        buffer_position: language::Anchor,
 1938        cx: &App,
 1939    ) -> bool {
 1940        let snapshot = buffer.read(cx).snapshot();
 1941        let settings = snapshot.settings_at(buffer_position, cx);
 1942
 1943        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1944            return false;
 1945        };
 1946
 1947        scope.override_name().map_or(false, |scope_name| {
 1948            settings
 1949                .inline_completions_disabled_in
 1950                .iter()
 1951                .any(|s| s == scope_name)
 1952        })
 1953    }
 1954
 1955    pub fn set_use_modal_editing(&mut self, to: bool) {
 1956        self.use_modal_editing = to;
 1957    }
 1958
 1959    pub fn use_modal_editing(&self) -> bool {
 1960        self.use_modal_editing
 1961    }
 1962
 1963    fn selections_did_change(
 1964        &mut self,
 1965        local: bool,
 1966        old_cursor_position: &Anchor,
 1967        show_completions: bool,
 1968        window: &mut Window,
 1969        cx: &mut Context<Self>,
 1970    ) {
 1971        window.invalidate_character_coordinates();
 1972
 1973        // Copy selections to primary selection buffer
 1974        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1975        if local {
 1976            let selections = self.selections.all::<usize>(cx);
 1977            let buffer_handle = self.buffer.read(cx).read(cx);
 1978
 1979            let mut text = String::new();
 1980            for (index, selection) in selections.iter().enumerate() {
 1981                let text_for_selection = buffer_handle
 1982                    .text_for_range(selection.start..selection.end)
 1983                    .collect::<String>();
 1984
 1985                text.push_str(&text_for_selection);
 1986                if index != selections.len() - 1 {
 1987                    text.push('\n');
 1988                }
 1989            }
 1990
 1991            if !text.is_empty() {
 1992                cx.write_to_primary(ClipboardItem::new_string(text));
 1993            }
 1994        }
 1995
 1996        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1997            self.buffer.update(cx, |buffer, cx| {
 1998                buffer.set_active_selections(
 1999                    &self.selections.disjoint_anchors(),
 2000                    self.selections.line_mode,
 2001                    self.cursor_shape,
 2002                    cx,
 2003                )
 2004            });
 2005        }
 2006        let display_map = self
 2007            .display_map
 2008            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2009        let buffer = &display_map.buffer_snapshot;
 2010        self.add_selections_state = None;
 2011        self.select_next_state = None;
 2012        self.select_prev_state = None;
 2013        self.select_larger_syntax_node_stack.clear();
 2014        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2015        self.snippet_stack
 2016            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2017        self.take_rename(false, window, cx);
 2018
 2019        let new_cursor_position = self.selections.newest_anchor().head();
 2020
 2021        self.push_to_nav_history(
 2022            *old_cursor_position,
 2023            Some(new_cursor_position.to_point(buffer)),
 2024            cx,
 2025        );
 2026
 2027        if local {
 2028            let new_cursor_position = self.selections.newest_anchor().head();
 2029            let mut context_menu = self.context_menu.borrow_mut();
 2030            let completion_menu = match context_menu.as_ref() {
 2031                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2032                _ => {
 2033                    *context_menu = None;
 2034                    None
 2035                }
 2036            };
 2037
 2038            if let Some(completion_menu) = completion_menu {
 2039                let cursor_position = new_cursor_position.to_offset(buffer);
 2040                let (word_range, kind) =
 2041                    buffer.surrounding_word(completion_menu.initial_position, true);
 2042                if kind == Some(CharKind::Word)
 2043                    && word_range.to_inclusive().contains(&cursor_position)
 2044                {
 2045                    let mut completion_menu = completion_menu.clone();
 2046                    drop(context_menu);
 2047
 2048                    let query = Self::completion_query(buffer, cursor_position);
 2049                    cx.spawn(move |this, mut cx| async move {
 2050                        completion_menu
 2051                            .filter(query.as_deref(), cx.background_executor().clone())
 2052                            .await;
 2053
 2054                        this.update(&mut cx, |this, cx| {
 2055                            let mut context_menu = this.context_menu.borrow_mut();
 2056                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2057                            else {
 2058                                return;
 2059                            };
 2060
 2061                            if menu.id > completion_menu.id {
 2062                                return;
 2063                            }
 2064
 2065                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2066                            drop(context_menu);
 2067                            cx.notify();
 2068                        })
 2069                    })
 2070                    .detach();
 2071
 2072                    if show_completions {
 2073                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2074                    }
 2075                } else {
 2076                    drop(context_menu);
 2077                    self.hide_context_menu(window, cx);
 2078                }
 2079            } else {
 2080                drop(context_menu);
 2081            }
 2082
 2083            hide_hover(self, cx);
 2084
 2085            if old_cursor_position.to_display_point(&display_map).row()
 2086                != new_cursor_position.to_display_point(&display_map).row()
 2087            {
 2088                self.available_code_actions.take();
 2089            }
 2090            self.refresh_code_actions(window, cx);
 2091            self.refresh_document_highlights(cx);
 2092            refresh_matching_bracket_highlights(self, window, cx);
 2093            self.update_visible_inline_completion(window, cx);
 2094            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2095            if self.git_blame_inline_enabled {
 2096                self.start_inline_blame_timer(window, cx);
 2097            }
 2098        }
 2099
 2100        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2101        cx.emit(EditorEvent::SelectionsChanged { local });
 2102
 2103        if self.selections.disjoint_anchors().len() == 1 {
 2104            cx.emit(SearchEvent::ActiveMatchChanged)
 2105        }
 2106        cx.notify();
 2107    }
 2108
 2109    pub fn change_selections<R>(
 2110        &mut self,
 2111        autoscroll: Option<Autoscroll>,
 2112        window: &mut Window,
 2113        cx: &mut Context<Self>,
 2114        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2115    ) -> R {
 2116        self.change_selections_inner(autoscroll, true, window, cx, change)
 2117    }
 2118
 2119    pub fn change_selections_inner<R>(
 2120        &mut self,
 2121        autoscroll: Option<Autoscroll>,
 2122        request_completions: bool,
 2123        window: &mut Window,
 2124        cx: &mut Context<Self>,
 2125        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2126    ) -> R {
 2127        let old_cursor_position = self.selections.newest_anchor().head();
 2128        self.push_to_selection_history();
 2129
 2130        let (changed, result) = self.selections.change_with(cx, change);
 2131
 2132        if changed {
 2133            if let Some(autoscroll) = autoscroll {
 2134                self.request_autoscroll(autoscroll, cx);
 2135            }
 2136            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2137
 2138            if self.should_open_signature_help_automatically(
 2139                &old_cursor_position,
 2140                self.signature_help_state.backspace_pressed(),
 2141                cx,
 2142            ) {
 2143                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2144            }
 2145            self.signature_help_state.set_backspace_pressed(false);
 2146        }
 2147
 2148        result
 2149    }
 2150
 2151    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2152    where
 2153        I: IntoIterator<Item = (Range<S>, T)>,
 2154        S: ToOffset,
 2155        T: Into<Arc<str>>,
 2156    {
 2157        if self.read_only(cx) {
 2158            return;
 2159        }
 2160
 2161        self.buffer
 2162            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2163    }
 2164
 2165    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2166    where
 2167        I: IntoIterator<Item = (Range<S>, T)>,
 2168        S: ToOffset,
 2169        T: Into<Arc<str>>,
 2170    {
 2171        if self.read_only(cx) {
 2172            return;
 2173        }
 2174
 2175        self.buffer.update(cx, |buffer, cx| {
 2176            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2177        });
 2178    }
 2179
 2180    pub fn edit_with_block_indent<I, S, T>(
 2181        &mut self,
 2182        edits: I,
 2183        original_indent_columns: Vec<u32>,
 2184        cx: &mut Context<Self>,
 2185    ) where
 2186        I: IntoIterator<Item = (Range<S>, T)>,
 2187        S: ToOffset,
 2188        T: Into<Arc<str>>,
 2189    {
 2190        if self.read_only(cx) {
 2191            return;
 2192        }
 2193
 2194        self.buffer.update(cx, |buffer, cx| {
 2195            buffer.edit(
 2196                edits,
 2197                Some(AutoindentMode::Block {
 2198                    original_indent_columns,
 2199                }),
 2200                cx,
 2201            )
 2202        });
 2203    }
 2204
 2205    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2206        self.hide_context_menu(window, cx);
 2207
 2208        match phase {
 2209            SelectPhase::Begin {
 2210                position,
 2211                add,
 2212                click_count,
 2213            } => self.begin_selection(position, add, click_count, window, cx),
 2214            SelectPhase::BeginColumnar {
 2215                position,
 2216                goal_column,
 2217                reset,
 2218            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2219            SelectPhase::Extend {
 2220                position,
 2221                click_count,
 2222            } => self.extend_selection(position, click_count, window, cx),
 2223            SelectPhase::Update {
 2224                position,
 2225                goal_column,
 2226                scroll_delta,
 2227            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2228            SelectPhase::End => self.end_selection(window, cx),
 2229        }
 2230    }
 2231
 2232    fn extend_selection(
 2233        &mut self,
 2234        position: DisplayPoint,
 2235        click_count: usize,
 2236        window: &mut Window,
 2237        cx: &mut Context<Self>,
 2238    ) {
 2239        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2240        let tail = self.selections.newest::<usize>(cx).tail();
 2241        self.begin_selection(position, false, click_count, window, cx);
 2242
 2243        let position = position.to_offset(&display_map, Bias::Left);
 2244        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2245
 2246        let mut pending_selection = self
 2247            .selections
 2248            .pending_anchor()
 2249            .expect("extend_selection not called with pending selection");
 2250        if position >= tail {
 2251            pending_selection.start = tail_anchor;
 2252        } else {
 2253            pending_selection.end = tail_anchor;
 2254            pending_selection.reversed = true;
 2255        }
 2256
 2257        let mut pending_mode = self.selections.pending_mode().unwrap();
 2258        match &mut pending_mode {
 2259            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2260            _ => {}
 2261        }
 2262
 2263        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2264            s.set_pending(pending_selection, pending_mode)
 2265        });
 2266    }
 2267
 2268    fn begin_selection(
 2269        &mut self,
 2270        position: DisplayPoint,
 2271        add: bool,
 2272        click_count: usize,
 2273        window: &mut Window,
 2274        cx: &mut Context<Self>,
 2275    ) {
 2276        if !self.focus_handle.is_focused(window) {
 2277            self.last_focused_descendant = None;
 2278            window.focus(&self.focus_handle);
 2279        }
 2280
 2281        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2282        let buffer = &display_map.buffer_snapshot;
 2283        let newest_selection = self.selections.newest_anchor().clone();
 2284        let position = display_map.clip_point(position, Bias::Left);
 2285
 2286        let start;
 2287        let end;
 2288        let mode;
 2289        let mut auto_scroll;
 2290        match click_count {
 2291            1 => {
 2292                start = buffer.anchor_before(position.to_point(&display_map));
 2293                end = start;
 2294                mode = SelectMode::Character;
 2295                auto_scroll = true;
 2296            }
 2297            2 => {
 2298                let range = movement::surrounding_word(&display_map, position);
 2299                start = buffer.anchor_before(range.start.to_point(&display_map));
 2300                end = buffer.anchor_before(range.end.to_point(&display_map));
 2301                mode = SelectMode::Word(start..end);
 2302                auto_scroll = true;
 2303            }
 2304            3 => {
 2305                let position = display_map
 2306                    .clip_point(position, Bias::Left)
 2307                    .to_point(&display_map);
 2308                let line_start = display_map.prev_line_boundary(position).0;
 2309                let next_line_start = buffer.clip_point(
 2310                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2311                    Bias::Left,
 2312                );
 2313                start = buffer.anchor_before(line_start);
 2314                end = buffer.anchor_before(next_line_start);
 2315                mode = SelectMode::Line(start..end);
 2316                auto_scroll = true;
 2317            }
 2318            _ => {
 2319                start = buffer.anchor_before(0);
 2320                end = buffer.anchor_before(buffer.len());
 2321                mode = SelectMode::All;
 2322                auto_scroll = false;
 2323            }
 2324        }
 2325        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2326
 2327        let point_to_delete: Option<usize> = {
 2328            let selected_points: Vec<Selection<Point>> =
 2329                self.selections.disjoint_in_range(start..end, cx);
 2330
 2331            if !add || click_count > 1 {
 2332                None
 2333            } else if !selected_points.is_empty() {
 2334                Some(selected_points[0].id)
 2335            } else {
 2336                let clicked_point_already_selected =
 2337                    self.selections.disjoint.iter().find(|selection| {
 2338                        selection.start.to_point(buffer) == start.to_point(buffer)
 2339                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2340                    });
 2341
 2342                clicked_point_already_selected.map(|selection| selection.id)
 2343            }
 2344        };
 2345
 2346        let selections_count = self.selections.count();
 2347
 2348        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2349            if let Some(point_to_delete) = point_to_delete {
 2350                s.delete(point_to_delete);
 2351
 2352                if selections_count == 1 {
 2353                    s.set_pending_anchor_range(start..end, mode);
 2354                }
 2355            } else {
 2356                if !add {
 2357                    s.clear_disjoint();
 2358                } else if click_count > 1 {
 2359                    s.delete(newest_selection.id)
 2360                }
 2361
 2362                s.set_pending_anchor_range(start..end, mode);
 2363            }
 2364        });
 2365    }
 2366
 2367    fn begin_columnar_selection(
 2368        &mut self,
 2369        position: DisplayPoint,
 2370        goal_column: u32,
 2371        reset: bool,
 2372        window: &mut Window,
 2373        cx: &mut Context<Self>,
 2374    ) {
 2375        if !self.focus_handle.is_focused(window) {
 2376            self.last_focused_descendant = None;
 2377            window.focus(&self.focus_handle);
 2378        }
 2379
 2380        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2381
 2382        if reset {
 2383            let pointer_position = display_map
 2384                .buffer_snapshot
 2385                .anchor_before(position.to_point(&display_map));
 2386
 2387            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2388                s.clear_disjoint();
 2389                s.set_pending_anchor_range(
 2390                    pointer_position..pointer_position,
 2391                    SelectMode::Character,
 2392                );
 2393            });
 2394        }
 2395
 2396        let tail = self.selections.newest::<Point>(cx).tail();
 2397        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2398
 2399        if !reset {
 2400            self.select_columns(
 2401                tail.to_display_point(&display_map),
 2402                position,
 2403                goal_column,
 2404                &display_map,
 2405                window,
 2406                cx,
 2407            );
 2408        }
 2409    }
 2410
 2411    fn update_selection(
 2412        &mut self,
 2413        position: DisplayPoint,
 2414        goal_column: u32,
 2415        scroll_delta: gpui::Point<f32>,
 2416        window: &mut Window,
 2417        cx: &mut Context<Self>,
 2418    ) {
 2419        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2420
 2421        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2422            let tail = tail.to_display_point(&display_map);
 2423            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2424        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2425            let buffer = self.buffer.read(cx).snapshot(cx);
 2426            let head;
 2427            let tail;
 2428            let mode = self.selections.pending_mode().unwrap();
 2429            match &mode {
 2430                SelectMode::Character => {
 2431                    head = position.to_point(&display_map);
 2432                    tail = pending.tail().to_point(&buffer);
 2433                }
 2434                SelectMode::Word(original_range) => {
 2435                    let original_display_range = original_range.start.to_display_point(&display_map)
 2436                        ..original_range.end.to_display_point(&display_map);
 2437                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2438                        ..original_display_range.end.to_point(&display_map);
 2439                    if movement::is_inside_word(&display_map, position)
 2440                        || original_display_range.contains(&position)
 2441                    {
 2442                        let word_range = movement::surrounding_word(&display_map, position);
 2443                        if word_range.start < original_display_range.start {
 2444                            head = word_range.start.to_point(&display_map);
 2445                        } else {
 2446                            head = word_range.end.to_point(&display_map);
 2447                        }
 2448                    } else {
 2449                        head = position.to_point(&display_map);
 2450                    }
 2451
 2452                    if head <= original_buffer_range.start {
 2453                        tail = original_buffer_range.end;
 2454                    } else {
 2455                        tail = original_buffer_range.start;
 2456                    }
 2457                }
 2458                SelectMode::Line(original_range) => {
 2459                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2460
 2461                    let position = display_map
 2462                        .clip_point(position, Bias::Left)
 2463                        .to_point(&display_map);
 2464                    let line_start = display_map.prev_line_boundary(position).0;
 2465                    let next_line_start = buffer.clip_point(
 2466                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2467                        Bias::Left,
 2468                    );
 2469
 2470                    if line_start < original_range.start {
 2471                        head = line_start
 2472                    } else {
 2473                        head = next_line_start
 2474                    }
 2475
 2476                    if head <= original_range.start {
 2477                        tail = original_range.end;
 2478                    } else {
 2479                        tail = original_range.start;
 2480                    }
 2481                }
 2482                SelectMode::All => {
 2483                    return;
 2484                }
 2485            };
 2486
 2487            if head < tail {
 2488                pending.start = buffer.anchor_before(head);
 2489                pending.end = buffer.anchor_before(tail);
 2490                pending.reversed = true;
 2491            } else {
 2492                pending.start = buffer.anchor_before(tail);
 2493                pending.end = buffer.anchor_before(head);
 2494                pending.reversed = false;
 2495            }
 2496
 2497            self.change_selections(None, window, cx, |s| {
 2498                s.set_pending(pending, mode);
 2499            });
 2500        } else {
 2501            log::error!("update_selection dispatched with no pending selection");
 2502            return;
 2503        }
 2504
 2505        self.apply_scroll_delta(scroll_delta, window, cx);
 2506        cx.notify();
 2507    }
 2508
 2509    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2510        self.columnar_selection_tail.take();
 2511        if self.selections.pending_anchor().is_some() {
 2512            let selections = self.selections.all::<usize>(cx);
 2513            self.change_selections(None, window, cx, |s| {
 2514                s.select(selections);
 2515                s.clear_pending();
 2516            });
 2517        }
 2518    }
 2519
 2520    fn select_columns(
 2521        &mut self,
 2522        tail: DisplayPoint,
 2523        head: DisplayPoint,
 2524        goal_column: u32,
 2525        display_map: &DisplaySnapshot,
 2526        window: &mut Window,
 2527        cx: &mut Context<Self>,
 2528    ) {
 2529        let start_row = cmp::min(tail.row(), head.row());
 2530        let end_row = cmp::max(tail.row(), head.row());
 2531        let start_column = cmp::min(tail.column(), goal_column);
 2532        let end_column = cmp::max(tail.column(), goal_column);
 2533        let reversed = start_column < tail.column();
 2534
 2535        let selection_ranges = (start_row.0..=end_row.0)
 2536            .map(DisplayRow)
 2537            .filter_map(|row| {
 2538                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2539                    let start = display_map
 2540                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2541                        .to_point(display_map);
 2542                    let end = display_map
 2543                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2544                        .to_point(display_map);
 2545                    if reversed {
 2546                        Some(end..start)
 2547                    } else {
 2548                        Some(start..end)
 2549                    }
 2550                } else {
 2551                    None
 2552                }
 2553            })
 2554            .collect::<Vec<_>>();
 2555
 2556        self.change_selections(None, window, cx, |s| {
 2557            s.select_ranges(selection_ranges);
 2558        });
 2559        cx.notify();
 2560    }
 2561
 2562    pub fn has_pending_nonempty_selection(&self) -> bool {
 2563        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2564            Some(Selection { start, end, .. }) => start != end,
 2565            None => false,
 2566        };
 2567
 2568        pending_nonempty_selection
 2569            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2570    }
 2571
 2572    pub fn has_pending_selection(&self) -> bool {
 2573        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2574    }
 2575
 2576    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2577        self.selection_mark_mode = false;
 2578
 2579        if self.clear_expanded_diff_hunks(cx) {
 2580            cx.notify();
 2581            return;
 2582        }
 2583        if self.dismiss_menus_and_popups(true, window, cx) {
 2584            return;
 2585        }
 2586
 2587        if self.mode == EditorMode::Full
 2588            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2589        {
 2590            return;
 2591        }
 2592
 2593        cx.propagate();
 2594    }
 2595
 2596    pub fn dismiss_menus_and_popups(
 2597        &mut self,
 2598        should_report_inline_completion_event: bool,
 2599        window: &mut Window,
 2600        cx: &mut Context<Self>,
 2601    ) -> bool {
 2602        if self.take_rename(false, window, cx).is_some() {
 2603            return true;
 2604        }
 2605
 2606        if hide_hover(self, cx) {
 2607            return true;
 2608        }
 2609
 2610        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2611            return true;
 2612        }
 2613
 2614        if self.hide_context_menu(window, cx).is_some() {
 2615            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2616                self.update_visible_inline_completion(window, cx);
 2617            }
 2618            return true;
 2619        }
 2620
 2621        if self.mouse_context_menu.take().is_some() {
 2622            return true;
 2623        }
 2624
 2625        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2626            return true;
 2627        }
 2628
 2629        if self.snippet_stack.pop().is_some() {
 2630            return true;
 2631        }
 2632
 2633        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2634            self.dismiss_diagnostics(cx);
 2635            return true;
 2636        }
 2637
 2638        false
 2639    }
 2640
 2641    fn linked_editing_ranges_for(
 2642        &self,
 2643        selection: Range<text::Anchor>,
 2644        cx: &App,
 2645    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2646        if self.linked_edit_ranges.is_empty() {
 2647            return None;
 2648        }
 2649        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2650            selection.end.buffer_id.and_then(|end_buffer_id| {
 2651                if selection.start.buffer_id != Some(end_buffer_id) {
 2652                    return None;
 2653                }
 2654                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2655                let snapshot = buffer.read(cx).snapshot();
 2656                self.linked_edit_ranges
 2657                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2658                    .map(|ranges| (ranges, snapshot, buffer))
 2659            })?;
 2660        use text::ToOffset as TO;
 2661        // find offset from the start of current range to current cursor position
 2662        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2663
 2664        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2665        let start_difference = start_offset - start_byte_offset;
 2666        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2667        let end_difference = end_offset - start_byte_offset;
 2668        // Current range has associated linked ranges.
 2669        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2670        for range in linked_ranges.iter() {
 2671            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2672            let end_offset = start_offset + end_difference;
 2673            let start_offset = start_offset + start_difference;
 2674            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2675                continue;
 2676            }
 2677            if self.selections.disjoint_anchor_ranges().any(|s| {
 2678                if s.start.buffer_id != selection.start.buffer_id
 2679                    || s.end.buffer_id != selection.end.buffer_id
 2680                {
 2681                    return false;
 2682                }
 2683                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2684                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2685            }) {
 2686                continue;
 2687            }
 2688            let start = buffer_snapshot.anchor_after(start_offset);
 2689            let end = buffer_snapshot.anchor_after(end_offset);
 2690            linked_edits
 2691                .entry(buffer.clone())
 2692                .or_default()
 2693                .push(start..end);
 2694        }
 2695        Some(linked_edits)
 2696    }
 2697
 2698    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2699        let text: Arc<str> = text.into();
 2700
 2701        if self.read_only(cx) {
 2702            return;
 2703        }
 2704
 2705        let selections = self.selections.all_adjusted(cx);
 2706        let mut bracket_inserted = false;
 2707        let mut edits = Vec::new();
 2708        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2709        let mut new_selections = Vec::with_capacity(selections.len());
 2710        let mut new_autoclose_regions = Vec::new();
 2711        let snapshot = self.buffer.read(cx).read(cx);
 2712
 2713        for (selection, autoclose_region) in
 2714            self.selections_with_autoclose_regions(selections, &snapshot)
 2715        {
 2716            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2717                // Determine if the inserted text matches the opening or closing
 2718                // bracket of any of this language's bracket pairs.
 2719                let mut bracket_pair = None;
 2720                let mut is_bracket_pair_start = false;
 2721                let mut is_bracket_pair_end = false;
 2722                if !text.is_empty() {
 2723                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2724                    //  and they are removing the character that triggered IME popup.
 2725                    for (pair, enabled) in scope.brackets() {
 2726                        if !pair.close && !pair.surround {
 2727                            continue;
 2728                        }
 2729
 2730                        if enabled && pair.start.ends_with(text.as_ref()) {
 2731                            let prefix_len = pair.start.len() - text.len();
 2732                            let preceding_text_matches_prefix = prefix_len == 0
 2733                                || (selection.start.column >= (prefix_len as u32)
 2734                                    && snapshot.contains_str_at(
 2735                                        Point::new(
 2736                                            selection.start.row,
 2737                                            selection.start.column - (prefix_len as u32),
 2738                                        ),
 2739                                        &pair.start[..prefix_len],
 2740                                    ));
 2741                            if preceding_text_matches_prefix {
 2742                                bracket_pair = Some(pair.clone());
 2743                                is_bracket_pair_start = true;
 2744                                break;
 2745                            }
 2746                        }
 2747                        if pair.end.as_str() == text.as_ref() {
 2748                            bracket_pair = Some(pair.clone());
 2749                            is_bracket_pair_end = true;
 2750                            break;
 2751                        }
 2752                    }
 2753                }
 2754
 2755                if let Some(bracket_pair) = bracket_pair {
 2756                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2757                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2758                    let auto_surround =
 2759                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2760                    if selection.is_empty() {
 2761                        if is_bracket_pair_start {
 2762                            // If the inserted text is a suffix of an opening bracket and the
 2763                            // selection is preceded by the rest of the opening bracket, then
 2764                            // insert the closing bracket.
 2765                            let following_text_allows_autoclose = snapshot
 2766                                .chars_at(selection.start)
 2767                                .next()
 2768                                .map_or(true, |c| scope.should_autoclose_before(c));
 2769
 2770                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2771                                && bracket_pair.start.len() == 1
 2772                            {
 2773                                let target = bracket_pair.start.chars().next().unwrap();
 2774                                let current_line_count = snapshot
 2775                                    .reversed_chars_at(selection.start)
 2776                                    .take_while(|&c| c != '\n')
 2777                                    .filter(|&c| c == target)
 2778                                    .count();
 2779                                current_line_count % 2 == 1
 2780                            } else {
 2781                                false
 2782                            };
 2783
 2784                            if autoclose
 2785                                && bracket_pair.close
 2786                                && following_text_allows_autoclose
 2787                                && !is_closing_quote
 2788                            {
 2789                                let anchor = snapshot.anchor_before(selection.end);
 2790                                new_selections.push((selection.map(|_| anchor), text.len()));
 2791                                new_autoclose_regions.push((
 2792                                    anchor,
 2793                                    text.len(),
 2794                                    selection.id,
 2795                                    bracket_pair.clone(),
 2796                                ));
 2797                                edits.push((
 2798                                    selection.range(),
 2799                                    format!("{}{}", text, bracket_pair.end).into(),
 2800                                ));
 2801                                bracket_inserted = true;
 2802                                continue;
 2803                            }
 2804                        }
 2805
 2806                        if let Some(region) = autoclose_region {
 2807                            // If the selection is followed by an auto-inserted closing bracket,
 2808                            // then don't insert that closing bracket again; just move the selection
 2809                            // past the closing bracket.
 2810                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2811                                && text.as_ref() == region.pair.end.as_str();
 2812                            if should_skip {
 2813                                let anchor = snapshot.anchor_after(selection.end);
 2814                                new_selections
 2815                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2816                                continue;
 2817                            }
 2818                        }
 2819
 2820                        let always_treat_brackets_as_autoclosed = snapshot
 2821                            .settings_at(selection.start, cx)
 2822                            .always_treat_brackets_as_autoclosed;
 2823                        if always_treat_brackets_as_autoclosed
 2824                            && is_bracket_pair_end
 2825                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2826                        {
 2827                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2828                            // and the inserted text is a closing bracket and the selection is followed
 2829                            // by the closing bracket then move the selection past the closing bracket.
 2830                            let anchor = snapshot.anchor_after(selection.end);
 2831                            new_selections.push((selection.map(|_| anchor), text.len()));
 2832                            continue;
 2833                        }
 2834                    }
 2835                    // If an opening bracket is 1 character long and is typed while
 2836                    // text is selected, then surround that text with the bracket pair.
 2837                    else if auto_surround
 2838                        && bracket_pair.surround
 2839                        && is_bracket_pair_start
 2840                        && bracket_pair.start.chars().count() == 1
 2841                    {
 2842                        edits.push((selection.start..selection.start, text.clone()));
 2843                        edits.push((
 2844                            selection.end..selection.end,
 2845                            bracket_pair.end.as_str().into(),
 2846                        ));
 2847                        bracket_inserted = true;
 2848                        new_selections.push((
 2849                            Selection {
 2850                                id: selection.id,
 2851                                start: snapshot.anchor_after(selection.start),
 2852                                end: snapshot.anchor_before(selection.end),
 2853                                reversed: selection.reversed,
 2854                                goal: selection.goal,
 2855                            },
 2856                            0,
 2857                        ));
 2858                        continue;
 2859                    }
 2860                }
 2861            }
 2862
 2863            if self.auto_replace_emoji_shortcode
 2864                && selection.is_empty()
 2865                && text.as_ref().ends_with(':')
 2866            {
 2867                if let Some(possible_emoji_short_code) =
 2868                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2869                {
 2870                    if !possible_emoji_short_code.is_empty() {
 2871                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2872                            let emoji_shortcode_start = Point::new(
 2873                                selection.start.row,
 2874                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2875                            );
 2876
 2877                            // Remove shortcode from buffer
 2878                            edits.push((
 2879                                emoji_shortcode_start..selection.start,
 2880                                "".to_string().into(),
 2881                            ));
 2882                            new_selections.push((
 2883                                Selection {
 2884                                    id: selection.id,
 2885                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2886                                    end: snapshot.anchor_before(selection.start),
 2887                                    reversed: selection.reversed,
 2888                                    goal: selection.goal,
 2889                                },
 2890                                0,
 2891                            ));
 2892
 2893                            // Insert emoji
 2894                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2895                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2896                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2897
 2898                            continue;
 2899                        }
 2900                    }
 2901                }
 2902            }
 2903
 2904            // If not handling any auto-close operation, then just replace the selected
 2905            // text with the given input and move the selection to the end of the
 2906            // newly inserted text.
 2907            let anchor = snapshot.anchor_after(selection.end);
 2908            if !self.linked_edit_ranges.is_empty() {
 2909                let start_anchor = snapshot.anchor_before(selection.start);
 2910
 2911                let is_word_char = text.chars().next().map_or(true, |char| {
 2912                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2913                    classifier.is_word(char)
 2914                });
 2915
 2916                if is_word_char {
 2917                    if let Some(ranges) = self
 2918                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2919                    {
 2920                        for (buffer, edits) in ranges {
 2921                            linked_edits
 2922                                .entry(buffer.clone())
 2923                                .or_default()
 2924                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2925                        }
 2926                    }
 2927                }
 2928            }
 2929
 2930            new_selections.push((selection.map(|_| anchor), 0));
 2931            edits.push((selection.start..selection.end, text.clone()));
 2932        }
 2933
 2934        drop(snapshot);
 2935
 2936        self.transact(window, cx, |this, window, cx| {
 2937            this.buffer.update(cx, |buffer, cx| {
 2938                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2939            });
 2940            for (buffer, edits) in linked_edits {
 2941                buffer.update(cx, |buffer, cx| {
 2942                    let snapshot = buffer.snapshot();
 2943                    let edits = edits
 2944                        .into_iter()
 2945                        .map(|(range, text)| {
 2946                            use text::ToPoint as TP;
 2947                            let end_point = TP::to_point(&range.end, &snapshot);
 2948                            let start_point = TP::to_point(&range.start, &snapshot);
 2949                            (start_point..end_point, text)
 2950                        })
 2951                        .sorted_by_key(|(range, _)| range.start)
 2952                        .collect::<Vec<_>>();
 2953                    buffer.edit(edits, None, cx);
 2954                })
 2955            }
 2956            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2957            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2958            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2959            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2960                .zip(new_selection_deltas)
 2961                .map(|(selection, delta)| Selection {
 2962                    id: selection.id,
 2963                    start: selection.start + delta,
 2964                    end: selection.end + delta,
 2965                    reversed: selection.reversed,
 2966                    goal: SelectionGoal::None,
 2967                })
 2968                .collect::<Vec<_>>();
 2969
 2970            let mut i = 0;
 2971            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2972                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2973                let start = map.buffer_snapshot.anchor_before(position);
 2974                let end = map.buffer_snapshot.anchor_after(position);
 2975                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2976                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2977                        Ordering::Less => i += 1,
 2978                        Ordering::Greater => break,
 2979                        Ordering::Equal => {
 2980                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2981                                Ordering::Less => i += 1,
 2982                                Ordering::Equal => break,
 2983                                Ordering::Greater => break,
 2984                            }
 2985                        }
 2986                    }
 2987                }
 2988                this.autoclose_regions.insert(
 2989                    i,
 2990                    AutocloseRegion {
 2991                        selection_id,
 2992                        range: start..end,
 2993                        pair,
 2994                    },
 2995                );
 2996            }
 2997
 2998            let had_active_inline_completion = this.has_active_inline_completion();
 2999            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3000                s.select(new_selections)
 3001            });
 3002
 3003            if !bracket_inserted {
 3004                if let Some(on_type_format_task) =
 3005                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3006                {
 3007                    on_type_format_task.detach_and_log_err(cx);
 3008                }
 3009            }
 3010
 3011            let editor_settings = EditorSettings::get_global(cx);
 3012            if bracket_inserted
 3013                && (editor_settings.auto_signature_help
 3014                    || editor_settings.show_signature_help_after_edits)
 3015            {
 3016                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3017            }
 3018
 3019            let trigger_in_words =
 3020                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3021            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3022            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3023            this.refresh_inline_completion(true, false, window, cx);
 3024        });
 3025    }
 3026
 3027    fn find_possible_emoji_shortcode_at_position(
 3028        snapshot: &MultiBufferSnapshot,
 3029        position: Point,
 3030    ) -> Option<String> {
 3031        let mut chars = Vec::new();
 3032        let mut found_colon = false;
 3033        for char in snapshot.reversed_chars_at(position).take(100) {
 3034            // Found a possible emoji shortcode in the middle of the buffer
 3035            if found_colon {
 3036                if char.is_whitespace() {
 3037                    chars.reverse();
 3038                    return Some(chars.iter().collect());
 3039                }
 3040                // If the previous character is not a whitespace, we are in the middle of a word
 3041                // and we only want to complete the shortcode if the word is made up of other emojis
 3042                let mut containing_word = String::new();
 3043                for ch in snapshot
 3044                    .reversed_chars_at(position)
 3045                    .skip(chars.len() + 1)
 3046                    .take(100)
 3047                {
 3048                    if ch.is_whitespace() {
 3049                        break;
 3050                    }
 3051                    containing_word.push(ch);
 3052                }
 3053                let containing_word = containing_word.chars().rev().collect::<String>();
 3054                if util::word_consists_of_emojis(containing_word.as_str()) {
 3055                    chars.reverse();
 3056                    return Some(chars.iter().collect());
 3057                }
 3058            }
 3059
 3060            if char.is_whitespace() || !char.is_ascii() {
 3061                return None;
 3062            }
 3063            if char == ':' {
 3064                found_colon = true;
 3065            } else {
 3066                chars.push(char);
 3067            }
 3068        }
 3069        // Found a possible emoji shortcode at the beginning of the buffer
 3070        chars.reverse();
 3071        Some(chars.iter().collect())
 3072    }
 3073
 3074    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3075        self.transact(window, cx, |this, window, cx| {
 3076            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3077                let selections = this.selections.all::<usize>(cx);
 3078                let multi_buffer = this.buffer.read(cx);
 3079                let buffer = multi_buffer.snapshot(cx);
 3080                selections
 3081                    .iter()
 3082                    .map(|selection| {
 3083                        let start_point = selection.start.to_point(&buffer);
 3084                        let mut indent =
 3085                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3086                        indent.len = cmp::min(indent.len, start_point.column);
 3087                        let start = selection.start;
 3088                        let end = selection.end;
 3089                        let selection_is_empty = start == end;
 3090                        let language_scope = buffer.language_scope_at(start);
 3091                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3092                            &language_scope
 3093                        {
 3094                            let leading_whitespace_len = buffer
 3095                                .reversed_chars_at(start)
 3096                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3097                                .map(|c| c.len_utf8())
 3098                                .sum::<usize>();
 3099
 3100                            let trailing_whitespace_len = buffer
 3101                                .chars_at(end)
 3102                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3103                                .map(|c| c.len_utf8())
 3104                                .sum::<usize>();
 3105
 3106                            let insert_extra_newline =
 3107                                language.brackets().any(|(pair, enabled)| {
 3108                                    let pair_start = pair.start.trim_end();
 3109                                    let pair_end = pair.end.trim_start();
 3110
 3111                                    enabled
 3112                                        && pair.newline
 3113                                        && buffer.contains_str_at(
 3114                                            end + trailing_whitespace_len,
 3115                                            pair_end,
 3116                                        )
 3117                                        && buffer.contains_str_at(
 3118                                            (start - leading_whitespace_len)
 3119                                                .saturating_sub(pair_start.len()),
 3120                                            pair_start,
 3121                                        )
 3122                                });
 3123
 3124                            // Comment extension on newline is allowed only for cursor selections
 3125                            let comment_delimiter = maybe!({
 3126                                if !selection_is_empty {
 3127                                    return None;
 3128                                }
 3129
 3130                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3131                                    return None;
 3132                                }
 3133
 3134                                let delimiters = language.line_comment_prefixes();
 3135                                let max_len_of_delimiter =
 3136                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3137                                let (snapshot, range) =
 3138                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3139
 3140                                let mut index_of_first_non_whitespace = 0;
 3141                                let comment_candidate = snapshot
 3142                                    .chars_for_range(range)
 3143                                    .skip_while(|c| {
 3144                                        let should_skip = c.is_whitespace();
 3145                                        if should_skip {
 3146                                            index_of_first_non_whitespace += 1;
 3147                                        }
 3148                                        should_skip
 3149                                    })
 3150                                    .take(max_len_of_delimiter)
 3151                                    .collect::<String>();
 3152                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3153                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3154                                })?;
 3155                                let cursor_is_placed_after_comment_marker =
 3156                                    index_of_first_non_whitespace + comment_prefix.len()
 3157                                        <= start_point.column as usize;
 3158                                if cursor_is_placed_after_comment_marker {
 3159                                    Some(comment_prefix.clone())
 3160                                } else {
 3161                                    None
 3162                                }
 3163                            });
 3164                            (comment_delimiter, insert_extra_newline)
 3165                        } else {
 3166                            (None, false)
 3167                        };
 3168
 3169                        let capacity_for_delimiter = comment_delimiter
 3170                            .as_deref()
 3171                            .map(str::len)
 3172                            .unwrap_or_default();
 3173                        let mut new_text =
 3174                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3175                        new_text.push('\n');
 3176                        new_text.extend(indent.chars());
 3177                        if let Some(delimiter) = &comment_delimiter {
 3178                            new_text.push_str(delimiter);
 3179                        }
 3180                        if insert_extra_newline {
 3181                            new_text = new_text.repeat(2);
 3182                        }
 3183
 3184                        let anchor = buffer.anchor_after(end);
 3185                        let new_selection = selection.map(|_| anchor);
 3186                        (
 3187                            (start..end, new_text),
 3188                            (insert_extra_newline, new_selection),
 3189                        )
 3190                    })
 3191                    .unzip()
 3192            };
 3193
 3194            this.edit_with_autoindent(edits, cx);
 3195            let buffer = this.buffer.read(cx).snapshot(cx);
 3196            let new_selections = selection_fixup_info
 3197                .into_iter()
 3198                .map(|(extra_newline_inserted, new_selection)| {
 3199                    let mut cursor = new_selection.end.to_point(&buffer);
 3200                    if extra_newline_inserted {
 3201                        cursor.row -= 1;
 3202                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3203                    }
 3204                    new_selection.map(|_| cursor)
 3205                })
 3206                .collect();
 3207
 3208            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3209                s.select(new_selections)
 3210            });
 3211            this.refresh_inline_completion(true, false, window, cx);
 3212        });
 3213    }
 3214
 3215    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3216        let buffer = self.buffer.read(cx);
 3217        let snapshot = buffer.snapshot(cx);
 3218
 3219        let mut edits = Vec::new();
 3220        let mut rows = Vec::new();
 3221
 3222        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3223            let cursor = selection.head();
 3224            let row = cursor.row;
 3225
 3226            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3227
 3228            let newline = "\n".to_string();
 3229            edits.push((start_of_line..start_of_line, newline));
 3230
 3231            rows.push(row + rows_inserted as u32);
 3232        }
 3233
 3234        self.transact(window, cx, |editor, window, cx| {
 3235            editor.edit(edits, cx);
 3236
 3237            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3238                let mut index = 0;
 3239                s.move_cursors_with(|map, _, _| {
 3240                    let row = rows[index];
 3241                    index += 1;
 3242
 3243                    let point = Point::new(row, 0);
 3244                    let boundary = map.next_line_boundary(point).1;
 3245                    let clipped = map.clip_point(boundary, Bias::Left);
 3246
 3247                    (clipped, SelectionGoal::None)
 3248                });
 3249            });
 3250
 3251            let mut indent_edits = Vec::new();
 3252            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3253            for row in rows {
 3254                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3255                for (row, indent) in indents {
 3256                    if indent.len == 0 {
 3257                        continue;
 3258                    }
 3259
 3260                    let text = match indent.kind {
 3261                        IndentKind::Space => " ".repeat(indent.len as usize),
 3262                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3263                    };
 3264                    let point = Point::new(row.0, 0);
 3265                    indent_edits.push((point..point, text));
 3266                }
 3267            }
 3268            editor.edit(indent_edits, cx);
 3269        });
 3270    }
 3271
 3272    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3273        let buffer = self.buffer.read(cx);
 3274        let snapshot = buffer.snapshot(cx);
 3275
 3276        let mut edits = Vec::new();
 3277        let mut rows = Vec::new();
 3278        let mut rows_inserted = 0;
 3279
 3280        for selection in self.selections.all_adjusted(cx) {
 3281            let cursor = selection.head();
 3282            let row = cursor.row;
 3283
 3284            let point = Point::new(row + 1, 0);
 3285            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3286
 3287            let newline = "\n".to_string();
 3288            edits.push((start_of_line..start_of_line, newline));
 3289
 3290            rows_inserted += 1;
 3291            rows.push(row + rows_inserted);
 3292        }
 3293
 3294        self.transact(window, cx, |editor, window, cx| {
 3295            editor.edit(edits, cx);
 3296
 3297            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3298                let mut index = 0;
 3299                s.move_cursors_with(|map, _, _| {
 3300                    let row = rows[index];
 3301                    index += 1;
 3302
 3303                    let point = Point::new(row, 0);
 3304                    let boundary = map.next_line_boundary(point).1;
 3305                    let clipped = map.clip_point(boundary, Bias::Left);
 3306
 3307                    (clipped, SelectionGoal::None)
 3308                });
 3309            });
 3310
 3311            let mut indent_edits = Vec::new();
 3312            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3313            for row in rows {
 3314                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3315                for (row, indent) in indents {
 3316                    if indent.len == 0 {
 3317                        continue;
 3318                    }
 3319
 3320                    let text = match indent.kind {
 3321                        IndentKind::Space => " ".repeat(indent.len as usize),
 3322                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3323                    };
 3324                    let point = Point::new(row.0, 0);
 3325                    indent_edits.push((point..point, text));
 3326                }
 3327            }
 3328            editor.edit(indent_edits, cx);
 3329        });
 3330    }
 3331
 3332    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3333        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3334            original_indent_columns: Vec::new(),
 3335        });
 3336        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3337    }
 3338
 3339    fn insert_with_autoindent_mode(
 3340        &mut self,
 3341        text: &str,
 3342        autoindent_mode: Option<AutoindentMode>,
 3343        window: &mut Window,
 3344        cx: &mut Context<Self>,
 3345    ) {
 3346        if self.read_only(cx) {
 3347            return;
 3348        }
 3349
 3350        let text: Arc<str> = text.into();
 3351        self.transact(window, cx, |this, window, cx| {
 3352            let old_selections = this.selections.all_adjusted(cx);
 3353            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3354                let anchors = {
 3355                    let snapshot = buffer.read(cx);
 3356                    old_selections
 3357                        .iter()
 3358                        .map(|s| {
 3359                            let anchor = snapshot.anchor_after(s.head());
 3360                            s.map(|_| anchor)
 3361                        })
 3362                        .collect::<Vec<_>>()
 3363                };
 3364                buffer.edit(
 3365                    old_selections
 3366                        .iter()
 3367                        .map(|s| (s.start..s.end, text.clone())),
 3368                    autoindent_mode,
 3369                    cx,
 3370                );
 3371                anchors
 3372            });
 3373
 3374            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3375                s.select_anchors(selection_anchors);
 3376            });
 3377
 3378            cx.notify();
 3379        });
 3380    }
 3381
 3382    fn trigger_completion_on_input(
 3383        &mut self,
 3384        text: &str,
 3385        trigger_in_words: bool,
 3386        window: &mut Window,
 3387        cx: &mut Context<Self>,
 3388    ) {
 3389        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3390            self.show_completions(
 3391                &ShowCompletions {
 3392                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3393                },
 3394                window,
 3395                cx,
 3396            );
 3397        } else {
 3398            self.hide_context_menu(window, cx);
 3399        }
 3400    }
 3401
 3402    fn is_completion_trigger(
 3403        &self,
 3404        text: &str,
 3405        trigger_in_words: bool,
 3406        cx: &mut Context<Self>,
 3407    ) -> bool {
 3408        let position = self.selections.newest_anchor().head();
 3409        let multibuffer = self.buffer.read(cx);
 3410        let Some(buffer) = position
 3411            .buffer_id
 3412            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3413        else {
 3414            return false;
 3415        };
 3416
 3417        if let Some(completion_provider) = &self.completion_provider {
 3418            completion_provider.is_completion_trigger(
 3419                &buffer,
 3420                position.text_anchor,
 3421                text,
 3422                trigger_in_words,
 3423                cx,
 3424            )
 3425        } else {
 3426            false
 3427        }
 3428    }
 3429
 3430    /// If any empty selections is touching the start of its innermost containing autoclose
 3431    /// region, expand it to select the brackets.
 3432    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3433        let selections = self.selections.all::<usize>(cx);
 3434        let buffer = self.buffer.read(cx).read(cx);
 3435        let new_selections = self
 3436            .selections_with_autoclose_regions(selections, &buffer)
 3437            .map(|(mut selection, region)| {
 3438                if !selection.is_empty() {
 3439                    return selection;
 3440                }
 3441
 3442                if let Some(region) = region {
 3443                    let mut range = region.range.to_offset(&buffer);
 3444                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3445                        range.start -= region.pair.start.len();
 3446                        if buffer.contains_str_at(range.start, &region.pair.start)
 3447                            && buffer.contains_str_at(range.end, &region.pair.end)
 3448                        {
 3449                            range.end += region.pair.end.len();
 3450                            selection.start = range.start;
 3451                            selection.end = range.end;
 3452
 3453                            return selection;
 3454                        }
 3455                    }
 3456                }
 3457
 3458                let always_treat_brackets_as_autoclosed = buffer
 3459                    .settings_at(selection.start, cx)
 3460                    .always_treat_brackets_as_autoclosed;
 3461
 3462                if !always_treat_brackets_as_autoclosed {
 3463                    return selection;
 3464                }
 3465
 3466                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3467                    for (pair, enabled) in scope.brackets() {
 3468                        if !enabled || !pair.close {
 3469                            continue;
 3470                        }
 3471
 3472                        if buffer.contains_str_at(selection.start, &pair.end) {
 3473                            let pair_start_len = pair.start.len();
 3474                            if buffer.contains_str_at(
 3475                                selection.start.saturating_sub(pair_start_len),
 3476                                &pair.start,
 3477                            ) {
 3478                                selection.start -= pair_start_len;
 3479                                selection.end += pair.end.len();
 3480
 3481                                return selection;
 3482                            }
 3483                        }
 3484                    }
 3485                }
 3486
 3487                selection
 3488            })
 3489            .collect();
 3490
 3491        drop(buffer);
 3492        self.change_selections(None, window, cx, |selections| {
 3493            selections.select(new_selections)
 3494        });
 3495    }
 3496
 3497    /// Iterate the given selections, and for each one, find the smallest surrounding
 3498    /// autoclose region. This uses the ordering of the selections and the autoclose
 3499    /// regions to avoid repeated comparisons.
 3500    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3501        &'a self,
 3502        selections: impl IntoIterator<Item = Selection<D>>,
 3503        buffer: &'a MultiBufferSnapshot,
 3504    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3505        let mut i = 0;
 3506        let mut regions = self.autoclose_regions.as_slice();
 3507        selections.into_iter().map(move |selection| {
 3508            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3509
 3510            let mut enclosing = None;
 3511            while let Some(pair_state) = regions.get(i) {
 3512                if pair_state.range.end.to_offset(buffer) < range.start {
 3513                    regions = &regions[i + 1..];
 3514                    i = 0;
 3515                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3516                    break;
 3517                } else {
 3518                    if pair_state.selection_id == selection.id {
 3519                        enclosing = Some(pair_state);
 3520                    }
 3521                    i += 1;
 3522                }
 3523            }
 3524
 3525            (selection, enclosing)
 3526        })
 3527    }
 3528
 3529    /// Remove any autoclose regions that no longer contain their selection.
 3530    fn invalidate_autoclose_regions(
 3531        &mut self,
 3532        mut selections: &[Selection<Anchor>],
 3533        buffer: &MultiBufferSnapshot,
 3534    ) {
 3535        self.autoclose_regions.retain(|state| {
 3536            let mut i = 0;
 3537            while let Some(selection) = selections.get(i) {
 3538                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3539                    selections = &selections[1..];
 3540                    continue;
 3541                }
 3542                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3543                    break;
 3544                }
 3545                if selection.id == state.selection_id {
 3546                    return true;
 3547                } else {
 3548                    i += 1;
 3549                }
 3550            }
 3551            false
 3552        });
 3553    }
 3554
 3555    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3556        let offset = position.to_offset(buffer);
 3557        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3558        if offset > word_range.start && kind == Some(CharKind::Word) {
 3559            Some(
 3560                buffer
 3561                    .text_for_range(word_range.start..offset)
 3562                    .collect::<String>(),
 3563            )
 3564        } else {
 3565            None
 3566        }
 3567    }
 3568
 3569    pub fn toggle_inlay_hints(
 3570        &mut self,
 3571        _: &ToggleInlayHints,
 3572        _: &mut Window,
 3573        cx: &mut Context<Self>,
 3574    ) {
 3575        self.refresh_inlay_hints(
 3576            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3577            cx,
 3578        );
 3579    }
 3580
 3581    pub fn inlay_hints_enabled(&self) -> bool {
 3582        self.inlay_hint_cache.enabled
 3583    }
 3584
 3585    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3586        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3587            return;
 3588        }
 3589
 3590        let reason_description = reason.description();
 3591        let ignore_debounce = matches!(
 3592            reason,
 3593            InlayHintRefreshReason::SettingsChange(_)
 3594                | InlayHintRefreshReason::Toggle(_)
 3595                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3596        );
 3597        let (invalidate_cache, required_languages) = match reason {
 3598            InlayHintRefreshReason::Toggle(enabled) => {
 3599                self.inlay_hint_cache.enabled = enabled;
 3600                if enabled {
 3601                    (InvalidationStrategy::RefreshRequested, None)
 3602                } else {
 3603                    self.inlay_hint_cache.clear();
 3604                    self.splice_inlays(
 3605                        self.visible_inlay_hints(cx)
 3606                            .iter()
 3607                            .map(|inlay| inlay.id)
 3608                            .collect(),
 3609                        Vec::new(),
 3610                        cx,
 3611                    );
 3612                    return;
 3613                }
 3614            }
 3615            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3616                match self.inlay_hint_cache.update_settings(
 3617                    &self.buffer,
 3618                    new_settings,
 3619                    self.visible_inlay_hints(cx),
 3620                    cx,
 3621                ) {
 3622                    ControlFlow::Break(Some(InlaySplice {
 3623                        to_remove,
 3624                        to_insert,
 3625                    })) => {
 3626                        self.splice_inlays(to_remove, to_insert, cx);
 3627                        return;
 3628                    }
 3629                    ControlFlow::Break(None) => return,
 3630                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3631                }
 3632            }
 3633            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3634                if let Some(InlaySplice {
 3635                    to_remove,
 3636                    to_insert,
 3637                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3638                {
 3639                    self.splice_inlays(to_remove, to_insert, cx);
 3640                }
 3641                return;
 3642            }
 3643            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3644            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3645                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3646            }
 3647            InlayHintRefreshReason::RefreshRequested => {
 3648                (InvalidationStrategy::RefreshRequested, None)
 3649            }
 3650        };
 3651
 3652        if let Some(InlaySplice {
 3653            to_remove,
 3654            to_insert,
 3655        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3656            reason_description,
 3657            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3658            invalidate_cache,
 3659            ignore_debounce,
 3660            cx,
 3661        ) {
 3662            self.splice_inlays(to_remove, to_insert, cx);
 3663        }
 3664    }
 3665
 3666    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3667        self.display_map
 3668            .read(cx)
 3669            .current_inlays()
 3670            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3671            .cloned()
 3672            .collect()
 3673    }
 3674
 3675    pub fn excerpts_for_inlay_hints_query(
 3676        &self,
 3677        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3678        cx: &mut Context<Editor>,
 3679    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3680        let Some(project) = self.project.as_ref() else {
 3681            return HashMap::default();
 3682        };
 3683        let project = project.read(cx);
 3684        let multi_buffer = self.buffer().read(cx);
 3685        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3686        let multi_buffer_visible_start = self
 3687            .scroll_manager
 3688            .anchor()
 3689            .anchor
 3690            .to_point(&multi_buffer_snapshot);
 3691        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3692            multi_buffer_visible_start
 3693                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3694            Bias::Left,
 3695        );
 3696        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3697        multi_buffer_snapshot
 3698            .range_to_buffer_ranges(multi_buffer_visible_range)
 3699            .into_iter()
 3700            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3701            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3702                let buffer_file = project::File::from_dyn(buffer.file())?;
 3703                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3704                let worktree_entry = buffer_worktree
 3705                    .read(cx)
 3706                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3707                if worktree_entry.is_ignored {
 3708                    return None;
 3709                }
 3710
 3711                let language = buffer.language()?;
 3712                if let Some(restrict_to_languages) = restrict_to_languages {
 3713                    if !restrict_to_languages.contains(language) {
 3714                        return None;
 3715                    }
 3716                }
 3717                Some((
 3718                    excerpt_id,
 3719                    (
 3720                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3721                        buffer.version().clone(),
 3722                        excerpt_visible_range,
 3723                    ),
 3724                ))
 3725            })
 3726            .collect()
 3727    }
 3728
 3729    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3730        TextLayoutDetails {
 3731            text_system: window.text_system().clone(),
 3732            editor_style: self.style.clone().unwrap(),
 3733            rem_size: window.rem_size(),
 3734            scroll_anchor: self.scroll_manager.anchor(),
 3735            visible_rows: self.visible_line_count(),
 3736            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3737        }
 3738    }
 3739
 3740    pub fn splice_inlays(
 3741        &self,
 3742        to_remove: Vec<InlayId>,
 3743        to_insert: Vec<Inlay>,
 3744        cx: &mut Context<Self>,
 3745    ) {
 3746        self.display_map.update(cx, |display_map, cx| {
 3747            display_map.splice_inlays(to_remove, to_insert, cx)
 3748        });
 3749        cx.notify();
 3750    }
 3751
 3752    fn trigger_on_type_formatting(
 3753        &self,
 3754        input: String,
 3755        window: &mut Window,
 3756        cx: &mut Context<Self>,
 3757    ) -> Option<Task<Result<()>>> {
 3758        if input.len() != 1 {
 3759            return None;
 3760        }
 3761
 3762        let project = self.project.as_ref()?;
 3763        let position = self.selections.newest_anchor().head();
 3764        let (buffer, buffer_position) = self
 3765            .buffer
 3766            .read(cx)
 3767            .text_anchor_for_position(position, cx)?;
 3768
 3769        let settings = language_settings::language_settings(
 3770            buffer
 3771                .read(cx)
 3772                .language_at(buffer_position)
 3773                .map(|l| l.name()),
 3774            buffer.read(cx).file(),
 3775            cx,
 3776        );
 3777        if !settings.use_on_type_format {
 3778            return None;
 3779        }
 3780
 3781        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3782        // hence we do LSP request & edit on host side only — add formats to host's history.
 3783        let push_to_lsp_host_history = true;
 3784        // If this is not the host, append its history with new edits.
 3785        let push_to_client_history = project.read(cx).is_via_collab();
 3786
 3787        let on_type_formatting = project.update(cx, |project, cx| {
 3788            project.on_type_format(
 3789                buffer.clone(),
 3790                buffer_position,
 3791                input,
 3792                push_to_lsp_host_history,
 3793                cx,
 3794            )
 3795        });
 3796        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3797            if let Some(transaction) = on_type_formatting.await? {
 3798                if push_to_client_history {
 3799                    buffer
 3800                        .update(&mut cx, |buffer, _| {
 3801                            buffer.push_transaction(transaction, Instant::now());
 3802                        })
 3803                        .ok();
 3804                }
 3805                editor.update(&mut cx, |editor, cx| {
 3806                    editor.refresh_document_highlights(cx);
 3807                })?;
 3808            }
 3809            Ok(())
 3810        }))
 3811    }
 3812
 3813    pub fn show_completions(
 3814        &mut self,
 3815        options: &ShowCompletions,
 3816        window: &mut Window,
 3817        cx: &mut Context<Self>,
 3818    ) {
 3819        if self.pending_rename.is_some() {
 3820            return;
 3821        }
 3822
 3823        let Some(provider) = self.completion_provider.as_ref() else {
 3824            return;
 3825        };
 3826
 3827        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3828            return;
 3829        }
 3830
 3831        let position = self.selections.newest_anchor().head();
 3832        if position.diff_base_anchor.is_some() {
 3833            return;
 3834        }
 3835        let (buffer, buffer_position) =
 3836            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3837                output
 3838            } else {
 3839                return;
 3840            };
 3841        let show_completion_documentation = buffer
 3842            .read(cx)
 3843            .snapshot()
 3844            .settings_at(buffer_position, cx)
 3845            .show_completion_documentation;
 3846
 3847        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3848
 3849        let trigger_kind = match &options.trigger {
 3850            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3851                CompletionTriggerKind::TRIGGER_CHARACTER
 3852            }
 3853            _ => CompletionTriggerKind::INVOKED,
 3854        };
 3855        let completion_context = CompletionContext {
 3856            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3857                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3858                    Some(String::from(trigger))
 3859                } else {
 3860                    None
 3861                }
 3862            }),
 3863            trigger_kind,
 3864        };
 3865        let completions =
 3866            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3867        let sort_completions = provider.sort_completions();
 3868
 3869        let id = post_inc(&mut self.next_completion_id);
 3870        let task = cx.spawn_in(window, |editor, mut cx| {
 3871            async move {
 3872                editor.update(&mut cx, |this, _| {
 3873                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3874                })?;
 3875                let completions = completions.await.log_err();
 3876                let menu = if let Some(completions) = completions {
 3877                    let mut menu = CompletionsMenu::new(
 3878                        id,
 3879                        sort_completions,
 3880                        show_completion_documentation,
 3881                        position,
 3882                        buffer.clone(),
 3883                        completions.into(),
 3884                    );
 3885
 3886                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3887                        .await;
 3888
 3889                    menu.visible().then_some(menu)
 3890                } else {
 3891                    None
 3892                };
 3893
 3894                editor.update_in(&mut cx, |editor, window, cx| {
 3895                    match editor.context_menu.borrow().as_ref() {
 3896                        None => {}
 3897                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3898                            if prev_menu.id > id {
 3899                                return;
 3900                            }
 3901                        }
 3902                        _ => return,
 3903                    }
 3904
 3905                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3906                        let mut menu = menu.unwrap();
 3907                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3908
 3909                        if editor.show_inline_completions_in_menu(cx) {
 3910                            if let Some(hint) = editor.inline_completion_menu_hint(window, cx) {
 3911                                menu.show_inline_completion_hint(hint);
 3912                            }
 3913                        } else {
 3914                            editor.discard_inline_completion(false, cx);
 3915                        }
 3916
 3917                        *editor.context_menu.borrow_mut() =
 3918                            Some(CodeContextMenu::Completions(menu));
 3919
 3920                        cx.notify();
 3921                    } else if editor.completion_tasks.len() <= 1 {
 3922                        // If there are no more completion tasks and the last menu was
 3923                        // empty, we should hide it.
 3924                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3925                        // If it was already hidden and we don't show inline
 3926                        // completions in the menu, we should also show the
 3927                        // inline-completion when available.
 3928                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3929                            editor.update_visible_inline_completion(window, cx);
 3930                        }
 3931                    }
 3932                })?;
 3933
 3934                Ok::<_, anyhow::Error>(())
 3935            }
 3936            .log_err()
 3937        });
 3938
 3939        self.completion_tasks.push((id, task));
 3940    }
 3941
 3942    pub fn confirm_completion(
 3943        &mut self,
 3944        action: &ConfirmCompletion,
 3945        window: &mut Window,
 3946        cx: &mut Context<Self>,
 3947    ) -> Option<Task<Result<()>>> {
 3948        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3949    }
 3950
 3951    pub fn compose_completion(
 3952        &mut self,
 3953        action: &ComposeCompletion,
 3954        window: &mut Window,
 3955        cx: &mut Context<Self>,
 3956    ) -> Option<Task<Result<()>>> {
 3957        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3958    }
 3959
 3960    fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3961        let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
 3962            return;
 3963        };
 3964
 3965        let project = project.read(cx);
 3966
 3967        ZedPredictModal::toggle(
 3968            workspace,
 3969            project.user_store().clone(),
 3970            project.client().clone(),
 3971            project.fs().clone(),
 3972            window,
 3973            cx,
 3974        );
 3975    }
 3976
 3977    fn do_completion(
 3978        &mut self,
 3979        item_ix: Option<usize>,
 3980        intent: CompletionIntent,
 3981        window: &mut Window,
 3982        cx: &mut Context<Editor>,
 3983    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3984        use language::ToOffset as _;
 3985
 3986        {
 3987            let context_menu = self.context_menu.borrow();
 3988            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3989                let entries = menu.entries.borrow();
 3990                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3991                match entry {
 3992                    Some(CompletionEntry::InlineCompletionHint(
 3993                        InlineCompletionMenuHint::Loading,
 3994                    )) => return Some(Task::ready(Ok(()))),
 3995                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3996                        drop(entries);
 3997                        drop(context_menu);
 3998                        self.context_menu_next(&Default::default(), window, cx);
 3999                        return Some(Task::ready(Ok(())));
 4000                    }
 4001                    Some(CompletionEntry::InlineCompletionHint(
 4002                        InlineCompletionMenuHint::PendingTermsAcceptance,
 4003                    )) => {
 4004                        drop(entries);
 4005                        drop(context_menu);
 4006                        self.toggle_zed_predict_onboarding(window, cx);
 4007                        return Some(Task::ready(Ok(())));
 4008                    }
 4009                    _ => {}
 4010                }
 4011            }
 4012        }
 4013
 4014        let completions_menu =
 4015            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4016                menu
 4017            } else {
 4018                return None;
 4019            };
 4020
 4021        let entries = completions_menu.entries.borrow();
 4022        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4023        let mat = match mat {
 4024            CompletionEntry::InlineCompletionHint(_) => {
 4025                self.accept_inline_completion(&AcceptInlineCompletion, window, cx);
 4026                cx.stop_propagation();
 4027                return Some(Task::ready(Ok(())));
 4028            }
 4029            CompletionEntry::Match(mat) => {
 4030                if self.show_inline_completions_in_menu(cx) {
 4031                    self.discard_inline_completion(true, cx);
 4032                }
 4033                mat
 4034            }
 4035        };
 4036        let candidate_id = mat.candidate_id;
 4037        drop(entries);
 4038
 4039        let buffer_handle = completions_menu.buffer;
 4040        let completion = completions_menu
 4041            .completions
 4042            .borrow()
 4043            .get(candidate_id)?
 4044            .clone();
 4045        cx.stop_propagation();
 4046
 4047        let snippet;
 4048        let text;
 4049
 4050        if completion.is_snippet() {
 4051            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4052            text = snippet.as_ref().unwrap().text.clone();
 4053        } else {
 4054            snippet = None;
 4055            text = completion.new_text.clone();
 4056        };
 4057        let selections = self.selections.all::<usize>(cx);
 4058        let buffer = buffer_handle.read(cx);
 4059        let old_range = completion.old_range.to_offset(buffer);
 4060        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4061
 4062        let newest_selection = self.selections.newest_anchor();
 4063        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4064            return None;
 4065        }
 4066
 4067        let lookbehind = newest_selection
 4068            .start
 4069            .text_anchor
 4070            .to_offset(buffer)
 4071            .saturating_sub(old_range.start);
 4072        let lookahead = old_range
 4073            .end
 4074            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4075        let mut common_prefix_len = old_text
 4076            .bytes()
 4077            .zip(text.bytes())
 4078            .take_while(|(a, b)| a == b)
 4079            .count();
 4080
 4081        let snapshot = self.buffer.read(cx).snapshot(cx);
 4082        let mut range_to_replace: Option<Range<isize>> = None;
 4083        let mut ranges = Vec::new();
 4084        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4085        for selection in &selections {
 4086            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4087                let start = selection.start.saturating_sub(lookbehind);
 4088                let end = selection.end + lookahead;
 4089                if selection.id == newest_selection.id {
 4090                    range_to_replace = Some(
 4091                        ((start + common_prefix_len) as isize - selection.start as isize)
 4092                            ..(end as isize - selection.start as isize),
 4093                    );
 4094                }
 4095                ranges.push(start + common_prefix_len..end);
 4096            } else {
 4097                common_prefix_len = 0;
 4098                ranges.clear();
 4099                ranges.extend(selections.iter().map(|s| {
 4100                    if s.id == newest_selection.id {
 4101                        range_to_replace = Some(
 4102                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4103                                - selection.start as isize
 4104                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4105                                    - selection.start as isize,
 4106                        );
 4107                        old_range.clone()
 4108                    } else {
 4109                        s.start..s.end
 4110                    }
 4111                }));
 4112                break;
 4113            }
 4114            if !self.linked_edit_ranges.is_empty() {
 4115                let start_anchor = snapshot.anchor_before(selection.head());
 4116                let end_anchor = snapshot.anchor_after(selection.tail());
 4117                if let Some(ranges) = self
 4118                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4119                {
 4120                    for (buffer, edits) in ranges {
 4121                        linked_edits.entry(buffer.clone()).or_default().extend(
 4122                            edits
 4123                                .into_iter()
 4124                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4125                        );
 4126                    }
 4127                }
 4128            }
 4129        }
 4130        let text = &text[common_prefix_len..];
 4131
 4132        cx.emit(EditorEvent::InputHandled {
 4133            utf16_range_to_replace: range_to_replace,
 4134            text: text.into(),
 4135        });
 4136
 4137        self.transact(window, cx, |this, window, cx| {
 4138            if let Some(mut snippet) = snippet {
 4139                snippet.text = text.to_string();
 4140                for tabstop in snippet
 4141                    .tabstops
 4142                    .iter_mut()
 4143                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4144                {
 4145                    tabstop.start -= common_prefix_len as isize;
 4146                    tabstop.end -= common_prefix_len as isize;
 4147                }
 4148
 4149                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4150            } else {
 4151                this.buffer.update(cx, |buffer, cx| {
 4152                    buffer.edit(
 4153                        ranges.iter().map(|range| (range.clone(), text)),
 4154                        this.autoindent_mode.clone(),
 4155                        cx,
 4156                    );
 4157                });
 4158            }
 4159            for (buffer, edits) in linked_edits {
 4160                buffer.update(cx, |buffer, cx| {
 4161                    let snapshot = buffer.snapshot();
 4162                    let edits = edits
 4163                        .into_iter()
 4164                        .map(|(range, text)| {
 4165                            use text::ToPoint as TP;
 4166                            let end_point = TP::to_point(&range.end, &snapshot);
 4167                            let start_point = TP::to_point(&range.start, &snapshot);
 4168                            (start_point..end_point, text)
 4169                        })
 4170                        .sorted_by_key(|(range, _)| range.start)
 4171                        .collect::<Vec<_>>();
 4172                    buffer.edit(edits, None, cx);
 4173                })
 4174            }
 4175
 4176            this.refresh_inline_completion(true, false, window, cx);
 4177        });
 4178
 4179        let show_new_completions_on_confirm = completion
 4180            .confirm
 4181            .as_ref()
 4182            .map_or(false, |confirm| confirm(intent, window, cx));
 4183        if show_new_completions_on_confirm {
 4184            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4185        }
 4186
 4187        let provider = self.completion_provider.as_ref()?;
 4188        drop(completion);
 4189        let apply_edits = provider.apply_additional_edits_for_completion(
 4190            buffer_handle,
 4191            completions_menu.completions.clone(),
 4192            candidate_id,
 4193            true,
 4194            cx,
 4195        );
 4196
 4197        let editor_settings = EditorSettings::get_global(cx);
 4198        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4199            // After the code completion is finished, users often want to know what signatures are needed.
 4200            // so we should automatically call signature_help
 4201            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4202        }
 4203
 4204        Some(cx.foreground_executor().spawn(async move {
 4205            apply_edits.await?;
 4206            Ok(())
 4207        }))
 4208    }
 4209
 4210    pub fn toggle_code_actions(
 4211        &mut self,
 4212        action: &ToggleCodeActions,
 4213        window: &mut Window,
 4214        cx: &mut Context<Self>,
 4215    ) {
 4216        let mut context_menu = self.context_menu.borrow_mut();
 4217        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4218            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4219                // Toggle if we're selecting the same one
 4220                *context_menu = None;
 4221                cx.notify();
 4222                return;
 4223            } else {
 4224                // Otherwise, clear it and start a new one
 4225                *context_menu = None;
 4226                cx.notify();
 4227            }
 4228        }
 4229        drop(context_menu);
 4230        let snapshot = self.snapshot(window, cx);
 4231        let deployed_from_indicator = action.deployed_from_indicator;
 4232        let mut task = self.code_actions_task.take();
 4233        let action = action.clone();
 4234        cx.spawn_in(window, |editor, mut cx| async move {
 4235            while let Some(prev_task) = task {
 4236                prev_task.await.log_err();
 4237                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4238            }
 4239
 4240            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4241                if editor.focus_handle.is_focused(window) {
 4242                    let multibuffer_point = action
 4243                        .deployed_from_indicator
 4244                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4245                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4246                    let (buffer, buffer_row) = snapshot
 4247                        .buffer_snapshot
 4248                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4249                        .and_then(|(buffer_snapshot, range)| {
 4250                            editor
 4251                                .buffer
 4252                                .read(cx)
 4253                                .buffer(buffer_snapshot.remote_id())
 4254                                .map(|buffer| (buffer, range.start.row))
 4255                        })?;
 4256                    let (_, code_actions) = editor
 4257                        .available_code_actions
 4258                        .clone()
 4259                        .and_then(|(location, code_actions)| {
 4260                            let snapshot = location.buffer.read(cx).snapshot();
 4261                            let point_range = location.range.to_point(&snapshot);
 4262                            let point_range = point_range.start.row..=point_range.end.row;
 4263                            if point_range.contains(&buffer_row) {
 4264                                Some((location, code_actions))
 4265                            } else {
 4266                                None
 4267                            }
 4268                        })
 4269                        .unzip();
 4270                    let buffer_id = buffer.read(cx).remote_id();
 4271                    let tasks = editor
 4272                        .tasks
 4273                        .get(&(buffer_id, buffer_row))
 4274                        .map(|t| Arc::new(t.to_owned()));
 4275                    if tasks.is_none() && code_actions.is_none() {
 4276                        return None;
 4277                    }
 4278
 4279                    editor.completion_tasks.clear();
 4280                    editor.discard_inline_completion(false, cx);
 4281                    let task_context =
 4282                        tasks
 4283                            .as_ref()
 4284                            .zip(editor.project.clone())
 4285                            .map(|(tasks, project)| {
 4286                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4287                            });
 4288
 4289                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4290                        let task_context = match task_context {
 4291                            Some(task_context) => task_context.await,
 4292                            None => None,
 4293                        };
 4294                        let resolved_tasks =
 4295                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4296                                Rc::new(ResolvedTasks {
 4297                                    templates: tasks.resolve(&task_context).collect(),
 4298                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4299                                        multibuffer_point.row,
 4300                                        tasks.column,
 4301                                    )),
 4302                                })
 4303                            });
 4304                        let spawn_straight_away = resolved_tasks
 4305                            .as_ref()
 4306                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4307                            && code_actions
 4308                                .as_ref()
 4309                                .map_or(true, |actions| actions.is_empty());
 4310                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4311                            *editor.context_menu.borrow_mut() =
 4312                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4313                                    buffer,
 4314                                    actions: CodeActionContents {
 4315                                        tasks: resolved_tasks,
 4316                                        actions: code_actions,
 4317                                    },
 4318                                    selected_item: Default::default(),
 4319                                    scroll_handle: UniformListScrollHandle::default(),
 4320                                    deployed_from_indicator,
 4321                                }));
 4322                            if spawn_straight_away {
 4323                                if let Some(task) = editor.confirm_code_action(
 4324                                    &ConfirmCodeAction { item_ix: Some(0) },
 4325                                    window,
 4326                                    cx,
 4327                                ) {
 4328                                    cx.notify();
 4329                                    return task;
 4330                                }
 4331                            }
 4332                            cx.notify();
 4333                            Task::ready(Ok(()))
 4334                        }) {
 4335                            task.await
 4336                        } else {
 4337                            Ok(())
 4338                        }
 4339                    }))
 4340                } else {
 4341                    Some(Task::ready(Ok(())))
 4342                }
 4343            })?;
 4344            if let Some(task) = spawned_test_task {
 4345                task.await?;
 4346            }
 4347
 4348            Ok::<_, anyhow::Error>(())
 4349        })
 4350        .detach_and_log_err(cx);
 4351    }
 4352
 4353    pub fn confirm_code_action(
 4354        &mut self,
 4355        action: &ConfirmCodeAction,
 4356        window: &mut Window,
 4357        cx: &mut Context<Self>,
 4358    ) -> Option<Task<Result<()>>> {
 4359        let actions_menu =
 4360            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4361                menu
 4362            } else {
 4363                return None;
 4364            };
 4365        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4366        let action = actions_menu.actions.get(action_ix)?;
 4367        let title = action.label();
 4368        let buffer = actions_menu.buffer;
 4369        let workspace = self.workspace()?;
 4370
 4371        match action {
 4372            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4373                workspace.update(cx, |workspace, cx| {
 4374                    workspace::tasks::schedule_resolved_task(
 4375                        workspace,
 4376                        task_source_kind,
 4377                        resolved_task,
 4378                        false,
 4379                        cx,
 4380                    );
 4381
 4382                    Some(Task::ready(Ok(())))
 4383                })
 4384            }
 4385            CodeActionsItem::CodeAction {
 4386                excerpt_id,
 4387                action,
 4388                provider,
 4389            } => {
 4390                let apply_code_action =
 4391                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4392                let workspace = workspace.downgrade();
 4393                Some(cx.spawn_in(window, |editor, cx| async move {
 4394                    let project_transaction = apply_code_action.await?;
 4395                    Self::open_project_transaction(
 4396                        &editor,
 4397                        workspace,
 4398                        project_transaction,
 4399                        title,
 4400                        cx,
 4401                    )
 4402                    .await
 4403                }))
 4404            }
 4405        }
 4406    }
 4407
 4408    pub async fn open_project_transaction(
 4409        this: &WeakEntity<Editor>,
 4410        workspace: WeakEntity<Workspace>,
 4411        transaction: ProjectTransaction,
 4412        title: String,
 4413        mut cx: AsyncWindowContext,
 4414    ) -> Result<()> {
 4415        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4416        cx.update(|_, cx| {
 4417            entries.sort_unstable_by_key(|(buffer, _)| {
 4418                buffer.read(cx).file().map(|f| f.path().clone())
 4419            });
 4420        })?;
 4421
 4422        // If the project transaction's edits are all contained within this editor, then
 4423        // avoid opening a new editor to display them.
 4424
 4425        if let Some((buffer, transaction)) = entries.first() {
 4426            if entries.len() == 1 {
 4427                let excerpt = this.update(&mut cx, |editor, cx| {
 4428                    editor
 4429                        .buffer()
 4430                        .read(cx)
 4431                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4432                })?;
 4433                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4434                    if excerpted_buffer == *buffer {
 4435                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4436                            let excerpt_range = excerpt_range.to_offset(buffer);
 4437                            buffer
 4438                                .edited_ranges_for_transaction::<usize>(transaction)
 4439                                .all(|range| {
 4440                                    excerpt_range.start <= range.start
 4441                                        && excerpt_range.end >= range.end
 4442                                })
 4443                        })?;
 4444
 4445                        if all_edits_within_excerpt {
 4446                            return Ok(());
 4447                        }
 4448                    }
 4449                }
 4450            }
 4451        } else {
 4452            return Ok(());
 4453        }
 4454
 4455        let mut ranges_to_highlight = Vec::new();
 4456        let excerpt_buffer = cx.new(|cx| {
 4457            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4458            for (buffer_handle, transaction) in &entries {
 4459                let buffer = buffer_handle.read(cx);
 4460                ranges_to_highlight.extend(
 4461                    multibuffer.push_excerpts_with_context_lines(
 4462                        buffer_handle.clone(),
 4463                        buffer
 4464                            .edited_ranges_for_transaction::<usize>(transaction)
 4465                            .collect(),
 4466                        DEFAULT_MULTIBUFFER_CONTEXT,
 4467                        cx,
 4468                    ),
 4469                );
 4470            }
 4471            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4472            multibuffer
 4473        })?;
 4474
 4475        workspace.update_in(&mut cx, |workspace, window, cx| {
 4476            let project = workspace.project().clone();
 4477            let editor = cx
 4478                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4479            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4480            editor.update(cx, |editor, cx| {
 4481                editor.highlight_background::<Self>(
 4482                    &ranges_to_highlight,
 4483                    |theme| theme.editor_highlighted_line_background,
 4484                    cx,
 4485                );
 4486            });
 4487        })?;
 4488
 4489        Ok(())
 4490    }
 4491
 4492    pub fn clear_code_action_providers(&mut self) {
 4493        self.code_action_providers.clear();
 4494        self.available_code_actions.take();
 4495    }
 4496
 4497    pub fn add_code_action_provider(
 4498        &mut self,
 4499        provider: Rc<dyn CodeActionProvider>,
 4500        window: &mut Window,
 4501        cx: &mut Context<Self>,
 4502    ) {
 4503        if self
 4504            .code_action_providers
 4505            .iter()
 4506            .any(|existing_provider| existing_provider.id() == provider.id())
 4507        {
 4508            return;
 4509        }
 4510
 4511        self.code_action_providers.push(provider);
 4512        self.refresh_code_actions(window, cx);
 4513    }
 4514
 4515    pub fn remove_code_action_provider(
 4516        &mut self,
 4517        id: Arc<str>,
 4518        window: &mut Window,
 4519        cx: &mut Context<Self>,
 4520    ) {
 4521        self.code_action_providers
 4522            .retain(|provider| provider.id() != id);
 4523        self.refresh_code_actions(window, cx);
 4524    }
 4525
 4526    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4527        let buffer = self.buffer.read(cx);
 4528        let newest_selection = self.selections.newest_anchor().clone();
 4529        if newest_selection.head().diff_base_anchor.is_some() {
 4530            return None;
 4531        }
 4532        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4533        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4534        if start_buffer != end_buffer {
 4535            return None;
 4536        }
 4537
 4538        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4539            cx.background_executor()
 4540                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4541                .await;
 4542
 4543            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4544                let providers = this.code_action_providers.clone();
 4545                let tasks = this
 4546                    .code_action_providers
 4547                    .iter()
 4548                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4549                    .collect::<Vec<_>>();
 4550                (providers, tasks)
 4551            })?;
 4552
 4553            let mut actions = Vec::new();
 4554            for (provider, provider_actions) in
 4555                providers.into_iter().zip(future::join_all(tasks).await)
 4556            {
 4557                if let Some(provider_actions) = provider_actions.log_err() {
 4558                    actions.extend(provider_actions.into_iter().map(|action| {
 4559                        AvailableCodeAction {
 4560                            excerpt_id: newest_selection.start.excerpt_id,
 4561                            action,
 4562                            provider: provider.clone(),
 4563                        }
 4564                    }));
 4565                }
 4566            }
 4567
 4568            this.update(&mut cx, |this, cx| {
 4569                this.available_code_actions = if actions.is_empty() {
 4570                    None
 4571                } else {
 4572                    Some((
 4573                        Location {
 4574                            buffer: start_buffer,
 4575                            range: start..end,
 4576                        },
 4577                        actions.into(),
 4578                    ))
 4579                };
 4580                cx.notify();
 4581            })
 4582        }));
 4583        None
 4584    }
 4585
 4586    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4587        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4588            self.show_git_blame_inline = false;
 4589
 4590            self.show_git_blame_inline_delay_task =
 4591                Some(cx.spawn_in(window, |this, mut cx| async move {
 4592                    cx.background_executor().timer(delay).await;
 4593
 4594                    this.update(&mut cx, |this, cx| {
 4595                        this.show_git_blame_inline = true;
 4596                        cx.notify();
 4597                    })
 4598                    .log_err();
 4599                }));
 4600        }
 4601    }
 4602
 4603    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4604        if self.pending_rename.is_some() {
 4605            return None;
 4606        }
 4607
 4608        let provider = self.semantics_provider.clone()?;
 4609        let buffer = self.buffer.read(cx);
 4610        let newest_selection = self.selections.newest_anchor().clone();
 4611        let cursor_position = newest_selection.head();
 4612        let (cursor_buffer, cursor_buffer_position) =
 4613            buffer.text_anchor_for_position(cursor_position, cx)?;
 4614        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4615        if cursor_buffer != tail_buffer {
 4616            return None;
 4617        }
 4618        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4619        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4620            cx.background_executor()
 4621                .timer(Duration::from_millis(debounce))
 4622                .await;
 4623
 4624            let highlights = if let Some(highlights) = cx
 4625                .update(|cx| {
 4626                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4627                })
 4628                .ok()
 4629                .flatten()
 4630            {
 4631                highlights.await.log_err()
 4632            } else {
 4633                None
 4634            };
 4635
 4636            if let Some(highlights) = highlights {
 4637                this.update(&mut cx, |this, cx| {
 4638                    if this.pending_rename.is_some() {
 4639                        return;
 4640                    }
 4641
 4642                    let buffer_id = cursor_position.buffer_id;
 4643                    let buffer = this.buffer.read(cx);
 4644                    if !buffer
 4645                        .text_anchor_for_position(cursor_position, cx)
 4646                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4647                    {
 4648                        return;
 4649                    }
 4650
 4651                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4652                    let mut write_ranges = Vec::new();
 4653                    let mut read_ranges = Vec::new();
 4654                    for highlight in highlights {
 4655                        for (excerpt_id, excerpt_range) in
 4656                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4657                        {
 4658                            let start = highlight
 4659                                .range
 4660                                .start
 4661                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4662                            let end = highlight
 4663                                .range
 4664                                .end
 4665                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4666                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4667                                continue;
 4668                            }
 4669
 4670                            let range = Anchor {
 4671                                buffer_id,
 4672                                excerpt_id,
 4673                                text_anchor: start,
 4674                                diff_base_anchor: None,
 4675                            }..Anchor {
 4676                                buffer_id,
 4677                                excerpt_id,
 4678                                text_anchor: end,
 4679                                diff_base_anchor: None,
 4680                            };
 4681                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4682                                write_ranges.push(range);
 4683                            } else {
 4684                                read_ranges.push(range);
 4685                            }
 4686                        }
 4687                    }
 4688
 4689                    this.highlight_background::<DocumentHighlightRead>(
 4690                        &read_ranges,
 4691                        |theme| theme.editor_document_highlight_read_background,
 4692                        cx,
 4693                    );
 4694                    this.highlight_background::<DocumentHighlightWrite>(
 4695                        &write_ranges,
 4696                        |theme| theme.editor_document_highlight_write_background,
 4697                        cx,
 4698                    );
 4699                    cx.notify();
 4700                })
 4701                .log_err();
 4702            }
 4703        }));
 4704        None
 4705    }
 4706
 4707    pub fn refresh_inline_completion(
 4708        &mut self,
 4709        debounce: bool,
 4710        user_requested: bool,
 4711        window: &mut Window,
 4712        cx: &mut Context<Self>,
 4713    ) -> Option<()> {
 4714        let provider = self.inline_completion_provider()?;
 4715        let cursor = self.selections.newest_anchor().head();
 4716        let (buffer, cursor_buffer_position) =
 4717            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4718
 4719        if !user_requested
 4720            && (!self.enable_inline_completions
 4721                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4722                || !self.is_focused(window)
 4723                || buffer.read(cx).is_empty())
 4724        {
 4725            self.discard_inline_completion(false, cx);
 4726            return None;
 4727        }
 4728
 4729        self.update_visible_inline_completion(window, cx);
 4730        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4731        Some(())
 4732    }
 4733
 4734    fn cycle_inline_completion(
 4735        &mut self,
 4736        direction: Direction,
 4737        window: &mut Window,
 4738        cx: &mut Context<Self>,
 4739    ) -> Option<()> {
 4740        let provider = self.inline_completion_provider()?;
 4741        let cursor = self.selections.newest_anchor().head();
 4742        let (buffer, cursor_buffer_position) =
 4743            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4744        if !self.enable_inline_completions
 4745            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4746        {
 4747            return None;
 4748        }
 4749
 4750        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4751        self.update_visible_inline_completion(window, cx);
 4752
 4753        Some(())
 4754    }
 4755
 4756    pub fn show_inline_completion(
 4757        &mut self,
 4758        _: &ShowInlineCompletion,
 4759        window: &mut Window,
 4760        cx: &mut Context<Self>,
 4761    ) {
 4762        if !self.inline_completions_enabled(cx) {
 4763            return;
 4764        }
 4765
 4766        if !self.has_active_inline_completion() {
 4767            self.refresh_inline_completion(false, true, window, cx);
 4768            return;
 4769        }
 4770
 4771        self.update_visible_inline_completion(window, cx);
 4772    }
 4773
 4774    pub fn display_cursor_names(
 4775        &mut self,
 4776        _: &DisplayCursorNames,
 4777        window: &mut Window,
 4778        cx: &mut Context<Self>,
 4779    ) {
 4780        self.show_cursor_names(window, cx);
 4781    }
 4782
 4783    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4784        self.show_cursor_names = true;
 4785        cx.notify();
 4786        cx.spawn_in(window, |this, mut cx| async move {
 4787            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4788            this.update(&mut cx, |this, cx| {
 4789                this.show_cursor_names = false;
 4790                cx.notify()
 4791            })
 4792            .ok()
 4793        })
 4794        .detach();
 4795    }
 4796
 4797    pub fn next_inline_completion(
 4798        &mut self,
 4799        _: &NextInlineCompletion,
 4800        window: &mut Window,
 4801        cx: &mut Context<Self>,
 4802    ) {
 4803        if self.has_active_inline_completion() {
 4804            self.cycle_inline_completion(Direction::Next, window, cx);
 4805        } else {
 4806            let is_copilot_disabled = self
 4807                .refresh_inline_completion(false, true, window, cx)
 4808                .is_none();
 4809            if is_copilot_disabled {
 4810                cx.propagate();
 4811            }
 4812        }
 4813    }
 4814
 4815    pub fn previous_inline_completion(
 4816        &mut self,
 4817        _: &PreviousInlineCompletion,
 4818        window: &mut Window,
 4819        cx: &mut Context<Self>,
 4820    ) {
 4821        if self.has_active_inline_completion() {
 4822            self.cycle_inline_completion(Direction::Prev, window, cx);
 4823        } else {
 4824            let is_copilot_disabled = self
 4825                .refresh_inline_completion(false, true, window, cx)
 4826                .is_none();
 4827            if is_copilot_disabled {
 4828                cx.propagate();
 4829            }
 4830        }
 4831    }
 4832
 4833    pub fn accept_inline_completion(
 4834        &mut self,
 4835        _: &AcceptInlineCompletion,
 4836        window: &mut Window,
 4837        cx: &mut Context<Self>,
 4838    ) {
 4839        let buffer = self.buffer.read(cx);
 4840        let snapshot = buffer.snapshot(cx);
 4841        let selection = self.selections.newest_adjusted(cx);
 4842        let cursor = selection.head();
 4843        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4844        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4845        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4846        {
 4847            if cursor.column < suggested_indent.len
 4848                && cursor.column <= current_indent.len
 4849                && current_indent.len <= suggested_indent.len
 4850            {
 4851                self.tab(&Default::default(), window, cx);
 4852                return;
 4853            }
 4854        }
 4855
 4856        if self.show_inline_completions_in_menu(cx) {
 4857            self.hide_context_menu(window, cx);
 4858        }
 4859
 4860        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4861            return;
 4862        };
 4863
 4864        self.report_inline_completion_event(true, cx);
 4865
 4866        match &active_inline_completion.completion {
 4867            InlineCompletion::Move(position) => {
 4868                let position = *position;
 4869                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4870                    selections.select_anchor_ranges([position..position]);
 4871                });
 4872            }
 4873            InlineCompletion::Edit { edits, .. } => {
 4874                if let Some(provider) = self.inline_completion_provider() {
 4875                    provider.accept(cx);
 4876                }
 4877
 4878                let snapshot = self.buffer.read(cx).snapshot(cx);
 4879                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4880
 4881                self.buffer.update(cx, |buffer, cx| {
 4882                    buffer.edit(edits.iter().cloned(), None, cx)
 4883                });
 4884
 4885                self.change_selections(None, window, cx, |s| {
 4886                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4887                });
 4888
 4889                self.update_visible_inline_completion(window, cx);
 4890                if self.active_inline_completion.is_none() {
 4891                    self.refresh_inline_completion(true, true, window, cx);
 4892                }
 4893
 4894                cx.notify();
 4895            }
 4896        }
 4897    }
 4898
 4899    pub fn accept_partial_inline_completion(
 4900        &mut self,
 4901        _: &AcceptPartialInlineCompletion,
 4902        window: &mut Window,
 4903        cx: &mut Context<Self>,
 4904    ) {
 4905        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4906            return;
 4907        };
 4908        if self.selections.count() != 1 {
 4909            return;
 4910        }
 4911
 4912        self.report_inline_completion_event(true, cx);
 4913
 4914        match &active_inline_completion.completion {
 4915            InlineCompletion::Move(position) => {
 4916                let position = *position;
 4917                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4918                    selections.select_anchor_ranges([position..position]);
 4919                });
 4920            }
 4921            InlineCompletion::Edit { edits, .. } => {
 4922                // Find an insertion that starts at the cursor position.
 4923                let snapshot = self.buffer.read(cx).snapshot(cx);
 4924                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4925                let insertion = edits.iter().find_map(|(range, text)| {
 4926                    let range = range.to_offset(&snapshot);
 4927                    if range.is_empty() && range.start == cursor_offset {
 4928                        Some(text)
 4929                    } else {
 4930                        None
 4931                    }
 4932                });
 4933
 4934                if let Some(text) = insertion {
 4935                    let mut partial_completion = text
 4936                        .chars()
 4937                        .by_ref()
 4938                        .take_while(|c| c.is_alphabetic())
 4939                        .collect::<String>();
 4940                    if partial_completion.is_empty() {
 4941                        partial_completion = text
 4942                            .chars()
 4943                            .by_ref()
 4944                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4945                            .collect::<String>();
 4946                    }
 4947
 4948                    cx.emit(EditorEvent::InputHandled {
 4949                        utf16_range_to_replace: None,
 4950                        text: partial_completion.clone().into(),
 4951                    });
 4952
 4953                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4954
 4955                    self.refresh_inline_completion(true, true, window, cx);
 4956                    cx.notify();
 4957                } else {
 4958                    self.accept_inline_completion(&Default::default(), window, cx);
 4959                }
 4960            }
 4961        }
 4962    }
 4963
 4964    fn discard_inline_completion(
 4965        &mut self,
 4966        should_report_inline_completion_event: bool,
 4967        cx: &mut Context<Self>,
 4968    ) -> bool {
 4969        if should_report_inline_completion_event {
 4970            self.report_inline_completion_event(false, cx);
 4971        }
 4972
 4973        if let Some(provider) = self.inline_completion_provider() {
 4974            provider.discard(cx);
 4975        }
 4976
 4977        self.take_active_inline_completion(cx).is_some()
 4978    }
 4979
 4980    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4981        let Some(provider) = self.inline_completion_provider() else {
 4982            return;
 4983        };
 4984
 4985        let Some((_, buffer, _)) = self
 4986            .buffer
 4987            .read(cx)
 4988            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4989        else {
 4990            return;
 4991        };
 4992
 4993        let extension = buffer
 4994            .read(cx)
 4995            .file()
 4996            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4997
 4998        let event_type = match accepted {
 4999            true => "Inline Completion Accepted",
 5000            false => "Inline Completion Discarded",
 5001        };
 5002        telemetry::event!(
 5003            event_type,
 5004            provider = provider.name(),
 5005            suggestion_accepted = accepted,
 5006            file_extension = extension,
 5007        );
 5008    }
 5009
 5010    pub fn has_active_inline_completion(&self) -> bool {
 5011        self.active_inline_completion.is_some()
 5012    }
 5013
 5014    fn take_active_inline_completion(
 5015        &mut self,
 5016        cx: &mut Context<Self>,
 5017    ) -> Option<InlineCompletion> {
 5018        let active_inline_completion = self.active_inline_completion.take()?;
 5019        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 5020        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5021        Some(active_inline_completion.completion)
 5022    }
 5023
 5024    fn update_visible_inline_completion(
 5025        &mut self,
 5026        window: &mut Window,
 5027        cx: &mut Context<Self>,
 5028    ) -> Option<()> {
 5029        let selection = self.selections.newest_anchor();
 5030        let cursor = selection.head();
 5031        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5032        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5033        let excerpt_id = cursor.excerpt_id;
 5034
 5035        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 5036            && (self.context_menu.borrow().is_some()
 5037                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5038        if completions_menu_has_precedence
 5039            || !offset_selection.is_empty()
 5040            || !self.enable_inline_completions
 5041            || self
 5042                .active_inline_completion
 5043                .as_ref()
 5044                .map_or(false, |completion| {
 5045                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5046                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5047                    !invalidation_range.contains(&offset_selection.head())
 5048                })
 5049        {
 5050            self.discard_inline_completion(false, cx);
 5051            return None;
 5052        }
 5053
 5054        self.take_active_inline_completion(cx);
 5055        let provider = self.inline_completion_provider()?;
 5056
 5057        let (buffer, cursor_buffer_position) =
 5058            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5059
 5060        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5061        let edits = inline_completion
 5062            .edits
 5063            .into_iter()
 5064            .flat_map(|(range, new_text)| {
 5065                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5066                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5067                Some((start..end, new_text))
 5068            })
 5069            .collect::<Vec<_>>();
 5070        if edits.is_empty() {
 5071            return None;
 5072        }
 5073
 5074        let first_edit_start = edits.first().unwrap().0.start;
 5075        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5076        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5077
 5078        let last_edit_end = edits.last().unwrap().0.end;
 5079        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5080        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5081
 5082        let cursor_row = cursor.to_point(&multibuffer).row;
 5083
 5084        let mut inlay_ids = Vec::new();
 5085        let invalidation_row_range;
 5086        let completion = if cursor_row < edit_start_row {
 5087            invalidation_row_range = cursor_row..edit_end_row;
 5088            InlineCompletion::Move(first_edit_start)
 5089        } else if cursor_row > edit_end_row {
 5090            invalidation_row_range = edit_start_row..cursor_row;
 5091            InlineCompletion::Move(first_edit_start)
 5092        } else {
 5093            if edits
 5094                .iter()
 5095                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5096            {
 5097                let mut inlays = Vec::new();
 5098                for (range, new_text) in &edits {
 5099                    let inlay = Inlay::inline_completion(
 5100                        post_inc(&mut self.next_inlay_id),
 5101                        range.start,
 5102                        new_text.as_str(),
 5103                    );
 5104                    inlay_ids.push(inlay.id);
 5105                    inlays.push(inlay);
 5106                }
 5107
 5108                self.splice_inlays(vec![], inlays, cx);
 5109            } else {
 5110                let background_color = cx.theme().status().deleted_background;
 5111                self.highlight_text::<InlineCompletionHighlight>(
 5112                    edits.iter().map(|(range, _)| range.clone()).collect(),
 5113                    HighlightStyle {
 5114                        background_color: Some(background_color),
 5115                        ..Default::default()
 5116                    },
 5117                    cx,
 5118                );
 5119            }
 5120
 5121            invalidation_row_range = edit_start_row..edit_end_row;
 5122
 5123            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5124                if provider.show_tab_accept_marker()
 5125                    && first_edit_start_point.row == last_edit_end_point.row
 5126                    && !edits.iter().any(|(_, edit)| edit.contains('\n'))
 5127                {
 5128                    EditDisplayMode::TabAccept
 5129                } else {
 5130                    EditDisplayMode::Inline
 5131                }
 5132            } else {
 5133                EditDisplayMode::DiffPopover
 5134            };
 5135
 5136            let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5137
 5138            InlineCompletion::Edit {
 5139                edits,
 5140                edit_preview: inline_completion.edit_preview,
 5141                display_mode,
 5142                snapshot,
 5143            }
 5144        };
 5145
 5146        let invalidation_range = multibuffer
 5147            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5148            ..multibuffer.anchor_after(Point::new(
 5149                invalidation_row_range.end,
 5150                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5151            ));
 5152
 5153        self.active_inline_completion = Some(InlineCompletionState {
 5154            inlay_ids,
 5155            completion,
 5156            invalidation_range,
 5157        });
 5158
 5159        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 5160            if let Some(hint) = self.inline_completion_menu_hint(window, cx) {
 5161                match self.context_menu.borrow_mut().as_mut() {
 5162                    Some(CodeContextMenu::Completions(menu)) => {
 5163                        menu.show_inline_completion_hint(hint);
 5164                    }
 5165                    _ => {}
 5166                }
 5167            }
 5168        }
 5169
 5170        cx.notify();
 5171
 5172        Some(())
 5173    }
 5174
 5175    fn inline_completion_menu_hint(
 5176        &self,
 5177        window: &mut Window,
 5178        cx: &mut Context<Self>,
 5179    ) -> Option<InlineCompletionMenuHint> {
 5180        let provider = self.inline_completion_provider()?;
 5181        if self.has_active_inline_completion() {
 5182            let editor_snapshot = self.snapshot(window, cx);
 5183
 5184            let text = match &self.active_inline_completion.as_ref()?.completion {
 5185                InlineCompletion::Edit {
 5186                    edits,
 5187                    edit_preview,
 5188                    display_mode: _,
 5189                    snapshot,
 5190                } => edit_preview
 5191                    .as_ref()
 5192                    .and_then(|edit_preview| {
 5193                        inline_completion_edit_text(&snapshot, &edits, edit_preview, true, cx)
 5194                    })
 5195                    .map(InlineCompletionText::Edit),
 5196                InlineCompletion::Move(target) => {
 5197                    let target_point =
 5198                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 5199                    let target_line = target_point.row + 1;
 5200                    Some(InlineCompletionText::Move(
 5201                        format!("Jump to edit in line {}", target_line).into(),
 5202                    ))
 5203                }
 5204            };
 5205
 5206            Some(InlineCompletionMenuHint::Loaded { text: text? })
 5207        } else if provider.is_refreshing(cx) {
 5208            Some(InlineCompletionMenuHint::Loading)
 5209        } else if provider.needs_terms_acceptance(cx) {
 5210            Some(InlineCompletionMenuHint::PendingTermsAcceptance)
 5211        } else {
 5212            Some(InlineCompletionMenuHint::None)
 5213        }
 5214    }
 5215
 5216    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5217        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5218    }
 5219
 5220    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5221        let by_provider = matches!(
 5222            self.menu_inline_completions_policy,
 5223            MenuInlineCompletionsPolicy::ByProvider
 5224        );
 5225
 5226        by_provider
 5227            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5228            && self
 5229                .inline_completion_provider()
 5230                .map_or(false, |provider| provider.show_completions_in_menu())
 5231    }
 5232
 5233    fn render_code_actions_indicator(
 5234        &self,
 5235        _style: &EditorStyle,
 5236        row: DisplayRow,
 5237        is_active: bool,
 5238        cx: &mut Context<Self>,
 5239    ) -> Option<IconButton> {
 5240        if self.available_code_actions.is_some() {
 5241            Some(
 5242                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5243                    .shape(ui::IconButtonShape::Square)
 5244                    .icon_size(IconSize::XSmall)
 5245                    .icon_color(Color::Muted)
 5246                    .toggle_state(is_active)
 5247                    .tooltip({
 5248                        let focus_handle = self.focus_handle.clone();
 5249                        move |window, cx| {
 5250                            Tooltip::for_action_in(
 5251                                "Toggle Code Actions",
 5252                                &ToggleCodeActions {
 5253                                    deployed_from_indicator: None,
 5254                                },
 5255                                &focus_handle,
 5256                                window,
 5257                                cx,
 5258                            )
 5259                        }
 5260                    })
 5261                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5262                        window.focus(&editor.focus_handle(cx));
 5263                        editor.toggle_code_actions(
 5264                            &ToggleCodeActions {
 5265                                deployed_from_indicator: Some(row),
 5266                            },
 5267                            window,
 5268                            cx,
 5269                        );
 5270                    })),
 5271            )
 5272        } else {
 5273            None
 5274        }
 5275    }
 5276
 5277    fn clear_tasks(&mut self) {
 5278        self.tasks.clear()
 5279    }
 5280
 5281    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5282        if self.tasks.insert(key, value).is_some() {
 5283            // This case should hopefully be rare, but just in case...
 5284            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5285        }
 5286    }
 5287
 5288    fn build_tasks_context(
 5289        project: &Entity<Project>,
 5290        buffer: &Entity<Buffer>,
 5291        buffer_row: u32,
 5292        tasks: &Arc<RunnableTasks>,
 5293        cx: &mut Context<Self>,
 5294    ) -> Task<Option<task::TaskContext>> {
 5295        let position = Point::new(buffer_row, tasks.column);
 5296        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5297        let location = Location {
 5298            buffer: buffer.clone(),
 5299            range: range_start..range_start,
 5300        };
 5301        // Fill in the environmental variables from the tree-sitter captures
 5302        let mut captured_task_variables = TaskVariables::default();
 5303        for (capture_name, value) in tasks.extra_variables.clone() {
 5304            captured_task_variables.insert(
 5305                task::VariableName::Custom(capture_name.into()),
 5306                value.clone(),
 5307            );
 5308        }
 5309        project.update(cx, |project, cx| {
 5310            project.task_store().update(cx, |task_store, cx| {
 5311                task_store.task_context_for_location(captured_task_variables, location, cx)
 5312            })
 5313        })
 5314    }
 5315
 5316    pub fn spawn_nearest_task(
 5317        &mut self,
 5318        action: &SpawnNearestTask,
 5319        window: &mut Window,
 5320        cx: &mut Context<Self>,
 5321    ) {
 5322        let Some((workspace, _)) = self.workspace.clone() else {
 5323            return;
 5324        };
 5325        let Some(project) = self.project.clone() else {
 5326            return;
 5327        };
 5328
 5329        // Try to find a closest, enclosing node using tree-sitter that has a
 5330        // task
 5331        let Some((buffer, buffer_row, tasks)) = self
 5332            .find_enclosing_node_task(cx)
 5333            // Or find the task that's closest in row-distance.
 5334            .or_else(|| self.find_closest_task(cx))
 5335        else {
 5336            return;
 5337        };
 5338
 5339        let reveal_strategy = action.reveal;
 5340        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5341        cx.spawn_in(window, |_, mut cx| async move {
 5342            let context = task_context.await?;
 5343            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5344
 5345            let resolved = resolved_task.resolved.as_mut()?;
 5346            resolved.reveal = reveal_strategy;
 5347
 5348            workspace
 5349                .update(&mut cx, |workspace, cx| {
 5350                    workspace::tasks::schedule_resolved_task(
 5351                        workspace,
 5352                        task_source_kind,
 5353                        resolved_task,
 5354                        false,
 5355                        cx,
 5356                    );
 5357                })
 5358                .ok()
 5359        })
 5360        .detach();
 5361    }
 5362
 5363    fn find_closest_task(
 5364        &mut self,
 5365        cx: &mut Context<Self>,
 5366    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5367        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5368
 5369        let ((buffer_id, row), tasks) = self
 5370            .tasks
 5371            .iter()
 5372            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5373
 5374        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5375        let tasks = Arc::new(tasks.to_owned());
 5376        Some((buffer, *row, tasks))
 5377    }
 5378
 5379    fn find_enclosing_node_task(
 5380        &mut self,
 5381        cx: &mut Context<Self>,
 5382    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5383        let snapshot = self.buffer.read(cx).snapshot(cx);
 5384        let offset = self.selections.newest::<usize>(cx).head();
 5385        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5386        let buffer_id = excerpt.buffer().remote_id();
 5387
 5388        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5389        let mut cursor = layer.node().walk();
 5390
 5391        while cursor.goto_first_child_for_byte(offset).is_some() {
 5392            if cursor.node().end_byte() == offset {
 5393                cursor.goto_next_sibling();
 5394            }
 5395        }
 5396
 5397        // Ascend to the smallest ancestor that contains the range and has a task.
 5398        loop {
 5399            let node = cursor.node();
 5400            let node_range = node.byte_range();
 5401            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5402
 5403            // Check if this node contains our offset
 5404            if node_range.start <= offset && node_range.end >= offset {
 5405                // If it contains offset, check for task
 5406                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5407                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5408                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5409                }
 5410            }
 5411
 5412            if !cursor.goto_parent() {
 5413                break;
 5414            }
 5415        }
 5416        None
 5417    }
 5418
 5419    fn render_run_indicator(
 5420        &self,
 5421        _style: &EditorStyle,
 5422        is_active: bool,
 5423        row: DisplayRow,
 5424        cx: &mut Context<Self>,
 5425    ) -> IconButton {
 5426        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5427            .shape(ui::IconButtonShape::Square)
 5428            .icon_size(IconSize::XSmall)
 5429            .icon_color(Color::Muted)
 5430            .toggle_state(is_active)
 5431            .on_click(cx.listener(move |editor, _e, window, cx| {
 5432                window.focus(&editor.focus_handle(cx));
 5433                editor.toggle_code_actions(
 5434                    &ToggleCodeActions {
 5435                        deployed_from_indicator: Some(row),
 5436                    },
 5437                    window,
 5438                    cx,
 5439                );
 5440            }))
 5441    }
 5442
 5443    #[cfg(any(test, feature = "test-support"))]
 5444    pub fn context_menu_visible(&self) -> bool {
 5445        self.context_menu
 5446            .borrow()
 5447            .as_ref()
 5448            .map_or(false, |menu| menu.visible())
 5449    }
 5450
 5451    #[cfg(feature = "test-support")]
 5452    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5453        self.context_menu
 5454            .borrow()
 5455            .as_ref()
 5456            .map_or(false, |menu| match menu {
 5457                CodeContextMenu::Completions(menu) => {
 5458                    menu.entries.borrow().first().map_or(false, |entry| {
 5459                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5460                    })
 5461                }
 5462                CodeContextMenu::CodeActions(_) => false,
 5463            })
 5464    }
 5465
 5466    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5467        self.context_menu
 5468            .borrow()
 5469            .as_ref()
 5470            .map(|menu| menu.origin(cursor_position))
 5471    }
 5472
 5473    fn render_context_menu(
 5474        &self,
 5475        style: &EditorStyle,
 5476        max_height_in_lines: u32,
 5477        y_flipped: bool,
 5478        window: &mut Window,
 5479        cx: &mut Context<Editor>,
 5480    ) -> Option<AnyElement> {
 5481        self.context_menu.borrow().as_ref().and_then(|menu| {
 5482            if menu.visible() {
 5483                Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5484            } else {
 5485                None
 5486            }
 5487        })
 5488    }
 5489
 5490    fn render_context_menu_aside(
 5491        &self,
 5492        style: &EditorStyle,
 5493        max_size: Size<Pixels>,
 5494        cx: &mut Context<Editor>,
 5495    ) -> Option<AnyElement> {
 5496        self.context_menu.borrow().as_ref().and_then(|menu| {
 5497            if menu.visible() {
 5498                menu.render_aside(
 5499                    style,
 5500                    max_size,
 5501                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5502                    cx,
 5503                )
 5504            } else {
 5505                None
 5506            }
 5507        })
 5508    }
 5509
 5510    fn hide_context_menu(
 5511        &mut self,
 5512        window: &mut Window,
 5513        cx: &mut Context<Self>,
 5514    ) -> Option<CodeContextMenu> {
 5515        cx.notify();
 5516        self.completion_tasks.clear();
 5517        let context_menu = self.context_menu.borrow_mut().take();
 5518        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5519            self.update_visible_inline_completion(window, cx);
 5520        }
 5521        context_menu
 5522    }
 5523
 5524    fn show_snippet_choices(
 5525        &mut self,
 5526        choices: &Vec<String>,
 5527        selection: Range<Anchor>,
 5528        cx: &mut Context<Self>,
 5529    ) {
 5530        if selection.start.buffer_id.is_none() {
 5531            return;
 5532        }
 5533        let buffer_id = selection.start.buffer_id.unwrap();
 5534        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5535        let id = post_inc(&mut self.next_completion_id);
 5536
 5537        if let Some(buffer) = buffer {
 5538            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5539                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5540            ));
 5541        }
 5542    }
 5543
 5544    pub fn insert_snippet(
 5545        &mut self,
 5546        insertion_ranges: &[Range<usize>],
 5547        snippet: Snippet,
 5548        window: &mut Window,
 5549        cx: &mut Context<Self>,
 5550    ) -> Result<()> {
 5551        struct Tabstop<T> {
 5552            is_end_tabstop: bool,
 5553            ranges: Vec<Range<T>>,
 5554            choices: Option<Vec<String>>,
 5555        }
 5556
 5557        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5558            let snippet_text: Arc<str> = snippet.text.clone().into();
 5559            buffer.edit(
 5560                insertion_ranges
 5561                    .iter()
 5562                    .cloned()
 5563                    .map(|range| (range, snippet_text.clone())),
 5564                Some(AutoindentMode::EachLine),
 5565                cx,
 5566            );
 5567
 5568            let snapshot = &*buffer.read(cx);
 5569            let snippet = &snippet;
 5570            snippet
 5571                .tabstops
 5572                .iter()
 5573                .map(|tabstop| {
 5574                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5575                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5576                    });
 5577                    let mut tabstop_ranges = tabstop
 5578                        .ranges
 5579                        .iter()
 5580                        .flat_map(|tabstop_range| {
 5581                            let mut delta = 0_isize;
 5582                            insertion_ranges.iter().map(move |insertion_range| {
 5583                                let insertion_start = insertion_range.start as isize + delta;
 5584                                delta +=
 5585                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5586
 5587                                let start = ((insertion_start + tabstop_range.start) as usize)
 5588                                    .min(snapshot.len());
 5589                                let end = ((insertion_start + tabstop_range.end) as usize)
 5590                                    .min(snapshot.len());
 5591                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5592                            })
 5593                        })
 5594                        .collect::<Vec<_>>();
 5595                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5596
 5597                    Tabstop {
 5598                        is_end_tabstop,
 5599                        ranges: tabstop_ranges,
 5600                        choices: tabstop.choices.clone(),
 5601                    }
 5602                })
 5603                .collect::<Vec<_>>()
 5604        });
 5605        if let Some(tabstop) = tabstops.first() {
 5606            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5607                s.select_ranges(tabstop.ranges.iter().cloned());
 5608            });
 5609
 5610            if let Some(choices) = &tabstop.choices {
 5611                if let Some(selection) = tabstop.ranges.first() {
 5612                    self.show_snippet_choices(choices, selection.clone(), cx)
 5613                }
 5614            }
 5615
 5616            // If we're already at the last tabstop and it's at the end of the snippet,
 5617            // we're done, we don't need to keep the state around.
 5618            if !tabstop.is_end_tabstop {
 5619                let choices = tabstops
 5620                    .iter()
 5621                    .map(|tabstop| tabstop.choices.clone())
 5622                    .collect();
 5623
 5624                let ranges = tabstops
 5625                    .into_iter()
 5626                    .map(|tabstop| tabstop.ranges)
 5627                    .collect::<Vec<_>>();
 5628
 5629                self.snippet_stack.push(SnippetState {
 5630                    active_index: 0,
 5631                    ranges,
 5632                    choices,
 5633                });
 5634            }
 5635
 5636            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5637            if self.autoclose_regions.is_empty() {
 5638                let snapshot = self.buffer.read(cx).snapshot(cx);
 5639                for selection in &mut self.selections.all::<Point>(cx) {
 5640                    let selection_head = selection.head();
 5641                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5642                        continue;
 5643                    };
 5644
 5645                    let mut bracket_pair = None;
 5646                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5647                    let prev_chars = snapshot
 5648                        .reversed_chars_at(selection_head)
 5649                        .collect::<String>();
 5650                    for (pair, enabled) in scope.brackets() {
 5651                        if enabled
 5652                            && pair.close
 5653                            && prev_chars.starts_with(pair.start.as_str())
 5654                            && next_chars.starts_with(pair.end.as_str())
 5655                        {
 5656                            bracket_pair = Some(pair.clone());
 5657                            break;
 5658                        }
 5659                    }
 5660                    if let Some(pair) = bracket_pair {
 5661                        let start = snapshot.anchor_after(selection_head);
 5662                        let end = snapshot.anchor_after(selection_head);
 5663                        self.autoclose_regions.push(AutocloseRegion {
 5664                            selection_id: selection.id,
 5665                            range: start..end,
 5666                            pair,
 5667                        });
 5668                    }
 5669                }
 5670            }
 5671        }
 5672        Ok(())
 5673    }
 5674
 5675    pub fn move_to_next_snippet_tabstop(
 5676        &mut self,
 5677        window: &mut Window,
 5678        cx: &mut Context<Self>,
 5679    ) -> bool {
 5680        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5681    }
 5682
 5683    pub fn move_to_prev_snippet_tabstop(
 5684        &mut self,
 5685        window: &mut Window,
 5686        cx: &mut Context<Self>,
 5687    ) -> bool {
 5688        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5689    }
 5690
 5691    pub fn move_to_snippet_tabstop(
 5692        &mut self,
 5693        bias: Bias,
 5694        window: &mut Window,
 5695        cx: &mut Context<Self>,
 5696    ) -> bool {
 5697        if let Some(mut snippet) = self.snippet_stack.pop() {
 5698            match bias {
 5699                Bias::Left => {
 5700                    if snippet.active_index > 0 {
 5701                        snippet.active_index -= 1;
 5702                    } else {
 5703                        self.snippet_stack.push(snippet);
 5704                        return false;
 5705                    }
 5706                }
 5707                Bias::Right => {
 5708                    if snippet.active_index + 1 < snippet.ranges.len() {
 5709                        snippet.active_index += 1;
 5710                    } else {
 5711                        self.snippet_stack.push(snippet);
 5712                        return false;
 5713                    }
 5714                }
 5715            }
 5716            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5717                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5718                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5719                });
 5720
 5721                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5722                    if let Some(selection) = current_ranges.first() {
 5723                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5724                    }
 5725                }
 5726
 5727                // If snippet state is not at the last tabstop, push it back on the stack
 5728                if snippet.active_index + 1 < snippet.ranges.len() {
 5729                    self.snippet_stack.push(snippet);
 5730                }
 5731                return true;
 5732            }
 5733        }
 5734
 5735        false
 5736    }
 5737
 5738    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5739        self.transact(window, cx, |this, window, cx| {
 5740            this.select_all(&SelectAll, window, cx);
 5741            this.insert("", window, cx);
 5742        });
 5743    }
 5744
 5745    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 5746        self.transact(window, cx, |this, window, cx| {
 5747            this.select_autoclose_pair(window, cx);
 5748            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5749            if !this.linked_edit_ranges.is_empty() {
 5750                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5751                let snapshot = this.buffer.read(cx).snapshot(cx);
 5752
 5753                for selection in selections.iter() {
 5754                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5755                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5756                    if selection_start.buffer_id != selection_end.buffer_id {
 5757                        continue;
 5758                    }
 5759                    if let Some(ranges) =
 5760                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5761                    {
 5762                        for (buffer, entries) in ranges {
 5763                            linked_ranges.entry(buffer).or_default().extend(entries);
 5764                        }
 5765                    }
 5766                }
 5767            }
 5768
 5769            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5770            if !this.selections.line_mode {
 5771                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5772                for selection in &mut selections {
 5773                    if selection.is_empty() {
 5774                        let old_head = selection.head();
 5775                        let mut new_head =
 5776                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5777                                .to_point(&display_map);
 5778                        if let Some((buffer, line_buffer_range)) = display_map
 5779                            .buffer_snapshot
 5780                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5781                        {
 5782                            let indent_size =
 5783                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5784                            let indent_len = match indent_size.kind {
 5785                                IndentKind::Space => {
 5786                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5787                                }
 5788                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5789                            };
 5790                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5791                                let indent_len = indent_len.get();
 5792                                new_head = cmp::min(
 5793                                    new_head,
 5794                                    MultiBufferPoint::new(
 5795                                        old_head.row,
 5796                                        ((old_head.column - 1) / indent_len) * indent_len,
 5797                                    ),
 5798                                );
 5799                            }
 5800                        }
 5801
 5802                        selection.set_head(new_head, SelectionGoal::None);
 5803                    }
 5804                }
 5805            }
 5806
 5807            this.signature_help_state.set_backspace_pressed(true);
 5808            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5809                s.select(selections)
 5810            });
 5811            this.insert("", window, cx);
 5812            let empty_str: Arc<str> = Arc::from("");
 5813            for (buffer, edits) in linked_ranges {
 5814                let snapshot = buffer.read(cx).snapshot();
 5815                use text::ToPoint as TP;
 5816
 5817                let edits = edits
 5818                    .into_iter()
 5819                    .map(|range| {
 5820                        let end_point = TP::to_point(&range.end, &snapshot);
 5821                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5822
 5823                        if end_point == start_point {
 5824                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5825                                .saturating_sub(1);
 5826                            start_point =
 5827                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5828                        };
 5829
 5830                        (start_point..end_point, empty_str.clone())
 5831                    })
 5832                    .sorted_by_key(|(range, _)| range.start)
 5833                    .collect::<Vec<_>>();
 5834                buffer.update(cx, |this, cx| {
 5835                    this.edit(edits, None, cx);
 5836                })
 5837            }
 5838            this.refresh_inline_completion(true, false, window, cx);
 5839            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 5840        });
 5841    }
 5842
 5843    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 5844        self.transact(window, cx, |this, window, cx| {
 5845            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5846                let line_mode = s.line_mode;
 5847                s.move_with(|map, selection| {
 5848                    if selection.is_empty() && !line_mode {
 5849                        let cursor = movement::right(map, selection.head());
 5850                        selection.end = cursor;
 5851                        selection.reversed = true;
 5852                        selection.goal = SelectionGoal::None;
 5853                    }
 5854                })
 5855            });
 5856            this.insert("", window, cx);
 5857            this.refresh_inline_completion(true, false, window, cx);
 5858        });
 5859    }
 5860
 5861    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 5862        if self.move_to_prev_snippet_tabstop(window, cx) {
 5863            return;
 5864        }
 5865
 5866        self.outdent(&Outdent, window, cx);
 5867    }
 5868
 5869    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 5870        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 5871            return;
 5872        }
 5873
 5874        let mut selections = self.selections.all_adjusted(cx);
 5875        let buffer = self.buffer.read(cx);
 5876        let snapshot = buffer.snapshot(cx);
 5877        let rows_iter = selections.iter().map(|s| s.head().row);
 5878        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5879
 5880        let mut edits = Vec::new();
 5881        let mut prev_edited_row = 0;
 5882        let mut row_delta = 0;
 5883        for selection in &mut selections {
 5884            if selection.start.row != prev_edited_row {
 5885                row_delta = 0;
 5886            }
 5887            prev_edited_row = selection.end.row;
 5888
 5889            // If the selection is non-empty, then increase the indentation of the selected lines.
 5890            if !selection.is_empty() {
 5891                row_delta =
 5892                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5893                continue;
 5894            }
 5895
 5896            // If the selection is empty and the cursor is in the leading whitespace before the
 5897            // suggested indentation, then auto-indent the line.
 5898            let cursor = selection.head();
 5899            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5900            if let Some(suggested_indent) =
 5901                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5902            {
 5903                if cursor.column < suggested_indent.len
 5904                    && cursor.column <= current_indent.len
 5905                    && current_indent.len <= suggested_indent.len
 5906                {
 5907                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5908                    selection.end = selection.start;
 5909                    if row_delta == 0 {
 5910                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5911                            cursor.row,
 5912                            current_indent,
 5913                            suggested_indent,
 5914                        ));
 5915                        row_delta = suggested_indent.len - current_indent.len;
 5916                    }
 5917                    continue;
 5918                }
 5919            }
 5920
 5921            // Otherwise, insert a hard or soft tab.
 5922            let settings = buffer.settings_at(cursor, cx);
 5923            let tab_size = if settings.hard_tabs {
 5924                IndentSize::tab()
 5925            } else {
 5926                let tab_size = settings.tab_size.get();
 5927                let char_column = snapshot
 5928                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5929                    .flat_map(str::chars)
 5930                    .count()
 5931                    + row_delta as usize;
 5932                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5933                IndentSize::spaces(chars_to_next_tab_stop)
 5934            };
 5935            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5936            selection.end = selection.start;
 5937            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5938            row_delta += tab_size.len;
 5939        }
 5940
 5941        self.transact(window, cx, |this, window, cx| {
 5942            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5943            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5944                s.select(selections)
 5945            });
 5946            this.refresh_inline_completion(true, false, window, cx);
 5947        });
 5948    }
 5949
 5950    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 5951        if self.read_only(cx) {
 5952            return;
 5953        }
 5954        let mut selections = self.selections.all::<Point>(cx);
 5955        let mut prev_edited_row = 0;
 5956        let mut row_delta = 0;
 5957        let mut edits = Vec::new();
 5958        let buffer = self.buffer.read(cx);
 5959        let snapshot = buffer.snapshot(cx);
 5960        for selection in &mut selections {
 5961            if selection.start.row != prev_edited_row {
 5962                row_delta = 0;
 5963            }
 5964            prev_edited_row = selection.end.row;
 5965
 5966            row_delta =
 5967                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5968        }
 5969
 5970        self.transact(window, cx, |this, window, cx| {
 5971            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5972            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5973                s.select(selections)
 5974            });
 5975        });
 5976    }
 5977
 5978    fn indent_selection(
 5979        buffer: &MultiBuffer,
 5980        snapshot: &MultiBufferSnapshot,
 5981        selection: &mut Selection<Point>,
 5982        edits: &mut Vec<(Range<Point>, String)>,
 5983        delta_for_start_row: u32,
 5984        cx: &App,
 5985    ) -> u32 {
 5986        let settings = buffer.settings_at(selection.start, cx);
 5987        let tab_size = settings.tab_size.get();
 5988        let indent_kind = if settings.hard_tabs {
 5989            IndentKind::Tab
 5990        } else {
 5991            IndentKind::Space
 5992        };
 5993        let mut start_row = selection.start.row;
 5994        let mut end_row = selection.end.row + 1;
 5995
 5996        // If a selection ends at the beginning of a line, don't indent
 5997        // that last line.
 5998        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5999            end_row -= 1;
 6000        }
 6001
 6002        // Avoid re-indenting a row that has already been indented by a
 6003        // previous selection, but still update this selection's column
 6004        // to reflect that indentation.
 6005        if delta_for_start_row > 0 {
 6006            start_row += 1;
 6007            selection.start.column += delta_for_start_row;
 6008            if selection.end.row == selection.start.row {
 6009                selection.end.column += delta_for_start_row;
 6010            }
 6011        }
 6012
 6013        let mut delta_for_end_row = 0;
 6014        let has_multiple_rows = start_row + 1 != end_row;
 6015        for row in start_row..end_row {
 6016            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6017            let indent_delta = match (current_indent.kind, indent_kind) {
 6018                (IndentKind::Space, IndentKind::Space) => {
 6019                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6020                    IndentSize::spaces(columns_to_next_tab_stop)
 6021                }
 6022                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6023                (_, IndentKind::Tab) => IndentSize::tab(),
 6024            };
 6025
 6026            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6027                0
 6028            } else {
 6029                selection.start.column
 6030            };
 6031            let row_start = Point::new(row, start);
 6032            edits.push((
 6033                row_start..row_start,
 6034                indent_delta.chars().collect::<String>(),
 6035            ));
 6036
 6037            // Update this selection's endpoints to reflect the indentation.
 6038            if row == selection.start.row {
 6039                selection.start.column += indent_delta.len;
 6040            }
 6041            if row == selection.end.row {
 6042                selection.end.column += indent_delta.len;
 6043                delta_for_end_row = indent_delta.len;
 6044            }
 6045        }
 6046
 6047        if selection.start.row == selection.end.row {
 6048            delta_for_start_row + delta_for_end_row
 6049        } else {
 6050            delta_for_end_row
 6051        }
 6052    }
 6053
 6054    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6055        if self.read_only(cx) {
 6056            return;
 6057        }
 6058        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6059        let selections = self.selections.all::<Point>(cx);
 6060        let mut deletion_ranges = Vec::new();
 6061        let mut last_outdent = None;
 6062        {
 6063            let buffer = self.buffer.read(cx);
 6064            let snapshot = buffer.snapshot(cx);
 6065            for selection in &selections {
 6066                let settings = buffer.settings_at(selection.start, cx);
 6067                let tab_size = settings.tab_size.get();
 6068                let mut rows = selection.spanned_rows(false, &display_map);
 6069
 6070                // Avoid re-outdenting a row that has already been outdented by a
 6071                // previous selection.
 6072                if let Some(last_row) = last_outdent {
 6073                    if last_row == rows.start {
 6074                        rows.start = rows.start.next_row();
 6075                    }
 6076                }
 6077                let has_multiple_rows = rows.len() > 1;
 6078                for row in rows.iter_rows() {
 6079                    let indent_size = snapshot.indent_size_for_line(row);
 6080                    if indent_size.len > 0 {
 6081                        let deletion_len = match indent_size.kind {
 6082                            IndentKind::Space => {
 6083                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6084                                if columns_to_prev_tab_stop == 0 {
 6085                                    tab_size
 6086                                } else {
 6087                                    columns_to_prev_tab_stop
 6088                                }
 6089                            }
 6090                            IndentKind::Tab => 1,
 6091                        };
 6092                        let start = if has_multiple_rows
 6093                            || deletion_len > selection.start.column
 6094                            || indent_size.len < selection.start.column
 6095                        {
 6096                            0
 6097                        } else {
 6098                            selection.start.column - deletion_len
 6099                        };
 6100                        deletion_ranges.push(
 6101                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6102                        );
 6103                        last_outdent = Some(row);
 6104                    }
 6105                }
 6106            }
 6107        }
 6108
 6109        self.transact(window, cx, |this, window, cx| {
 6110            this.buffer.update(cx, |buffer, cx| {
 6111                let empty_str: Arc<str> = Arc::default();
 6112                buffer.edit(
 6113                    deletion_ranges
 6114                        .into_iter()
 6115                        .map(|range| (range, empty_str.clone())),
 6116                    None,
 6117                    cx,
 6118                );
 6119            });
 6120            let selections = this.selections.all::<usize>(cx);
 6121            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6122                s.select(selections)
 6123            });
 6124        });
 6125    }
 6126
 6127    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6128        if self.read_only(cx) {
 6129            return;
 6130        }
 6131        let selections = self
 6132            .selections
 6133            .all::<usize>(cx)
 6134            .into_iter()
 6135            .map(|s| s.range());
 6136
 6137        self.transact(window, cx, |this, window, cx| {
 6138            this.buffer.update(cx, |buffer, cx| {
 6139                buffer.autoindent_ranges(selections, cx);
 6140            });
 6141            let selections = this.selections.all::<usize>(cx);
 6142            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6143                s.select(selections)
 6144            });
 6145        });
 6146    }
 6147
 6148    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6149        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6150        let selections = self.selections.all::<Point>(cx);
 6151
 6152        let mut new_cursors = Vec::new();
 6153        let mut edit_ranges = Vec::new();
 6154        let mut selections = selections.iter().peekable();
 6155        while let Some(selection) = selections.next() {
 6156            let mut rows = selection.spanned_rows(false, &display_map);
 6157            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6158
 6159            // Accumulate contiguous regions of rows that we want to delete.
 6160            while let Some(next_selection) = selections.peek() {
 6161                let next_rows = next_selection.spanned_rows(false, &display_map);
 6162                if next_rows.start <= rows.end {
 6163                    rows.end = next_rows.end;
 6164                    selections.next().unwrap();
 6165                } else {
 6166                    break;
 6167                }
 6168            }
 6169
 6170            let buffer = &display_map.buffer_snapshot;
 6171            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6172            let edit_end;
 6173            let cursor_buffer_row;
 6174            if buffer.max_point().row >= rows.end.0 {
 6175                // If there's a line after the range, delete the \n from the end of the row range
 6176                // and position the cursor on the next line.
 6177                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6178                cursor_buffer_row = rows.end;
 6179            } else {
 6180                // If there isn't a line after the range, delete the \n from the line before the
 6181                // start of the row range and position the cursor there.
 6182                edit_start = edit_start.saturating_sub(1);
 6183                edit_end = buffer.len();
 6184                cursor_buffer_row = rows.start.previous_row();
 6185            }
 6186
 6187            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6188            *cursor.column_mut() =
 6189                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6190
 6191            new_cursors.push((
 6192                selection.id,
 6193                buffer.anchor_after(cursor.to_point(&display_map)),
 6194            ));
 6195            edit_ranges.push(edit_start..edit_end);
 6196        }
 6197
 6198        self.transact(window, cx, |this, window, cx| {
 6199            let buffer = this.buffer.update(cx, |buffer, cx| {
 6200                let empty_str: Arc<str> = Arc::default();
 6201                buffer.edit(
 6202                    edit_ranges
 6203                        .into_iter()
 6204                        .map(|range| (range, empty_str.clone())),
 6205                    None,
 6206                    cx,
 6207                );
 6208                buffer.snapshot(cx)
 6209            });
 6210            let new_selections = new_cursors
 6211                .into_iter()
 6212                .map(|(id, cursor)| {
 6213                    let cursor = cursor.to_point(&buffer);
 6214                    Selection {
 6215                        id,
 6216                        start: cursor,
 6217                        end: cursor,
 6218                        reversed: false,
 6219                        goal: SelectionGoal::None,
 6220                    }
 6221                })
 6222                .collect();
 6223
 6224            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6225                s.select(new_selections);
 6226            });
 6227        });
 6228    }
 6229
 6230    pub fn join_lines_impl(
 6231        &mut self,
 6232        insert_whitespace: bool,
 6233        window: &mut Window,
 6234        cx: &mut Context<Self>,
 6235    ) {
 6236        if self.read_only(cx) {
 6237            return;
 6238        }
 6239        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6240        for selection in self.selections.all::<Point>(cx) {
 6241            let start = MultiBufferRow(selection.start.row);
 6242            // Treat single line selections as if they include the next line. Otherwise this action
 6243            // would do nothing for single line selections individual cursors.
 6244            let end = if selection.start.row == selection.end.row {
 6245                MultiBufferRow(selection.start.row + 1)
 6246            } else {
 6247                MultiBufferRow(selection.end.row)
 6248            };
 6249
 6250            if let Some(last_row_range) = row_ranges.last_mut() {
 6251                if start <= last_row_range.end {
 6252                    last_row_range.end = end;
 6253                    continue;
 6254                }
 6255            }
 6256            row_ranges.push(start..end);
 6257        }
 6258
 6259        let snapshot = self.buffer.read(cx).snapshot(cx);
 6260        let mut cursor_positions = Vec::new();
 6261        for row_range in &row_ranges {
 6262            let anchor = snapshot.anchor_before(Point::new(
 6263                row_range.end.previous_row().0,
 6264                snapshot.line_len(row_range.end.previous_row()),
 6265            ));
 6266            cursor_positions.push(anchor..anchor);
 6267        }
 6268
 6269        self.transact(window, cx, |this, window, cx| {
 6270            for row_range in row_ranges.into_iter().rev() {
 6271                for row in row_range.iter_rows().rev() {
 6272                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6273                    let next_line_row = row.next_row();
 6274                    let indent = snapshot.indent_size_for_line(next_line_row);
 6275                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6276
 6277                    let replace =
 6278                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6279                            " "
 6280                        } else {
 6281                            ""
 6282                        };
 6283
 6284                    this.buffer.update(cx, |buffer, cx| {
 6285                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6286                    });
 6287                }
 6288            }
 6289
 6290            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6291                s.select_anchor_ranges(cursor_positions)
 6292            });
 6293        });
 6294    }
 6295
 6296    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6297        self.join_lines_impl(true, window, cx);
 6298    }
 6299
 6300    pub fn sort_lines_case_sensitive(
 6301        &mut self,
 6302        _: &SortLinesCaseSensitive,
 6303        window: &mut Window,
 6304        cx: &mut Context<Self>,
 6305    ) {
 6306        self.manipulate_lines(window, cx, |lines| lines.sort())
 6307    }
 6308
 6309    pub fn sort_lines_case_insensitive(
 6310        &mut self,
 6311        _: &SortLinesCaseInsensitive,
 6312        window: &mut Window,
 6313        cx: &mut Context<Self>,
 6314    ) {
 6315        self.manipulate_lines(window, cx, |lines| {
 6316            lines.sort_by_key(|line| line.to_lowercase())
 6317        })
 6318    }
 6319
 6320    pub fn unique_lines_case_insensitive(
 6321        &mut self,
 6322        _: &UniqueLinesCaseInsensitive,
 6323        window: &mut Window,
 6324        cx: &mut Context<Self>,
 6325    ) {
 6326        self.manipulate_lines(window, cx, |lines| {
 6327            let mut seen = HashSet::default();
 6328            lines.retain(|line| seen.insert(line.to_lowercase()));
 6329        })
 6330    }
 6331
 6332    pub fn unique_lines_case_sensitive(
 6333        &mut self,
 6334        _: &UniqueLinesCaseSensitive,
 6335        window: &mut Window,
 6336        cx: &mut Context<Self>,
 6337    ) {
 6338        self.manipulate_lines(window, cx, |lines| {
 6339            let mut seen = HashSet::default();
 6340            lines.retain(|line| seen.insert(*line));
 6341        })
 6342    }
 6343
 6344    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6345        let mut revert_changes = HashMap::default();
 6346        let snapshot = self.snapshot(window, cx);
 6347        for hunk in snapshot
 6348            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6349        {
 6350            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6351        }
 6352        if !revert_changes.is_empty() {
 6353            self.transact(window, cx, |editor, window, cx| {
 6354                editor.revert(revert_changes, window, cx);
 6355            });
 6356        }
 6357    }
 6358
 6359    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6360        let Some(project) = self.project.clone() else {
 6361            return;
 6362        };
 6363        self.reload(project, window, cx)
 6364            .detach_and_notify_err(window, cx);
 6365    }
 6366
 6367    pub fn revert_selected_hunks(
 6368        &mut self,
 6369        _: &RevertSelectedHunks,
 6370        window: &mut Window,
 6371        cx: &mut Context<Self>,
 6372    ) {
 6373        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6374        self.revert_hunks_in_ranges(selections, window, cx);
 6375    }
 6376
 6377    fn revert_hunks_in_ranges(
 6378        &mut self,
 6379        ranges: impl Iterator<Item = Range<Point>>,
 6380        window: &mut Window,
 6381        cx: &mut Context<Editor>,
 6382    ) {
 6383        let mut revert_changes = HashMap::default();
 6384        let snapshot = self.snapshot(window, cx);
 6385        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6386            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6387        }
 6388        if !revert_changes.is_empty() {
 6389            self.transact(window, cx, |editor, window, cx| {
 6390                editor.revert(revert_changes, window, cx);
 6391            });
 6392        }
 6393    }
 6394
 6395    pub fn open_active_item_in_terminal(
 6396        &mut self,
 6397        _: &OpenInTerminal,
 6398        window: &mut Window,
 6399        cx: &mut Context<Self>,
 6400    ) {
 6401        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6402            let project_path = buffer.read(cx).project_path(cx)?;
 6403            let project = self.project.as_ref()?.read(cx);
 6404            let entry = project.entry_for_path(&project_path, cx)?;
 6405            let parent = match &entry.canonical_path {
 6406                Some(canonical_path) => canonical_path.to_path_buf(),
 6407                None => project.absolute_path(&project_path, cx)?,
 6408            }
 6409            .parent()?
 6410            .to_path_buf();
 6411            Some(parent)
 6412        }) {
 6413            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6414        }
 6415    }
 6416
 6417    pub fn prepare_revert_change(
 6418        &self,
 6419        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6420        hunk: &MultiBufferDiffHunk,
 6421        cx: &mut App,
 6422    ) -> Option<()> {
 6423        let buffer = self.buffer.read(cx);
 6424        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6425        let buffer = buffer.buffer(hunk.buffer_id)?;
 6426        let buffer = buffer.read(cx);
 6427        let original_text = change_set
 6428            .read(cx)
 6429            .base_text
 6430            .as_ref()?
 6431            .as_rope()
 6432            .slice(hunk.diff_base_byte_range.clone());
 6433        let buffer_snapshot = buffer.snapshot();
 6434        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6435        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6436            probe
 6437                .0
 6438                .start
 6439                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6440                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6441        }) {
 6442            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6443            Some(())
 6444        } else {
 6445            None
 6446        }
 6447    }
 6448
 6449    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6450        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6451    }
 6452
 6453    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6454        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6455    }
 6456
 6457    fn manipulate_lines<Fn>(
 6458        &mut self,
 6459        window: &mut Window,
 6460        cx: &mut Context<Self>,
 6461        mut callback: Fn,
 6462    ) where
 6463        Fn: FnMut(&mut Vec<&str>),
 6464    {
 6465        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6466        let buffer = self.buffer.read(cx).snapshot(cx);
 6467
 6468        let mut edits = Vec::new();
 6469
 6470        let selections = self.selections.all::<Point>(cx);
 6471        let mut selections = selections.iter().peekable();
 6472        let mut contiguous_row_selections = Vec::new();
 6473        let mut new_selections = Vec::new();
 6474        let mut added_lines = 0;
 6475        let mut removed_lines = 0;
 6476
 6477        while let Some(selection) = selections.next() {
 6478            let (start_row, end_row) = consume_contiguous_rows(
 6479                &mut contiguous_row_selections,
 6480                selection,
 6481                &display_map,
 6482                &mut selections,
 6483            );
 6484
 6485            let start_point = Point::new(start_row.0, 0);
 6486            let end_point = Point::new(
 6487                end_row.previous_row().0,
 6488                buffer.line_len(end_row.previous_row()),
 6489            );
 6490            let text = buffer
 6491                .text_for_range(start_point..end_point)
 6492                .collect::<String>();
 6493
 6494            let mut lines = text.split('\n').collect_vec();
 6495
 6496            let lines_before = lines.len();
 6497            callback(&mut lines);
 6498            let lines_after = lines.len();
 6499
 6500            edits.push((start_point..end_point, lines.join("\n")));
 6501
 6502            // Selections must change based on added and removed line count
 6503            let start_row =
 6504                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6505            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6506            new_selections.push(Selection {
 6507                id: selection.id,
 6508                start: start_row,
 6509                end: end_row,
 6510                goal: SelectionGoal::None,
 6511                reversed: selection.reversed,
 6512            });
 6513
 6514            if lines_after > lines_before {
 6515                added_lines += lines_after - lines_before;
 6516            } else if lines_before > lines_after {
 6517                removed_lines += lines_before - lines_after;
 6518            }
 6519        }
 6520
 6521        self.transact(window, cx, |this, window, cx| {
 6522            let buffer = this.buffer.update(cx, |buffer, cx| {
 6523                buffer.edit(edits, None, cx);
 6524                buffer.snapshot(cx)
 6525            });
 6526
 6527            // Recalculate offsets on newly edited buffer
 6528            let new_selections = new_selections
 6529                .iter()
 6530                .map(|s| {
 6531                    let start_point = Point::new(s.start.0, 0);
 6532                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6533                    Selection {
 6534                        id: s.id,
 6535                        start: buffer.point_to_offset(start_point),
 6536                        end: buffer.point_to_offset(end_point),
 6537                        goal: s.goal,
 6538                        reversed: s.reversed,
 6539                    }
 6540                })
 6541                .collect();
 6542
 6543            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6544                s.select(new_selections);
 6545            });
 6546
 6547            this.request_autoscroll(Autoscroll::fit(), cx);
 6548        });
 6549    }
 6550
 6551    pub fn convert_to_upper_case(
 6552        &mut self,
 6553        _: &ConvertToUpperCase,
 6554        window: &mut Window,
 6555        cx: &mut Context<Self>,
 6556    ) {
 6557        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6558    }
 6559
 6560    pub fn convert_to_lower_case(
 6561        &mut self,
 6562        _: &ConvertToLowerCase,
 6563        window: &mut Window,
 6564        cx: &mut Context<Self>,
 6565    ) {
 6566        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6567    }
 6568
 6569    pub fn convert_to_title_case(
 6570        &mut self,
 6571        _: &ConvertToTitleCase,
 6572        window: &mut Window,
 6573        cx: &mut Context<Self>,
 6574    ) {
 6575        self.manipulate_text(window, cx, |text| {
 6576            text.split('\n')
 6577                .map(|line| line.to_case(Case::Title))
 6578                .join("\n")
 6579        })
 6580    }
 6581
 6582    pub fn convert_to_snake_case(
 6583        &mut self,
 6584        _: &ConvertToSnakeCase,
 6585        window: &mut Window,
 6586        cx: &mut Context<Self>,
 6587    ) {
 6588        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6589    }
 6590
 6591    pub fn convert_to_kebab_case(
 6592        &mut self,
 6593        _: &ConvertToKebabCase,
 6594        window: &mut Window,
 6595        cx: &mut Context<Self>,
 6596    ) {
 6597        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6598    }
 6599
 6600    pub fn convert_to_upper_camel_case(
 6601        &mut self,
 6602        _: &ConvertToUpperCamelCase,
 6603        window: &mut Window,
 6604        cx: &mut Context<Self>,
 6605    ) {
 6606        self.manipulate_text(window, cx, |text| {
 6607            text.split('\n')
 6608                .map(|line| line.to_case(Case::UpperCamel))
 6609                .join("\n")
 6610        })
 6611    }
 6612
 6613    pub fn convert_to_lower_camel_case(
 6614        &mut self,
 6615        _: &ConvertToLowerCamelCase,
 6616        window: &mut Window,
 6617        cx: &mut Context<Self>,
 6618    ) {
 6619        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6620    }
 6621
 6622    pub fn convert_to_opposite_case(
 6623        &mut self,
 6624        _: &ConvertToOppositeCase,
 6625        window: &mut Window,
 6626        cx: &mut Context<Self>,
 6627    ) {
 6628        self.manipulate_text(window, cx, |text| {
 6629            text.chars()
 6630                .fold(String::with_capacity(text.len()), |mut t, c| {
 6631                    if c.is_uppercase() {
 6632                        t.extend(c.to_lowercase());
 6633                    } else {
 6634                        t.extend(c.to_uppercase());
 6635                    }
 6636                    t
 6637                })
 6638        })
 6639    }
 6640
 6641    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6642    where
 6643        Fn: FnMut(&str) -> String,
 6644    {
 6645        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6646        let buffer = self.buffer.read(cx).snapshot(cx);
 6647
 6648        let mut new_selections = Vec::new();
 6649        let mut edits = Vec::new();
 6650        let mut selection_adjustment = 0i32;
 6651
 6652        for selection in self.selections.all::<usize>(cx) {
 6653            let selection_is_empty = selection.is_empty();
 6654
 6655            let (start, end) = if selection_is_empty {
 6656                let word_range = movement::surrounding_word(
 6657                    &display_map,
 6658                    selection.start.to_display_point(&display_map),
 6659                );
 6660                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6661                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6662                (start, end)
 6663            } else {
 6664                (selection.start, selection.end)
 6665            };
 6666
 6667            let text = buffer.text_for_range(start..end).collect::<String>();
 6668            let old_length = text.len() as i32;
 6669            let text = callback(&text);
 6670
 6671            new_selections.push(Selection {
 6672                start: (start as i32 - selection_adjustment) as usize,
 6673                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6674                goal: SelectionGoal::None,
 6675                ..selection
 6676            });
 6677
 6678            selection_adjustment += old_length - text.len() as i32;
 6679
 6680            edits.push((start..end, text));
 6681        }
 6682
 6683        self.transact(window, cx, |this, window, cx| {
 6684            this.buffer.update(cx, |buffer, cx| {
 6685                buffer.edit(edits, None, cx);
 6686            });
 6687
 6688            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6689                s.select(new_selections);
 6690            });
 6691
 6692            this.request_autoscroll(Autoscroll::fit(), cx);
 6693        });
 6694    }
 6695
 6696    pub fn duplicate(
 6697        &mut self,
 6698        upwards: bool,
 6699        whole_lines: bool,
 6700        window: &mut Window,
 6701        cx: &mut Context<Self>,
 6702    ) {
 6703        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6704        let buffer = &display_map.buffer_snapshot;
 6705        let selections = self.selections.all::<Point>(cx);
 6706
 6707        let mut edits = Vec::new();
 6708        let mut selections_iter = selections.iter().peekable();
 6709        while let Some(selection) = selections_iter.next() {
 6710            let mut rows = selection.spanned_rows(false, &display_map);
 6711            // duplicate line-wise
 6712            if whole_lines || selection.start == selection.end {
 6713                // Avoid duplicating the same lines twice.
 6714                while let Some(next_selection) = selections_iter.peek() {
 6715                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6716                    if next_rows.start < rows.end {
 6717                        rows.end = next_rows.end;
 6718                        selections_iter.next().unwrap();
 6719                    } else {
 6720                        break;
 6721                    }
 6722                }
 6723
 6724                // Copy the text from the selected row region and splice it either at the start
 6725                // or end of the region.
 6726                let start = Point::new(rows.start.0, 0);
 6727                let end = Point::new(
 6728                    rows.end.previous_row().0,
 6729                    buffer.line_len(rows.end.previous_row()),
 6730                );
 6731                let text = buffer
 6732                    .text_for_range(start..end)
 6733                    .chain(Some("\n"))
 6734                    .collect::<String>();
 6735                let insert_location = if upwards {
 6736                    Point::new(rows.end.0, 0)
 6737                } else {
 6738                    start
 6739                };
 6740                edits.push((insert_location..insert_location, text));
 6741            } else {
 6742                // duplicate character-wise
 6743                let start = selection.start;
 6744                let end = selection.end;
 6745                let text = buffer.text_for_range(start..end).collect::<String>();
 6746                edits.push((selection.end..selection.end, text));
 6747            }
 6748        }
 6749
 6750        self.transact(window, cx, |this, _, cx| {
 6751            this.buffer.update(cx, |buffer, cx| {
 6752                buffer.edit(edits, None, cx);
 6753            });
 6754
 6755            this.request_autoscroll(Autoscroll::fit(), cx);
 6756        });
 6757    }
 6758
 6759    pub fn duplicate_line_up(
 6760        &mut self,
 6761        _: &DuplicateLineUp,
 6762        window: &mut Window,
 6763        cx: &mut Context<Self>,
 6764    ) {
 6765        self.duplicate(true, true, window, cx);
 6766    }
 6767
 6768    pub fn duplicate_line_down(
 6769        &mut self,
 6770        _: &DuplicateLineDown,
 6771        window: &mut Window,
 6772        cx: &mut Context<Self>,
 6773    ) {
 6774        self.duplicate(false, true, window, cx);
 6775    }
 6776
 6777    pub fn duplicate_selection(
 6778        &mut self,
 6779        _: &DuplicateSelection,
 6780        window: &mut Window,
 6781        cx: &mut Context<Self>,
 6782    ) {
 6783        self.duplicate(false, false, window, cx);
 6784    }
 6785
 6786    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 6787        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6788        let buffer = self.buffer.read(cx).snapshot(cx);
 6789
 6790        let mut edits = Vec::new();
 6791        let mut unfold_ranges = Vec::new();
 6792        let mut refold_creases = Vec::new();
 6793
 6794        let selections = self.selections.all::<Point>(cx);
 6795        let mut selections = selections.iter().peekable();
 6796        let mut contiguous_row_selections = Vec::new();
 6797        let mut new_selections = Vec::new();
 6798
 6799        while let Some(selection) = selections.next() {
 6800            // Find all the selections that span a contiguous row range
 6801            let (start_row, end_row) = consume_contiguous_rows(
 6802                &mut contiguous_row_selections,
 6803                selection,
 6804                &display_map,
 6805                &mut selections,
 6806            );
 6807
 6808            // Move the text spanned by the row range to be before the line preceding the row range
 6809            if start_row.0 > 0 {
 6810                let range_to_move = Point::new(
 6811                    start_row.previous_row().0,
 6812                    buffer.line_len(start_row.previous_row()),
 6813                )
 6814                    ..Point::new(
 6815                        end_row.previous_row().0,
 6816                        buffer.line_len(end_row.previous_row()),
 6817                    );
 6818                let insertion_point = display_map
 6819                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6820                    .0;
 6821
 6822                // Don't move lines across excerpts
 6823                if buffer
 6824                    .excerpt_containing(insertion_point..range_to_move.end)
 6825                    .is_some()
 6826                {
 6827                    let text = buffer
 6828                        .text_for_range(range_to_move.clone())
 6829                        .flat_map(|s| s.chars())
 6830                        .skip(1)
 6831                        .chain(['\n'])
 6832                        .collect::<String>();
 6833
 6834                    edits.push((
 6835                        buffer.anchor_after(range_to_move.start)
 6836                            ..buffer.anchor_before(range_to_move.end),
 6837                        String::new(),
 6838                    ));
 6839                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6840                    edits.push((insertion_anchor..insertion_anchor, text));
 6841
 6842                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6843
 6844                    // Move selections up
 6845                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6846                        |mut selection| {
 6847                            selection.start.row -= row_delta;
 6848                            selection.end.row -= row_delta;
 6849                            selection
 6850                        },
 6851                    ));
 6852
 6853                    // Move folds up
 6854                    unfold_ranges.push(range_to_move.clone());
 6855                    for fold in display_map.folds_in_range(
 6856                        buffer.anchor_before(range_to_move.start)
 6857                            ..buffer.anchor_after(range_to_move.end),
 6858                    ) {
 6859                        let mut start = fold.range.start.to_point(&buffer);
 6860                        let mut end = fold.range.end.to_point(&buffer);
 6861                        start.row -= row_delta;
 6862                        end.row -= row_delta;
 6863                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6864                    }
 6865                }
 6866            }
 6867
 6868            // If we didn't move line(s), preserve the existing selections
 6869            new_selections.append(&mut contiguous_row_selections);
 6870        }
 6871
 6872        self.transact(window, cx, |this, window, cx| {
 6873            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6874            this.buffer.update(cx, |buffer, cx| {
 6875                for (range, text) in edits {
 6876                    buffer.edit([(range, text)], None, cx);
 6877                }
 6878            });
 6879            this.fold_creases(refold_creases, true, window, cx);
 6880            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6881                s.select(new_selections);
 6882            })
 6883        });
 6884    }
 6885
 6886    pub fn move_line_down(
 6887        &mut self,
 6888        _: &MoveLineDown,
 6889        window: &mut Window,
 6890        cx: &mut Context<Self>,
 6891    ) {
 6892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6893        let buffer = self.buffer.read(cx).snapshot(cx);
 6894
 6895        let mut edits = Vec::new();
 6896        let mut unfold_ranges = Vec::new();
 6897        let mut refold_creases = Vec::new();
 6898
 6899        let selections = self.selections.all::<Point>(cx);
 6900        let mut selections = selections.iter().peekable();
 6901        let mut contiguous_row_selections = Vec::new();
 6902        let mut new_selections = Vec::new();
 6903
 6904        while let Some(selection) = selections.next() {
 6905            // Find all the selections that span a contiguous row range
 6906            let (start_row, end_row) = consume_contiguous_rows(
 6907                &mut contiguous_row_selections,
 6908                selection,
 6909                &display_map,
 6910                &mut selections,
 6911            );
 6912
 6913            // Move the text spanned by the row range to be after the last line of the row range
 6914            if end_row.0 <= buffer.max_point().row {
 6915                let range_to_move =
 6916                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6917                let insertion_point = display_map
 6918                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6919                    .0;
 6920
 6921                // Don't move lines across excerpt boundaries
 6922                if buffer
 6923                    .excerpt_containing(range_to_move.start..insertion_point)
 6924                    .is_some()
 6925                {
 6926                    let mut text = String::from("\n");
 6927                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6928                    text.pop(); // Drop trailing newline
 6929                    edits.push((
 6930                        buffer.anchor_after(range_to_move.start)
 6931                            ..buffer.anchor_before(range_to_move.end),
 6932                        String::new(),
 6933                    ));
 6934                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6935                    edits.push((insertion_anchor..insertion_anchor, text));
 6936
 6937                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6938
 6939                    // Move selections down
 6940                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6941                        |mut selection| {
 6942                            selection.start.row += row_delta;
 6943                            selection.end.row += row_delta;
 6944                            selection
 6945                        },
 6946                    ));
 6947
 6948                    // Move folds down
 6949                    unfold_ranges.push(range_to_move.clone());
 6950                    for fold in display_map.folds_in_range(
 6951                        buffer.anchor_before(range_to_move.start)
 6952                            ..buffer.anchor_after(range_to_move.end),
 6953                    ) {
 6954                        let mut start = fold.range.start.to_point(&buffer);
 6955                        let mut end = fold.range.end.to_point(&buffer);
 6956                        start.row += row_delta;
 6957                        end.row += row_delta;
 6958                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6959                    }
 6960                }
 6961            }
 6962
 6963            // If we didn't move line(s), preserve the existing selections
 6964            new_selections.append(&mut contiguous_row_selections);
 6965        }
 6966
 6967        self.transact(window, cx, |this, window, cx| {
 6968            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6969            this.buffer.update(cx, |buffer, cx| {
 6970                for (range, text) in edits {
 6971                    buffer.edit([(range, text)], None, cx);
 6972                }
 6973            });
 6974            this.fold_creases(refold_creases, true, window, cx);
 6975            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6976                s.select(new_selections)
 6977            });
 6978        });
 6979    }
 6980
 6981    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 6982        let text_layout_details = &self.text_layout_details(window);
 6983        self.transact(window, cx, |this, window, cx| {
 6984            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6985                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6986                let line_mode = s.line_mode;
 6987                s.move_with(|display_map, selection| {
 6988                    if !selection.is_empty() || line_mode {
 6989                        return;
 6990                    }
 6991
 6992                    let mut head = selection.head();
 6993                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6994                    if head.column() == display_map.line_len(head.row()) {
 6995                        transpose_offset = display_map
 6996                            .buffer_snapshot
 6997                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6998                    }
 6999
 7000                    if transpose_offset == 0 {
 7001                        return;
 7002                    }
 7003
 7004                    *head.column_mut() += 1;
 7005                    head = display_map.clip_point(head, Bias::Right);
 7006                    let goal = SelectionGoal::HorizontalPosition(
 7007                        display_map
 7008                            .x_for_display_point(head, text_layout_details)
 7009                            .into(),
 7010                    );
 7011                    selection.collapse_to(head, goal);
 7012
 7013                    let transpose_start = display_map
 7014                        .buffer_snapshot
 7015                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7016                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7017                        let transpose_end = display_map
 7018                            .buffer_snapshot
 7019                            .clip_offset(transpose_offset + 1, Bias::Right);
 7020                        if let Some(ch) =
 7021                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7022                        {
 7023                            edits.push((transpose_start..transpose_offset, String::new()));
 7024                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7025                        }
 7026                    }
 7027                });
 7028                edits
 7029            });
 7030            this.buffer
 7031                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7032            let selections = this.selections.all::<usize>(cx);
 7033            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7034                s.select(selections);
 7035            });
 7036        });
 7037    }
 7038
 7039    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7040        self.rewrap_impl(IsVimMode::No, cx)
 7041    }
 7042
 7043    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7044        let buffer = self.buffer.read(cx).snapshot(cx);
 7045        let selections = self.selections.all::<Point>(cx);
 7046        let mut selections = selections.iter().peekable();
 7047
 7048        let mut edits = Vec::new();
 7049        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7050
 7051        while let Some(selection) = selections.next() {
 7052            let mut start_row = selection.start.row;
 7053            let mut end_row = selection.end.row;
 7054
 7055            // Skip selections that overlap with a range that has already been rewrapped.
 7056            let selection_range = start_row..end_row;
 7057            if rewrapped_row_ranges
 7058                .iter()
 7059                .any(|range| range.overlaps(&selection_range))
 7060            {
 7061                continue;
 7062            }
 7063
 7064            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7065
 7066            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7067                match language_scope.language_name().as_ref() {
 7068                    "Markdown" | "Plain Text" => {
 7069                        should_rewrap = true;
 7070                    }
 7071                    _ => {}
 7072                }
 7073            }
 7074
 7075            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7076
 7077            // Since not all lines in the selection may be at the same indent
 7078            // level, choose the indent size that is the most common between all
 7079            // of the lines.
 7080            //
 7081            // If there is a tie, we use the deepest indent.
 7082            let (indent_size, indent_end) = {
 7083                let mut indent_size_occurrences = HashMap::default();
 7084                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7085
 7086                for row in start_row..=end_row {
 7087                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7088                    rows_by_indent_size.entry(indent).or_default().push(row);
 7089                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7090                }
 7091
 7092                let indent_size = indent_size_occurrences
 7093                    .into_iter()
 7094                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7095                    .map(|(indent, _)| indent)
 7096                    .unwrap_or_default();
 7097                let row = rows_by_indent_size[&indent_size][0];
 7098                let indent_end = Point::new(row, indent_size.len);
 7099
 7100                (indent_size, indent_end)
 7101            };
 7102
 7103            let mut line_prefix = indent_size.chars().collect::<String>();
 7104
 7105            if let Some(comment_prefix) =
 7106                buffer
 7107                    .language_scope_at(selection.head())
 7108                    .and_then(|language| {
 7109                        language
 7110                            .line_comment_prefixes()
 7111                            .iter()
 7112                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7113                            .cloned()
 7114                    })
 7115            {
 7116                line_prefix.push_str(&comment_prefix);
 7117                should_rewrap = true;
 7118            }
 7119
 7120            if !should_rewrap {
 7121                continue;
 7122            }
 7123
 7124            if selection.is_empty() {
 7125                'expand_upwards: while start_row > 0 {
 7126                    let prev_row = start_row - 1;
 7127                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7128                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7129                    {
 7130                        start_row = prev_row;
 7131                    } else {
 7132                        break 'expand_upwards;
 7133                    }
 7134                }
 7135
 7136                'expand_downwards: while end_row < buffer.max_point().row {
 7137                    let next_row = end_row + 1;
 7138                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7139                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7140                    {
 7141                        end_row = next_row;
 7142                    } else {
 7143                        break 'expand_downwards;
 7144                    }
 7145                }
 7146            }
 7147
 7148            let start = Point::new(start_row, 0);
 7149            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7150            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7151            let Some(lines_without_prefixes) = selection_text
 7152                .lines()
 7153                .map(|line| {
 7154                    line.strip_prefix(&line_prefix)
 7155                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7156                        .ok_or_else(|| {
 7157                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7158                        })
 7159                })
 7160                .collect::<Result<Vec<_>, _>>()
 7161                .log_err()
 7162            else {
 7163                continue;
 7164            };
 7165
 7166            let wrap_column = buffer
 7167                .settings_at(Point::new(start_row, 0), cx)
 7168                .preferred_line_length as usize;
 7169            let wrapped_text = wrap_with_prefix(
 7170                line_prefix,
 7171                lines_without_prefixes.join(" "),
 7172                wrap_column,
 7173                tab_size,
 7174            );
 7175
 7176            // TODO: should always use char-based diff while still supporting cursor behavior that
 7177            // matches vim.
 7178            let diff = match is_vim_mode {
 7179                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7180                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7181            };
 7182            let mut offset = start.to_offset(&buffer);
 7183            let mut moved_since_edit = true;
 7184
 7185            for change in diff.iter_all_changes() {
 7186                let value = change.value();
 7187                match change.tag() {
 7188                    ChangeTag::Equal => {
 7189                        offset += value.len();
 7190                        moved_since_edit = true;
 7191                    }
 7192                    ChangeTag::Delete => {
 7193                        let start = buffer.anchor_after(offset);
 7194                        let end = buffer.anchor_before(offset + value.len());
 7195
 7196                        if moved_since_edit {
 7197                            edits.push((start..end, String::new()));
 7198                        } else {
 7199                            edits.last_mut().unwrap().0.end = end;
 7200                        }
 7201
 7202                        offset += value.len();
 7203                        moved_since_edit = false;
 7204                    }
 7205                    ChangeTag::Insert => {
 7206                        if moved_since_edit {
 7207                            let anchor = buffer.anchor_after(offset);
 7208                            edits.push((anchor..anchor, value.to_string()));
 7209                        } else {
 7210                            edits.last_mut().unwrap().1.push_str(value);
 7211                        }
 7212
 7213                        moved_since_edit = false;
 7214                    }
 7215                }
 7216            }
 7217
 7218            rewrapped_row_ranges.push(start_row..=end_row);
 7219        }
 7220
 7221        self.buffer
 7222            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7223    }
 7224
 7225    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7226        let mut text = String::new();
 7227        let buffer = self.buffer.read(cx).snapshot(cx);
 7228        let mut selections = self.selections.all::<Point>(cx);
 7229        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7230        {
 7231            let max_point = buffer.max_point();
 7232            let mut is_first = true;
 7233            for selection in &mut selections {
 7234                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7235                if is_entire_line {
 7236                    selection.start = Point::new(selection.start.row, 0);
 7237                    if !selection.is_empty() && selection.end.column == 0 {
 7238                        selection.end = cmp::min(max_point, selection.end);
 7239                    } else {
 7240                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7241                    }
 7242                    selection.goal = SelectionGoal::None;
 7243                }
 7244                if is_first {
 7245                    is_first = false;
 7246                } else {
 7247                    text += "\n";
 7248                }
 7249                let mut len = 0;
 7250                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7251                    text.push_str(chunk);
 7252                    len += chunk.len();
 7253                }
 7254                clipboard_selections.push(ClipboardSelection {
 7255                    len,
 7256                    is_entire_line,
 7257                    first_line_indent: buffer
 7258                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7259                        .len,
 7260                });
 7261            }
 7262        }
 7263
 7264        self.transact(window, cx, |this, window, cx| {
 7265            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7266                s.select(selections);
 7267            });
 7268            this.insert("", window, cx);
 7269        });
 7270        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7271    }
 7272
 7273    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7274        let item = self.cut_common(window, cx);
 7275        cx.write_to_clipboard(item);
 7276    }
 7277
 7278    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7279        self.change_selections(None, window, cx, |s| {
 7280            s.move_with(|snapshot, sel| {
 7281                if sel.is_empty() {
 7282                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7283                }
 7284            });
 7285        });
 7286        let item = self.cut_common(window, cx);
 7287        cx.set_global(KillRing(item))
 7288    }
 7289
 7290    pub fn kill_ring_yank(
 7291        &mut self,
 7292        _: &KillRingYank,
 7293        window: &mut Window,
 7294        cx: &mut Context<Self>,
 7295    ) {
 7296        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7297            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7298                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7299            } else {
 7300                return;
 7301            }
 7302        } else {
 7303            return;
 7304        };
 7305        self.do_paste(&text, metadata, false, window, cx);
 7306    }
 7307
 7308    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7309        let selections = self.selections.all::<Point>(cx);
 7310        let buffer = self.buffer.read(cx).read(cx);
 7311        let mut text = String::new();
 7312
 7313        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7314        {
 7315            let max_point = buffer.max_point();
 7316            let mut is_first = true;
 7317            for selection in selections.iter() {
 7318                let mut start = selection.start;
 7319                let mut end = selection.end;
 7320                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7321                if is_entire_line {
 7322                    start = Point::new(start.row, 0);
 7323                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7324                }
 7325                if is_first {
 7326                    is_first = false;
 7327                } else {
 7328                    text += "\n";
 7329                }
 7330                let mut len = 0;
 7331                for chunk in buffer.text_for_range(start..end) {
 7332                    text.push_str(chunk);
 7333                    len += chunk.len();
 7334                }
 7335                clipboard_selections.push(ClipboardSelection {
 7336                    len,
 7337                    is_entire_line,
 7338                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7339                });
 7340            }
 7341        }
 7342
 7343        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7344            text,
 7345            clipboard_selections,
 7346        ));
 7347    }
 7348
 7349    pub fn do_paste(
 7350        &mut self,
 7351        text: &String,
 7352        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7353        handle_entire_lines: bool,
 7354        window: &mut Window,
 7355        cx: &mut Context<Self>,
 7356    ) {
 7357        if self.read_only(cx) {
 7358            return;
 7359        }
 7360
 7361        let clipboard_text = Cow::Borrowed(text);
 7362
 7363        self.transact(window, cx, |this, window, cx| {
 7364            if let Some(mut clipboard_selections) = clipboard_selections {
 7365                let old_selections = this.selections.all::<usize>(cx);
 7366                let all_selections_were_entire_line =
 7367                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7368                let first_selection_indent_column =
 7369                    clipboard_selections.first().map(|s| s.first_line_indent);
 7370                if clipboard_selections.len() != old_selections.len() {
 7371                    clipboard_selections.drain(..);
 7372                }
 7373                let cursor_offset = this.selections.last::<usize>(cx).head();
 7374                let mut auto_indent_on_paste = true;
 7375
 7376                this.buffer.update(cx, |buffer, cx| {
 7377                    let snapshot = buffer.read(cx);
 7378                    auto_indent_on_paste =
 7379                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7380
 7381                    let mut start_offset = 0;
 7382                    let mut edits = Vec::new();
 7383                    let mut original_indent_columns = Vec::new();
 7384                    for (ix, selection) in old_selections.iter().enumerate() {
 7385                        let to_insert;
 7386                        let entire_line;
 7387                        let original_indent_column;
 7388                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7389                            let end_offset = start_offset + clipboard_selection.len;
 7390                            to_insert = &clipboard_text[start_offset..end_offset];
 7391                            entire_line = clipboard_selection.is_entire_line;
 7392                            start_offset = end_offset + 1;
 7393                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7394                        } else {
 7395                            to_insert = clipboard_text.as_str();
 7396                            entire_line = all_selections_were_entire_line;
 7397                            original_indent_column = first_selection_indent_column
 7398                        }
 7399
 7400                        // If the corresponding selection was empty when this slice of the
 7401                        // clipboard text was written, then the entire line containing the
 7402                        // selection was copied. If this selection is also currently empty,
 7403                        // then paste the line before the current line of the buffer.
 7404                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7405                            let column = selection.start.to_point(&snapshot).column as usize;
 7406                            let line_start = selection.start - column;
 7407                            line_start..line_start
 7408                        } else {
 7409                            selection.range()
 7410                        };
 7411
 7412                        edits.push((range, to_insert));
 7413                        original_indent_columns.extend(original_indent_column);
 7414                    }
 7415                    drop(snapshot);
 7416
 7417                    buffer.edit(
 7418                        edits,
 7419                        if auto_indent_on_paste {
 7420                            Some(AutoindentMode::Block {
 7421                                original_indent_columns,
 7422                            })
 7423                        } else {
 7424                            None
 7425                        },
 7426                        cx,
 7427                    );
 7428                });
 7429
 7430                let selections = this.selections.all::<usize>(cx);
 7431                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7432                    s.select(selections)
 7433                });
 7434            } else {
 7435                this.insert(&clipboard_text, window, cx);
 7436            }
 7437        });
 7438    }
 7439
 7440    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7441        if let Some(item) = cx.read_from_clipboard() {
 7442            let entries = item.entries();
 7443
 7444            match entries.first() {
 7445                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7446                // of all the pasted entries.
 7447                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7448                    .do_paste(
 7449                        clipboard_string.text(),
 7450                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7451                        true,
 7452                        window,
 7453                        cx,
 7454                    ),
 7455                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7456            }
 7457        }
 7458    }
 7459
 7460    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7461        if self.read_only(cx) {
 7462            return;
 7463        }
 7464
 7465        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7466            if let Some((selections, _)) =
 7467                self.selection_history.transaction(transaction_id).cloned()
 7468            {
 7469                self.change_selections(None, window, cx, |s| {
 7470                    s.select_anchors(selections.to_vec());
 7471                });
 7472            }
 7473            self.request_autoscroll(Autoscroll::fit(), cx);
 7474            self.unmark_text(window, cx);
 7475            self.refresh_inline_completion(true, false, window, cx);
 7476            cx.emit(EditorEvent::Edited { transaction_id });
 7477            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7478        }
 7479    }
 7480
 7481    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7482        if self.read_only(cx) {
 7483            return;
 7484        }
 7485
 7486        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7487            if let Some((_, Some(selections))) =
 7488                self.selection_history.transaction(transaction_id).cloned()
 7489            {
 7490                self.change_selections(None, window, cx, |s| {
 7491                    s.select_anchors(selections.to_vec());
 7492                });
 7493            }
 7494            self.request_autoscroll(Autoscroll::fit(), cx);
 7495            self.unmark_text(window, cx);
 7496            self.refresh_inline_completion(true, false, window, cx);
 7497            cx.emit(EditorEvent::Edited { transaction_id });
 7498        }
 7499    }
 7500
 7501    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7502        self.buffer
 7503            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7504    }
 7505
 7506    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7507        self.buffer
 7508            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7509    }
 7510
 7511    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7512        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7513            let line_mode = s.line_mode;
 7514            s.move_with(|map, selection| {
 7515                let cursor = if selection.is_empty() && !line_mode {
 7516                    movement::left(map, selection.start)
 7517                } else {
 7518                    selection.start
 7519                };
 7520                selection.collapse_to(cursor, SelectionGoal::None);
 7521            });
 7522        })
 7523    }
 7524
 7525    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7526        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7527            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7528        })
 7529    }
 7530
 7531    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7532        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7533            let line_mode = s.line_mode;
 7534            s.move_with(|map, selection| {
 7535                let cursor = if selection.is_empty() && !line_mode {
 7536                    movement::right(map, selection.end)
 7537                } else {
 7538                    selection.end
 7539                };
 7540                selection.collapse_to(cursor, SelectionGoal::None)
 7541            });
 7542        })
 7543    }
 7544
 7545    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7546        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7547            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7548        })
 7549    }
 7550
 7551    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7552        if self.take_rename(true, window, cx).is_some() {
 7553            return;
 7554        }
 7555
 7556        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7557            cx.propagate();
 7558            return;
 7559        }
 7560
 7561        let text_layout_details = &self.text_layout_details(window);
 7562        let selection_count = self.selections.count();
 7563        let first_selection = self.selections.first_anchor();
 7564
 7565        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7566            let line_mode = s.line_mode;
 7567            s.move_with(|map, selection| {
 7568                if !selection.is_empty() && !line_mode {
 7569                    selection.goal = SelectionGoal::None;
 7570                }
 7571                let (cursor, goal) = movement::up(
 7572                    map,
 7573                    selection.start,
 7574                    selection.goal,
 7575                    false,
 7576                    text_layout_details,
 7577                );
 7578                selection.collapse_to(cursor, goal);
 7579            });
 7580        });
 7581
 7582        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7583        {
 7584            cx.propagate();
 7585        }
 7586    }
 7587
 7588    pub fn move_up_by_lines(
 7589        &mut self,
 7590        action: &MoveUpByLines,
 7591        window: &mut Window,
 7592        cx: &mut Context<Self>,
 7593    ) {
 7594        if self.take_rename(true, window, cx).is_some() {
 7595            return;
 7596        }
 7597
 7598        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7599            cx.propagate();
 7600            return;
 7601        }
 7602
 7603        let text_layout_details = &self.text_layout_details(window);
 7604
 7605        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7606            let line_mode = s.line_mode;
 7607            s.move_with(|map, selection| {
 7608                if !selection.is_empty() && !line_mode {
 7609                    selection.goal = SelectionGoal::None;
 7610                }
 7611                let (cursor, goal) = movement::up_by_rows(
 7612                    map,
 7613                    selection.start,
 7614                    action.lines,
 7615                    selection.goal,
 7616                    false,
 7617                    text_layout_details,
 7618                );
 7619                selection.collapse_to(cursor, goal);
 7620            });
 7621        })
 7622    }
 7623
 7624    pub fn move_down_by_lines(
 7625        &mut self,
 7626        action: &MoveDownByLines,
 7627        window: &mut Window,
 7628        cx: &mut Context<Self>,
 7629    ) {
 7630        if self.take_rename(true, window, cx).is_some() {
 7631            return;
 7632        }
 7633
 7634        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7635            cx.propagate();
 7636            return;
 7637        }
 7638
 7639        let text_layout_details = &self.text_layout_details(window);
 7640
 7641        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7642            let line_mode = s.line_mode;
 7643            s.move_with(|map, selection| {
 7644                if !selection.is_empty() && !line_mode {
 7645                    selection.goal = SelectionGoal::None;
 7646                }
 7647                let (cursor, goal) = movement::down_by_rows(
 7648                    map,
 7649                    selection.start,
 7650                    action.lines,
 7651                    selection.goal,
 7652                    false,
 7653                    text_layout_details,
 7654                );
 7655                selection.collapse_to(cursor, goal);
 7656            });
 7657        })
 7658    }
 7659
 7660    pub fn select_down_by_lines(
 7661        &mut self,
 7662        action: &SelectDownByLines,
 7663        window: &mut Window,
 7664        cx: &mut Context<Self>,
 7665    ) {
 7666        let text_layout_details = &self.text_layout_details(window);
 7667        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7668            s.move_heads_with(|map, head, goal| {
 7669                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7670            })
 7671        })
 7672    }
 7673
 7674    pub fn select_up_by_lines(
 7675        &mut self,
 7676        action: &SelectUpByLines,
 7677        window: &mut Window,
 7678        cx: &mut Context<Self>,
 7679    ) {
 7680        let text_layout_details = &self.text_layout_details(window);
 7681        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7682            s.move_heads_with(|map, head, goal| {
 7683                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7684            })
 7685        })
 7686    }
 7687
 7688    pub fn select_page_up(
 7689        &mut self,
 7690        _: &SelectPageUp,
 7691        window: &mut Window,
 7692        cx: &mut Context<Self>,
 7693    ) {
 7694        let Some(row_count) = self.visible_row_count() else {
 7695            return;
 7696        };
 7697
 7698        let text_layout_details = &self.text_layout_details(window);
 7699
 7700        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7701            s.move_heads_with(|map, head, goal| {
 7702                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7703            })
 7704        })
 7705    }
 7706
 7707    pub fn move_page_up(
 7708        &mut self,
 7709        action: &MovePageUp,
 7710        window: &mut Window,
 7711        cx: &mut Context<Self>,
 7712    ) {
 7713        if self.take_rename(true, window, cx).is_some() {
 7714            return;
 7715        }
 7716
 7717        if self
 7718            .context_menu
 7719            .borrow_mut()
 7720            .as_mut()
 7721            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7722            .unwrap_or(false)
 7723        {
 7724            return;
 7725        }
 7726
 7727        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7728            cx.propagate();
 7729            return;
 7730        }
 7731
 7732        let Some(row_count) = self.visible_row_count() else {
 7733            return;
 7734        };
 7735
 7736        let autoscroll = if action.center_cursor {
 7737            Autoscroll::center()
 7738        } else {
 7739            Autoscroll::fit()
 7740        };
 7741
 7742        let text_layout_details = &self.text_layout_details(window);
 7743
 7744        self.change_selections(Some(autoscroll), window, cx, |s| {
 7745            let line_mode = s.line_mode;
 7746            s.move_with(|map, selection| {
 7747                if !selection.is_empty() && !line_mode {
 7748                    selection.goal = SelectionGoal::None;
 7749                }
 7750                let (cursor, goal) = movement::up_by_rows(
 7751                    map,
 7752                    selection.end,
 7753                    row_count,
 7754                    selection.goal,
 7755                    false,
 7756                    text_layout_details,
 7757                );
 7758                selection.collapse_to(cursor, goal);
 7759            });
 7760        });
 7761    }
 7762
 7763    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 7764        let text_layout_details = &self.text_layout_details(window);
 7765        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7766            s.move_heads_with(|map, head, goal| {
 7767                movement::up(map, head, goal, false, text_layout_details)
 7768            })
 7769        })
 7770    }
 7771
 7772    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 7773        self.take_rename(true, window, cx);
 7774
 7775        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7776            cx.propagate();
 7777            return;
 7778        }
 7779
 7780        let text_layout_details = &self.text_layout_details(window);
 7781        let selection_count = self.selections.count();
 7782        let first_selection = self.selections.first_anchor();
 7783
 7784        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7785            let line_mode = s.line_mode;
 7786            s.move_with(|map, selection| {
 7787                if !selection.is_empty() && !line_mode {
 7788                    selection.goal = SelectionGoal::None;
 7789                }
 7790                let (cursor, goal) = movement::down(
 7791                    map,
 7792                    selection.end,
 7793                    selection.goal,
 7794                    false,
 7795                    text_layout_details,
 7796                );
 7797                selection.collapse_to(cursor, goal);
 7798            });
 7799        });
 7800
 7801        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7802        {
 7803            cx.propagate();
 7804        }
 7805    }
 7806
 7807    pub fn select_page_down(
 7808        &mut self,
 7809        _: &SelectPageDown,
 7810        window: &mut Window,
 7811        cx: &mut Context<Self>,
 7812    ) {
 7813        let Some(row_count) = self.visible_row_count() else {
 7814            return;
 7815        };
 7816
 7817        let text_layout_details = &self.text_layout_details(window);
 7818
 7819        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7820            s.move_heads_with(|map, head, goal| {
 7821                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7822            })
 7823        })
 7824    }
 7825
 7826    pub fn move_page_down(
 7827        &mut self,
 7828        action: &MovePageDown,
 7829        window: &mut Window,
 7830        cx: &mut Context<Self>,
 7831    ) {
 7832        if self.take_rename(true, window, cx).is_some() {
 7833            return;
 7834        }
 7835
 7836        if self
 7837            .context_menu
 7838            .borrow_mut()
 7839            .as_mut()
 7840            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7841            .unwrap_or(false)
 7842        {
 7843            return;
 7844        }
 7845
 7846        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7847            cx.propagate();
 7848            return;
 7849        }
 7850
 7851        let Some(row_count) = self.visible_row_count() else {
 7852            return;
 7853        };
 7854
 7855        let autoscroll = if action.center_cursor {
 7856            Autoscroll::center()
 7857        } else {
 7858            Autoscroll::fit()
 7859        };
 7860
 7861        let text_layout_details = &self.text_layout_details(window);
 7862        self.change_selections(Some(autoscroll), window, cx, |s| {
 7863            let line_mode = s.line_mode;
 7864            s.move_with(|map, selection| {
 7865                if !selection.is_empty() && !line_mode {
 7866                    selection.goal = SelectionGoal::None;
 7867                }
 7868                let (cursor, goal) = movement::down_by_rows(
 7869                    map,
 7870                    selection.end,
 7871                    row_count,
 7872                    selection.goal,
 7873                    false,
 7874                    text_layout_details,
 7875                );
 7876                selection.collapse_to(cursor, goal);
 7877            });
 7878        });
 7879    }
 7880
 7881    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 7882        let text_layout_details = &self.text_layout_details(window);
 7883        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7884            s.move_heads_with(|map, head, goal| {
 7885                movement::down(map, head, goal, false, text_layout_details)
 7886            })
 7887        });
 7888    }
 7889
 7890    pub fn context_menu_first(
 7891        &mut self,
 7892        _: &ContextMenuFirst,
 7893        _window: &mut Window,
 7894        cx: &mut Context<Self>,
 7895    ) {
 7896        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7897            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7898        }
 7899    }
 7900
 7901    pub fn context_menu_prev(
 7902        &mut self,
 7903        _: &ContextMenuPrev,
 7904        _window: &mut Window,
 7905        cx: &mut Context<Self>,
 7906    ) {
 7907        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7908            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7909        }
 7910    }
 7911
 7912    pub fn context_menu_next(
 7913        &mut self,
 7914        _: &ContextMenuNext,
 7915        _window: &mut Window,
 7916        cx: &mut Context<Self>,
 7917    ) {
 7918        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7919            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7920        }
 7921    }
 7922
 7923    pub fn context_menu_last(
 7924        &mut self,
 7925        _: &ContextMenuLast,
 7926        _window: &mut Window,
 7927        cx: &mut Context<Self>,
 7928    ) {
 7929        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7930            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7931        }
 7932    }
 7933
 7934    pub fn move_to_previous_word_start(
 7935        &mut self,
 7936        _: &MoveToPreviousWordStart,
 7937        window: &mut Window,
 7938        cx: &mut Context<Self>,
 7939    ) {
 7940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7941            s.move_cursors_with(|map, head, _| {
 7942                (
 7943                    movement::previous_word_start(map, head),
 7944                    SelectionGoal::None,
 7945                )
 7946            });
 7947        })
 7948    }
 7949
 7950    pub fn move_to_previous_subword_start(
 7951        &mut self,
 7952        _: &MoveToPreviousSubwordStart,
 7953        window: &mut Window,
 7954        cx: &mut Context<Self>,
 7955    ) {
 7956        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7957            s.move_cursors_with(|map, head, _| {
 7958                (
 7959                    movement::previous_subword_start(map, head),
 7960                    SelectionGoal::None,
 7961                )
 7962            });
 7963        })
 7964    }
 7965
 7966    pub fn select_to_previous_word_start(
 7967        &mut self,
 7968        _: &SelectToPreviousWordStart,
 7969        window: &mut Window,
 7970        cx: &mut Context<Self>,
 7971    ) {
 7972        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7973            s.move_heads_with(|map, head, _| {
 7974                (
 7975                    movement::previous_word_start(map, head),
 7976                    SelectionGoal::None,
 7977                )
 7978            });
 7979        })
 7980    }
 7981
 7982    pub fn select_to_previous_subword_start(
 7983        &mut self,
 7984        _: &SelectToPreviousSubwordStart,
 7985        window: &mut Window,
 7986        cx: &mut Context<Self>,
 7987    ) {
 7988        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7989            s.move_heads_with(|map, head, _| {
 7990                (
 7991                    movement::previous_subword_start(map, head),
 7992                    SelectionGoal::None,
 7993                )
 7994            });
 7995        })
 7996    }
 7997
 7998    pub fn delete_to_previous_word_start(
 7999        &mut self,
 8000        action: &DeleteToPreviousWordStart,
 8001        window: &mut Window,
 8002        cx: &mut Context<Self>,
 8003    ) {
 8004        self.transact(window, cx, |this, window, cx| {
 8005            this.select_autoclose_pair(window, cx);
 8006            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8007                let line_mode = s.line_mode;
 8008                s.move_with(|map, selection| {
 8009                    if selection.is_empty() && !line_mode {
 8010                        let cursor = if action.ignore_newlines {
 8011                            movement::previous_word_start(map, selection.head())
 8012                        } else {
 8013                            movement::previous_word_start_or_newline(map, selection.head())
 8014                        };
 8015                        selection.set_head(cursor, SelectionGoal::None);
 8016                    }
 8017                });
 8018            });
 8019            this.insert("", window, cx);
 8020        });
 8021    }
 8022
 8023    pub fn delete_to_previous_subword_start(
 8024        &mut self,
 8025        _: &DeleteToPreviousSubwordStart,
 8026        window: &mut Window,
 8027        cx: &mut Context<Self>,
 8028    ) {
 8029        self.transact(window, cx, |this, window, cx| {
 8030            this.select_autoclose_pair(window, cx);
 8031            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8032                let line_mode = s.line_mode;
 8033                s.move_with(|map, selection| {
 8034                    if selection.is_empty() && !line_mode {
 8035                        let cursor = movement::previous_subword_start(map, selection.head());
 8036                        selection.set_head(cursor, SelectionGoal::None);
 8037                    }
 8038                });
 8039            });
 8040            this.insert("", window, cx);
 8041        });
 8042    }
 8043
 8044    pub fn move_to_next_word_end(
 8045        &mut self,
 8046        _: &MoveToNextWordEnd,
 8047        window: &mut Window,
 8048        cx: &mut Context<Self>,
 8049    ) {
 8050        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8051            s.move_cursors_with(|map, head, _| {
 8052                (movement::next_word_end(map, head), SelectionGoal::None)
 8053            });
 8054        })
 8055    }
 8056
 8057    pub fn move_to_next_subword_end(
 8058        &mut self,
 8059        _: &MoveToNextSubwordEnd,
 8060        window: &mut Window,
 8061        cx: &mut Context<Self>,
 8062    ) {
 8063        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8064            s.move_cursors_with(|map, head, _| {
 8065                (movement::next_subword_end(map, head), SelectionGoal::None)
 8066            });
 8067        })
 8068    }
 8069
 8070    pub fn select_to_next_word_end(
 8071        &mut self,
 8072        _: &SelectToNextWordEnd,
 8073        window: &mut Window,
 8074        cx: &mut Context<Self>,
 8075    ) {
 8076        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8077            s.move_heads_with(|map, head, _| {
 8078                (movement::next_word_end(map, head), SelectionGoal::None)
 8079            });
 8080        })
 8081    }
 8082
 8083    pub fn select_to_next_subword_end(
 8084        &mut self,
 8085        _: &SelectToNextSubwordEnd,
 8086        window: &mut Window,
 8087        cx: &mut Context<Self>,
 8088    ) {
 8089        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8090            s.move_heads_with(|map, head, _| {
 8091                (movement::next_subword_end(map, head), SelectionGoal::None)
 8092            });
 8093        })
 8094    }
 8095
 8096    pub fn delete_to_next_word_end(
 8097        &mut self,
 8098        action: &DeleteToNextWordEnd,
 8099        window: &mut Window,
 8100        cx: &mut Context<Self>,
 8101    ) {
 8102        self.transact(window, cx, |this, window, cx| {
 8103            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8104                let line_mode = s.line_mode;
 8105                s.move_with(|map, selection| {
 8106                    if selection.is_empty() && !line_mode {
 8107                        let cursor = if action.ignore_newlines {
 8108                            movement::next_word_end(map, selection.head())
 8109                        } else {
 8110                            movement::next_word_end_or_newline(map, selection.head())
 8111                        };
 8112                        selection.set_head(cursor, SelectionGoal::None);
 8113                    }
 8114                });
 8115            });
 8116            this.insert("", window, cx);
 8117        });
 8118    }
 8119
 8120    pub fn delete_to_next_subword_end(
 8121        &mut self,
 8122        _: &DeleteToNextSubwordEnd,
 8123        window: &mut Window,
 8124        cx: &mut Context<Self>,
 8125    ) {
 8126        self.transact(window, cx, |this, window, cx| {
 8127            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8128                s.move_with(|map, selection| {
 8129                    if selection.is_empty() {
 8130                        let cursor = movement::next_subword_end(map, selection.head());
 8131                        selection.set_head(cursor, SelectionGoal::None);
 8132                    }
 8133                });
 8134            });
 8135            this.insert("", window, cx);
 8136        });
 8137    }
 8138
 8139    pub fn move_to_beginning_of_line(
 8140        &mut self,
 8141        action: &MoveToBeginningOfLine,
 8142        window: &mut Window,
 8143        cx: &mut Context<Self>,
 8144    ) {
 8145        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8146            s.move_cursors_with(|map, head, _| {
 8147                (
 8148                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8149                    SelectionGoal::None,
 8150                )
 8151            });
 8152        })
 8153    }
 8154
 8155    pub fn select_to_beginning_of_line(
 8156        &mut self,
 8157        action: &SelectToBeginningOfLine,
 8158        window: &mut Window,
 8159        cx: &mut Context<Self>,
 8160    ) {
 8161        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8162            s.move_heads_with(|map, head, _| {
 8163                (
 8164                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8165                    SelectionGoal::None,
 8166                )
 8167            });
 8168        });
 8169    }
 8170
 8171    pub fn delete_to_beginning_of_line(
 8172        &mut self,
 8173        _: &DeleteToBeginningOfLine,
 8174        window: &mut Window,
 8175        cx: &mut Context<Self>,
 8176    ) {
 8177        self.transact(window, cx, |this, window, cx| {
 8178            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8179                s.move_with(|_, selection| {
 8180                    selection.reversed = true;
 8181                });
 8182            });
 8183
 8184            this.select_to_beginning_of_line(
 8185                &SelectToBeginningOfLine {
 8186                    stop_at_soft_wraps: false,
 8187                },
 8188                window,
 8189                cx,
 8190            );
 8191            this.backspace(&Backspace, window, cx);
 8192        });
 8193    }
 8194
 8195    pub fn move_to_end_of_line(
 8196        &mut self,
 8197        action: &MoveToEndOfLine,
 8198        window: &mut Window,
 8199        cx: &mut Context<Self>,
 8200    ) {
 8201        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8202            s.move_cursors_with(|map, head, _| {
 8203                (
 8204                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8205                    SelectionGoal::None,
 8206                )
 8207            });
 8208        })
 8209    }
 8210
 8211    pub fn select_to_end_of_line(
 8212        &mut self,
 8213        action: &SelectToEndOfLine,
 8214        window: &mut Window,
 8215        cx: &mut Context<Self>,
 8216    ) {
 8217        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8218            s.move_heads_with(|map, head, _| {
 8219                (
 8220                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8221                    SelectionGoal::None,
 8222                )
 8223            });
 8224        })
 8225    }
 8226
 8227    pub fn delete_to_end_of_line(
 8228        &mut self,
 8229        _: &DeleteToEndOfLine,
 8230        window: &mut Window,
 8231        cx: &mut Context<Self>,
 8232    ) {
 8233        self.transact(window, cx, |this, window, cx| {
 8234            this.select_to_end_of_line(
 8235                &SelectToEndOfLine {
 8236                    stop_at_soft_wraps: false,
 8237                },
 8238                window,
 8239                cx,
 8240            );
 8241            this.delete(&Delete, window, cx);
 8242        });
 8243    }
 8244
 8245    pub fn cut_to_end_of_line(
 8246        &mut self,
 8247        _: &CutToEndOfLine,
 8248        window: &mut Window,
 8249        cx: &mut Context<Self>,
 8250    ) {
 8251        self.transact(window, cx, |this, window, cx| {
 8252            this.select_to_end_of_line(
 8253                &SelectToEndOfLine {
 8254                    stop_at_soft_wraps: false,
 8255                },
 8256                window,
 8257                cx,
 8258            );
 8259            this.cut(&Cut, window, cx);
 8260        });
 8261    }
 8262
 8263    pub fn move_to_start_of_paragraph(
 8264        &mut self,
 8265        _: &MoveToStartOfParagraph,
 8266        window: &mut Window,
 8267        cx: &mut Context<Self>,
 8268    ) {
 8269        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8270            cx.propagate();
 8271            return;
 8272        }
 8273
 8274        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8275            s.move_with(|map, selection| {
 8276                selection.collapse_to(
 8277                    movement::start_of_paragraph(map, selection.head(), 1),
 8278                    SelectionGoal::None,
 8279                )
 8280            });
 8281        })
 8282    }
 8283
 8284    pub fn move_to_end_of_paragraph(
 8285        &mut self,
 8286        _: &MoveToEndOfParagraph,
 8287        window: &mut Window,
 8288        cx: &mut Context<Self>,
 8289    ) {
 8290        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8291            cx.propagate();
 8292            return;
 8293        }
 8294
 8295        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8296            s.move_with(|map, selection| {
 8297                selection.collapse_to(
 8298                    movement::end_of_paragraph(map, selection.head(), 1),
 8299                    SelectionGoal::None,
 8300                )
 8301            });
 8302        })
 8303    }
 8304
 8305    pub fn select_to_start_of_paragraph(
 8306        &mut self,
 8307        _: &SelectToStartOfParagraph,
 8308        window: &mut Window,
 8309        cx: &mut Context<Self>,
 8310    ) {
 8311        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8312            cx.propagate();
 8313            return;
 8314        }
 8315
 8316        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8317            s.move_heads_with(|map, head, _| {
 8318                (
 8319                    movement::start_of_paragraph(map, head, 1),
 8320                    SelectionGoal::None,
 8321                )
 8322            });
 8323        })
 8324    }
 8325
 8326    pub fn select_to_end_of_paragraph(
 8327        &mut self,
 8328        _: &SelectToEndOfParagraph,
 8329        window: &mut Window,
 8330        cx: &mut Context<Self>,
 8331    ) {
 8332        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8333            cx.propagate();
 8334            return;
 8335        }
 8336
 8337        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8338            s.move_heads_with(|map, head, _| {
 8339                (
 8340                    movement::end_of_paragraph(map, head, 1),
 8341                    SelectionGoal::None,
 8342                )
 8343            });
 8344        })
 8345    }
 8346
 8347    pub fn move_to_beginning(
 8348        &mut self,
 8349        _: &MoveToBeginning,
 8350        window: &mut Window,
 8351        cx: &mut Context<Self>,
 8352    ) {
 8353        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8354            cx.propagate();
 8355            return;
 8356        }
 8357
 8358        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8359            s.select_ranges(vec![0..0]);
 8360        });
 8361    }
 8362
 8363    pub fn select_to_beginning(
 8364        &mut self,
 8365        _: &SelectToBeginning,
 8366        window: &mut Window,
 8367        cx: &mut Context<Self>,
 8368    ) {
 8369        let mut selection = self.selections.last::<Point>(cx);
 8370        selection.set_head(Point::zero(), SelectionGoal::None);
 8371
 8372        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8373            s.select(vec![selection]);
 8374        });
 8375    }
 8376
 8377    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8378        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8379            cx.propagate();
 8380            return;
 8381        }
 8382
 8383        let cursor = self.buffer.read(cx).read(cx).len();
 8384        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8385            s.select_ranges(vec![cursor..cursor])
 8386        });
 8387    }
 8388
 8389    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8390        self.nav_history = nav_history;
 8391    }
 8392
 8393    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8394        self.nav_history.as_ref()
 8395    }
 8396
 8397    fn push_to_nav_history(
 8398        &mut self,
 8399        cursor_anchor: Anchor,
 8400        new_position: Option<Point>,
 8401        cx: &mut Context<Self>,
 8402    ) {
 8403        if let Some(nav_history) = self.nav_history.as_mut() {
 8404            let buffer = self.buffer.read(cx).read(cx);
 8405            let cursor_position = cursor_anchor.to_point(&buffer);
 8406            let scroll_state = self.scroll_manager.anchor();
 8407            let scroll_top_row = scroll_state.top_row(&buffer);
 8408            drop(buffer);
 8409
 8410            if let Some(new_position) = new_position {
 8411                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8412                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8413                    return;
 8414                }
 8415            }
 8416
 8417            nav_history.push(
 8418                Some(NavigationData {
 8419                    cursor_anchor,
 8420                    cursor_position,
 8421                    scroll_anchor: scroll_state,
 8422                    scroll_top_row,
 8423                }),
 8424                cx,
 8425            );
 8426        }
 8427    }
 8428
 8429    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8430        let buffer = self.buffer.read(cx).snapshot(cx);
 8431        let mut selection = self.selections.first::<usize>(cx);
 8432        selection.set_head(buffer.len(), SelectionGoal::None);
 8433        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8434            s.select(vec![selection]);
 8435        });
 8436    }
 8437
 8438    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8439        let end = self.buffer.read(cx).read(cx).len();
 8440        self.change_selections(None, window, cx, |s| {
 8441            s.select_ranges(vec![0..end]);
 8442        });
 8443    }
 8444
 8445    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8447        let mut selections = self.selections.all::<Point>(cx);
 8448        let max_point = display_map.buffer_snapshot.max_point();
 8449        for selection in &mut selections {
 8450            let rows = selection.spanned_rows(true, &display_map);
 8451            selection.start = Point::new(rows.start.0, 0);
 8452            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8453            selection.reversed = false;
 8454        }
 8455        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8456            s.select(selections);
 8457        });
 8458    }
 8459
 8460    pub fn split_selection_into_lines(
 8461        &mut self,
 8462        _: &SplitSelectionIntoLines,
 8463        window: &mut Window,
 8464        cx: &mut Context<Self>,
 8465    ) {
 8466        let mut to_unfold = Vec::new();
 8467        let mut new_selection_ranges = Vec::new();
 8468        {
 8469            let selections = self.selections.all::<Point>(cx);
 8470            let buffer = self.buffer.read(cx).read(cx);
 8471            for selection in selections {
 8472                for row in selection.start.row..selection.end.row {
 8473                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8474                    new_selection_ranges.push(cursor..cursor);
 8475                }
 8476                new_selection_ranges.push(selection.end..selection.end);
 8477                to_unfold.push(selection.start..selection.end);
 8478            }
 8479        }
 8480        self.unfold_ranges(&to_unfold, true, true, cx);
 8481        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8482            s.select_ranges(new_selection_ranges);
 8483        });
 8484    }
 8485
 8486    pub fn add_selection_above(
 8487        &mut self,
 8488        _: &AddSelectionAbove,
 8489        window: &mut Window,
 8490        cx: &mut Context<Self>,
 8491    ) {
 8492        self.add_selection(true, window, cx);
 8493    }
 8494
 8495    pub fn add_selection_below(
 8496        &mut self,
 8497        _: &AddSelectionBelow,
 8498        window: &mut Window,
 8499        cx: &mut Context<Self>,
 8500    ) {
 8501        self.add_selection(false, window, cx);
 8502    }
 8503
 8504    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8505        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8506        let mut selections = self.selections.all::<Point>(cx);
 8507        let text_layout_details = self.text_layout_details(window);
 8508        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8509            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8510            let range = oldest_selection.display_range(&display_map).sorted();
 8511
 8512            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8513            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8514            let positions = start_x.min(end_x)..start_x.max(end_x);
 8515
 8516            selections.clear();
 8517            let mut stack = Vec::new();
 8518            for row in range.start.row().0..=range.end.row().0 {
 8519                if let Some(selection) = self.selections.build_columnar_selection(
 8520                    &display_map,
 8521                    DisplayRow(row),
 8522                    &positions,
 8523                    oldest_selection.reversed,
 8524                    &text_layout_details,
 8525                ) {
 8526                    stack.push(selection.id);
 8527                    selections.push(selection);
 8528                }
 8529            }
 8530
 8531            if above {
 8532                stack.reverse();
 8533            }
 8534
 8535            AddSelectionsState { above, stack }
 8536        });
 8537
 8538        let last_added_selection = *state.stack.last().unwrap();
 8539        let mut new_selections = Vec::new();
 8540        if above == state.above {
 8541            let end_row = if above {
 8542                DisplayRow(0)
 8543            } else {
 8544                display_map.max_point().row()
 8545            };
 8546
 8547            'outer: for selection in selections {
 8548                if selection.id == last_added_selection {
 8549                    let range = selection.display_range(&display_map).sorted();
 8550                    debug_assert_eq!(range.start.row(), range.end.row());
 8551                    let mut row = range.start.row();
 8552                    let positions =
 8553                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8554                            px(start)..px(end)
 8555                        } else {
 8556                            let start_x =
 8557                                display_map.x_for_display_point(range.start, &text_layout_details);
 8558                            let end_x =
 8559                                display_map.x_for_display_point(range.end, &text_layout_details);
 8560                            start_x.min(end_x)..start_x.max(end_x)
 8561                        };
 8562
 8563                    while row != end_row {
 8564                        if above {
 8565                            row.0 -= 1;
 8566                        } else {
 8567                            row.0 += 1;
 8568                        }
 8569
 8570                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8571                            &display_map,
 8572                            row,
 8573                            &positions,
 8574                            selection.reversed,
 8575                            &text_layout_details,
 8576                        ) {
 8577                            state.stack.push(new_selection.id);
 8578                            if above {
 8579                                new_selections.push(new_selection);
 8580                                new_selections.push(selection);
 8581                            } else {
 8582                                new_selections.push(selection);
 8583                                new_selections.push(new_selection);
 8584                            }
 8585
 8586                            continue 'outer;
 8587                        }
 8588                    }
 8589                }
 8590
 8591                new_selections.push(selection);
 8592            }
 8593        } else {
 8594            new_selections = selections;
 8595            new_selections.retain(|s| s.id != last_added_selection);
 8596            state.stack.pop();
 8597        }
 8598
 8599        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8600            s.select(new_selections);
 8601        });
 8602        if state.stack.len() > 1 {
 8603            self.add_selections_state = Some(state);
 8604        }
 8605    }
 8606
 8607    pub fn select_next_match_internal(
 8608        &mut self,
 8609        display_map: &DisplaySnapshot,
 8610        replace_newest: bool,
 8611        autoscroll: Option<Autoscroll>,
 8612        window: &mut Window,
 8613        cx: &mut Context<Self>,
 8614    ) -> Result<()> {
 8615        fn select_next_match_ranges(
 8616            this: &mut Editor,
 8617            range: Range<usize>,
 8618            replace_newest: bool,
 8619            auto_scroll: Option<Autoscroll>,
 8620            window: &mut Window,
 8621            cx: &mut Context<Editor>,
 8622        ) {
 8623            this.unfold_ranges(&[range.clone()], false, true, cx);
 8624            this.change_selections(auto_scroll, window, cx, |s| {
 8625                if replace_newest {
 8626                    s.delete(s.newest_anchor().id);
 8627                }
 8628                s.insert_range(range.clone());
 8629            });
 8630        }
 8631
 8632        let buffer = &display_map.buffer_snapshot;
 8633        let mut selections = self.selections.all::<usize>(cx);
 8634        if let Some(mut select_next_state) = self.select_next_state.take() {
 8635            let query = &select_next_state.query;
 8636            if !select_next_state.done {
 8637                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8638                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8639                let mut next_selected_range = None;
 8640
 8641                let bytes_after_last_selection =
 8642                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8643                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8644                let query_matches = query
 8645                    .stream_find_iter(bytes_after_last_selection)
 8646                    .map(|result| (last_selection.end, result))
 8647                    .chain(
 8648                        query
 8649                            .stream_find_iter(bytes_before_first_selection)
 8650                            .map(|result| (0, result)),
 8651                    );
 8652
 8653                for (start_offset, query_match) in query_matches {
 8654                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8655                    let offset_range =
 8656                        start_offset + query_match.start()..start_offset + query_match.end();
 8657                    let display_range = offset_range.start.to_display_point(display_map)
 8658                        ..offset_range.end.to_display_point(display_map);
 8659
 8660                    if !select_next_state.wordwise
 8661                        || (!movement::is_inside_word(display_map, display_range.start)
 8662                            && !movement::is_inside_word(display_map, display_range.end))
 8663                    {
 8664                        // TODO: This is n^2, because we might check all the selections
 8665                        if !selections
 8666                            .iter()
 8667                            .any(|selection| selection.range().overlaps(&offset_range))
 8668                        {
 8669                            next_selected_range = Some(offset_range);
 8670                            break;
 8671                        }
 8672                    }
 8673                }
 8674
 8675                if let Some(next_selected_range) = next_selected_range {
 8676                    select_next_match_ranges(
 8677                        self,
 8678                        next_selected_range,
 8679                        replace_newest,
 8680                        autoscroll,
 8681                        window,
 8682                        cx,
 8683                    );
 8684                } else {
 8685                    select_next_state.done = true;
 8686                }
 8687            }
 8688
 8689            self.select_next_state = Some(select_next_state);
 8690        } else {
 8691            let mut only_carets = true;
 8692            let mut same_text_selected = true;
 8693            let mut selected_text = None;
 8694
 8695            let mut selections_iter = selections.iter().peekable();
 8696            while let Some(selection) = selections_iter.next() {
 8697                if selection.start != selection.end {
 8698                    only_carets = false;
 8699                }
 8700
 8701                if same_text_selected {
 8702                    if selected_text.is_none() {
 8703                        selected_text =
 8704                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8705                    }
 8706
 8707                    if let Some(next_selection) = selections_iter.peek() {
 8708                        if next_selection.range().len() == selection.range().len() {
 8709                            let next_selected_text = buffer
 8710                                .text_for_range(next_selection.range())
 8711                                .collect::<String>();
 8712                            if Some(next_selected_text) != selected_text {
 8713                                same_text_selected = false;
 8714                                selected_text = None;
 8715                            }
 8716                        } else {
 8717                            same_text_selected = false;
 8718                            selected_text = None;
 8719                        }
 8720                    }
 8721                }
 8722            }
 8723
 8724            if only_carets {
 8725                for selection in &mut selections {
 8726                    let word_range = movement::surrounding_word(
 8727                        display_map,
 8728                        selection.start.to_display_point(display_map),
 8729                    );
 8730                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8731                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8732                    selection.goal = SelectionGoal::None;
 8733                    selection.reversed = false;
 8734                    select_next_match_ranges(
 8735                        self,
 8736                        selection.start..selection.end,
 8737                        replace_newest,
 8738                        autoscroll,
 8739                        window,
 8740                        cx,
 8741                    );
 8742                }
 8743
 8744                if selections.len() == 1 {
 8745                    let selection = selections
 8746                        .last()
 8747                        .expect("ensured that there's only one selection");
 8748                    let query = buffer
 8749                        .text_for_range(selection.start..selection.end)
 8750                        .collect::<String>();
 8751                    let is_empty = query.is_empty();
 8752                    let select_state = SelectNextState {
 8753                        query: AhoCorasick::new(&[query])?,
 8754                        wordwise: true,
 8755                        done: is_empty,
 8756                    };
 8757                    self.select_next_state = Some(select_state);
 8758                } else {
 8759                    self.select_next_state = None;
 8760                }
 8761            } else if let Some(selected_text) = selected_text {
 8762                self.select_next_state = Some(SelectNextState {
 8763                    query: AhoCorasick::new(&[selected_text])?,
 8764                    wordwise: false,
 8765                    done: false,
 8766                });
 8767                self.select_next_match_internal(
 8768                    display_map,
 8769                    replace_newest,
 8770                    autoscroll,
 8771                    window,
 8772                    cx,
 8773                )?;
 8774            }
 8775        }
 8776        Ok(())
 8777    }
 8778
 8779    pub fn select_all_matches(
 8780        &mut self,
 8781        _action: &SelectAllMatches,
 8782        window: &mut Window,
 8783        cx: &mut Context<Self>,
 8784    ) -> Result<()> {
 8785        self.push_to_selection_history();
 8786        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8787
 8788        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 8789        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8790            return Ok(());
 8791        };
 8792        if select_next_state.done {
 8793            return Ok(());
 8794        }
 8795
 8796        let mut new_selections = self.selections.all::<usize>(cx);
 8797
 8798        let buffer = &display_map.buffer_snapshot;
 8799        let query_matches = select_next_state
 8800            .query
 8801            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8802
 8803        for query_match in query_matches {
 8804            let query_match = query_match.unwrap(); // can only fail due to I/O
 8805            let offset_range = query_match.start()..query_match.end();
 8806            let display_range = offset_range.start.to_display_point(&display_map)
 8807                ..offset_range.end.to_display_point(&display_map);
 8808
 8809            if !select_next_state.wordwise
 8810                || (!movement::is_inside_word(&display_map, display_range.start)
 8811                    && !movement::is_inside_word(&display_map, display_range.end))
 8812            {
 8813                self.selections.change_with(cx, |selections| {
 8814                    new_selections.push(Selection {
 8815                        id: selections.new_selection_id(),
 8816                        start: offset_range.start,
 8817                        end: offset_range.end,
 8818                        reversed: false,
 8819                        goal: SelectionGoal::None,
 8820                    });
 8821                });
 8822            }
 8823        }
 8824
 8825        new_selections.sort_by_key(|selection| selection.start);
 8826        let mut ix = 0;
 8827        while ix + 1 < new_selections.len() {
 8828            let current_selection = &new_selections[ix];
 8829            let next_selection = &new_selections[ix + 1];
 8830            if current_selection.range().overlaps(&next_selection.range()) {
 8831                if current_selection.id < next_selection.id {
 8832                    new_selections.remove(ix + 1);
 8833                } else {
 8834                    new_selections.remove(ix);
 8835                }
 8836            } else {
 8837                ix += 1;
 8838            }
 8839        }
 8840
 8841        let reversed = self.selections.oldest::<usize>(cx).reversed;
 8842
 8843        for selection in new_selections.iter_mut() {
 8844            selection.reversed = reversed;
 8845        }
 8846
 8847        select_next_state.done = true;
 8848        self.unfold_ranges(
 8849            &new_selections
 8850                .iter()
 8851                .map(|selection| selection.range())
 8852                .collect::<Vec<_>>(),
 8853            false,
 8854            false,
 8855            cx,
 8856        );
 8857        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 8858            selections.select(new_selections)
 8859        });
 8860
 8861        Ok(())
 8862    }
 8863
 8864    pub fn select_next(
 8865        &mut self,
 8866        action: &SelectNext,
 8867        window: &mut Window,
 8868        cx: &mut Context<Self>,
 8869    ) -> Result<()> {
 8870        self.push_to_selection_history();
 8871        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8872        self.select_next_match_internal(
 8873            &display_map,
 8874            action.replace_newest,
 8875            Some(Autoscroll::newest()),
 8876            window,
 8877            cx,
 8878        )?;
 8879        Ok(())
 8880    }
 8881
 8882    pub fn select_previous(
 8883        &mut self,
 8884        action: &SelectPrevious,
 8885        window: &mut Window,
 8886        cx: &mut Context<Self>,
 8887    ) -> Result<()> {
 8888        self.push_to_selection_history();
 8889        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8890        let buffer = &display_map.buffer_snapshot;
 8891        let mut selections = self.selections.all::<usize>(cx);
 8892        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8893            let query = &select_prev_state.query;
 8894            if !select_prev_state.done {
 8895                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8896                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8897                let mut next_selected_range = None;
 8898                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8899                let bytes_before_last_selection =
 8900                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8901                let bytes_after_first_selection =
 8902                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8903                let query_matches = query
 8904                    .stream_find_iter(bytes_before_last_selection)
 8905                    .map(|result| (last_selection.start, result))
 8906                    .chain(
 8907                        query
 8908                            .stream_find_iter(bytes_after_first_selection)
 8909                            .map(|result| (buffer.len(), result)),
 8910                    );
 8911                for (end_offset, query_match) in query_matches {
 8912                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8913                    let offset_range =
 8914                        end_offset - query_match.end()..end_offset - query_match.start();
 8915                    let display_range = offset_range.start.to_display_point(&display_map)
 8916                        ..offset_range.end.to_display_point(&display_map);
 8917
 8918                    if !select_prev_state.wordwise
 8919                        || (!movement::is_inside_word(&display_map, display_range.start)
 8920                            && !movement::is_inside_word(&display_map, display_range.end))
 8921                    {
 8922                        next_selected_range = Some(offset_range);
 8923                        break;
 8924                    }
 8925                }
 8926
 8927                if let Some(next_selected_range) = next_selected_range {
 8928                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8929                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8930                        if action.replace_newest {
 8931                            s.delete(s.newest_anchor().id);
 8932                        }
 8933                        s.insert_range(next_selected_range);
 8934                    });
 8935                } else {
 8936                    select_prev_state.done = true;
 8937                }
 8938            }
 8939
 8940            self.select_prev_state = Some(select_prev_state);
 8941        } else {
 8942            let mut only_carets = true;
 8943            let mut same_text_selected = true;
 8944            let mut selected_text = None;
 8945
 8946            let mut selections_iter = selections.iter().peekable();
 8947            while let Some(selection) = selections_iter.next() {
 8948                if selection.start != selection.end {
 8949                    only_carets = false;
 8950                }
 8951
 8952                if same_text_selected {
 8953                    if selected_text.is_none() {
 8954                        selected_text =
 8955                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8956                    }
 8957
 8958                    if let Some(next_selection) = selections_iter.peek() {
 8959                        if next_selection.range().len() == selection.range().len() {
 8960                            let next_selected_text = buffer
 8961                                .text_for_range(next_selection.range())
 8962                                .collect::<String>();
 8963                            if Some(next_selected_text) != selected_text {
 8964                                same_text_selected = false;
 8965                                selected_text = None;
 8966                            }
 8967                        } else {
 8968                            same_text_selected = false;
 8969                            selected_text = None;
 8970                        }
 8971                    }
 8972                }
 8973            }
 8974
 8975            if only_carets {
 8976                for selection in &mut selections {
 8977                    let word_range = movement::surrounding_word(
 8978                        &display_map,
 8979                        selection.start.to_display_point(&display_map),
 8980                    );
 8981                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8982                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8983                    selection.goal = SelectionGoal::None;
 8984                    selection.reversed = false;
 8985                }
 8986                if selections.len() == 1 {
 8987                    let selection = selections
 8988                        .last()
 8989                        .expect("ensured that there's only one selection");
 8990                    let query = buffer
 8991                        .text_for_range(selection.start..selection.end)
 8992                        .collect::<String>();
 8993                    let is_empty = query.is_empty();
 8994                    let select_state = SelectNextState {
 8995                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8996                        wordwise: true,
 8997                        done: is_empty,
 8998                    };
 8999                    self.select_prev_state = Some(select_state);
 9000                } else {
 9001                    self.select_prev_state = None;
 9002                }
 9003
 9004                self.unfold_ranges(
 9005                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9006                    false,
 9007                    true,
 9008                    cx,
 9009                );
 9010                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9011                    s.select(selections);
 9012                });
 9013            } else if let Some(selected_text) = selected_text {
 9014                self.select_prev_state = Some(SelectNextState {
 9015                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9016                    wordwise: false,
 9017                    done: false,
 9018                });
 9019                self.select_previous(action, window, cx)?;
 9020            }
 9021        }
 9022        Ok(())
 9023    }
 9024
 9025    pub fn toggle_comments(
 9026        &mut self,
 9027        action: &ToggleComments,
 9028        window: &mut Window,
 9029        cx: &mut Context<Self>,
 9030    ) {
 9031        if self.read_only(cx) {
 9032            return;
 9033        }
 9034        let text_layout_details = &self.text_layout_details(window);
 9035        self.transact(window, cx, |this, window, cx| {
 9036            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9037            let mut edits = Vec::new();
 9038            let mut selection_edit_ranges = Vec::new();
 9039            let mut last_toggled_row = None;
 9040            let snapshot = this.buffer.read(cx).read(cx);
 9041            let empty_str: Arc<str> = Arc::default();
 9042            let mut suffixes_inserted = Vec::new();
 9043            let ignore_indent = action.ignore_indent;
 9044
 9045            fn comment_prefix_range(
 9046                snapshot: &MultiBufferSnapshot,
 9047                row: MultiBufferRow,
 9048                comment_prefix: &str,
 9049                comment_prefix_whitespace: &str,
 9050                ignore_indent: bool,
 9051            ) -> Range<Point> {
 9052                let indent_size = if ignore_indent {
 9053                    0
 9054                } else {
 9055                    snapshot.indent_size_for_line(row).len
 9056                };
 9057
 9058                let start = Point::new(row.0, indent_size);
 9059
 9060                let mut line_bytes = snapshot
 9061                    .bytes_in_range(start..snapshot.max_point())
 9062                    .flatten()
 9063                    .copied();
 9064
 9065                // If this line currently begins with the line comment prefix, then record
 9066                // the range containing the prefix.
 9067                if line_bytes
 9068                    .by_ref()
 9069                    .take(comment_prefix.len())
 9070                    .eq(comment_prefix.bytes())
 9071                {
 9072                    // Include any whitespace that matches the comment prefix.
 9073                    let matching_whitespace_len = line_bytes
 9074                        .zip(comment_prefix_whitespace.bytes())
 9075                        .take_while(|(a, b)| a == b)
 9076                        .count() as u32;
 9077                    let end = Point::new(
 9078                        start.row,
 9079                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9080                    );
 9081                    start..end
 9082                } else {
 9083                    start..start
 9084                }
 9085            }
 9086
 9087            fn comment_suffix_range(
 9088                snapshot: &MultiBufferSnapshot,
 9089                row: MultiBufferRow,
 9090                comment_suffix: &str,
 9091                comment_suffix_has_leading_space: bool,
 9092            ) -> Range<Point> {
 9093                let end = Point::new(row.0, snapshot.line_len(row));
 9094                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9095
 9096                let mut line_end_bytes = snapshot
 9097                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9098                    .flatten()
 9099                    .copied();
 9100
 9101                let leading_space_len = if suffix_start_column > 0
 9102                    && line_end_bytes.next() == Some(b' ')
 9103                    && comment_suffix_has_leading_space
 9104                {
 9105                    1
 9106                } else {
 9107                    0
 9108                };
 9109
 9110                // If this line currently begins with the line comment prefix, then record
 9111                // the range containing the prefix.
 9112                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9113                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9114                    start..end
 9115                } else {
 9116                    end..end
 9117                }
 9118            }
 9119
 9120            // TODO: Handle selections that cross excerpts
 9121            for selection in &mut selections {
 9122                let start_column = snapshot
 9123                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9124                    .len;
 9125                let language = if let Some(language) =
 9126                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9127                {
 9128                    language
 9129                } else {
 9130                    continue;
 9131                };
 9132
 9133                selection_edit_ranges.clear();
 9134
 9135                // If multiple selections contain a given row, avoid processing that
 9136                // row more than once.
 9137                let mut start_row = MultiBufferRow(selection.start.row);
 9138                if last_toggled_row == Some(start_row) {
 9139                    start_row = start_row.next_row();
 9140                }
 9141                let end_row =
 9142                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9143                        MultiBufferRow(selection.end.row - 1)
 9144                    } else {
 9145                        MultiBufferRow(selection.end.row)
 9146                    };
 9147                last_toggled_row = Some(end_row);
 9148
 9149                if start_row > end_row {
 9150                    continue;
 9151                }
 9152
 9153                // If the language has line comments, toggle those.
 9154                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9155
 9156                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9157                if ignore_indent {
 9158                    full_comment_prefixes = full_comment_prefixes
 9159                        .into_iter()
 9160                        .map(|s| Arc::from(s.trim_end()))
 9161                        .collect();
 9162                }
 9163
 9164                if !full_comment_prefixes.is_empty() {
 9165                    let first_prefix = full_comment_prefixes
 9166                        .first()
 9167                        .expect("prefixes is non-empty");
 9168                    let prefix_trimmed_lengths = full_comment_prefixes
 9169                        .iter()
 9170                        .map(|p| p.trim_end_matches(' ').len())
 9171                        .collect::<SmallVec<[usize; 4]>>();
 9172
 9173                    let mut all_selection_lines_are_comments = true;
 9174
 9175                    for row in start_row.0..=end_row.0 {
 9176                        let row = MultiBufferRow(row);
 9177                        if start_row < end_row && snapshot.is_line_blank(row) {
 9178                            continue;
 9179                        }
 9180
 9181                        let prefix_range = full_comment_prefixes
 9182                            .iter()
 9183                            .zip(prefix_trimmed_lengths.iter().copied())
 9184                            .map(|(prefix, trimmed_prefix_len)| {
 9185                                comment_prefix_range(
 9186                                    snapshot.deref(),
 9187                                    row,
 9188                                    &prefix[..trimmed_prefix_len],
 9189                                    &prefix[trimmed_prefix_len..],
 9190                                    ignore_indent,
 9191                                )
 9192                            })
 9193                            .max_by_key(|range| range.end.column - range.start.column)
 9194                            .expect("prefixes is non-empty");
 9195
 9196                        if prefix_range.is_empty() {
 9197                            all_selection_lines_are_comments = false;
 9198                        }
 9199
 9200                        selection_edit_ranges.push(prefix_range);
 9201                    }
 9202
 9203                    if all_selection_lines_are_comments {
 9204                        edits.extend(
 9205                            selection_edit_ranges
 9206                                .iter()
 9207                                .cloned()
 9208                                .map(|range| (range, empty_str.clone())),
 9209                        );
 9210                    } else {
 9211                        let min_column = selection_edit_ranges
 9212                            .iter()
 9213                            .map(|range| range.start.column)
 9214                            .min()
 9215                            .unwrap_or(0);
 9216                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9217                            let position = Point::new(range.start.row, min_column);
 9218                            (position..position, first_prefix.clone())
 9219                        }));
 9220                    }
 9221                } else if let Some((full_comment_prefix, comment_suffix)) =
 9222                    language.block_comment_delimiters()
 9223                {
 9224                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9225                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9226                    let prefix_range = comment_prefix_range(
 9227                        snapshot.deref(),
 9228                        start_row,
 9229                        comment_prefix,
 9230                        comment_prefix_whitespace,
 9231                        ignore_indent,
 9232                    );
 9233                    let suffix_range = comment_suffix_range(
 9234                        snapshot.deref(),
 9235                        end_row,
 9236                        comment_suffix.trim_start_matches(' '),
 9237                        comment_suffix.starts_with(' '),
 9238                    );
 9239
 9240                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9241                        edits.push((
 9242                            prefix_range.start..prefix_range.start,
 9243                            full_comment_prefix.clone(),
 9244                        ));
 9245                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9246                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9247                    } else {
 9248                        edits.push((prefix_range, empty_str.clone()));
 9249                        edits.push((suffix_range, empty_str.clone()));
 9250                    }
 9251                } else {
 9252                    continue;
 9253                }
 9254            }
 9255
 9256            drop(snapshot);
 9257            this.buffer.update(cx, |buffer, cx| {
 9258                buffer.edit(edits, None, cx);
 9259            });
 9260
 9261            // Adjust selections so that they end before any comment suffixes that
 9262            // were inserted.
 9263            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9264            let mut selections = this.selections.all::<Point>(cx);
 9265            let snapshot = this.buffer.read(cx).read(cx);
 9266            for selection in &mut selections {
 9267                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9268                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9269                        Ordering::Less => {
 9270                            suffixes_inserted.next();
 9271                            continue;
 9272                        }
 9273                        Ordering::Greater => break,
 9274                        Ordering::Equal => {
 9275                            if selection.end.column == snapshot.line_len(row) {
 9276                                if selection.is_empty() {
 9277                                    selection.start.column -= suffix_len as u32;
 9278                                }
 9279                                selection.end.column -= suffix_len as u32;
 9280                            }
 9281                            break;
 9282                        }
 9283                    }
 9284                }
 9285            }
 9286
 9287            drop(snapshot);
 9288            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9289                s.select(selections)
 9290            });
 9291
 9292            let selections = this.selections.all::<Point>(cx);
 9293            let selections_on_single_row = selections.windows(2).all(|selections| {
 9294                selections[0].start.row == selections[1].start.row
 9295                    && selections[0].end.row == selections[1].end.row
 9296                    && selections[0].start.row == selections[0].end.row
 9297            });
 9298            let selections_selecting = selections
 9299                .iter()
 9300                .any(|selection| selection.start != selection.end);
 9301            let advance_downwards = action.advance_downwards
 9302                && selections_on_single_row
 9303                && !selections_selecting
 9304                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9305
 9306            if advance_downwards {
 9307                let snapshot = this.buffer.read(cx).snapshot(cx);
 9308
 9309                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9310                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9311                        let mut point = display_point.to_point(display_snapshot);
 9312                        point.row += 1;
 9313                        point = snapshot.clip_point(point, Bias::Left);
 9314                        let display_point = point.to_display_point(display_snapshot);
 9315                        let goal = SelectionGoal::HorizontalPosition(
 9316                            display_snapshot
 9317                                .x_for_display_point(display_point, text_layout_details)
 9318                                .into(),
 9319                        );
 9320                        (display_point, goal)
 9321                    })
 9322                });
 9323            }
 9324        });
 9325    }
 9326
 9327    pub fn select_enclosing_symbol(
 9328        &mut self,
 9329        _: &SelectEnclosingSymbol,
 9330        window: &mut Window,
 9331        cx: &mut Context<Self>,
 9332    ) {
 9333        let buffer = self.buffer.read(cx).snapshot(cx);
 9334        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9335
 9336        fn update_selection(
 9337            selection: &Selection<usize>,
 9338            buffer_snap: &MultiBufferSnapshot,
 9339        ) -> Option<Selection<usize>> {
 9340            let cursor = selection.head();
 9341            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9342            for symbol in symbols.iter().rev() {
 9343                let start = symbol.range.start.to_offset(buffer_snap);
 9344                let end = symbol.range.end.to_offset(buffer_snap);
 9345                let new_range = start..end;
 9346                if start < selection.start || end > selection.end {
 9347                    return Some(Selection {
 9348                        id: selection.id,
 9349                        start: new_range.start,
 9350                        end: new_range.end,
 9351                        goal: SelectionGoal::None,
 9352                        reversed: selection.reversed,
 9353                    });
 9354                }
 9355            }
 9356            None
 9357        }
 9358
 9359        let mut selected_larger_symbol = false;
 9360        let new_selections = old_selections
 9361            .iter()
 9362            .map(|selection| match update_selection(selection, &buffer) {
 9363                Some(new_selection) => {
 9364                    if new_selection.range() != selection.range() {
 9365                        selected_larger_symbol = true;
 9366                    }
 9367                    new_selection
 9368                }
 9369                None => selection.clone(),
 9370            })
 9371            .collect::<Vec<_>>();
 9372
 9373        if selected_larger_symbol {
 9374            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9375                s.select(new_selections);
 9376            });
 9377        }
 9378    }
 9379
 9380    pub fn select_larger_syntax_node(
 9381        &mut self,
 9382        _: &SelectLargerSyntaxNode,
 9383        window: &mut Window,
 9384        cx: &mut Context<Self>,
 9385    ) {
 9386        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9387        let buffer = self.buffer.read(cx).snapshot(cx);
 9388        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9389
 9390        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9391        let mut selected_larger_node = false;
 9392        let new_selections = old_selections
 9393            .iter()
 9394            .map(|selection| {
 9395                let old_range = selection.start..selection.end;
 9396                let mut new_range = old_range.clone();
 9397                let mut new_node = None;
 9398                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9399                {
 9400                    new_node = Some(node);
 9401                    new_range = containing_range;
 9402                    if !display_map.intersects_fold(new_range.start)
 9403                        && !display_map.intersects_fold(new_range.end)
 9404                    {
 9405                        break;
 9406                    }
 9407                }
 9408
 9409                if let Some(node) = new_node {
 9410                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9411                    // nodes. Parent and grandparent are also logged because this operation will not
 9412                    // visit nodes that have the same range as their parent.
 9413                    log::info!("Node: {node:?}");
 9414                    let parent = node.parent();
 9415                    log::info!("Parent: {parent:?}");
 9416                    let grandparent = parent.and_then(|x| x.parent());
 9417                    log::info!("Grandparent: {grandparent:?}");
 9418                }
 9419
 9420                selected_larger_node |= new_range != old_range;
 9421                Selection {
 9422                    id: selection.id,
 9423                    start: new_range.start,
 9424                    end: new_range.end,
 9425                    goal: SelectionGoal::None,
 9426                    reversed: selection.reversed,
 9427                }
 9428            })
 9429            .collect::<Vec<_>>();
 9430
 9431        if selected_larger_node {
 9432            stack.push(old_selections);
 9433            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9434                s.select(new_selections);
 9435            });
 9436        }
 9437        self.select_larger_syntax_node_stack = stack;
 9438    }
 9439
 9440    pub fn select_smaller_syntax_node(
 9441        &mut self,
 9442        _: &SelectSmallerSyntaxNode,
 9443        window: &mut Window,
 9444        cx: &mut Context<Self>,
 9445    ) {
 9446        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9447        if let Some(selections) = stack.pop() {
 9448            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9449                s.select(selections.to_vec());
 9450            });
 9451        }
 9452        self.select_larger_syntax_node_stack = stack;
 9453    }
 9454
 9455    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9456        if !EditorSettings::get_global(cx).gutter.runnables {
 9457            self.clear_tasks();
 9458            return Task::ready(());
 9459        }
 9460        let project = self.project.as_ref().map(Entity::downgrade);
 9461        cx.spawn_in(window, |this, mut cx| async move {
 9462            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9463            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9464                return;
 9465            };
 9466            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9467                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9468            }) else {
 9469                return;
 9470            };
 9471
 9472            let hide_runnables = project
 9473                .update(&mut cx, |project, cx| {
 9474                    // Do not display any test indicators in non-dev server remote projects.
 9475                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9476                })
 9477                .unwrap_or(true);
 9478            if hide_runnables {
 9479                return;
 9480            }
 9481            let new_rows =
 9482                cx.background_executor()
 9483                    .spawn({
 9484                        let snapshot = display_snapshot.clone();
 9485                        async move {
 9486                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9487                        }
 9488                    })
 9489                    .await;
 9490
 9491            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9492            this.update(&mut cx, |this, _| {
 9493                this.clear_tasks();
 9494                for (key, value) in rows {
 9495                    this.insert_tasks(key, value);
 9496                }
 9497            })
 9498            .ok();
 9499        })
 9500    }
 9501    fn fetch_runnable_ranges(
 9502        snapshot: &DisplaySnapshot,
 9503        range: Range<Anchor>,
 9504    ) -> Vec<language::RunnableRange> {
 9505        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9506    }
 9507
 9508    fn runnable_rows(
 9509        project: Entity<Project>,
 9510        snapshot: DisplaySnapshot,
 9511        runnable_ranges: Vec<RunnableRange>,
 9512        mut cx: AsyncWindowContext,
 9513    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9514        runnable_ranges
 9515            .into_iter()
 9516            .filter_map(|mut runnable| {
 9517                let tasks = cx
 9518                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9519                    .ok()?;
 9520                if tasks.is_empty() {
 9521                    return None;
 9522                }
 9523
 9524                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9525
 9526                let row = snapshot
 9527                    .buffer_snapshot
 9528                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9529                    .1
 9530                    .start
 9531                    .row;
 9532
 9533                let context_range =
 9534                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9535                Some((
 9536                    (runnable.buffer_id, row),
 9537                    RunnableTasks {
 9538                        templates: tasks,
 9539                        offset: MultiBufferOffset(runnable.run_range.start),
 9540                        context_range,
 9541                        column: point.column,
 9542                        extra_variables: runnable.extra_captures,
 9543                    },
 9544                ))
 9545            })
 9546            .collect()
 9547    }
 9548
 9549    fn templates_with_tags(
 9550        project: &Entity<Project>,
 9551        runnable: &mut Runnable,
 9552        cx: &mut App,
 9553    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9554        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9555            let (worktree_id, file) = project
 9556                .buffer_for_id(runnable.buffer, cx)
 9557                .and_then(|buffer| buffer.read(cx).file())
 9558                .map(|file| (file.worktree_id(cx), file.clone()))
 9559                .unzip();
 9560
 9561            (
 9562                project.task_store().read(cx).task_inventory().cloned(),
 9563                worktree_id,
 9564                file,
 9565            )
 9566        });
 9567
 9568        let tags = mem::take(&mut runnable.tags);
 9569        let mut tags: Vec<_> = tags
 9570            .into_iter()
 9571            .flat_map(|tag| {
 9572                let tag = tag.0.clone();
 9573                inventory
 9574                    .as_ref()
 9575                    .into_iter()
 9576                    .flat_map(|inventory| {
 9577                        inventory.read(cx).list_tasks(
 9578                            file.clone(),
 9579                            Some(runnable.language.clone()),
 9580                            worktree_id,
 9581                            cx,
 9582                        )
 9583                    })
 9584                    .filter(move |(_, template)| {
 9585                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9586                    })
 9587            })
 9588            .sorted_by_key(|(kind, _)| kind.to_owned())
 9589            .collect();
 9590        if let Some((leading_tag_source, _)) = tags.first() {
 9591            // Strongest source wins; if we have worktree tag binding, prefer that to
 9592            // global and language bindings;
 9593            // if we have a global binding, prefer that to language binding.
 9594            let first_mismatch = tags
 9595                .iter()
 9596                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9597            if let Some(index) = first_mismatch {
 9598                tags.truncate(index);
 9599            }
 9600        }
 9601
 9602        tags
 9603    }
 9604
 9605    pub fn move_to_enclosing_bracket(
 9606        &mut self,
 9607        _: &MoveToEnclosingBracket,
 9608        window: &mut Window,
 9609        cx: &mut Context<Self>,
 9610    ) {
 9611        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9612            s.move_offsets_with(|snapshot, selection| {
 9613                let Some(enclosing_bracket_ranges) =
 9614                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9615                else {
 9616                    return;
 9617                };
 9618
 9619                let mut best_length = usize::MAX;
 9620                let mut best_inside = false;
 9621                let mut best_in_bracket_range = false;
 9622                let mut best_destination = None;
 9623                for (open, close) in enclosing_bracket_ranges {
 9624                    let close = close.to_inclusive();
 9625                    let length = close.end() - open.start;
 9626                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9627                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9628                        || close.contains(&selection.head());
 9629
 9630                    // If best is next to a bracket and current isn't, skip
 9631                    if !in_bracket_range && best_in_bracket_range {
 9632                        continue;
 9633                    }
 9634
 9635                    // Prefer smaller lengths unless best is inside and current isn't
 9636                    if length > best_length && (best_inside || !inside) {
 9637                        continue;
 9638                    }
 9639
 9640                    best_length = length;
 9641                    best_inside = inside;
 9642                    best_in_bracket_range = in_bracket_range;
 9643                    best_destination = Some(
 9644                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9645                            if inside {
 9646                                open.end
 9647                            } else {
 9648                                open.start
 9649                            }
 9650                        } else if inside {
 9651                            *close.start()
 9652                        } else {
 9653                            *close.end()
 9654                        },
 9655                    );
 9656                }
 9657
 9658                if let Some(destination) = best_destination {
 9659                    selection.collapse_to(destination, SelectionGoal::None);
 9660                }
 9661            })
 9662        });
 9663    }
 9664
 9665    pub fn undo_selection(
 9666        &mut self,
 9667        _: &UndoSelection,
 9668        window: &mut Window,
 9669        cx: &mut Context<Self>,
 9670    ) {
 9671        self.end_selection(window, cx);
 9672        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9673        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9674            self.change_selections(None, window, cx, |s| {
 9675                s.select_anchors(entry.selections.to_vec())
 9676            });
 9677            self.select_next_state = entry.select_next_state;
 9678            self.select_prev_state = entry.select_prev_state;
 9679            self.add_selections_state = entry.add_selections_state;
 9680            self.request_autoscroll(Autoscroll::newest(), cx);
 9681        }
 9682        self.selection_history.mode = SelectionHistoryMode::Normal;
 9683    }
 9684
 9685    pub fn redo_selection(
 9686        &mut self,
 9687        _: &RedoSelection,
 9688        window: &mut Window,
 9689        cx: &mut Context<Self>,
 9690    ) {
 9691        self.end_selection(window, cx);
 9692        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9693        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9694            self.change_selections(None, window, cx, |s| {
 9695                s.select_anchors(entry.selections.to_vec())
 9696            });
 9697            self.select_next_state = entry.select_next_state;
 9698            self.select_prev_state = entry.select_prev_state;
 9699            self.add_selections_state = entry.add_selections_state;
 9700            self.request_autoscroll(Autoscroll::newest(), cx);
 9701        }
 9702        self.selection_history.mode = SelectionHistoryMode::Normal;
 9703    }
 9704
 9705    pub fn expand_excerpts(
 9706        &mut self,
 9707        action: &ExpandExcerpts,
 9708        _: &mut Window,
 9709        cx: &mut Context<Self>,
 9710    ) {
 9711        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9712    }
 9713
 9714    pub fn expand_excerpts_down(
 9715        &mut self,
 9716        action: &ExpandExcerptsDown,
 9717        _: &mut Window,
 9718        cx: &mut Context<Self>,
 9719    ) {
 9720        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9721    }
 9722
 9723    pub fn expand_excerpts_up(
 9724        &mut self,
 9725        action: &ExpandExcerptsUp,
 9726        _: &mut Window,
 9727        cx: &mut Context<Self>,
 9728    ) {
 9729        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9730    }
 9731
 9732    pub fn expand_excerpts_for_direction(
 9733        &mut self,
 9734        lines: u32,
 9735        direction: ExpandExcerptDirection,
 9736
 9737        cx: &mut Context<Self>,
 9738    ) {
 9739        let selections = self.selections.disjoint_anchors();
 9740
 9741        let lines = if lines == 0 {
 9742            EditorSettings::get_global(cx).expand_excerpt_lines
 9743        } else {
 9744            lines
 9745        };
 9746
 9747        self.buffer.update(cx, |buffer, cx| {
 9748            let snapshot = buffer.snapshot(cx);
 9749            let mut excerpt_ids = selections
 9750                .iter()
 9751                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
 9752                .collect::<Vec<_>>();
 9753            excerpt_ids.sort();
 9754            excerpt_ids.dedup();
 9755            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9756        })
 9757    }
 9758
 9759    pub fn expand_excerpt(
 9760        &mut self,
 9761        excerpt: ExcerptId,
 9762        direction: ExpandExcerptDirection,
 9763        cx: &mut Context<Self>,
 9764    ) {
 9765        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9766        self.buffer.update(cx, |buffer, cx| {
 9767            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9768        })
 9769    }
 9770
 9771    pub fn go_to_singleton_buffer_point(
 9772        &mut self,
 9773        point: Point,
 9774        window: &mut Window,
 9775        cx: &mut Context<Self>,
 9776    ) {
 9777        self.go_to_singleton_buffer_range(point..point, window, cx);
 9778    }
 9779
 9780    pub fn go_to_singleton_buffer_range(
 9781        &mut self,
 9782        range: Range<Point>,
 9783        window: &mut Window,
 9784        cx: &mut Context<Self>,
 9785    ) {
 9786        let multibuffer = self.buffer().read(cx);
 9787        let Some(buffer) = multibuffer.as_singleton() else {
 9788            return;
 9789        };
 9790        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
 9791            return;
 9792        };
 9793        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
 9794            return;
 9795        };
 9796        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
 9797            s.select_anchor_ranges([start..end])
 9798        });
 9799    }
 9800
 9801    fn go_to_diagnostic(
 9802        &mut self,
 9803        _: &GoToDiagnostic,
 9804        window: &mut Window,
 9805        cx: &mut Context<Self>,
 9806    ) {
 9807        self.go_to_diagnostic_impl(Direction::Next, window, cx)
 9808    }
 9809
 9810    fn go_to_prev_diagnostic(
 9811        &mut self,
 9812        _: &GoToPrevDiagnostic,
 9813        window: &mut Window,
 9814        cx: &mut Context<Self>,
 9815    ) {
 9816        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
 9817    }
 9818
 9819    pub fn go_to_diagnostic_impl(
 9820        &mut self,
 9821        direction: Direction,
 9822        window: &mut Window,
 9823        cx: &mut Context<Self>,
 9824    ) {
 9825        let buffer = self.buffer.read(cx).snapshot(cx);
 9826        let selection = self.selections.newest::<usize>(cx);
 9827
 9828        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9829        if direction == Direction::Next {
 9830            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9831                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
 9832                    return;
 9833                };
 9834                self.activate_diagnostics(
 9835                    buffer_id,
 9836                    popover.local_diagnostic.diagnostic.group_id,
 9837                    window,
 9838                    cx,
 9839                );
 9840                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9841                    let primary_range_start = active_diagnostics.primary_range.start;
 9842                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9843                        let mut new_selection = s.newest_anchor().clone();
 9844                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9845                        s.select_anchors(vec![new_selection.clone()]);
 9846                    });
 9847                    self.refresh_inline_completion(false, true, window, cx);
 9848                }
 9849                return;
 9850            }
 9851        }
 9852
 9853        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9854            active_diagnostics
 9855                .primary_range
 9856                .to_offset(&buffer)
 9857                .to_inclusive()
 9858        });
 9859        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9860            if active_primary_range.contains(&selection.head()) {
 9861                *active_primary_range.start()
 9862            } else {
 9863                selection.head()
 9864            }
 9865        } else {
 9866            selection.head()
 9867        };
 9868        let snapshot = self.snapshot(window, cx);
 9869        loop {
 9870            let mut diagnostics;
 9871            if direction == Direction::Prev {
 9872                diagnostics = buffer
 9873                    .diagnostics_in_range::<_, usize>(0..search_start)
 9874                    .collect::<Vec<_>>();
 9875                diagnostics.reverse();
 9876            } else {
 9877                diagnostics = buffer
 9878                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
 9879                    .collect::<Vec<_>>();
 9880            };
 9881            let group = diagnostics
 9882                .into_iter()
 9883                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
 9884                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9885                // be sorted in a stable way
 9886                // skip until we are at current active diagnostic, if it exists
 9887                .skip_while(|entry| {
 9888                    let is_in_range = match direction {
 9889                        Direction::Prev => entry.range.end > search_start,
 9890                        Direction::Next => entry.range.start < search_start,
 9891                    };
 9892                    is_in_range
 9893                        && self
 9894                            .active_diagnostics
 9895                            .as_ref()
 9896                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9897                })
 9898                .find_map(|entry| {
 9899                    if entry.diagnostic.is_primary
 9900                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9901                        && entry.range.start != entry.range.end
 9902                        // if we match with the active diagnostic, skip it
 9903                        && Some(entry.diagnostic.group_id)
 9904                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9905                    {
 9906                        Some((entry.range, entry.diagnostic.group_id))
 9907                    } else {
 9908                        None
 9909                    }
 9910                });
 9911
 9912            if let Some((primary_range, group_id)) = group {
 9913                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
 9914                    return;
 9915                };
 9916                self.activate_diagnostics(buffer_id, group_id, window, cx);
 9917                if self.active_diagnostics.is_some() {
 9918                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9919                        s.select(vec![Selection {
 9920                            id: selection.id,
 9921                            start: primary_range.start,
 9922                            end: primary_range.start,
 9923                            reversed: false,
 9924                            goal: SelectionGoal::None,
 9925                        }]);
 9926                    });
 9927                    self.refresh_inline_completion(false, true, window, cx);
 9928                }
 9929                break;
 9930            } else {
 9931                // Cycle around to the start of the buffer, potentially moving back to the start of
 9932                // the currently active diagnostic.
 9933                active_primary_range.take();
 9934                if direction == Direction::Prev {
 9935                    if search_start == buffer.len() {
 9936                        break;
 9937                    } else {
 9938                        search_start = buffer.len();
 9939                    }
 9940                } else if search_start == 0 {
 9941                    break;
 9942                } else {
 9943                    search_start = 0;
 9944                }
 9945            }
 9946        }
 9947    }
 9948
 9949    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
 9950        let snapshot = self.snapshot(window, cx);
 9951        let selection = self.selections.newest::<Point>(cx);
 9952        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
 9953    }
 9954
 9955    fn go_to_hunk_after_position(
 9956        &mut self,
 9957        snapshot: &EditorSnapshot,
 9958        position: Point,
 9959        window: &mut Window,
 9960        cx: &mut Context<Editor>,
 9961    ) -> Option<MultiBufferDiffHunk> {
 9962        let mut hunk = snapshot
 9963            .buffer_snapshot
 9964            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
 9965            .find(|hunk| hunk.row_range.start.0 > position.row);
 9966        if hunk.is_none() {
 9967            hunk = snapshot
 9968                .buffer_snapshot
 9969                .diff_hunks_in_range(Point::zero()..position)
 9970                .find(|hunk| hunk.row_range.end.0 < position.row)
 9971        }
 9972        if let Some(hunk) = &hunk {
 9973            let destination = Point::new(hunk.row_range.start.0, 0);
 9974            self.unfold_ranges(&[destination..destination], false, false, cx);
 9975            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9976                s.select_ranges(vec![destination..destination]);
 9977            });
 9978        }
 9979
 9980        hunk
 9981    }
 9982
 9983    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
 9984        let snapshot = self.snapshot(window, cx);
 9985        let selection = self.selections.newest::<Point>(cx);
 9986        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
 9987    }
 9988
 9989    fn go_to_hunk_before_position(
 9990        &mut self,
 9991        snapshot: &EditorSnapshot,
 9992        position: Point,
 9993        window: &mut Window,
 9994        cx: &mut Context<Editor>,
 9995    ) -> Option<MultiBufferDiffHunk> {
 9996        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
 9997        if hunk.is_none() {
 9998            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
 9999        }
10000        if let Some(hunk) = &hunk {
10001            let destination = Point::new(hunk.row_range.start.0, 0);
10002            self.unfold_ranges(&[destination..destination], false, false, cx);
10003            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10004                s.select_ranges(vec![destination..destination]);
10005            });
10006        }
10007
10008        hunk
10009    }
10010
10011    pub fn go_to_definition(
10012        &mut self,
10013        _: &GoToDefinition,
10014        window: &mut Window,
10015        cx: &mut Context<Self>,
10016    ) -> Task<Result<Navigated>> {
10017        let definition =
10018            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10019        cx.spawn_in(window, |editor, mut cx| async move {
10020            if definition.await? == Navigated::Yes {
10021                return Ok(Navigated::Yes);
10022            }
10023            match editor.update_in(&mut cx, |editor, window, cx| {
10024                editor.find_all_references(&FindAllReferences, window, cx)
10025            })? {
10026                Some(references) => references.await,
10027                None => Ok(Navigated::No),
10028            }
10029        })
10030    }
10031
10032    pub fn go_to_declaration(
10033        &mut self,
10034        _: &GoToDeclaration,
10035        window: &mut Window,
10036        cx: &mut Context<Self>,
10037    ) -> Task<Result<Navigated>> {
10038        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10039    }
10040
10041    pub fn go_to_declaration_split(
10042        &mut self,
10043        _: &GoToDeclaration,
10044        window: &mut Window,
10045        cx: &mut Context<Self>,
10046    ) -> Task<Result<Navigated>> {
10047        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10048    }
10049
10050    pub fn go_to_implementation(
10051        &mut self,
10052        _: &GoToImplementation,
10053        window: &mut Window,
10054        cx: &mut Context<Self>,
10055    ) -> Task<Result<Navigated>> {
10056        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10057    }
10058
10059    pub fn go_to_implementation_split(
10060        &mut self,
10061        _: &GoToImplementationSplit,
10062        window: &mut Window,
10063        cx: &mut Context<Self>,
10064    ) -> Task<Result<Navigated>> {
10065        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10066    }
10067
10068    pub fn go_to_type_definition(
10069        &mut self,
10070        _: &GoToTypeDefinition,
10071        window: &mut Window,
10072        cx: &mut Context<Self>,
10073    ) -> Task<Result<Navigated>> {
10074        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10075    }
10076
10077    pub fn go_to_definition_split(
10078        &mut self,
10079        _: &GoToDefinitionSplit,
10080        window: &mut Window,
10081        cx: &mut Context<Self>,
10082    ) -> Task<Result<Navigated>> {
10083        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10084    }
10085
10086    pub fn go_to_type_definition_split(
10087        &mut self,
10088        _: &GoToTypeDefinitionSplit,
10089        window: &mut Window,
10090        cx: &mut Context<Self>,
10091    ) -> Task<Result<Navigated>> {
10092        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10093    }
10094
10095    fn go_to_definition_of_kind(
10096        &mut self,
10097        kind: GotoDefinitionKind,
10098        split: bool,
10099        window: &mut Window,
10100        cx: &mut Context<Self>,
10101    ) -> Task<Result<Navigated>> {
10102        let Some(provider) = self.semantics_provider.clone() else {
10103            return Task::ready(Ok(Navigated::No));
10104        };
10105        let head = self.selections.newest::<usize>(cx).head();
10106        let buffer = self.buffer.read(cx);
10107        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10108            text_anchor
10109        } else {
10110            return Task::ready(Ok(Navigated::No));
10111        };
10112
10113        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10114            return Task::ready(Ok(Navigated::No));
10115        };
10116
10117        cx.spawn_in(window, |editor, mut cx| async move {
10118            let definitions = definitions.await?;
10119            let navigated = editor
10120                .update_in(&mut cx, |editor, window, cx| {
10121                    editor.navigate_to_hover_links(
10122                        Some(kind),
10123                        definitions
10124                            .into_iter()
10125                            .filter(|location| {
10126                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10127                            })
10128                            .map(HoverLink::Text)
10129                            .collect::<Vec<_>>(),
10130                        split,
10131                        window,
10132                        cx,
10133                    )
10134                })?
10135                .await?;
10136            anyhow::Ok(navigated)
10137        })
10138    }
10139
10140    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10141        let selection = self.selections.newest_anchor();
10142        let head = selection.head();
10143        let tail = selection.tail();
10144
10145        let Some((buffer, start_position)) =
10146            self.buffer.read(cx).text_anchor_for_position(head, cx)
10147        else {
10148            return;
10149        };
10150
10151        let end_position = if head != tail {
10152            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10153                return;
10154            };
10155            Some(pos)
10156        } else {
10157            None
10158        };
10159
10160        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10161            let url = if let Some(end_pos) = end_position {
10162                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10163            } else {
10164                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10165            };
10166
10167            if let Some(url) = url {
10168                editor.update(&mut cx, |_, cx| {
10169                    cx.open_url(&url);
10170                })
10171            } else {
10172                Ok(())
10173            }
10174        });
10175
10176        url_finder.detach();
10177    }
10178
10179    pub fn open_selected_filename(
10180        &mut self,
10181        _: &OpenSelectedFilename,
10182        window: &mut Window,
10183        cx: &mut Context<Self>,
10184    ) {
10185        let Some(workspace) = self.workspace() else {
10186            return;
10187        };
10188
10189        let position = self.selections.newest_anchor().head();
10190
10191        let Some((buffer, buffer_position)) =
10192            self.buffer.read(cx).text_anchor_for_position(position, cx)
10193        else {
10194            return;
10195        };
10196
10197        let project = self.project.clone();
10198
10199        cx.spawn_in(window, |_, mut cx| async move {
10200            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10201
10202            if let Some((_, path)) = result {
10203                workspace
10204                    .update_in(&mut cx, |workspace, window, cx| {
10205                        workspace.open_resolved_path(path, window, cx)
10206                    })?
10207                    .await?;
10208            }
10209            anyhow::Ok(())
10210        })
10211        .detach();
10212    }
10213
10214    pub(crate) fn navigate_to_hover_links(
10215        &mut self,
10216        kind: Option<GotoDefinitionKind>,
10217        mut definitions: Vec<HoverLink>,
10218        split: bool,
10219        window: &mut Window,
10220        cx: &mut Context<Editor>,
10221    ) -> Task<Result<Navigated>> {
10222        // If there is one definition, just open it directly
10223        if definitions.len() == 1 {
10224            let definition = definitions.pop().unwrap();
10225
10226            enum TargetTaskResult {
10227                Location(Option<Location>),
10228                AlreadyNavigated,
10229            }
10230
10231            let target_task = match definition {
10232                HoverLink::Text(link) => {
10233                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10234                }
10235                HoverLink::InlayHint(lsp_location, server_id) => {
10236                    let computation =
10237                        self.compute_target_location(lsp_location, server_id, window, cx);
10238                    cx.background_executor().spawn(async move {
10239                        let location = computation.await?;
10240                        Ok(TargetTaskResult::Location(location))
10241                    })
10242                }
10243                HoverLink::Url(url) => {
10244                    cx.open_url(&url);
10245                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10246                }
10247                HoverLink::File(path) => {
10248                    if let Some(workspace) = self.workspace() {
10249                        cx.spawn_in(window, |_, mut cx| async move {
10250                            workspace
10251                                .update_in(&mut cx, |workspace, window, cx| {
10252                                    workspace.open_resolved_path(path, window, cx)
10253                                })?
10254                                .await
10255                                .map(|_| TargetTaskResult::AlreadyNavigated)
10256                        })
10257                    } else {
10258                        Task::ready(Ok(TargetTaskResult::Location(None)))
10259                    }
10260                }
10261            };
10262            cx.spawn_in(window, |editor, mut cx| async move {
10263                let target = match target_task.await.context("target resolution task")? {
10264                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10265                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10266                    TargetTaskResult::Location(Some(target)) => target,
10267                };
10268
10269                editor.update_in(&mut cx, |editor, window, cx| {
10270                    let Some(workspace) = editor.workspace() else {
10271                        return Navigated::No;
10272                    };
10273                    let pane = workspace.read(cx).active_pane().clone();
10274
10275                    let range = target.range.to_point(target.buffer.read(cx));
10276                    let range = editor.range_for_match(&range);
10277                    let range = collapse_multiline_range(range);
10278
10279                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10280                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10281                    } else {
10282                        window.defer(cx, move |window, cx| {
10283                            let target_editor: Entity<Self> =
10284                                workspace.update(cx, |workspace, cx| {
10285                                    let pane = if split {
10286                                        workspace.adjacent_pane(window, cx)
10287                                    } else {
10288                                        workspace.active_pane().clone()
10289                                    };
10290
10291                                    workspace.open_project_item(
10292                                        pane,
10293                                        target.buffer.clone(),
10294                                        true,
10295                                        true,
10296                                        window,
10297                                        cx,
10298                                    )
10299                                });
10300                            target_editor.update(cx, |target_editor, cx| {
10301                                // When selecting a definition in a different buffer, disable the nav history
10302                                // to avoid creating a history entry at the previous cursor location.
10303                                pane.update(cx, |pane, _| pane.disable_history());
10304                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10305                                pane.update(cx, |pane, _| pane.enable_history());
10306                            });
10307                        });
10308                    }
10309                    Navigated::Yes
10310                })
10311            })
10312        } else if !definitions.is_empty() {
10313            cx.spawn_in(window, |editor, mut cx| async move {
10314                let (title, location_tasks, workspace) = editor
10315                    .update_in(&mut cx, |editor, window, cx| {
10316                        let tab_kind = match kind {
10317                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10318                            _ => "Definitions",
10319                        };
10320                        let title = definitions
10321                            .iter()
10322                            .find_map(|definition| match definition {
10323                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10324                                    let buffer = origin.buffer.read(cx);
10325                                    format!(
10326                                        "{} for {}",
10327                                        tab_kind,
10328                                        buffer
10329                                            .text_for_range(origin.range.clone())
10330                                            .collect::<String>()
10331                                    )
10332                                }),
10333                                HoverLink::InlayHint(_, _) => None,
10334                                HoverLink::Url(_) => None,
10335                                HoverLink::File(_) => None,
10336                            })
10337                            .unwrap_or(tab_kind.to_string());
10338                        let location_tasks = definitions
10339                            .into_iter()
10340                            .map(|definition| match definition {
10341                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10342                                HoverLink::InlayHint(lsp_location, server_id) => editor
10343                                    .compute_target_location(lsp_location, server_id, window, cx),
10344                                HoverLink::Url(_) => Task::ready(Ok(None)),
10345                                HoverLink::File(_) => Task::ready(Ok(None)),
10346                            })
10347                            .collect::<Vec<_>>();
10348                        (title, location_tasks, editor.workspace().clone())
10349                    })
10350                    .context("location tasks preparation")?;
10351
10352                let locations = future::join_all(location_tasks)
10353                    .await
10354                    .into_iter()
10355                    .filter_map(|location| location.transpose())
10356                    .collect::<Result<_>>()
10357                    .context("location tasks")?;
10358
10359                let Some(workspace) = workspace else {
10360                    return Ok(Navigated::No);
10361                };
10362                let opened = workspace
10363                    .update_in(&mut cx, |workspace, window, cx| {
10364                        Self::open_locations_in_multibuffer(
10365                            workspace,
10366                            locations,
10367                            title,
10368                            split,
10369                            MultibufferSelectionMode::First,
10370                            window,
10371                            cx,
10372                        )
10373                    })
10374                    .ok();
10375
10376                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10377            })
10378        } else {
10379            Task::ready(Ok(Navigated::No))
10380        }
10381    }
10382
10383    fn compute_target_location(
10384        &self,
10385        lsp_location: lsp::Location,
10386        server_id: LanguageServerId,
10387        window: &mut Window,
10388        cx: &mut Context<Self>,
10389    ) -> Task<anyhow::Result<Option<Location>>> {
10390        let Some(project) = self.project.clone() else {
10391            return Task::ready(Ok(None));
10392        };
10393
10394        cx.spawn_in(window, move |editor, mut cx| async move {
10395            let location_task = editor.update(&mut cx, |_, cx| {
10396                project.update(cx, |project, cx| {
10397                    let language_server_name = project
10398                        .language_server_statuses(cx)
10399                        .find(|(id, _)| server_id == *id)
10400                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10401                    language_server_name.map(|language_server_name| {
10402                        project.open_local_buffer_via_lsp(
10403                            lsp_location.uri.clone(),
10404                            server_id,
10405                            language_server_name,
10406                            cx,
10407                        )
10408                    })
10409                })
10410            })?;
10411            let location = match location_task {
10412                Some(task) => Some({
10413                    let target_buffer_handle = task.await.context("open local buffer")?;
10414                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10415                        let target_start = target_buffer
10416                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10417                        let target_end = target_buffer
10418                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10419                        target_buffer.anchor_after(target_start)
10420                            ..target_buffer.anchor_before(target_end)
10421                    })?;
10422                    Location {
10423                        buffer: target_buffer_handle,
10424                        range,
10425                    }
10426                }),
10427                None => None,
10428            };
10429            Ok(location)
10430        })
10431    }
10432
10433    pub fn find_all_references(
10434        &mut self,
10435        _: &FindAllReferences,
10436        window: &mut Window,
10437        cx: &mut Context<Self>,
10438    ) -> Option<Task<Result<Navigated>>> {
10439        let selection = self.selections.newest::<usize>(cx);
10440        let multi_buffer = self.buffer.read(cx);
10441        let head = selection.head();
10442
10443        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10444        let head_anchor = multi_buffer_snapshot.anchor_at(
10445            head,
10446            if head < selection.tail() {
10447                Bias::Right
10448            } else {
10449                Bias::Left
10450            },
10451        );
10452
10453        match self
10454            .find_all_references_task_sources
10455            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10456        {
10457            Ok(_) => {
10458                log::info!(
10459                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10460                );
10461                return None;
10462            }
10463            Err(i) => {
10464                self.find_all_references_task_sources.insert(i, head_anchor);
10465            }
10466        }
10467
10468        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10469        let workspace = self.workspace()?;
10470        let project = workspace.read(cx).project().clone();
10471        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10472        Some(cx.spawn_in(window, |editor, mut cx| async move {
10473            let _cleanup = defer({
10474                let mut cx = cx.clone();
10475                move || {
10476                    let _ = editor.update(&mut cx, |editor, _| {
10477                        if let Ok(i) =
10478                            editor
10479                                .find_all_references_task_sources
10480                                .binary_search_by(|anchor| {
10481                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10482                                })
10483                        {
10484                            editor.find_all_references_task_sources.remove(i);
10485                        }
10486                    });
10487                }
10488            });
10489
10490            let locations = references.await?;
10491            if locations.is_empty() {
10492                return anyhow::Ok(Navigated::No);
10493            }
10494
10495            workspace.update_in(&mut cx, |workspace, window, cx| {
10496                let title = locations
10497                    .first()
10498                    .as_ref()
10499                    .map(|location| {
10500                        let buffer = location.buffer.read(cx);
10501                        format!(
10502                            "References to `{}`",
10503                            buffer
10504                                .text_for_range(location.range.clone())
10505                                .collect::<String>()
10506                        )
10507                    })
10508                    .unwrap();
10509                Self::open_locations_in_multibuffer(
10510                    workspace,
10511                    locations,
10512                    title,
10513                    false,
10514                    MultibufferSelectionMode::First,
10515                    window,
10516                    cx,
10517                );
10518                Navigated::Yes
10519            })
10520        }))
10521    }
10522
10523    /// Opens a multibuffer with the given project locations in it
10524    pub fn open_locations_in_multibuffer(
10525        workspace: &mut Workspace,
10526        mut locations: Vec<Location>,
10527        title: String,
10528        split: bool,
10529        multibuffer_selection_mode: MultibufferSelectionMode,
10530        window: &mut Window,
10531        cx: &mut Context<Workspace>,
10532    ) {
10533        // If there are multiple definitions, open them in a multibuffer
10534        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10535        let mut locations = locations.into_iter().peekable();
10536        let mut ranges = Vec::new();
10537        let capability = workspace.project().read(cx).capability();
10538
10539        let excerpt_buffer = cx.new(|cx| {
10540            let mut multibuffer = MultiBuffer::new(capability);
10541            while let Some(location) = locations.next() {
10542                let buffer = location.buffer.read(cx);
10543                let mut ranges_for_buffer = Vec::new();
10544                let range = location.range.to_offset(buffer);
10545                ranges_for_buffer.push(range.clone());
10546
10547                while let Some(next_location) = locations.peek() {
10548                    if next_location.buffer == location.buffer {
10549                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10550                        locations.next();
10551                    } else {
10552                        break;
10553                    }
10554                }
10555
10556                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10557                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10558                    location.buffer.clone(),
10559                    ranges_for_buffer,
10560                    DEFAULT_MULTIBUFFER_CONTEXT,
10561                    cx,
10562                ))
10563            }
10564
10565            multibuffer.with_title(title)
10566        });
10567
10568        let editor = cx.new(|cx| {
10569            Editor::for_multibuffer(
10570                excerpt_buffer,
10571                Some(workspace.project().clone()),
10572                true,
10573                window,
10574                cx,
10575            )
10576        });
10577        editor.update(cx, |editor, cx| {
10578            match multibuffer_selection_mode {
10579                MultibufferSelectionMode::First => {
10580                    if let Some(first_range) = ranges.first() {
10581                        editor.change_selections(None, window, cx, |selections| {
10582                            selections.clear_disjoint();
10583                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10584                        });
10585                    }
10586                    editor.highlight_background::<Self>(
10587                        &ranges,
10588                        |theme| theme.editor_highlighted_line_background,
10589                        cx,
10590                    );
10591                }
10592                MultibufferSelectionMode::All => {
10593                    editor.change_selections(None, window, cx, |selections| {
10594                        selections.clear_disjoint();
10595                        selections.select_anchor_ranges(ranges);
10596                    });
10597                }
10598            }
10599            editor.register_buffers_with_language_servers(cx);
10600        });
10601
10602        let item = Box::new(editor);
10603        let item_id = item.item_id();
10604
10605        if split {
10606            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10607        } else {
10608            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10609                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10610                    pane.close_current_preview_item(window, cx)
10611                } else {
10612                    None
10613                }
10614            });
10615            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10616        }
10617        workspace.active_pane().update(cx, |pane, cx| {
10618            pane.set_preview_item_id(Some(item_id), cx);
10619        });
10620    }
10621
10622    pub fn rename(
10623        &mut self,
10624        _: &Rename,
10625        window: &mut Window,
10626        cx: &mut Context<Self>,
10627    ) -> Option<Task<Result<()>>> {
10628        use language::ToOffset as _;
10629
10630        let provider = self.semantics_provider.clone()?;
10631        let selection = self.selections.newest_anchor().clone();
10632        let (cursor_buffer, cursor_buffer_position) = self
10633            .buffer
10634            .read(cx)
10635            .text_anchor_for_position(selection.head(), cx)?;
10636        let (tail_buffer, cursor_buffer_position_end) = self
10637            .buffer
10638            .read(cx)
10639            .text_anchor_for_position(selection.tail(), cx)?;
10640        if tail_buffer != cursor_buffer {
10641            return None;
10642        }
10643
10644        let snapshot = cursor_buffer.read(cx).snapshot();
10645        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10646        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10647        let prepare_rename = provider
10648            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10649            .unwrap_or_else(|| Task::ready(Ok(None)));
10650        drop(snapshot);
10651
10652        Some(cx.spawn_in(window, |this, mut cx| async move {
10653            let rename_range = if let Some(range) = prepare_rename.await? {
10654                Some(range)
10655            } else {
10656                this.update(&mut cx, |this, cx| {
10657                    let buffer = this.buffer.read(cx).snapshot(cx);
10658                    let mut buffer_highlights = this
10659                        .document_highlights_for_position(selection.head(), &buffer)
10660                        .filter(|highlight| {
10661                            highlight.start.excerpt_id == selection.head().excerpt_id
10662                                && highlight.end.excerpt_id == selection.head().excerpt_id
10663                        });
10664                    buffer_highlights
10665                        .next()
10666                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10667                })?
10668            };
10669            if let Some(rename_range) = rename_range {
10670                this.update_in(&mut cx, |this, window, cx| {
10671                    let snapshot = cursor_buffer.read(cx).snapshot();
10672                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10673                    let cursor_offset_in_rename_range =
10674                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10675                    let cursor_offset_in_rename_range_end =
10676                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10677
10678                    this.take_rename(false, window, cx);
10679                    let buffer = this.buffer.read(cx).read(cx);
10680                    let cursor_offset = selection.head().to_offset(&buffer);
10681                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10682                    let rename_end = rename_start + rename_buffer_range.len();
10683                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10684                    let mut old_highlight_id = None;
10685                    let old_name: Arc<str> = buffer
10686                        .chunks(rename_start..rename_end, true)
10687                        .map(|chunk| {
10688                            if old_highlight_id.is_none() {
10689                                old_highlight_id = chunk.syntax_highlight_id;
10690                            }
10691                            chunk.text
10692                        })
10693                        .collect::<String>()
10694                        .into();
10695
10696                    drop(buffer);
10697
10698                    // Position the selection in the rename editor so that it matches the current selection.
10699                    this.show_local_selections = false;
10700                    let rename_editor = cx.new(|cx| {
10701                        let mut editor = Editor::single_line(window, cx);
10702                        editor.buffer.update(cx, |buffer, cx| {
10703                            buffer.edit([(0..0, old_name.clone())], None, cx)
10704                        });
10705                        let rename_selection_range = match cursor_offset_in_rename_range
10706                            .cmp(&cursor_offset_in_rename_range_end)
10707                        {
10708                            Ordering::Equal => {
10709                                editor.select_all(&SelectAll, window, cx);
10710                                return editor;
10711                            }
10712                            Ordering::Less => {
10713                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10714                            }
10715                            Ordering::Greater => {
10716                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10717                            }
10718                        };
10719                        if rename_selection_range.end > old_name.len() {
10720                            editor.select_all(&SelectAll, window, cx);
10721                        } else {
10722                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10723                                s.select_ranges([rename_selection_range]);
10724                            });
10725                        }
10726                        editor
10727                    });
10728                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10729                        if e == &EditorEvent::Focused {
10730                            cx.emit(EditorEvent::FocusedIn)
10731                        }
10732                    })
10733                    .detach();
10734
10735                    let write_highlights =
10736                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10737                    let read_highlights =
10738                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10739                    let ranges = write_highlights
10740                        .iter()
10741                        .flat_map(|(_, ranges)| ranges.iter())
10742                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10743                        .cloned()
10744                        .collect();
10745
10746                    this.highlight_text::<Rename>(
10747                        ranges,
10748                        HighlightStyle {
10749                            fade_out: Some(0.6),
10750                            ..Default::default()
10751                        },
10752                        cx,
10753                    );
10754                    let rename_focus_handle = rename_editor.focus_handle(cx);
10755                    window.focus(&rename_focus_handle);
10756                    let block_id = this.insert_blocks(
10757                        [BlockProperties {
10758                            style: BlockStyle::Flex,
10759                            placement: BlockPlacement::Below(range.start),
10760                            height: 1,
10761                            render: Arc::new({
10762                                let rename_editor = rename_editor.clone();
10763                                move |cx: &mut BlockContext| {
10764                                    let mut text_style = cx.editor_style.text.clone();
10765                                    if let Some(highlight_style) = old_highlight_id
10766                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10767                                    {
10768                                        text_style = text_style.highlight(highlight_style);
10769                                    }
10770                                    div()
10771                                        .block_mouse_down()
10772                                        .pl(cx.anchor_x)
10773                                        .child(EditorElement::new(
10774                                            &rename_editor,
10775                                            EditorStyle {
10776                                                background: cx.theme().system().transparent,
10777                                                local_player: cx.editor_style.local_player,
10778                                                text: text_style,
10779                                                scrollbar_width: cx.editor_style.scrollbar_width,
10780                                                syntax: cx.editor_style.syntax.clone(),
10781                                                status: cx.editor_style.status.clone(),
10782                                                inlay_hints_style: HighlightStyle {
10783                                                    font_weight: Some(FontWeight::BOLD),
10784                                                    ..make_inlay_hints_style(cx.app)
10785                                                },
10786                                                inline_completion_styles: make_suggestion_styles(
10787                                                    cx.app,
10788                                                ),
10789                                                ..EditorStyle::default()
10790                                            },
10791                                        ))
10792                                        .into_any_element()
10793                                }
10794                            }),
10795                            priority: 0,
10796                        }],
10797                        Some(Autoscroll::fit()),
10798                        cx,
10799                    )[0];
10800                    this.pending_rename = Some(RenameState {
10801                        range,
10802                        old_name,
10803                        editor: rename_editor,
10804                        block_id,
10805                    });
10806                })?;
10807            }
10808
10809            Ok(())
10810        }))
10811    }
10812
10813    pub fn confirm_rename(
10814        &mut self,
10815        _: &ConfirmRename,
10816        window: &mut Window,
10817        cx: &mut Context<Self>,
10818    ) -> Option<Task<Result<()>>> {
10819        let rename = self.take_rename(false, window, cx)?;
10820        let workspace = self.workspace()?.downgrade();
10821        let (buffer, start) = self
10822            .buffer
10823            .read(cx)
10824            .text_anchor_for_position(rename.range.start, cx)?;
10825        let (end_buffer, _) = self
10826            .buffer
10827            .read(cx)
10828            .text_anchor_for_position(rename.range.end, cx)?;
10829        if buffer != end_buffer {
10830            return None;
10831        }
10832
10833        let old_name = rename.old_name;
10834        let new_name = rename.editor.read(cx).text(cx);
10835
10836        let rename = self.semantics_provider.as_ref()?.perform_rename(
10837            &buffer,
10838            start,
10839            new_name.clone(),
10840            cx,
10841        )?;
10842
10843        Some(cx.spawn_in(window, |editor, mut cx| async move {
10844            let project_transaction = rename.await?;
10845            Self::open_project_transaction(
10846                &editor,
10847                workspace,
10848                project_transaction,
10849                format!("Rename: {}{}", old_name, new_name),
10850                cx.clone(),
10851            )
10852            .await?;
10853
10854            editor.update(&mut cx, |editor, cx| {
10855                editor.refresh_document_highlights(cx);
10856            })?;
10857            Ok(())
10858        }))
10859    }
10860
10861    fn take_rename(
10862        &mut self,
10863        moving_cursor: bool,
10864        window: &mut Window,
10865        cx: &mut Context<Self>,
10866    ) -> Option<RenameState> {
10867        let rename = self.pending_rename.take()?;
10868        if rename.editor.focus_handle(cx).is_focused(window) {
10869            window.focus(&self.focus_handle);
10870        }
10871
10872        self.remove_blocks(
10873            [rename.block_id].into_iter().collect(),
10874            Some(Autoscroll::fit()),
10875            cx,
10876        );
10877        self.clear_highlights::<Rename>(cx);
10878        self.show_local_selections = true;
10879
10880        if moving_cursor {
10881            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10882                editor.selections.newest::<usize>(cx).head()
10883            });
10884
10885            // Update the selection to match the position of the selection inside
10886            // the rename editor.
10887            let snapshot = self.buffer.read(cx).read(cx);
10888            let rename_range = rename.range.to_offset(&snapshot);
10889            let cursor_in_editor = snapshot
10890                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10891                .min(rename_range.end);
10892            drop(snapshot);
10893
10894            self.change_selections(None, window, cx, |s| {
10895                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10896            });
10897        } else {
10898            self.refresh_document_highlights(cx);
10899        }
10900
10901        Some(rename)
10902    }
10903
10904    pub fn pending_rename(&self) -> Option<&RenameState> {
10905        self.pending_rename.as_ref()
10906    }
10907
10908    fn format(
10909        &mut self,
10910        _: &Format,
10911        window: &mut Window,
10912        cx: &mut Context<Self>,
10913    ) -> Option<Task<Result<()>>> {
10914        let project = match &self.project {
10915            Some(project) => project.clone(),
10916            None => return None,
10917        };
10918
10919        Some(self.perform_format(
10920            project,
10921            FormatTrigger::Manual,
10922            FormatTarget::Buffers,
10923            window,
10924            cx,
10925        ))
10926    }
10927
10928    fn format_selections(
10929        &mut self,
10930        _: &FormatSelections,
10931        window: &mut Window,
10932        cx: &mut Context<Self>,
10933    ) -> Option<Task<Result<()>>> {
10934        let project = match &self.project {
10935            Some(project) => project.clone(),
10936            None => return None,
10937        };
10938
10939        let ranges = self
10940            .selections
10941            .all_adjusted(cx)
10942            .into_iter()
10943            .map(|selection| selection.range())
10944            .collect_vec();
10945
10946        Some(self.perform_format(
10947            project,
10948            FormatTrigger::Manual,
10949            FormatTarget::Ranges(ranges),
10950            window,
10951            cx,
10952        ))
10953    }
10954
10955    fn perform_format(
10956        &mut self,
10957        project: Entity<Project>,
10958        trigger: FormatTrigger,
10959        target: FormatTarget,
10960        window: &mut Window,
10961        cx: &mut Context<Self>,
10962    ) -> Task<Result<()>> {
10963        let buffer = self.buffer.clone();
10964        let (buffers, target) = match target {
10965            FormatTarget::Buffers => {
10966                let mut buffers = buffer.read(cx).all_buffers();
10967                if trigger == FormatTrigger::Save {
10968                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10969                }
10970                (buffers, LspFormatTarget::Buffers)
10971            }
10972            FormatTarget::Ranges(selection_ranges) => {
10973                let multi_buffer = buffer.read(cx);
10974                let snapshot = multi_buffer.read(cx);
10975                let mut buffers = HashSet::default();
10976                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10977                    BTreeMap::new();
10978                for selection_range in selection_ranges {
10979                    for (buffer, buffer_range, _) in
10980                        snapshot.range_to_buffer_ranges(selection_range)
10981                    {
10982                        let buffer_id = buffer.remote_id();
10983                        let start = buffer.anchor_before(buffer_range.start);
10984                        let end = buffer.anchor_after(buffer_range.end);
10985                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10986                        buffer_id_to_ranges
10987                            .entry(buffer_id)
10988                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10989                            .or_insert_with(|| vec![start..end]);
10990                    }
10991                }
10992                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10993            }
10994        };
10995
10996        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10997        let format = project.update(cx, |project, cx| {
10998            project.format(buffers, target, true, trigger, cx)
10999        });
11000
11001        cx.spawn_in(window, |_, mut cx| async move {
11002            let transaction = futures::select_biased! {
11003                () = timeout => {
11004                    log::warn!("timed out waiting for formatting");
11005                    None
11006                }
11007                transaction = format.log_err().fuse() => transaction,
11008            };
11009
11010            buffer
11011                .update(&mut cx, |buffer, cx| {
11012                    if let Some(transaction) = transaction {
11013                        if !buffer.is_singleton() {
11014                            buffer.push_transaction(&transaction.0, cx);
11015                        }
11016                    }
11017
11018                    cx.notify();
11019                })
11020                .ok();
11021
11022            Ok(())
11023        })
11024    }
11025
11026    fn restart_language_server(
11027        &mut self,
11028        _: &RestartLanguageServer,
11029        _: &mut Window,
11030        cx: &mut Context<Self>,
11031    ) {
11032        if let Some(project) = self.project.clone() {
11033            self.buffer.update(cx, |multi_buffer, cx| {
11034                project.update(cx, |project, cx| {
11035                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11036                });
11037            })
11038        }
11039    }
11040
11041    fn cancel_language_server_work(
11042        &mut self,
11043        _: &actions::CancelLanguageServerWork,
11044        _: &mut Window,
11045        cx: &mut Context<Self>,
11046    ) {
11047        if let Some(project) = self.project.clone() {
11048            self.buffer.update(cx, |multi_buffer, cx| {
11049                project.update(cx, |project, cx| {
11050                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11051                });
11052            })
11053        }
11054    }
11055
11056    fn show_character_palette(
11057        &mut self,
11058        _: &ShowCharacterPalette,
11059        window: &mut Window,
11060        _: &mut Context<Self>,
11061    ) {
11062        window.show_character_palette();
11063    }
11064
11065    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11066        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11067            let buffer = self.buffer.read(cx).snapshot(cx);
11068            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11069            let is_valid = buffer
11070                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11071                .any(|entry| {
11072                    entry.diagnostic.is_primary
11073                        && !entry.range.is_empty()
11074                        && entry.range.start == primary_range_start
11075                        && entry.diagnostic.message == active_diagnostics.primary_message
11076                });
11077
11078            if is_valid != active_diagnostics.is_valid {
11079                active_diagnostics.is_valid = is_valid;
11080                let mut new_styles = HashMap::default();
11081                for (block_id, diagnostic) in &active_diagnostics.blocks {
11082                    new_styles.insert(
11083                        *block_id,
11084                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11085                    );
11086                }
11087                self.display_map.update(cx, |display_map, _cx| {
11088                    display_map.replace_blocks(new_styles)
11089                });
11090            }
11091        }
11092    }
11093
11094    fn activate_diagnostics(
11095        &mut self,
11096        buffer_id: BufferId,
11097        group_id: usize,
11098        window: &mut Window,
11099        cx: &mut Context<Self>,
11100    ) {
11101        self.dismiss_diagnostics(cx);
11102        let snapshot = self.snapshot(window, cx);
11103        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11104            let buffer = self.buffer.read(cx).snapshot(cx);
11105
11106            let mut primary_range = None;
11107            let mut primary_message = None;
11108            let diagnostic_group = buffer
11109                .diagnostic_group(buffer_id, group_id)
11110                .filter_map(|entry| {
11111                    let start = entry.range.start;
11112                    let end = entry.range.end;
11113                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11114                        && (start.row == end.row
11115                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11116                    {
11117                        return None;
11118                    }
11119                    if entry.diagnostic.is_primary {
11120                        primary_range = Some(entry.range.clone());
11121                        primary_message = Some(entry.diagnostic.message.clone());
11122                    }
11123                    Some(entry)
11124                })
11125                .collect::<Vec<_>>();
11126            let primary_range = primary_range?;
11127            let primary_message = primary_message?;
11128
11129            let blocks = display_map
11130                .insert_blocks(
11131                    diagnostic_group.iter().map(|entry| {
11132                        let diagnostic = entry.diagnostic.clone();
11133                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11134                        BlockProperties {
11135                            style: BlockStyle::Fixed,
11136                            placement: BlockPlacement::Below(
11137                                buffer.anchor_after(entry.range.start),
11138                            ),
11139                            height: message_height,
11140                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11141                            priority: 0,
11142                        }
11143                    }),
11144                    cx,
11145                )
11146                .into_iter()
11147                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11148                .collect();
11149
11150            Some(ActiveDiagnosticGroup {
11151                primary_range: buffer.anchor_before(primary_range.start)
11152                    ..buffer.anchor_after(primary_range.end),
11153                primary_message,
11154                group_id,
11155                blocks,
11156                is_valid: true,
11157            })
11158        });
11159    }
11160
11161    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11162        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11163            self.display_map.update(cx, |display_map, cx| {
11164                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11165            });
11166            cx.notify();
11167        }
11168    }
11169
11170    pub fn set_selections_from_remote(
11171        &mut self,
11172        selections: Vec<Selection<Anchor>>,
11173        pending_selection: Option<Selection<Anchor>>,
11174        window: &mut Window,
11175        cx: &mut Context<Self>,
11176    ) {
11177        let old_cursor_position = self.selections.newest_anchor().head();
11178        self.selections.change_with(cx, |s| {
11179            s.select_anchors(selections);
11180            if let Some(pending_selection) = pending_selection {
11181                s.set_pending(pending_selection, SelectMode::Character);
11182            } else {
11183                s.clear_pending();
11184            }
11185        });
11186        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11187    }
11188
11189    fn push_to_selection_history(&mut self) {
11190        self.selection_history.push(SelectionHistoryEntry {
11191            selections: self.selections.disjoint_anchors(),
11192            select_next_state: self.select_next_state.clone(),
11193            select_prev_state: self.select_prev_state.clone(),
11194            add_selections_state: self.add_selections_state.clone(),
11195        });
11196    }
11197
11198    pub fn transact(
11199        &mut self,
11200        window: &mut Window,
11201        cx: &mut Context<Self>,
11202        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11203    ) -> Option<TransactionId> {
11204        self.start_transaction_at(Instant::now(), window, cx);
11205        update(self, window, cx);
11206        self.end_transaction_at(Instant::now(), cx)
11207    }
11208
11209    pub fn start_transaction_at(
11210        &mut self,
11211        now: Instant,
11212        window: &mut Window,
11213        cx: &mut Context<Self>,
11214    ) {
11215        self.end_selection(window, cx);
11216        if let Some(tx_id) = self
11217            .buffer
11218            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11219        {
11220            self.selection_history
11221                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11222            cx.emit(EditorEvent::TransactionBegun {
11223                transaction_id: tx_id,
11224            })
11225        }
11226    }
11227
11228    pub fn end_transaction_at(
11229        &mut self,
11230        now: Instant,
11231        cx: &mut Context<Self>,
11232    ) -> Option<TransactionId> {
11233        if let Some(transaction_id) = self
11234            .buffer
11235            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11236        {
11237            if let Some((_, end_selections)) =
11238                self.selection_history.transaction_mut(transaction_id)
11239            {
11240                *end_selections = Some(self.selections.disjoint_anchors());
11241            } else {
11242                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11243            }
11244
11245            cx.emit(EditorEvent::Edited { transaction_id });
11246            Some(transaction_id)
11247        } else {
11248            None
11249        }
11250    }
11251
11252    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11253        if self.selection_mark_mode {
11254            self.change_selections(None, window, cx, |s| {
11255                s.move_with(|_, sel| {
11256                    sel.collapse_to(sel.head(), SelectionGoal::None);
11257                });
11258            })
11259        }
11260        self.selection_mark_mode = true;
11261        cx.notify();
11262    }
11263
11264    pub fn swap_selection_ends(
11265        &mut self,
11266        _: &actions::SwapSelectionEnds,
11267        window: &mut Window,
11268        cx: &mut Context<Self>,
11269    ) {
11270        self.change_selections(None, window, cx, |s| {
11271            s.move_with(|_, sel| {
11272                if sel.start != sel.end {
11273                    sel.reversed = !sel.reversed
11274                }
11275            });
11276        });
11277        self.request_autoscroll(Autoscroll::newest(), cx);
11278        cx.notify();
11279    }
11280
11281    pub fn toggle_fold(
11282        &mut self,
11283        _: &actions::ToggleFold,
11284        window: &mut Window,
11285        cx: &mut Context<Self>,
11286    ) {
11287        if self.is_singleton(cx) {
11288            let selection = self.selections.newest::<Point>(cx);
11289
11290            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11291            let range = if selection.is_empty() {
11292                let point = selection.head().to_display_point(&display_map);
11293                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11294                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11295                    .to_point(&display_map);
11296                start..end
11297            } else {
11298                selection.range()
11299            };
11300            if display_map.folds_in_range(range).next().is_some() {
11301                self.unfold_lines(&Default::default(), window, cx)
11302            } else {
11303                self.fold(&Default::default(), window, cx)
11304            }
11305        } else {
11306            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11307            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11308                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11309                .map(|(snapshot, _, _)| snapshot.remote_id())
11310                .collect();
11311
11312            for buffer_id in buffer_ids {
11313                if self.is_buffer_folded(buffer_id, cx) {
11314                    self.unfold_buffer(buffer_id, cx);
11315                } else {
11316                    self.fold_buffer(buffer_id, cx);
11317                }
11318            }
11319        }
11320    }
11321
11322    pub fn toggle_fold_recursive(
11323        &mut self,
11324        _: &actions::ToggleFoldRecursive,
11325        window: &mut Window,
11326        cx: &mut Context<Self>,
11327    ) {
11328        let selection = self.selections.newest::<Point>(cx);
11329
11330        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11331        let range = if selection.is_empty() {
11332            let point = selection.head().to_display_point(&display_map);
11333            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11334            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11335                .to_point(&display_map);
11336            start..end
11337        } else {
11338            selection.range()
11339        };
11340        if display_map.folds_in_range(range).next().is_some() {
11341            self.unfold_recursive(&Default::default(), window, cx)
11342        } else {
11343            self.fold_recursive(&Default::default(), window, cx)
11344        }
11345    }
11346
11347    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11348        if self.is_singleton(cx) {
11349            let mut to_fold = Vec::new();
11350            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11351            let selections = self.selections.all_adjusted(cx);
11352
11353            for selection in selections {
11354                let range = selection.range().sorted();
11355                let buffer_start_row = range.start.row;
11356
11357                if range.start.row != range.end.row {
11358                    let mut found = false;
11359                    let mut row = range.start.row;
11360                    while row <= range.end.row {
11361                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11362                        {
11363                            found = true;
11364                            row = crease.range().end.row + 1;
11365                            to_fold.push(crease);
11366                        } else {
11367                            row += 1
11368                        }
11369                    }
11370                    if found {
11371                        continue;
11372                    }
11373                }
11374
11375                for row in (0..=range.start.row).rev() {
11376                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11377                        if crease.range().end.row >= buffer_start_row {
11378                            to_fold.push(crease);
11379                            if row <= range.start.row {
11380                                break;
11381                            }
11382                        }
11383                    }
11384                }
11385            }
11386
11387            self.fold_creases(to_fold, true, window, cx);
11388        } else {
11389            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11390
11391            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11392                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11393                .map(|(snapshot, _, _)| snapshot.remote_id())
11394                .collect();
11395            for buffer_id in buffer_ids {
11396                self.fold_buffer(buffer_id, cx);
11397            }
11398        }
11399    }
11400
11401    fn fold_at_level(
11402        &mut self,
11403        fold_at: &FoldAtLevel,
11404        window: &mut Window,
11405        cx: &mut Context<Self>,
11406    ) {
11407        if !self.buffer.read(cx).is_singleton() {
11408            return;
11409        }
11410
11411        let fold_at_level = fold_at.level;
11412        let snapshot = self.buffer.read(cx).snapshot(cx);
11413        let mut to_fold = Vec::new();
11414        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11415
11416        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11417            while start_row < end_row {
11418                match self
11419                    .snapshot(window, cx)
11420                    .crease_for_buffer_row(MultiBufferRow(start_row))
11421                {
11422                    Some(crease) => {
11423                        let nested_start_row = crease.range().start.row + 1;
11424                        let nested_end_row = crease.range().end.row;
11425
11426                        if current_level < fold_at_level {
11427                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11428                        } else if current_level == fold_at_level {
11429                            to_fold.push(crease);
11430                        }
11431
11432                        start_row = nested_end_row + 1;
11433                    }
11434                    None => start_row += 1,
11435                }
11436            }
11437        }
11438
11439        self.fold_creases(to_fold, true, window, cx);
11440    }
11441
11442    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11443        if self.buffer.read(cx).is_singleton() {
11444            let mut fold_ranges = Vec::new();
11445            let snapshot = self.buffer.read(cx).snapshot(cx);
11446
11447            for row in 0..snapshot.max_row().0 {
11448                if let Some(foldable_range) = self
11449                    .snapshot(window, cx)
11450                    .crease_for_buffer_row(MultiBufferRow(row))
11451                {
11452                    fold_ranges.push(foldable_range);
11453                }
11454            }
11455
11456            self.fold_creases(fold_ranges, true, window, cx);
11457        } else {
11458            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11459                editor
11460                    .update_in(&mut cx, |editor, _, cx| {
11461                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11462                            editor.fold_buffer(buffer_id, cx);
11463                        }
11464                    })
11465                    .ok();
11466            });
11467        }
11468    }
11469
11470    pub fn fold_function_bodies(
11471        &mut self,
11472        _: &actions::FoldFunctionBodies,
11473        window: &mut Window,
11474        cx: &mut Context<Self>,
11475    ) {
11476        let snapshot = self.buffer.read(cx).snapshot(cx);
11477
11478        let ranges = snapshot
11479            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11480            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11481            .collect::<Vec<_>>();
11482
11483        let creases = ranges
11484            .into_iter()
11485            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11486            .collect();
11487
11488        self.fold_creases(creases, true, window, cx);
11489    }
11490
11491    pub fn fold_recursive(
11492        &mut self,
11493        _: &actions::FoldRecursive,
11494        window: &mut Window,
11495        cx: &mut Context<Self>,
11496    ) {
11497        let mut to_fold = Vec::new();
11498        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11499        let selections = self.selections.all_adjusted(cx);
11500
11501        for selection in selections {
11502            let range = selection.range().sorted();
11503            let buffer_start_row = range.start.row;
11504
11505            if range.start.row != range.end.row {
11506                let mut found = false;
11507                for row in range.start.row..=range.end.row {
11508                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11509                        found = true;
11510                        to_fold.push(crease);
11511                    }
11512                }
11513                if found {
11514                    continue;
11515                }
11516            }
11517
11518            for row in (0..=range.start.row).rev() {
11519                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11520                    if crease.range().end.row >= buffer_start_row {
11521                        to_fold.push(crease);
11522                    } else {
11523                        break;
11524                    }
11525                }
11526            }
11527        }
11528
11529        self.fold_creases(to_fold, true, window, cx);
11530    }
11531
11532    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11533        let buffer_row = fold_at.buffer_row;
11534        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11535
11536        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11537            let autoscroll = self
11538                .selections
11539                .all::<Point>(cx)
11540                .iter()
11541                .any(|selection| crease.range().overlaps(&selection.range()));
11542
11543            self.fold_creases(vec![crease], autoscroll, window, cx);
11544        }
11545    }
11546
11547    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11548        if self.is_singleton(cx) {
11549            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11550            let buffer = &display_map.buffer_snapshot;
11551            let selections = self.selections.all::<Point>(cx);
11552            let ranges = selections
11553                .iter()
11554                .map(|s| {
11555                    let range = s.display_range(&display_map).sorted();
11556                    let mut start = range.start.to_point(&display_map);
11557                    let mut end = range.end.to_point(&display_map);
11558                    start.column = 0;
11559                    end.column = buffer.line_len(MultiBufferRow(end.row));
11560                    start..end
11561                })
11562                .collect::<Vec<_>>();
11563
11564            self.unfold_ranges(&ranges, true, true, cx);
11565        } else {
11566            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11567            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11568                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11569                .map(|(snapshot, _, _)| snapshot.remote_id())
11570                .collect();
11571            for buffer_id in buffer_ids {
11572                self.unfold_buffer(buffer_id, cx);
11573            }
11574        }
11575    }
11576
11577    pub fn unfold_recursive(
11578        &mut self,
11579        _: &UnfoldRecursive,
11580        _window: &mut Window,
11581        cx: &mut Context<Self>,
11582    ) {
11583        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11584        let selections = self.selections.all::<Point>(cx);
11585        let ranges = selections
11586            .iter()
11587            .map(|s| {
11588                let mut range = s.display_range(&display_map).sorted();
11589                *range.start.column_mut() = 0;
11590                *range.end.column_mut() = display_map.line_len(range.end.row());
11591                let start = range.start.to_point(&display_map);
11592                let end = range.end.to_point(&display_map);
11593                start..end
11594            })
11595            .collect::<Vec<_>>();
11596
11597        self.unfold_ranges(&ranges, true, true, cx);
11598    }
11599
11600    pub fn unfold_at(
11601        &mut self,
11602        unfold_at: &UnfoldAt,
11603        _window: &mut Window,
11604        cx: &mut Context<Self>,
11605    ) {
11606        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11607
11608        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11609            ..Point::new(
11610                unfold_at.buffer_row.0,
11611                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11612            );
11613
11614        let autoscroll = self
11615            .selections
11616            .all::<Point>(cx)
11617            .iter()
11618            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11619
11620        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11621    }
11622
11623    pub fn unfold_all(
11624        &mut self,
11625        _: &actions::UnfoldAll,
11626        _window: &mut Window,
11627        cx: &mut Context<Self>,
11628    ) {
11629        if self.buffer.read(cx).is_singleton() {
11630            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11631            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11632        } else {
11633            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11634                editor
11635                    .update(&mut cx, |editor, cx| {
11636                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11637                            editor.unfold_buffer(buffer_id, cx);
11638                        }
11639                    })
11640                    .ok();
11641            });
11642        }
11643    }
11644
11645    pub fn fold_selected_ranges(
11646        &mut self,
11647        _: &FoldSelectedRanges,
11648        window: &mut Window,
11649        cx: &mut Context<Self>,
11650    ) {
11651        let selections = self.selections.all::<Point>(cx);
11652        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11653        let line_mode = self.selections.line_mode;
11654        let ranges = selections
11655            .into_iter()
11656            .map(|s| {
11657                if line_mode {
11658                    let start = Point::new(s.start.row, 0);
11659                    let end = Point::new(
11660                        s.end.row,
11661                        display_map
11662                            .buffer_snapshot
11663                            .line_len(MultiBufferRow(s.end.row)),
11664                    );
11665                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11666                } else {
11667                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11668                }
11669            })
11670            .collect::<Vec<_>>();
11671        self.fold_creases(ranges, true, window, cx);
11672    }
11673
11674    pub fn fold_ranges<T: ToOffset + Clone>(
11675        &mut self,
11676        ranges: Vec<Range<T>>,
11677        auto_scroll: bool,
11678        window: &mut Window,
11679        cx: &mut Context<Self>,
11680    ) {
11681        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11682        let ranges = ranges
11683            .into_iter()
11684            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11685            .collect::<Vec<_>>();
11686        self.fold_creases(ranges, auto_scroll, window, cx);
11687    }
11688
11689    pub fn fold_creases<T: ToOffset + Clone>(
11690        &mut self,
11691        creases: Vec<Crease<T>>,
11692        auto_scroll: bool,
11693        window: &mut Window,
11694        cx: &mut Context<Self>,
11695    ) {
11696        if creases.is_empty() {
11697            return;
11698        }
11699
11700        let mut buffers_affected = HashSet::default();
11701        let multi_buffer = self.buffer().read(cx);
11702        for crease in &creases {
11703            if let Some((_, buffer, _)) =
11704                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11705            {
11706                buffers_affected.insert(buffer.read(cx).remote_id());
11707            };
11708        }
11709
11710        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11711
11712        if auto_scroll {
11713            self.request_autoscroll(Autoscroll::fit(), cx);
11714        }
11715
11716        cx.notify();
11717
11718        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11719            // Clear diagnostics block when folding a range that contains it.
11720            let snapshot = self.snapshot(window, cx);
11721            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11722                drop(snapshot);
11723                self.active_diagnostics = Some(active_diagnostics);
11724                self.dismiss_diagnostics(cx);
11725            } else {
11726                self.active_diagnostics = Some(active_diagnostics);
11727            }
11728        }
11729
11730        self.scrollbar_marker_state.dirty = true;
11731    }
11732
11733    /// Removes any folds whose ranges intersect any of the given ranges.
11734    pub fn unfold_ranges<T: ToOffset + Clone>(
11735        &mut self,
11736        ranges: &[Range<T>],
11737        inclusive: bool,
11738        auto_scroll: bool,
11739        cx: &mut Context<Self>,
11740    ) {
11741        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11742            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11743        });
11744    }
11745
11746    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11747        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11748            return;
11749        }
11750        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11751            return;
11752        };
11753        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11754        self.display_map
11755            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11756        cx.emit(EditorEvent::BufferFoldToggled {
11757            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11758            folded: true,
11759        });
11760        cx.notify();
11761    }
11762
11763    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11764        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11765            return;
11766        }
11767        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11768            return;
11769        };
11770        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11771        self.display_map.update(cx, |display_map, cx| {
11772            display_map.unfold_buffer(buffer_id, cx);
11773        });
11774        cx.emit(EditorEvent::BufferFoldToggled {
11775            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11776            folded: false,
11777        });
11778        cx.notify();
11779    }
11780
11781    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11782        self.display_map.read(cx).is_buffer_folded(buffer)
11783    }
11784
11785    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
11786        self.display_map.read(cx).folded_buffers()
11787    }
11788
11789    /// Removes any folds with the given ranges.
11790    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11791        &mut self,
11792        ranges: &[Range<T>],
11793        type_id: TypeId,
11794        auto_scroll: bool,
11795        cx: &mut Context<Self>,
11796    ) {
11797        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11798            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11799        });
11800    }
11801
11802    fn remove_folds_with<T: ToOffset + Clone>(
11803        &mut self,
11804        ranges: &[Range<T>],
11805        auto_scroll: bool,
11806        cx: &mut Context<Self>,
11807        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
11808    ) {
11809        if ranges.is_empty() {
11810            return;
11811        }
11812
11813        let mut buffers_affected = HashSet::default();
11814        let multi_buffer = self.buffer().read(cx);
11815        for range in ranges {
11816            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11817                buffers_affected.insert(buffer.read(cx).remote_id());
11818            };
11819        }
11820
11821        self.display_map.update(cx, update);
11822
11823        if auto_scroll {
11824            self.request_autoscroll(Autoscroll::fit(), cx);
11825        }
11826
11827        cx.notify();
11828        self.scrollbar_marker_state.dirty = true;
11829        self.active_indent_guides_state.dirty = true;
11830    }
11831
11832    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
11833        self.display_map.read(cx).fold_placeholder.clone()
11834    }
11835
11836    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
11837        self.buffer.update(cx, |buffer, cx| {
11838            buffer.set_all_diff_hunks_expanded(cx);
11839        });
11840    }
11841
11842    pub fn expand_all_diff_hunks(
11843        &mut self,
11844        _: &ExpandAllHunkDiffs,
11845        _window: &mut Window,
11846        cx: &mut Context<Self>,
11847    ) {
11848        self.buffer.update(cx, |buffer, cx| {
11849            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11850        });
11851    }
11852
11853    pub fn toggle_selected_diff_hunks(
11854        &mut self,
11855        _: &ToggleSelectedDiffHunks,
11856        _window: &mut Window,
11857        cx: &mut Context<Self>,
11858    ) {
11859        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11860        self.toggle_diff_hunks_in_ranges(ranges, cx);
11861    }
11862
11863    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
11864        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11865        self.buffer
11866            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11867    }
11868
11869    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
11870        self.buffer.update(cx, |buffer, cx| {
11871            let ranges = vec![Anchor::min()..Anchor::max()];
11872            if !buffer.all_diff_hunks_expanded()
11873                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11874            {
11875                buffer.collapse_diff_hunks(ranges, cx);
11876                true
11877            } else {
11878                false
11879            }
11880        })
11881    }
11882
11883    fn toggle_diff_hunks_in_ranges(
11884        &mut self,
11885        ranges: Vec<Range<Anchor>>,
11886        cx: &mut Context<'_, Editor>,
11887    ) {
11888        self.buffer.update(cx, |buffer, cx| {
11889            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11890                buffer.collapse_diff_hunks(ranges, cx)
11891            } else {
11892                buffer.expand_diff_hunks(ranges, cx)
11893            }
11894        })
11895    }
11896
11897    pub(crate) fn apply_all_diff_hunks(
11898        &mut self,
11899        _: &ApplyAllDiffHunks,
11900        window: &mut Window,
11901        cx: &mut Context<Self>,
11902    ) {
11903        let buffers = self.buffer.read(cx).all_buffers();
11904        for branch_buffer in buffers {
11905            branch_buffer.update(cx, |branch_buffer, cx| {
11906                branch_buffer.merge_into_base(Vec::new(), cx);
11907            });
11908        }
11909
11910        if let Some(project) = self.project.clone() {
11911            self.save(true, project, window, cx).detach_and_log_err(cx);
11912        }
11913    }
11914
11915    pub(crate) fn apply_selected_diff_hunks(
11916        &mut self,
11917        _: &ApplyDiffHunk,
11918        window: &mut Window,
11919        cx: &mut Context<Self>,
11920    ) {
11921        let snapshot = self.snapshot(window, cx);
11922        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11923        let mut ranges_by_buffer = HashMap::default();
11924        self.transact(window, cx, |editor, _window, cx| {
11925            for hunk in hunks {
11926                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11927                    ranges_by_buffer
11928                        .entry(buffer.clone())
11929                        .or_insert_with(Vec::new)
11930                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11931                }
11932            }
11933
11934            for (buffer, ranges) in ranges_by_buffer {
11935                buffer.update(cx, |buffer, cx| {
11936                    buffer.merge_into_base(ranges, cx);
11937                });
11938            }
11939        });
11940
11941        if let Some(project) = self.project.clone() {
11942            self.save(true, project, window, cx).detach_and_log_err(cx);
11943        }
11944    }
11945
11946    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
11947        if hovered != self.gutter_hovered {
11948            self.gutter_hovered = hovered;
11949            cx.notify();
11950        }
11951    }
11952
11953    pub fn insert_blocks(
11954        &mut self,
11955        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11956        autoscroll: Option<Autoscroll>,
11957        cx: &mut Context<Self>,
11958    ) -> Vec<CustomBlockId> {
11959        let blocks = self
11960            .display_map
11961            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11962        if let Some(autoscroll) = autoscroll {
11963            self.request_autoscroll(autoscroll, cx);
11964        }
11965        cx.notify();
11966        blocks
11967    }
11968
11969    pub fn resize_blocks(
11970        &mut self,
11971        heights: HashMap<CustomBlockId, u32>,
11972        autoscroll: Option<Autoscroll>,
11973        cx: &mut Context<Self>,
11974    ) {
11975        self.display_map
11976            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11977        if let Some(autoscroll) = autoscroll {
11978            self.request_autoscroll(autoscroll, cx);
11979        }
11980        cx.notify();
11981    }
11982
11983    pub fn replace_blocks(
11984        &mut self,
11985        renderers: HashMap<CustomBlockId, RenderBlock>,
11986        autoscroll: Option<Autoscroll>,
11987        cx: &mut Context<Self>,
11988    ) {
11989        self.display_map
11990            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11991        if let Some(autoscroll) = autoscroll {
11992            self.request_autoscroll(autoscroll, cx);
11993        }
11994        cx.notify();
11995    }
11996
11997    pub fn remove_blocks(
11998        &mut self,
11999        block_ids: HashSet<CustomBlockId>,
12000        autoscroll: Option<Autoscroll>,
12001        cx: &mut Context<Self>,
12002    ) {
12003        self.display_map.update(cx, |display_map, cx| {
12004            display_map.remove_blocks(block_ids, cx)
12005        });
12006        if let Some(autoscroll) = autoscroll {
12007            self.request_autoscroll(autoscroll, cx);
12008        }
12009        cx.notify();
12010    }
12011
12012    pub fn row_for_block(
12013        &self,
12014        block_id: CustomBlockId,
12015        cx: &mut Context<Self>,
12016    ) -> Option<DisplayRow> {
12017        self.display_map
12018            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12019    }
12020
12021    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12022        self.focused_block = Some(focused_block);
12023    }
12024
12025    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12026        self.focused_block.take()
12027    }
12028
12029    pub fn insert_creases(
12030        &mut self,
12031        creases: impl IntoIterator<Item = Crease<Anchor>>,
12032        cx: &mut Context<Self>,
12033    ) -> Vec<CreaseId> {
12034        self.display_map
12035            .update(cx, |map, cx| map.insert_creases(creases, cx))
12036    }
12037
12038    pub fn remove_creases(
12039        &mut self,
12040        ids: impl IntoIterator<Item = CreaseId>,
12041        cx: &mut Context<Self>,
12042    ) {
12043        self.display_map
12044            .update(cx, |map, cx| map.remove_creases(ids, cx));
12045    }
12046
12047    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12048        self.display_map
12049            .update(cx, |map, cx| map.snapshot(cx))
12050            .longest_row()
12051    }
12052
12053    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12054        self.display_map
12055            .update(cx, |map, cx| map.snapshot(cx))
12056            .max_point()
12057    }
12058
12059    pub fn text(&self, cx: &App) -> String {
12060        self.buffer.read(cx).read(cx).text()
12061    }
12062
12063    pub fn text_option(&self, cx: &App) -> Option<String> {
12064        let text = self.text(cx);
12065        let text = text.trim();
12066
12067        if text.is_empty() {
12068            return None;
12069        }
12070
12071        Some(text.to_string())
12072    }
12073
12074    pub fn set_text(
12075        &mut self,
12076        text: impl Into<Arc<str>>,
12077        window: &mut Window,
12078        cx: &mut Context<Self>,
12079    ) {
12080        self.transact(window, cx, |this, _, cx| {
12081            this.buffer
12082                .read(cx)
12083                .as_singleton()
12084                .expect("you can only call set_text on editors for singleton buffers")
12085                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12086        });
12087    }
12088
12089    pub fn display_text(&self, cx: &mut App) -> String {
12090        self.display_map
12091            .update(cx, |map, cx| map.snapshot(cx))
12092            .text()
12093    }
12094
12095    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12096        let mut wrap_guides = smallvec::smallvec![];
12097
12098        if self.show_wrap_guides == Some(false) {
12099            return wrap_guides;
12100        }
12101
12102        let settings = self.buffer.read(cx).settings_at(0, cx);
12103        if settings.show_wrap_guides {
12104            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12105                wrap_guides.push((soft_wrap as usize, true));
12106            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12107                wrap_guides.push((soft_wrap as usize, true));
12108            }
12109            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12110        }
12111
12112        wrap_guides
12113    }
12114
12115    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12116        let settings = self.buffer.read(cx).settings_at(0, cx);
12117        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12118        match mode {
12119            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12120                SoftWrap::None
12121            }
12122            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12123            language_settings::SoftWrap::PreferredLineLength => {
12124                SoftWrap::Column(settings.preferred_line_length)
12125            }
12126            language_settings::SoftWrap::Bounded => {
12127                SoftWrap::Bounded(settings.preferred_line_length)
12128            }
12129        }
12130    }
12131
12132    pub fn set_soft_wrap_mode(
12133        &mut self,
12134        mode: language_settings::SoftWrap,
12135
12136        cx: &mut Context<Self>,
12137    ) {
12138        self.soft_wrap_mode_override = Some(mode);
12139        cx.notify();
12140    }
12141
12142    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12143        self.text_style_refinement = Some(style);
12144    }
12145
12146    /// called by the Element so we know what style we were most recently rendered with.
12147    pub(crate) fn set_style(
12148        &mut self,
12149        style: EditorStyle,
12150        window: &mut Window,
12151        cx: &mut Context<Self>,
12152    ) {
12153        let rem_size = window.rem_size();
12154        self.display_map.update(cx, |map, cx| {
12155            map.set_font(
12156                style.text.font(),
12157                style.text.font_size.to_pixels(rem_size),
12158                cx,
12159            )
12160        });
12161        self.style = Some(style);
12162    }
12163
12164    pub fn style(&self) -> Option<&EditorStyle> {
12165        self.style.as_ref()
12166    }
12167
12168    // Called by the element. This method is not designed to be called outside of the editor
12169    // element's layout code because it does not notify when rewrapping is computed synchronously.
12170    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12171        self.display_map
12172            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12173    }
12174
12175    pub fn set_soft_wrap(&mut self) {
12176        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12177    }
12178
12179    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12180        if self.soft_wrap_mode_override.is_some() {
12181            self.soft_wrap_mode_override.take();
12182        } else {
12183            let soft_wrap = match self.soft_wrap_mode(cx) {
12184                SoftWrap::GitDiff => return,
12185                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12186                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12187                    language_settings::SoftWrap::None
12188                }
12189            };
12190            self.soft_wrap_mode_override = Some(soft_wrap);
12191        }
12192        cx.notify();
12193    }
12194
12195    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12196        let Some(workspace) = self.workspace() else {
12197            return;
12198        };
12199        let fs = workspace.read(cx).app_state().fs.clone();
12200        let current_show = TabBarSettings::get_global(cx).show;
12201        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12202            setting.show = Some(!current_show);
12203        });
12204    }
12205
12206    pub fn toggle_indent_guides(
12207        &mut self,
12208        _: &ToggleIndentGuides,
12209        _: &mut Window,
12210        cx: &mut Context<Self>,
12211    ) {
12212        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12213            self.buffer
12214                .read(cx)
12215                .settings_at(0, cx)
12216                .indent_guides
12217                .enabled
12218        });
12219        self.show_indent_guides = Some(!currently_enabled);
12220        cx.notify();
12221    }
12222
12223    fn should_show_indent_guides(&self) -> Option<bool> {
12224        self.show_indent_guides
12225    }
12226
12227    pub fn toggle_line_numbers(
12228        &mut self,
12229        _: &ToggleLineNumbers,
12230        _: &mut Window,
12231        cx: &mut Context<Self>,
12232    ) {
12233        let mut editor_settings = EditorSettings::get_global(cx).clone();
12234        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12235        EditorSettings::override_global(editor_settings, cx);
12236    }
12237
12238    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12239        self.use_relative_line_numbers
12240            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12241    }
12242
12243    pub fn toggle_relative_line_numbers(
12244        &mut self,
12245        _: &ToggleRelativeLineNumbers,
12246        _: &mut Window,
12247        cx: &mut Context<Self>,
12248    ) {
12249        let is_relative = self.should_use_relative_line_numbers(cx);
12250        self.set_relative_line_number(Some(!is_relative), cx)
12251    }
12252
12253    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12254        self.use_relative_line_numbers = is_relative;
12255        cx.notify();
12256    }
12257
12258    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12259        self.show_gutter = show_gutter;
12260        cx.notify();
12261    }
12262
12263    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12264        self.show_scrollbars = show_scrollbars;
12265        cx.notify();
12266    }
12267
12268    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12269        self.show_line_numbers = Some(show_line_numbers);
12270        cx.notify();
12271    }
12272
12273    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12274        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12275        cx.notify();
12276    }
12277
12278    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12279        self.show_code_actions = Some(show_code_actions);
12280        cx.notify();
12281    }
12282
12283    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12284        self.show_runnables = Some(show_runnables);
12285        cx.notify();
12286    }
12287
12288    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12289        if self.display_map.read(cx).masked != masked {
12290            self.display_map.update(cx, |map, _| map.masked = masked);
12291        }
12292        cx.notify()
12293    }
12294
12295    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12296        self.show_wrap_guides = Some(show_wrap_guides);
12297        cx.notify();
12298    }
12299
12300    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12301        self.show_indent_guides = Some(show_indent_guides);
12302        cx.notify();
12303    }
12304
12305    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12306        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12307            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12308                if let Some(dir) = file.abs_path(cx).parent() {
12309                    return Some(dir.to_owned());
12310                }
12311            }
12312
12313            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12314                return Some(project_path.path.to_path_buf());
12315            }
12316        }
12317
12318        None
12319    }
12320
12321    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12322        self.active_excerpt(cx)?
12323            .1
12324            .read(cx)
12325            .file()
12326            .and_then(|f| f.as_local())
12327    }
12328
12329    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12330        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12331            let project_path = buffer.read(cx).project_path(cx)?;
12332            let project = self.project.as_ref()?.read(cx);
12333            project.absolute_path(&project_path, cx)
12334        })
12335    }
12336
12337    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12338        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12339            let project_path = buffer.read(cx).project_path(cx)?;
12340            let project = self.project.as_ref()?.read(cx);
12341            let entry = project.entry_for_path(&project_path, cx)?;
12342            let path = entry.path.to_path_buf();
12343            Some(path)
12344        })
12345    }
12346
12347    pub fn reveal_in_finder(
12348        &mut self,
12349        _: &RevealInFileManager,
12350        _window: &mut Window,
12351        cx: &mut Context<Self>,
12352    ) {
12353        if let Some(target) = self.target_file(cx) {
12354            cx.reveal_path(&target.abs_path(cx));
12355        }
12356    }
12357
12358    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12359        if let Some(path) = self.target_file_abs_path(cx) {
12360            if let Some(path) = path.to_str() {
12361                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12362            }
12363        }
12364    }
12365
12366    pub fn copy_relative_path(
12367        &mut self,
12368        _: &CopyRelativePath,
12369        _window: &mut Window,
12370        cx: &mut Context<Self>,
12371    ) {
12372        if let Some(path) = self.target_file_path(cx) {
12373            if let Some(path) = path.to_str() {
12374                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12375            }
12376        }
12377    }
12378
12379    pub fn toggle_git_blame(
12380        &mut self,
12381        _: &ToggleGitBlame,
12382        window: &mut Window,
12383        cx: &mut Context<Self>,
12384    ) {
12385        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12386
12387        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12388            self.start_git_blame(true, window, cx);
12389        }
12390
12391        cx.notify();
12392    }
12393
12394    pub fn toggle_git_blame_inline(
12395        &mut self,
12396        _: &ToggleGitBlameInline,
12397        window: &mut Window,
12398        cx: &mut Context<Self>,
12399    ) {
12400        self.toggle_git_blame_inline_internal(true, window, cx);
12401        cx.notify();
12402    }
12403
12404    pub fn git_blame_inline_enabled(&self) -> bool {
12405        self.git_blame_inline_enabled
12406    }
12407
12408    pub fn toggle_selection_menu(
12409        &mut self,
12410        _: &ToggleSelectionMenu,
12411        _: &mut Window,
12412        cx: &mut Context<Self>,
12413    ) {
12414        self.show_selection_menu = self
12415            .show_selection_menu
12416            .map(|show_selections_menu| !show_selections_menu)
12417            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12418
12419        cx.notify();
12420    }
12421
12422    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12423        self.show_selection_menu
12424            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12425    }
12426
12427    fn start_git_blame(
12428        &mut self,
12429        user_triggered: bool,
12430        window: &mut Window,
12431        cx: &mut Context<Self>,
12432    ) {
12433        if let Some(project) = self.project.as_ref() {
12434            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12435                return;
12436            };
12437
12438            if buffer.read(cx).file().is_none() {
12439                return;
12440            }
12441
12442            let focused = self.focus_handle(cx).contains_focused(window, cx);
12443
12444            let project = project.clone();
12445            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12446            self.blame_subscription =
12447                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12448            self.blame = Some(blame);
12449        }
12450    }
12451
12452    fn toggle_git_blame_inline_internal(
12453        &mut self,
12454        user_triggered: bool,
12455        window: &mut Window,
12456        cx: &mut Context<Self>,
12457    ) {
12458        if self.git_blame_inline_enabled {
12459            self.git_blame_inline_enabled = false;
12460            self.show_git_blame_inline = false;
12461            self.show_git_blame_inline_delay_task.take();
12462        } else {
12463            self.git_blame_inline_enabled = true;
12464            self.start_git_blame_inline(user_triggered, window, cx);
12465        }
12466
12467        cx.notify();
12468    }
12469
12470    fn start_git_blame_inline(
12471        &mut self,
12472        user_triggered: bool,
12473        window: &mut Window,
12474        cx: &mut Context<Self>,
12475    ) {
12476        self.start_git_blame(user_triggered, window, cx);
12477
12478        if ProjectSettings::get_global(cx)
12479            .git
12480            .inline_blame_delay()
12481            .is_some()
12482        {
12483            self.start_inline_blame_timer(window, cx);
12484        } else {
12485            self.show_git_blame_inline = true
12486        }
12487    }
12488
12489    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12490        self.blame.as_ref()
12491    }
12492
12493    pub fn show_git_blame_gutter(&self) -> bool {
12494        self.show_git_blame_gutter
12495    }
12496
12497    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12498        self.show_git_blame_gutter && self.has_blame_entries(cx)
12499    }
12500
12501    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12502        self.show_git_blame_inline
12503            && self.focus_handle.is_focused(window)
12504            && !self.newest_selection_head_on_empty_line(cx)
12505            && self.has_blame_entries(cx)
12506    }
12507
12508    fn has_blame_entries(&self, cx: &App) -> bool {
12509        self.blame()
12510            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12511    }
12512
12513    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12514        let cursor_anchor = self.selections.newest_anchor().head();
12515
12516        let snapshot = self.buffer.read(cx).snapshot(cx);
12517        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12518
12519        snapshot.line_len(buffer_row) == 0
12520    }
12521
12522    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12523        let buffer_and_selection = maybe!({
12524            let selection = self.selections.newest::<Point>(cx);
12525            let selection_range = selection.range();
12526
12527            let multi_buffer = self.buffer().read(cx);
12528            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12529            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12530
12531            let (buffer, range, _) = if selection.reversed {
12532                buffer_ranges.first()
12533            } else {
12534                buffer_ranges.last()
12535            }?;
12536
12537            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12538                ..text::ToPoint::to_point(&range.end, &buffer).row;
12539            Some((
12540                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12541                selection,
12542            ))
12543        });
12544
12545        let Some((buffer, selection)) = buffer_and_selection else {
12546            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12547        };
12548
12549        let Some(project) = self.project.as_ref() else {
12550            return Task::ready(Err(anyhow!("editor does not have project")));
12551        };
12552
12553        project.update(cx, |project, cx| {
12554            project.get_permalink_to_line(&buffer, selection, cx)
12555        })
12556    }
12557
12558    pub fn copy_permalink_to_line(
12559        &mut self,
12560        _: &CopyPermalinkToLine,
12561        window: &mut Window,
12562        cx: &mut Context<Self>,
12563    ) {
12564        let permalink_task = self.get_permalink_to_line(cx);
12565        let workspace = self.workspace();
12566
12567        cx.spawn_in(window, |_, mut cx| async move {
12568            match permalink_task.await {
12569                Ok(permalink) => {
12570                    cx.update(|_, cx| {
12571                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12572                    })
12573                    .ok();
12574                }
12575                Err(err) => {
12576                    let message = format!("Failed to copy permalink: {err}");
12577
12578                    Err::<(), anyhow::Error>(err).log_err();
12579
12580                    if let Some(workspace) = workspace {
12581                        workspace
12582                            .update_in(&mut cx, |workspace, _, cx| {
12583                                struct CopyPermalinkToLine;
12584
12585                                workspace.show_toast(
12586                                    Toast::new(
12587                                        NotificationId::unique::<CopyPermalinkToLine>(),
12588                                        message,
12589                                    ),
12590                                    cx,
12591                                )
12592                            })
12593                            .ok();
12594                    }
12595                }
12596            }
12597        })
12598        .detach();
12599    }
12600
12601    pub fn copy_file_location(
12602        &mut self,
12603        _: &CopyFileLocation,
12604        _: &mut Window,
12605        cx: &mut Context<Self>,
12606    ) {
12607        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12608        if let Some(file) = self.target_file(cx) {
12609            if let Some(path) = file.path().to_str() {
12610                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12611            }
12612        }
12613    }
12614
12615    pub fn open_permalink_to_line(
12616        &mut self,
12617        _: &OpenPermalinkToLine,
12618        window: &mut Window,
12619        cx: &mut Context<Self>,
12620    ) {
12621        let permalink_task = self.get_permalink_to_line(cx);
12622        let workspace = self.workspace();
12623
12624        cx.spawn_in(window, |_, mut cx| async move {
12625            match permalink_task.await {
12626                Ok(permalink) => {
12627                    cx.update(|_, cx| {
12628                        cx.open_url(permalink.as_ref());
12629                    })
12630                    .ok();
12631                }
12632                Err(err) => {
12633                    let message = format!("Failed to open permalink: {err}");
12634
12635                    Err::<(), anyhow::Error>(err).log_err();
12636
12637                    if let Some(workspace) = workspace {
12638                        workspace
12639                            .update(&mut cx, |workspace, cx| {
12640                                struct OpenPermalinkToLine;
12641
12642                                workspace.show_toast(
12643                                    Toast::new(
12644                                        NotificationId::unique::<OpenPermalinkToLine>(),
12645                                        message,
12646                                    ),
12647                                    cx,
12648                                )
12649                            })
12650                            .ok();
12651                    }
12652                }
12653            }
12654        })
12655        .detach();
12656    }
12657
12658    pub fn insert_uuid_v4(
12659        &mut self,
12660        _: &InsertUuidV4,
12661        window: &mut Window,
12662        cx: &mut Context<Self>,
12663    ) {
12664        self.insert_uuid(UuidVersion::V4, window, cx);
12665    }
12666
12667    pub fn insert_uuid_v7(
12668        &mut self,
12669        _: &InsertUuidV7,
12670        window: &mut Window,
12671        cx: &mut Context<Self>,
12672    ) {
12673        self.insert_uuid(UuidVersion::V7, window, cx);
12674    }
12675
12676    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12677        self.transact(window, cx, |this, window, cx| {
12678            let edits = this
12679                .selections
12680                .all::<Point>(cx)
12681                .into_iter()
12682                .map(|selection| {
12683                    let uuid = match version {
12684                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12685                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12686                    };
12687
12688                    (selection.range(), uuid.to_string())
12689                });
12690            this.edit(edits, cx);
12691            this.refresh_inline_completion(true, false, window, cx);
12692        });
12693    }
12694
12695    pub fn open_selections_in_multibuffer(
12696        &mut self,
12697        _: &OpenSelectionsInMultibuffer,
12698        window: &mut Window,
12699        cx: &mut Context<Self>,
12700    ) {
12701        let multibuffer = self.buffer.read(cx);
12702
12703        let Some(buffer) = multibuffer.as_singleton() else {
12704            return;
12705        };
12706
12707        let Some(workspace) = self.workspace() else {
12708            return;
12709        };
12710
12711        let locations = self
12712            .selections
12713            .disjoint_anchors()
12714            .iter()
12715            .map(|range| Location {
12716                buffer: buffer.clone(),
12717                range: range.start.text_anchor..range.end.text_anchor,
12718            })
12719            .collect::<Vec<_>>();
12720
12721        let title = multibuffer.title(cx).to_string();
12722
12723        cx.spawn_in(window, |_, mut cx| async move {
12724            workspace.update_in(&mut cx, |workspace, window, cx| {
12725                Self::open_locations_in_multibuffer(
12726                    workspace,
12727                    locations,
12728                    format!("Selections for '{title}'"),
12729                    false,
12730                    MultibufferSelectionMode::All,
12731                    window,
12732                    cx,
12733                );
12734            })
12735        })
12736        .detach();
12737    }
12738
12739    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12740    /// last highlight added will be used.
12741    ///
12742    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12743    pub fn highlight_rows<T: 'static>(
12744        &mut self,
12745        range: Range<Anchor>,
12746        color: Hsla,
12747        should_autoscroll: bool,
12748        cx: &mut Context<Self>,
12749    ) {
12750        let snapshot = self.buffer().read(cx).snapshot(cx);
12751        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12752        let ix = row_highlights.binary_search_by(|highlight| {
12753            Ordering::Equal
12754                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12755                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12756        });
12757
12758        if let Err(mut ix) = ix {
12759            let index = post_inc(&mut self.highlight_order);
12760
12761            // If this range intersects with the preceding highlight, then merge it with
12762            // the preceding highlight. Otherwise insert a new highlight.
12763            let mut merged = false;
12764            if ix > 0 {
12765                let prev_highlight = &mut row_highlights[ix - 1];
12766                if prev_highlight
12767                    .range
12768                    .end
12769                    .cmp(&range.start, &snapshot)
12770                    .is_ge()
12771                {
12772                    ix -= 1;
12773                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12774                        prev_highlight.range.end = range.end;
12775                    }
12776                    merged = true;
12777                    prev_highlight.index = index;
12778                    prev_highlight.color = color;
12779                    prev_highlight.should_autoscroll = should_autoscroll;
12780                }
12781            }
12782
12783            if !merged {
12784                row_highlights.insert(
12785                    ix,
12786                    RowHighlight {
12787                        range: range.clone(),
12788                        index,
12789                        color,
12790                        should_autoscroll,
12791                    },
12792                );
12793            }
12794
12795            // If any of the following highlights intersect with this one, merge them.
12796            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12797                let highlight = &row_highlights[ix];
12798                if next_highlight
12799                    .range
12800                    .start
12801                    .cmp(&highlight.range.end, &snapshot)
12802                    .is_le()
12803                {
12804                    if next_highlight
12805                        .range
12806                        .end
12807                        .cmp(&highlight.range.end, &snapshot)
12808                        .is_gt()
12809                    {
12810                        row_highlights[ix].range.end = next_highlight.range.end;
12811                    }
12812                    row_highlights.remove(ix + 1);
12813                } else {
12814                    break;
12815                }
12816            }
12817        }
12818    }
12819
12820    /// Remove any highlighted row ranges of the given type that intersect the
12821    /// given ranges.
12822    pub fn remove_highlighted_rows<T: 'static>(
12823        &mut self,
12824        ranges_to_remove: Vec<Range<Anchor>>,
12825        cx: &mut Context<Self>,
12826    ) {
12827        let snapshot = self.buffer().read(cx).snapshot(cx);
12828        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12829        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12830        row_highlights.retain(|highlight| {
12831            while let Some(range_to_remove) = ranges_to_remove.peek() {
12832                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12833                    Ordering::Less | Ordering::Equal => {
12834                        ranges_to_remove.next();
12835                    }
12836                    Ordering::Greater => {
12837                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12838                            Ordering::Less | Ordering::Equal => {
12839                                return false;
12840                            }
12841                            Ordering::Greater => break,
12842                        }
12843                    }
12844                }
12845            }
12846
12847            true
12848        })
12849    }
12850
12851    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12852    pub fn clear_row_highlights<T: 'static>(&mut self) {
12853        self.highlighted_rows.remove(&TypeId::of::<T>());
12854    }
12855
12856    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12857    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12858        self.highlighted_rows
12859            .get(&TypeId::of::<T>())
12860            .map_or(&[] as &[_], |vec| vec.as_slice())
12861            .iter()
12862            .map(|highlight| (highlight.range.clone(), highlight.color))
12863    }
12864
12865    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12866    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12867    /// Allows to ignore certain kinds of highlights.
12868    pub fn highlighted_display_rows(
12869        &self,
12870        window: &mut Window,
12871        cx: &mut App,
12872    ) -> BTreeMap<DisplayRow, Hsla> {
12873        let snapshot = self.snapshot(window, cx);
12874        let mut used_highlight_orders = HashMap::default();
12875        self.highlighted_rows
12876            .iter()
12877            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12878            .fold(
12879                BTreeMap::<DisplayRow, Hsla>::new(),
12880                |mut unique_rows, highlight| {
12881                    let start = highlight.range.start.to_display_point(&snapshot);
12882                    let end = highlight.range.end.to_display_point(&snapshot);
12883                    let start_row = start.row().0;
12884                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12885                        && end.column() == 0
12886                    {
12887                        end.row().0.saturating_sub(1)
12888                    } else {
12889                        end.row().0
12890                    };
12891                    for row in start_row..=end_row {
12892                        let used_index =
12893                            used_highlight_orders.entry(row).or_insert(highlight.index);
12894                        if highlight.index >= *used_index {
12895                            *used_index = highlight.index;
12896                            unique_rows.insert(DisplayRow(row), highlight.color);
12897                        }
12898                    }
12899                    unique_rows
12900                },
12901            )
12902    }
12903
12904    pub fn highlighted_display_row_for_autoscroll(
12905        &self,
12906        snapshot: &DisplaySnapshot,
12907    ) -> Option<DisplayRow> {
12908        self.highlighted_rows
12909            .values()
12910            .flat_map(|highlighted_rows| highlighted_rows.iter())
12911            .filter_map(|highlight| {
12912                if highlight.should_autoscroll {
12913                    Some(highlight.range.start.to_display_point(snapshot).row())
12914                } else {
12915                    None
12916                }
12917            })
12918            .min()
12919    }
12920
12921    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
12922        self.highlight_background::<SearchWithinRange>(
12923            ranges,
12924            |colors| colors.editor_document_highlight_read_background,
12925            cx,
12926        )
12927    }
12928
12929    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12930        self.breadcrumb_header = Some(new_header);
12931    }
12932
12933    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
12934        self.clear_background_highlights::<SearchWithinRange>(cx);
12935    }
12936
12937    pub fn highlight_background<T: 'static>(
12938        &mut self,
12939        ranges: &[Range<Anchor>],
12940        color_fetcher: fn(&ThemeColors) -> Hsla,
12941        cx: &mut Context<Self>,
12942    ) {
12943        self.background_highlights
12944            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12945        self.scrollbar_marker_state.dirty = true;
12946        cx.notify();
12947    }
12948
12949    pub fn clear_background_highlights<T: 'static>(
12950        &mut self,
12951        cx: &mut Context<Self>,
12952    ) -> Option<BackgroundHighlight> {
12953        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12954        if !text_highlights.1.is_empty() {
12955            self.scrollbar_marker_state.dirty = true;
12956            cx.notify();
12957        }
12958        Some(text_highlights)
12959    }
12960
12961    pub fn highlight_gutter<T: 'static>(
12962        &mut self,
12963        ranges: &[Range<Anchor>],
12964        color_fetcher: fn(&App) -> Hsla,
12965        cx: &mut Context<Self>,
12966    ) {
12967        self.gutter_highlights
12968            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12969        cx.notify();
12970    }
12971
12972    pub fn clear_gutter_highlights<T: 'static>(
12973        &mut self,
12974        cx: &mut Context<Self>,
12975    ) -> Option<GutterHighlight> {
12976        cx.notify();
12977        self.gutter_highlights.remove(&TypeId::of::<T>())
12978    }
12979
12980    #[cfg(feature = "test-support")]
12981    pub fn all_text_background_highlights(
12982        &self,
12983        window: &mut Window,
12984        cx: &mut Context<Self>,
12985    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12986        let snapshot = self.snapshot(window, cx);
12987        let buffer = &snapshot.buffer_snapshot;
12988        let start = buffer.anchor_before(0);
12989        let end = buffer.anchor_after(buffer.len());
12990        let theme = cx.theme().colors();
12991        self.background_highlights_in_range(start..end, &snapshot, theme)
12992    }
12993
12994    #[cfg(feature = "test-support")]
12995    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
12996        let snapshot = self.buffer().read(cx).snapshot(cx);
12997
12998        let highlights = self
12999            .background_highlights
13000            .get(&TypeId::of::<items::BufferSearchHighlights>());
13001
13002        if let Some((_color, ranges)) = highlights {
13003            ranges
13004                .iter()
13005                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13006                .collect_vec()
13007        } else {
13008            vec![]
13009        }
13010    }
13011
13012    fn document_highlights_for_position<'a>(
13013        &'a self,
13014        position: Anchor,
13015        buffer: &'a MultiBufferSnapshot,
13016    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13017        let read_highlights = self
13018            .background_highlights
13019            .get(&TypeId::of::<DocumentHighlightRead>())
13020            .map(|h| &h.1);
13021        let write_highlights = self
13022            .background_highlights
13023            .get(&TypeId::of::<DocumentHighlightWrite>())
13024            .map(|h| &h.1);
13025        let left_position = position.bias_left(buffer);
13026        let right_position = position.bias_right(buffer);
13027        read_highlights
13028            .into_iter()
13029            .chain(write_highlights)
13030            .flat_map(move |ranges| {
13031                let start_ix = match ranges.binary_search_by(|probe| {
13032                    let cmp = probe.end.cmp(&left_position, buffer);
13033                    if cmp.is_ge() {
13034                        Ordering::Greater
13035                    } else {
13036                        Ordering::Less
13037                    }
13038                }) {
13039                    Ok(i) | Err(i) => i,
13040                };
13041
13042                ranges[start_ix..]
13043                    .iter()
13044                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13045            })
13046    }
13047
13048    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13049        self.background_highlights
13050            .get(&TypeId::of::<T>())
13051            .map_or(false, |(_, highlights)| !highlights.is_empty())
13052    }
13053
13054    pub fn background_highlights_in_range(
13055        &self,
13056        search_range: Range<Anchor>,
13057        display_snapshot: &DisplaySnapshot,
13058        theme: &ThemeColors,
13059    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13060        let mut results = Vec::new();
13061        for (color_fetcher, ranges) in self.background_highlights.values() {
13062            let color = color_fetcher(theme);
13063            let start_ix = match ranges.binary_search_by(|probe| {
13064                let cmp = probe
13065                    .end
13066                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13067                if cmp.is_gt() {
13068                    Ordering::Greater
13069                } else {
13070                    Ordering::Less
13071                }
13072            }) {
13073                Ok(i) | Err(i) => i,
13074            };
13075            for range in &ranges[start_ix..] {
13076                if range
13077                    .start
13078                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13079                    .is_ge()
13080                {
13081                    break;
13082                }
13083
13084                let start = range.start.to_display_point(display_snapshot);
13085                let end = range.end.to_display_point(display_snapshot);
13086                results.push((start..end, color))
13087            }
13088        }
13089        results
13090    }
13091
13092    pub fn background_highlight_row_ranges<T: 'static>(
13093        &self,
13094        search_range: Range<Anchor>,
13095        display_snapshot: &DisplaySnapshot,
13096        count: usize,
13097    ) -> Vec<RangeInclusive<DisplayPoint>> {
13098        let mut results = Vec::new();
13099        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13100            return vec![];
13101        };
13102
13103        let start_ix = match ranges.binary_search_by(|probe| {
13104            let cmp = probe
13105                .end
13106                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13107            if cmp.is_gt() {
13108                Ordering::Greater
13109            } else {
13110                Ordering::Less
13111            }
13112        }) {
13113            Ok(i) | Err(i) => i,
13114        };
13115        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13116            if let (Some(start_display), Some(end_display)) = (start, end) {
13117                results.push(
13118                    start_display.to_display_point(display_snapshot)
13119                        ..=end_display.to_display_point(display_snapshot),
13120                );
13121            }
13122        };
13123        let mut start_row: Option<Point> = None;
13124        let mut end_row: Option<Point> = None;
13125        if ranges.len() > count {
13126            return Vec::new();
13127        }
13128        for range in &ranges[start_ix..] {
13129            if range
13130                .start
13131                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13132                .is_ge()
13133            {
13134                break;
13135            }
13136            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13137            if let Some(current_row) = &end_row {
13138                if end.row == current_row.row {
13139                    continue;
13140                }
13141            }
13142            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13143            if start_row.is_none() {
13144                assert_eq!(end_row, None);
13145                start_row = Some(start);
13146                end_row = Some(end);
13147                continue;
13148            }
13149            if let Some(current_end) = end_row.as_mut() {
13150                if start.row > current_end.row + 1 {
13151                    push_region(start_row, end_row);
13152                    start_row = Some(start);
13153                    end_row = Some(end);
13154                } else {
13155                    // Merge two hunks.
13156                    *current_end = end;
13157                }
13158            } else {
13159                unreachable!();
13160            }
13161        }
13162        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13163        push_region(start_row, end_row);
13164        results
13165    }
13166
13167    pub fn gutter_highlights_in_range(
13168        &self,
13169        search_range: Range<Anchor>,
13170        display_snapshot: &DisplaySnapshot,
13171        cx: &App,
13172    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13173        let mut results = Vec::new();
13174        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13175            let color = color_fetcher(cx);
13176            let start_ix = match ranges.binary_search_by(|probe| {
13177                let cmp = probe
13178                    .end
13179                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13180                if cmp.is_gt() {
13181                    Ordering::Greater
13182                } else {
13183                    Ordering::Less
13184                }
13185            }) {
13186                Ok(i) | Err(i) => i,
13187            };
13188            for range in &ranges[start_ix..] {
13189                if range
13190                    .start
13191                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13192                    .is_ge()
13193                {
13194                    break;
13195                }
13196
13197                let start = range.start.to_display_point(display_snapshot);
13198                let end = range.end.to_display_point(display_snapshot);
13199                results.push((start..end, color))
13200            }
13201        }
13202        results
13203    }
13204
13205    /// Get the text ranges corresponding to the redaction query
13206    pub fn redacted_ranges(
13207        &self,
13208        search_range: Range<Anchor>,
13209        display_snapshot: &DisplaySnapshot,
13210        cx: &App,
13211    ) -> Vec<Range<DisplayPoint>> {
13212        display_snapshot
13213            .buffer_snapshot
13214            .redacted_ranges(search_range, |file| {
13215                if let Some(file) = file {
13216                    file.is_private()
13217                        && EditorSettings::get(
13218                            Some(SettingsLocation {
13219                                worktree_id: file.worktree_id(cx),
13220                                path: file.path().as_ref(),
13221                            }),
13222                            cx,
13223                        )
13224                        .redact_private_values
13225                } else {
13226                    false
13227                }
13228            })
13229            .map(|range| {
13230                range.start.to_display_point(display_snapshot)
13231                    ..range.end.to_display_point(display_snapshot)
13232            })
13233            .collect()
13234    }
13235
13236    pub fn highlight_text<T: 'static>(
13237        &mut self,
13238        ranges: Vec<Range<Anchor>>,
13239        style: HighlightStyle,
13240        cx: &mut Context<Self>,
13241    ) {
13242        self.display_map.update(cx, |map, _| {
13243            map.highlight_text(TypeId::of::<T>(), ranges, style)
13244        });
13245        cx.notify();
13246    }
13247
13248    pub(crate) fn highlight_inlays<T: 'static>(
13249        &mut self,
13250        highlights: Vec<InlayHighlight>,
13251        style: HighlightStyle,
13252        cx: &mut Context<Self>,
13253    ) {
13254        self.display_map.update(cx, |map, _| {
13255            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13256        });
13257        cx.notify();
13258    }
13259
13260    pub fn text_highlights<'a, T: 'static>(
13261        &'a self,
13262        cx: &'a App,
13263    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13264        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13265    }
13266
13267    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13268        let cleared = self
13269            .display_map
13270            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13271        if cleared {
13272            cx.notify();
13273        }
13274    }
13275
13276    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13277        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13278            && self.focus_handle.is_focused(window)
13279    }
13280
13281    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13282        self.show_cursor_when_unfocused = is_enabled;
13283        cx.notify();
13284    }
13285
13286    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13287        self.project
13288            .as_ref()
13289            .map(|project| project.read(cx).lsp_store())
13290    }
13291
13292    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13293        cx.notify();
13294    }
13295
13296    fn on_buffer_event(
13297        &mut self,
13298        multibuffer: &Entity<MultiBuffer>,
13299        event: &multi_buffer::Event,
13300        window: &mut Window,
13301        cx: &mut Context<Self>,
13302    ) {
13303        match event {
13304            multi_buffer::Event::Edited {
13305                singleton_buffer_edited,
13306                edited_buffer: buffer_edited,
13307            } => {
13308                self.scrollbar_marker_state.dirty = true;
13309                self.active_indent_guides_state.dirty = true;
13310                self.refresh_active_diagnostics(cx);
13311                self.refresh_code_actions(window, cx);
13312                if self.has_active_inline_completion() {
13313                    self.update_visible_inline_completion(window, cx);
13314                }
13315                if let Some(buffer) = buffer_edited {
13316                    let buffer_id = buffer.read(cx).remote_id();
13317                    if !self.registered_buffers.contains_key(&buffer_id) {
13318                        if let Some(lsp_store) = self.lsp_store(cx) {
13319                            lsp_store.update(cx, |lsp_store, cx| {
13320                                self.registered_buffers.insert(
13321                                    buffer_id,
13322                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13323                                );
13324                            })
13325                        }
13326                    }
13327                }
13328                cx.emit(EditorEvent::BufferEdited);
13329                cx.emit(SearchEvent::MatchesInvalidated);
13330                if *singleton_buffer_edited {
13331                    if let Some(project) = &self.project {
13332                        let project = project.read(cx);
13333                        #[allow(clippy::mutable_key_type)]
13334                        let languages_affected = multibuffer
13335                            .read(cx)
13336                            .all_buffers()
13337                            .into_iter()
13338                            .filter_map(|buffer| {
13339                                let buffer = buffer.read(cx);
13340                                let language = buffer.language()?;
13341                                if project.is_local()
13342                                    && project
13343                                        .language_servers_for_local_buffer(buffer, cx)
13344                                        .count()
13345                                        == 0
13346                                {
13347                                    None
13348                                } else {
13349                                    Some(language)
13350                                }
13351                            })
13352                            .cloned()
13353                            .collect::<HashSet<_>>();
13354                        if !languages_affected.is_empty() {
13355                            self.refresh_inlay_hints(
13356                                InlayHintRefreshReason::BufferEdited(languages_affected),
13357                                cx,
13358                            );
13359                        }
13360                    }
13361                }
13362
13363                let Some(project) = &self.project else { return };
13364                let (telemetry, is_via_ssh) = {
13365                    let project = project.read(cx);
13366                    let telemetry = project.client().telemetry().clone();
13367                    let is_via_ssh = project.is_via_ssh();
13368                    (telemetry, is_via_ssh)
13369                };
13370                refresh_linked_ranges(self, window, cx);
13371                telemetry.log_edit_event("editor", is_via_ssh);
13372            }
13373            multi_buffer::Event::ExcerptsAdded {
13374                buffer,
13375                predecessor,
13376                excerpts,
13377            } => {
13378                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13379                let buffer_id = buffer.read(cx).remote_id();
13380                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13381                    if let Some(project) = &self.project {
13382                        get_unstaged_changes_for_buffers(
13383                            project,
13384                            [buffer.clone()],
13385                            self.buffer.clone(),
13386                            cx,
13387                        );
13388                    }
13389                }
13390                cx.emit(EditorEvent::ExcerptsAdded {
13391                    buffer: buffer.clone(),
13392                    predecessor: *predecessor,
13393                    excerpts: excerpts.clone(),
13394                });
13395                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13396            }
13397            multi_buffer::Event::ExcerptsRemoved { ids } => {
13398                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13399                let buffer = self.buffer.read(cx);
13400                self.registered_buffers
13401                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13402                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13403            }
13404            multi_buffer::Event::ExcerptsEdited { ids } => {
13405                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13406            }
13407            multi_buffer::Event::ExcerptsExpanded { ids } => {
13408                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13409                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13410            }
13411            multi_buffer::Event::Reparsed(buffer_id) => {
13412                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13413
13414                cx.emit(EditorEvent::Reparsed(*buffer_id));
13415            }
13416            multi_buffer::Event::DiffHunksToggled => {
13417                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13418            }
13419            multi_buffer::Event::LanguageChanged(buffer_id) => {
13420                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13421                cx.emit(EditorEvent::Reparsed(*buffer_id));
13422                cx.notify();
13423            }
13424            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13425            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13426            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13427                cx.emit(EditorEvent::TitleChanged)
13428            }
13429            // multi_buffer::Event::DiffBaseChanged => {
13430            //     self.scrollbar_marker_state.dirty = true;
13431            //     cx.emit(EditorEvent::DiffBaseChanged);
13432            //     cx.notify();
13433            // }
13434            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13435            multi_buffer::Event::DiagnosticsUpdated => {
13436                self.refresh_active_diagnostics(cx);
13437                self.scrollbar_marker_state.dirty = true;
13438                cx.notify();
13439            }
13440            _ => {}
13441        };
13442    }
13443
13444    fn on_display_map_changed(
13445        &mut self,
13446        _: Entity<DisplayMap>,
13447        _: &mut Window,
13448        cx: &mut Context<Self>,
13449    ) {
13450        cx.notify();
13451    }
13452
13453    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13454        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13455        self.refresh_inline_completion(true, false, window, cx);
13456        self.refresh_inlay_hints(
13457            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13458                self.selections.newest_anchor().head(),
13459                &self.buffer.read(cx).snapshot(cx),
13460                cx,
13461            )),
13462            cx,
13463        );
13464
13465        let old_cursor_shape = self.cursor_shape;
13466
13467        {
13468            let editor_settings = EditorSettings::get_global(cx);
13469            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13470            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13471            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13472        }
13473
13474        if old_cursor_shape != self.cursor_shape {
13475            cx.emit(EditorEvent::CursorShapeChanged);
13476        }
13477
13478        let project_settings = ProjectSettings::get_global(cx);
13479        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13480
13481        if self.mode == EditorMode::Full {
13482            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13483            if self.git_blame_inline_enabled != inline_blame_enabled {
13484                self.toggle_git_blame_inline_internal(false, window, cx);
13485            }
13486        }
13487
13488        cx.notify();
13489    }
13490
13491    pub fn set_searchable(&mut self, searchable: bool) {
13492        self.searchable = searchable;
13493    }
13494
13495    pub fn searchable(&self) -> bool {
13496        self.searchable
13497    }
13498
13499    fn open_proposed_changes_editor(
13500        &mut self,
13501        _: &OpenProposedChangesEditor,
13502        window: &mut Window,
13503        cx: &mut Context<Self>,
13504    ) {
13505        let Some(workspace) = self.workspace() else {
13506            cx.propagate();
13507            return;
13508        };
13509
13510        let selections = self.selections.all::<usize>(cx);
13511        let multi_buffer = self.buffer.read(cx);
13512        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13513        let mut new_selections_by_buffer = HashMap::default();
13514        for selection in selections {
13515            for (buffer, range, _) in
13516                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13517            {
13518                let mut range = range.to_point(buffer);
13519                range.start.column = 0;
13520                range.end.column = buffer.line_len(range.end.row);
13521                new_selections_by_buffer
13522                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13523                    .or_insert(Vec::new())
13524                    .push(range)
13525            }
13526        }
13527
13528        let proposed_changes_buffers = new_selections_by_buffer
13529            .into_iter()
13530            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13531            .collect::<Vec<_>>();
13532        let proposed_changes_editor = cx.new(|cx| {
13533            ProposedChangesEditor::new(
13534                "Proposed changes",
13535                proposed_changes_buffers,
13536                self.project.clone(),
13537                window,
13538                cx,
13539            )
13540        });
13541
13542        window.defer(cx, move |window, cx| {
13543            workspace.update(cx, |workspace, cx| {
13544                workspace.active_pane().update(cx, |pane, cx| {
13545                    pane.add_item(
13546                        Box::new(proposed_changes_editor),
13547                        true,
13548                        true,
13549                        None,
13550                        window,
13551                        cx,
13552                    );
13553                });
13554            });
13555        });
13556    }
13557
13558    pub fn open_excerpts_in_split(
13559        &mut self,
13560        _: &OpenExcerptsSplit,
13561        window: &mut Window,
13562        cx: &mut Context<Self>,
13563    ) {
13564        self.open_excerpts_common(None, true, window, cx)
13565    }
13566
13567    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13568        self.open_excerpts_common(None, false, window, cx)
13569    }
13570
13571    fn open_excerpts_common(
13572        &mut self,
13573        jump_data: Option<JumpData>,
13574        split: bool,
13575        window: &mut Window,
13576        cx: &mut Context<Self>,
13577    ) {
13578        let Some(workspace) = self.workspace() else {
13579            cx.propagate();
13580            return;
13581        };
13582
13583        if self.buffer.read(cx).is_singleton() {
13584            cx.propagate();
13585            return;
13586        }
13587
13588        let mut new_selections_by_buffer = HashMap::default();
13589        match &jump_data {
13590            Some(JumpData::MultiBufferPoint {
13591                excerpt_id,
13592                position,
13593                anchor,
13594                line_offset_from_top,
13595            }) => {
13596                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13597                if let Some(buffer) = multi_buffer_snapshot
13598                    .buffer_id_for_excerpt(*excerpt_id)
13599                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13600                {
13601                    let buffer_snapshot = buffer.read(cx).snapshot();
13602                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13603                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13604                    } else {
13605                        buffer_snapshot.clip_point(*position, Bias::Left)
13606                    };
13607                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13608                    new_selections_by_buffer.insert(
13609                        buffer,
13610                        (
13611                            vec![jump_to_offset..jump_to_offset],
13612                            Some(*line_offset_from_top),
13613                        ),
13614                    );
13615                }
13616            }
13617            Some(JumpData::MultiBufferRow {
13618                row,
13619                line_offset_from_top,
13620            }) => {
13621                let point = MultiBufferPoint::new(row.0, 0);
13622                if let Some((buffer, buffer_point, _)) =
13623                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13624                {
13625                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13626                    new_selections_by_buffer
13627                        .entry(buffer)
13628                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13629                        .0
13630                        .push(buffer_offset..buffer_offset)
13631                }
13632            }
13633            None => {
13634                let selections = self.selections.all::<usize>(cx);
13635                let multi_buffer = self.buffer.read(cx);
13636                for selection in selections {
13637                    for (buffer, mut range, _) in multi_buffer
13638                        .snapshot(cx)
13639                        .range_to_buffer_ranges(selection.range())
13640                    {
13641                        // When editing branch buffers, jump to the corresponding location
13642                        // in their base buffer.
13643                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13644                        let buffer = buffer_handle.read(cx);
13645                        if let Some(base_buffer) = buffer.base_buffer() {
13646                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13647                            buffer_handle = base_buffer;
13648                        }
13649
13650                        if selection.reversed {
13651                            mem::swap(&mut range.start, &mut range.end);
13652                        }
13653                        new_selections_by_buffer
13654                            .entry(buffer_handle)
13655                            .or_insert((Vec::new(), None))
13656                            .0
13657                            .push(range)
13658                    }
13659                }
13660            }
13661        }
13662
13663        if new_selections_by_buffer.is_empty() {
13664            return;
13665        }
13666
13667        // We defer the pane interaction because we ourselves are a workspace item
13668        // and activating a new item causes the pane to call a method on us reentrantly,
13669        // which panics if we're on the stack.
13670        window.defer(cx, move |window, cx| {
13671            workspace.update(cx, |workspace, cx| {
13672                let pane = if split {
13673                    workspace.adjacent_pane(window, cx)
13674                } else {
13675                    workspace.active_pane().clone()
13676                };
13677
13678                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13679                    let editor = buffer
13680                        .read(cx)
13681                        .file()
13682                        .is_none()
13683                        .then(|| {
13684                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13685                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13686                            // Instead, we try to activate the existing editor in the pane first.
13687                            let (editor, pane_item_index) =
13688                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13689                                    let editor = item.downcast::<Editor>()?;
13690                                    let singleton_buffer =
13691                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13692                                    if singleton_buffer == buffer {
13693                                        Some((editor, i))
13694                                    } else {
13695                                        None
13696                                    }
13697                                })?;
13698                            pane.update(cx, |pane, cx| {
13699                                pane.activate_item(pane_item_index, true, true, window, cx)
13700                            });
13701                            Some(editor)
13702                        })
13703                        .flatten()
13704                        .unwrap_or_else(|| {
13705                            workspace.open_project_item::<Self>(
13706                                pane.clone(),
13707                                buffer,
13708                                true,
13709                                true,
13710                                window,
13711                                cx,
13712                            )
13713                        });
13714
13715                    editor.update(cx, |editor, cx| {
13716                        let autoscroll = match scroll_offset {
13717                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13718                            None => Autoscroll::newest(),
13719                        };
13720                        let nav_history = editor.nav_history.take();
13721                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13722                            s.select_ranges(ranges);
13723                        });
13724                        editor.nav_history = nav_history;
13725                    });
13726                }
13727            })
13728        });
13729    }
13730
13731    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13732        let snapshot = self.buffer.read(cx).read(cx);
13733        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13734        Some(
13735            ranges
13736                .iter()
13737                .map(move |range| {
13738                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13739                })
13740                .collect(),
13741        )
13742    }
13743
13744    fn selection_replacement_ranges(
13745        &self,
13746        range: Range<OffsetUtf16>,
13747        cx: &mut App,
13748    ) -> Vec<Range<OffsetUtf16>> {
13749        let selections = self.selections.all::<OffsetUtf16>(cx);
13750        let newest_selection = selections
13751            .iter()
13752            .max_by_key(|selection| selection.id)
13753            .unwrap();
13754        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13755        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13756        let snapshot = self.buffer.read(cx).read(cx);
13757        selections
13758            .into_iter()
13759            .map(|mut selection| {
13760                selection.start.0 =
13761                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
13762                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13763                snapshot.clip_offset_utf16(selection.start, Bias::Left)
13764                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13765            })
13766            .collect()
13767    }
13768
13769    fn report_editor_event(
13770        &self,
13771        event_type: &'static str,
13772        file_extension: Option<String>,
13773        cx: &App,
13774    ) {
13775        if cfg!(any(test, feature = "test-support")) {
13776            return;
13777        }
13778
13779        let Some(project) = &self.project else { return };
13780
13781        // If None, we are in a file without an extension
13782        let file = self
13783            .buffer
13784            .read(cx)
13785            .as_singleton()
13786            .and_then(|b| b.read(cx).file());
13787        let file_extension = file_extension.or(file
13788            .as_ref()
13789            .and_then(|file| Path::new(file.file_name(cx)).extension())
13790            .and_then(|e| e.to_str())
13791            .map(|a| a.to_string()));
13792
13793        let vim_mode = cx
13794            .global::<SettingsStore>()
13795            .raw_user_settings()
13796            .get("vim_mode")
13797            == Some(&serde_json::Value::Bool(true));
13798
13799        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13800            == language::language_settings::InlineCompletionProvider::Copilot;
13801        let copilot_enabled_for_language = self
13802            .buffer
13803            .read(cx)
13804            .settings_at(0, cx)
13805            .show_inline_completions;
13806
13807        let project = project.read(cx);
13808        telemetry::event!(
13809            event_type,
13810            file_extension,
13811            vim_mode,
13812            copilot_enabled,
13813            copilot_enabled_for_language,
13814            is_via_ssh = project.is_via_ssh(),
13815        );
13816    }
13817
13818    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13819    /// with each line being an array of {text, highlight} objects.
13820    fn copy_highlight_json(
13821        &mut self,
13822        _: &CopyHighlightJson,
13823        window: &mut Window,
13824        cx: &mut Context<Self>,
13825    ) {
13826        #[derive(Serialize)]
13827        struct Chunk<'a> {
13828            text: String,
13829            highlight: Option<&'a str>,
13830        }
13831
13832        let snapshot = self.buffer.read(cx).snapshot(cx);
13833        let range = self
13834            .selected_text_range(false, window, cx)
13835            .and_then(|selection| {
13836                if selection.range.is_empty() {
13837                    None
13838                } else {
13839                    Some(selection.range)
13840                }
13841            })
13842            .unwrap_or_else(|| 0..snapshot.len());
13843
13844        let chunks = snapshot.chunks(range, true);
13845        let mut lines = Vec::new();
13846        let mut line: VecDeque<Chunk> = VecDeque::new();
13847
13848        let Some(style) = self.style.as_ref() else {
13849            return;
13850        };
13851
13852        for chunk in chunks {
13853            let highlight = chunk
13854                .syntax_highlight_id
13855                .and_then(|id| id.name(&style.syntax));
13856            let mut chunk_lines = chunk.text.split('\n').peekable();
13857            while let Some(text) = chunk_lines.next() {
13858                let mut merged_with_last_token = false;
13859                if let Some(last_token) = line.back_mut() {
13860                    if last_token.highlight == highlight {
13861                        last_token.text.push_str(text);
13862                        merged_with_last_token = true;
13863                    }
13864                }
13865
13866                if !merged_with_last_token {
13867                    line.push_back(Chunk {
13868                        text: text.into(),
13869                        highlight,
13870                    });
13871                }
13872
13873                if chunk_lines.peek().is_some() {
13874                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13875                        line.pop_front();
13876                    }
13877                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13878                        line.pop_back();
13879                    }
13880
13881                    lines.push(mem::take(&mut line));
13882                }
13883            }
13884        }
13885
13886        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13887            return;
13888        };
13889        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13890    }
13891
13892    pub fn open_context_menu(
13893        &mut self,
13894        _: &OpenContextMenu,
13895        window: &mut Window,
13896        cx: &mut Context<Self>,
13897    ) {
13898        self.request_autoscroll(Autoscroll::newest(), cx);
13899        let position = self.selections.newest_display(cx).start;
13900        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
13901    }
13902
13903    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13904        &self.inlay_hint_cache
13905    }
13906
13907    pub fn replay_insert_event(
13908        &mut self,
13909        text: &str,
13910        relative_utf16_range: Option<Range<isize>>,
13911        window: &mut Window,
13912        cx: &mut Context<Self>,
13913    ) {
13914        if !self.input_enabled {
13915            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13916            return;
13917        }
13918        if let Some(relative_utf16_range) = relative_utf16_range {
13919            let selections = self.selections.all::<OffsetUtf16>(cx);
13920            self.change_selections(None, window, cx, |s| {
13921                let new_ranges = selections.into_iter().map(|range| {
13922                    let start = OffsetUtf16(
13923                        range
13924                            .head()
13925                            .0
13926                            .saturating_add_signed(relative_utf16_range.start),
13927                    );
13928                    let end = OffsetUtf16(
13929                        range
13930                            .head()
13931                            .0
13932                            .saturating_add_signed(relative_utf16_range.end),
13933                    );
13934                    start..end
13935                });
13936                s.select_ranges(new_ranges);
13937            });
13938        }
13939
13940        self.handle_input(text, window, cx);
13941    }
13942
13943    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
13944        let Some(provider) = self.semantics_provider.as_ref() else {
13945            return false;
13946        };
13947
13948        let mut supports = false;
13949        self.buffer().read(cx).for_each_buffer(|buffer| {
13950            supports |= provider.supports_inlay_hints(buffer, cx);
13951        });
13952        supports
13953    }
13954    pub fn is_focused(&self, window: &mut Window) -> bool {
13955        self.focus_handle.is_focused(window)
13956    }
13957
13958    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13959        cx.emit(EditorEvent::Focused);
13960
13961        if let Some(descendant) = self
13962            .last_focused_descendant
13963            .take()
13964            .and_then(|descendant| descendant.upgrade())
13965        {
13966            window.focus(&descendant);
13967        } else {
13968            if let Some(blame) = self.blame.as_ref() {
13969                blame.update(cx, GitBlame::focus)
13970            }
13971
13972            self.blink_manager.update(cx, BlinkManager::enable);
13973            self.show_cursor_names(window, cx);
13974            self.buffer.update(cx, |buffer, cx| {
13975                buffer.finalize_last_transaction(cx);
13976                if self.leader_peer_id.is_none() {
13977                    buffer.set_active_selections(
13978                        &self.selections.disjoint_anchors(),
13979                        self.selections.line_mode,
13980                        self.cursor_shape,
13981                        cx,
13982                    );
13983                }
13984            });
13985        }
13986    }
13987
13988    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
13989        cx.emit(EditorEvent::FocusedIn)
13990    }
13991
13992    fn handle_focus_out(
13993        &mut self,
13994        event: FocusOutEvent,
13995        _window: &mut Window,
13996        _cx: &mut Context<Self>,
13997    ) {
13998        if event.blurred != self.focus_handle {
13999            self.last_focused_descendant = Some(event.blurred);
14000        }
14001    }
14002
14003    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14004        self.blink_manager.update(cx, BlinkManager::disable);
14005        self.buffer
14006            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14007
14008        if let Some(blame) = self.blame.as_ref() {
14009            blame.update(cx, GitBlame::blur)
14010        }
14011        if !self.hover_state.focused(window, cx) {
14012            hide_hover(self, cx);
14013        }
14014
14015        self.hide_context_menu(window, cx);
14016        cx.emit(EditorEvent::Blurred);
14017        cx.notify();
14018    }
14019
14020    pub fn register_action<A: Action>(
14021        &mut self,
14022        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14023    ) -> Subscription {
14024        let id = self.next_editor_action_id.post_inc();
14025        let listener = Arc::new(listener);
14026        self.editor_actions.borrow_mut().insert(
14027            id,
14028            Box::new(move |window, _| {
14029                let listener = listener.clone();
14030                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14031                    let action = action.downcast_ref().unwrap();
14032                    if phase == DispatchPhase::Bubble {
14033                        listener(action, window, cx)
14034                    }
14035                })
14036            }),
14037        );
14038
14039        let editor_actions = self.editor_actions.clone();
14040        Subscription::new(move || {
14041            editor_actions.borrow_mut().remove(&id);
14042        })
14043    }
14044
14045    pub fn file_header_size(&self) -> u32 {
14046        FILE_HEADER_HEIGHT
14047    }
14048
14049    pub fn revert(
14050        &mut self,
14051        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14052        window: &mut Window,
14053        cx: &mut Context<Self>,
14054    ) {
14055        self.buffer().update(cx, |multi_buffer, cx| {
14056            for (buffer_id, changes) in revert_changes {
14057                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14058                    buffer.update(cx, |buffer, cx| {
14059                        buffer.edit(
14060                            changes.into_iter().map(|(range, text)| {
14061                                (range, text.to_string().map(Arc::<str>::from))
14062                            }),
14063                            None,
14064                            cx,
14065                        );
14066                    });
14067                }
14068            }
14069        });
14070        self.change_selections(None, window, cx, |selections| selections.refresh());
14071    }
14072
14073    pub fn to_pixel_point(
14074        &self,
14075        source: multi_buffer::Anchor,
14076        editor_snapshot: &EditorSnapshot,
14077        window: &mut Window,
14078    ) -> Option<gpui::Point<Pixels>> {
14079        let source_point = source.to_display_point(editor_snapshot);
14080        self.display_to_pixel_point(source_point, editor_snapshot, window)
14081    }
14082
14083    pub fn display_to_pixel_point(
14084        &self,
14085        source: DisplayPoint,
14086        editor_snapshot: &EditorSnapshot,
14087        window: &mut Window,
14088    ) -> Option<gpui::Point<Pixels>> {
14089        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14090        let text_layout_details = self.text_layout_details(window);
14091        let scroll_top = text_layout_details
14092            .scroll_anchor
14093            .scroll_position(editor_snapshot)
14094            .y;
14095
14096        if source.row().as_f32() < scroll_top.floor() {
14097            return None;
14098        }
14099        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14100        let source_y = line_height * (source.row().as_f32() - scroll_top);
14101        Some(gpui::Point::new(source_x, source_y))
14102    }
14103
14104    pub fn has_active_completions_menu(&self) -> bool {
14105        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14106            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14107        })
14108    }
14109
14110    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14111        self.addons
14112            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14113    }
14114
14115    pub fn unregister_addon<T: Addon>(&mut self) {
14116        self.addons.remove(&std::any::TypeId::of::<T>());
14117    }
14118
14119    pub fn addon<T: Addon>(&self) -> Option<&T> {
14120        let type_id = std::any::TypeId::of::<T>();
14121        self.addons
14122            .get(&type_id)
14123            .and_then(|item| item.to_any().downcast_ref::<T>())
14124    }
14125
14126    fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14127        let text_layout_details = self.text_layout_details(window);
14128        let style = &text_layout_details.editor_style;
14129        let font_id = window.text_system().resolve_font(&style.text.font());
14130        let font_size = style.text.font_size.to_pixels(window.rem_size());
14131        let line_height = style.text.line_height_in_pixels(window.rem_size());
14132        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14133
14134        gpui::Point::new(em_width, line_height)
14135    }
14136}
14137
14138fn get_unstaged_changes_for_buffers(
14139    project: &Entity<Project>,
14140    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14141    buffer: Entity<MultiBuffer>,
14142    cx: &mut App,
14143) {
14144    let mut tasks = Vec::new();
14145    project.update(cx, |project, cx| {
14146        for buffer in buffers {
14147            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14148        }
14149    });
14150    cx.spawn(|mut cx| async move {
14151        let change_sets = futures::future::join_all(tasks).await;
14152        buffer
14153            .update(&mut cx, |buffer, cx| {
14154                for change_set in change_sets {
14155                    if let Some(change_set) = change_set.log_err() {
14156                        buffer.add_change_set(change_set, cx);
14157                    }
14158                }
14159            })
14160            .ok();
14161    })
14162    .detach();
14163}
14164
14165fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14166    let tab_size = tab_size.get() as usize;
14167    let mut width = offset;
14168
14169    for ch in text.chars() {
14170        width += if ch == '\t' {
14171            tab_size - (width % tab_size)
14172        } else {
14173            1
14174        };
14175    }
14176
14177    width - offset
14178}
14179
14180#[cfg(test)]
14181mod tests {
14182    use super::*;
14183
14184    #[test]
14185    fn test_string_size_with_expanded_tabs() {
14186        let nz = |val| NonZeroU32::new(val).unwrap();
14187        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14188        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14189        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14190        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14191        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14192        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14193        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14194        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14195    }
14196}
14197
14198/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14199struct WordBreakingTokenizer<'a> {
14200    input: &'a str,
14201}
14202
14203impl<'a> WordBreakingTokenizer<'a> {
14204    fn new(input: &'a str) -> Self {
14205        Self { input }
14206    }
14207}
14208
14209fn is_char_ideographic(ch: char) -> bool {
14210    use unicode_script::Script::*;
14211    use unicode_script::UnicodeScript;
14212    matches!(ch.script(), Han | Tangut | Yi)
14213}
14214
14215fn is_grapheme_ideographic(text: &str) -> bool {
14216    text.chars().any(is_char_ideographic)
14217}
14218
14219fn is_grapheme_whitespace(text: &str) -> bool {
14220    text.chars().any(|x| x.is_whitespace())
14221}
14222
14223fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14224    text.chars().next().map_or(false, |ch| {
14225        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14226    })
14227}
14228
14229#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14230struct WordBreakToken<'a> {
14231    token: &'a str,
14232    grapheme_len: usize,
14233    is_whitespace: bool,
14234}
14235
14236impl<'a> Iterator for WordBreakingTokenizer<'a> {
14237    /// Yields a span, the count of graphemes in the token, and whether it was
14238    /// whitespace. Note that it also breaks at word boundaries.
14239    type Item = WordBreakToken<'a>;
14240
14241    fn next(&mut self) -> Option<Self::Item> {
14242        use unicode_segmentation::UnicodeSegmentation;
14243        if self.input.is_empty() {
14244            return None;
14245        }
14246
14247        let mut iter = self.input.graphemes(true).peekable();
14248        let mut offset = 0;
14249        let mut graphemes = 0;
14250        if let Some(first_grapheme) = iter.next() {
14251            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14252            offset += first_grapheme.len();
14253            graphemes += 1;
14254            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14255                if let Some(grapheme) = iter.peek().copied() {
14256                    if should_stay_with_preceding_ideograph(grapheme) {
14257                        offset += grapheme.len();
14258                        graphemes += 1;
14259                    }
14260                }
14261            } else {
14262                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14263                let mut next_word_bound = words.peek().copied();
14264                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14265                    next_word_bound = words.next();
14266                }
14267                while let Some(grapheme) = iter.peek().copied() {
14268                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14269                        break;
14270                    };
14271                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14272                        break;
14273                    };
14274                    offset += grapheme.len();
14275                    graphemes += 1;
14276                    iter.next();
14277                }
14278            }
14279            let token = &self.input[..offset];
14280            self.input = &self.input[offset..];
14281            if is_whitespace {
14282                Some(WordBreakToken {
14283                    token: " ",
14284                    grapheme_len: 1,
14285                    is_whitespace: true,
14286                })
14287            } else {
14288                Some(WordBreakToken {
14289                    token,
14290                    grapheme_len: graphemes,
14291                    is_whitespace: false,
14292                })
14293            }
14294        } else {
14295            None
14296        }
14297    }
14298}
14299
14300#[test]
14301fn test_word_breaking_tokenizer() {
14302    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14303        ("", &[]),
14304        ("  ", &[(" ", 1, true)]),
14305        ("Ʒ", &[("Ʒ", 1, false)]),
14306        ("Ǽ", &[("Ǽ", 1, false)]),
14307        ("", &[("", 1, false)]),
14308        ("⋑⋑", &[("⋑⋑", 2, false)]),
14309        (
14310            "原理,进而",
14311            &[
14312                ("", 1, false),
14313                ("理,", 2, false),
14314                ("", 1, false),
14315                ("", 1, false),
14316            ],
14317        ),
14318        (
14319            "hello world",
14320            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14321        ),
14322        (
14323            "hello, world",
14324            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14325        ),
14326        (
14327            "  hello world",
14328            &[
14329                (" ", 1, true),
14330                ("hello", 5, false),
14331                (" ", 1, true),
14332                ("world", 5, false),
14333            ],
14334        ),
14335        (
14336            "这是什么 \n 钢笔",
14337            &[
14338                ("", 1, false),
14339                ("", 1, false),
14340                ("", 1, false),
14341                ("", 1, false),
14342                (" ", 1, true),
14343                ("", 1, false),
14344                ("", 1, false),
14345            ],
14346        ),
14347        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14348    ];
14349
14350    for (input, result) in tests {
14351        assert_eq!(
14352            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14353            result
14354                .iter()
14355                .copied()
14356                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14357                    token,
14358                    grapheme_len,
14359                    is_whitespace,
14360                })
14361                .collect::<Vec<_>>()
14362        );
14363    }
14364}
14365
14366fn wrap_with_prefix(
14367    line_prefix: String,
14368    unwrapped_text: String,
14369    wrap_column: usize,
14370    tab_size: NonZeroU32,
14371) -> String {
14372    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14373    let mut wrapped_text = String::new();
14374    let mut current_line = line_prefix.clone();
14375
14376    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14377    let mut current_line_len = line_prefix_len;
14378    for WordBreakToken {
14379        token,
14380        grapheme_len,
14381        is_whitespace,
14382    } in tokenizer
14383    {
14384        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14385            wrapped_text.push_str(current_line.trim_end());
14386            wrapped_text.push('\n');
14387            current_line.truncate(line_prefix.len());
14388            current_line_len = line_prefix_len;
14389            if !is_whitespace {
14390                current_line.push_str(token);
14391                current_line_len += grapheme_len;
14392            }
14393        } else if !is_whitespace {
14394            current_line.push_str(token);
14395            current_line_len += grapheme_len;
14396        } else if current_line_len != line_prefix_len {
14397            current_line.push(' ');
14398            current_line_len += 1;
14399        }
14400    }
14401
14402    if !current_line.is_empty() {
14403        wrapped_text.push_str(&current_line);
14404    }
14405    wrapped_text
14406}
14407
14408#[test]
14409fn test_wrap_with_prefix() {
14410    assert_eq!(
14411        wrap_with_prefix(
14412            "# ".to_string(),
14413            "abcdefg".to_string(),
14414            4,
14415            NonZeroU32::new(4).unwrap()
14416        ),
14417        "# abcdefg"
14418    );
14419    assert_eq!(
14420        wrap_with_prefix(
14421            "".to_string(),
14422            "\thello world".to_string(),
14423            8,
14424            NonZeroU32::new(4).unwrap()
14425        ),
14426        "hello\nworld"
14427    );
14428    assert_eq!(
14429        wrap_with_prefix(
14430            "// ".to_string(),
14431            "xx \nyy zz aa bb cc".to_string(),
14432            12,
14433            NonZeroU32::new(4).unwrap()
14434        ),
14435        "// xx yy zz\n// aa bb cc"
14436    );
14437    assert_eq!(
14438        wrap_with_prefix(
14439            String::new(),
14440            "这是什么 \n 钢笔".to_string(),
14441            3,
14442            NonZeroU32::new(4).unwrap()
14443        ),
14444        "这是什\n么 钢\n"
14445    );
14446}
14447
14448pub trait CollaborationHub {
14449    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14450    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14451    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14452}
14453
14454impl CollaborationHub for Entity<Project> {
14455    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14456        self.read(cx).collaborators()
14457    }
14458
14459    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14460        self.read(cx).user_store().read(cx).participant_indices()
14461    }
14462
14463    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14464        let this = self.read(cx);
14465        let user_ids = this.collaborators().values().map(|c| c.user_id);
14466        this.user_store().read_with(cx, |user_store, cx| {
14467            user_store.participant_names(user_ids, cx)
14468        })
14469    }
14470}
14471
14472pub trait SemanticsProvider {
14473    fn hover(
14474        &self,
14475        buffer: &Entity<Buffer>,
14476        position: text::Anchor,
14477        cx: &mut App,
14478    ) -> Option<Task<Vec<project::Hover>>>;
14479
14480    fn inlay_hints(
14481        &self,
14482        buffer_handle: Entity<Buffer>,
14483        range: Range<text::Anchor>,
14484        cx: &mut App,
14485    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14486
14487    fn resolve_inlay_hint(
14488        &self,
14489        hint: InlayHint,
14490        buffer_handle: Entity<Buffer>,
14491        server_id: LanguageServerId,
14492        cx: &mut App,
14493    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14494
14495    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14496
14497    fn document_highlights(
14498        &self,
14499        buffer: &Entity<Buffer>,
14500        position: text::Anchor,
14501        cx: &mut App,
14502    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14503
14504    fn definitions(
14505        &self,
14506        buffer: &Entity<Buffer>,
14507        position: text::Anchor,
14508        kind: GotoDefinitionKind,
14509        cx: &mut App,
14510    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14511
14512    fn range_for_rename(
14513        &self,
14514        buffer: &Entity<Buffer>,
14515        position: text::Anchor,
14516        cx: &mut App,
14517    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14518
14519    fn perform_rename(
14520        &self,
14521        buffer: &Entity<Buffer>,
14522        position: text::Anchor,
14523        new_name: String,
14524        cx: &mut App,
14525    ) -> Option<Task<Result<ProjectTransaction>>>;
14526}
14527
14528pub trait CompletionProvider {
14529    fn completions(
14530        &self,
14531        buffer: &Entity<Buffer>,
14532        buffer_position: text::Anchor,
14533        trigger: CompletionContext,
14534        window: &mut Window,
14535        cx: &mut Context<Editor>,
14536    ) -> Task<Result<Vec<Completion>>>;
14537
14538    fn resolve_completions(
14539        &self,
14540        buffer: Entity<Buffer>,
14541        completion_indices: Vec<usize>,
14542        completions: Rc<RefCell<Box<[Completion]>>>,
14543        cx: &mut Context<Editor>,
14544    ) -> Task<Result<bool>>;
14545
14546    fn apply_additional_edits_for_completion(
14547        &self,
14548        _buffer: Entity<Buffer>,
14549        _completions: Rc<RefCell<Box<[Completion]>>>,
14550        _completion_index: usize,
14551        _push_to_history: bool,
14552        _cx: &mut Context<Editor>,
14553    ) -> Task<Result<Option<language::Transaction>>> {
14554        Task::ready(Ok(None))
14555    }
14556
14557    fn is_completion_trigger(
14558        &self,
14559        buffer: &Entity<Buffer>,
14560        position: language::Anchor,
14561        text: &str,
14562        trigger_in_words: bool,
14563        cx: &mut Context<Editor>,
14564    ) -> bool;
14565
14566    fn sort_completions(&self) -> bool {
14567        true
14568    }
14569}
14570
14571pub trait CodeActionProvider {
14572    fn id(&self) -> Arc<str>;
14573
14574    fn code_actions(
14575        &self,
14576        buffer: &Entity<Buffer>,
14577        range: Range<text::Anchor>,
14578        window: &mut Window,
14579        cx: &mut App,
14580    ) -> Task<Result<Vec<CodeAction>>>;
14581
14582    fn apply_code_action(
14583        &self,
14584        buffer_handle: Entity<Buffer>,
14585        action: CodeAction,
14586        excerpt_id: ExcerptId,
14587        push_to_history: bool,
14588        window: &mut Window,
14589        cx: &mut App,
14590    ) -> Task<Result<ProjectTransaction>>;
14591}
14592
14593impl CodeActionProvider for Entity<Project> {
14594    fn id(&self) -> Arc<str> {
14595        "project".into()
14596    }
14597
14598    fn code_actions(
14599        &self,
14600        buffer: &Entity<Buffer>,
14601        range: Range<text::Anchor>,
14602        _window: &mut Window,
14603        cx: &mut App,
14604    ) -> Task<Result<Vec<CodeAction>>> {
14605        self.update(cx, |project, cx| {
14606            project.code_actions(buffer, range, None, cx)
14607        })
14608    }
14609
14610    fn apply_code_action(
14611        &self,
14612        buffer_handle: Entity<Buffer>,
14613        action: CodeAction,
14614        _excerpt_id: ExcerptId,
14615        push_to_history: bool,
14616        _window: &mut Window,
14617        cx: &mut App,
14618    ) -> Task<Result<ProjectTransaction>> {
14619        self.update(cx, |project, cx| {
14620            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14621        })
14622    }
14623}
14624
14625fn snippet_completions(
14626    project: &Project,
14627    buffer: &Entity<Buffer>,
14628    buffer_position: text::Anchor,
14629    cx: &mut App,
14630) -> Task<Result<Vec<Completion>>> {
14631    let language = buffer.read(cx).language_at(buffer_position);
14632    let language_name = language.as_ref().map(|language| language.lsp_id());
14633    let snippet_store = project.snippets().read(cx);
14634    let snippets = snippet_store.snippets_for(language_name, cx);
14635
14636    if snippets.is_empty() {
14637        return Task::ready(Ok(vec![]));
14638    }
14639    let snapshot = buffer.read(cx).text_snapshot();
14640    let chars: String = snapshot
14641        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14642        .collect();
14643
14644    let scope = language.map(|language| language.default_scope());
14645    let executor = cx.background_executor().clone();
14646
14647    cx.background_executor().spawn(async move {
14648        let classifier = CharClassifier::new(scope).for_completion(true);
14649        let mut last_word = chars
14650            .chars()
14651            .take_while(|c| classifier.is_word(*c))
14652            .collect::<String>();
14653        last_word = last_word.chars().rev().collect();
14654
14655        if last_word.is_empty() {
14656            return Ok(vec![]);
14657        }
14658
14659        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14660        let to_lsp = |point: &text::Anchor| {
14661            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14662            point_to_lsp(end)
14663        };
14664        let lsp_end = to_lsp(&buffer_position);
14665
14666        let candidates = snippets
14667            .iter()
14668            .enumerate()
14669            .flat_map(|(ix, snippet)| {
14670                snippet
14671                    .prefix
14672                    .iter()
14673                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14674            })
14675            .collect::<Vec<StringMatchCandidate>>();
14676
14677        let mut matches = fuzzy::match_strings(
14678            &candidates,
14679            &last_word,
14680            last_word.chars().any(|c| c.is_uppercase()),
14681            100,
14682            &Default::default(),
14683            executor,
14684        )
14685        .await;
14686
14687        // Remove all candidates where the query's start does not match the start of any word in the candidate
14688        if let Some(query_start) = last_word.chars().next() {
14689            matches.retain(|string_match| {
14690                split_words(&string_match.string).any(|word| {
14691                    // Check that the first codepoint of the word as lowercase matches the first
14692                    // codepoint of the query as lowercase
14693                    word.chars()
14694                        .flat_map(|codepoint| codepoint.to_lowercase())
14695                        .zip(query_start.to_lowercase())
14696                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14697                })
14698            });
14699        }
14700
14701        let matched_strings = matches
14702            .into_iter()
14703            .map(|m| m.string)
14704            .collect::<HashSet<_>>();
14705
14706        let result: Vec<Completion> = snippets
14707            .into_iter()
14708            .filter_map(|snippet| {
14709                let matching_prefix = snippet
14710                    .prefix
14711                    .iter()
14712                    .find(|prefix| matched_strings.contains(*prefix))?;
14713                let start = as_offset - last_word.len();
14714                let start = snapshot.anchor_before(start);
14715                let range = start..buffer_position;
14716                let lsp_start = to_lsp(&start);
14717                let lsp_range = lsp::Range {
14718                    start: lsp_start,
14719                    end: lsp_end,
14720                };
14721                Some(Completion {
14722                    old_range: range,
14723                    new_text: snippet.body.clone(),
14724                    resolved: false,
14725                    label: CodeLabel {
14726                        text: matching_prefix.clone(),
14727                        runs: vec![],
14728                        filter_range: 0..matching_prefix.len(),
14729                    },
14730                    server_id: LanguageServerId(usize::MAX),
14731                    documentation: snippet
14732                        .description
14733                        .clone()
14734                        .map(CompletionDocumentation::SingleLine),
14735                    lsp_completion: lsp::CompletionItem {
14736                        label: snippet.prefix.first().unwrap().clone(),
14737                        kind: Some(CompletionItemKind::SNIPPET),
14738                        label_details: snippet.description.as_ref().map(|description| {
14739                            lsp::CompletionItemLabelDetails {
14740                                detail: Some(description.clone()),
14741                                description: None,
14742                            }
14743                        }),
14744                        insert_text_format: Some(InsertTextFormat::SNIPPET),
14745                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14746                            lsp::InsertReplaceEdit {
14747                                new_text: snippet.body.clone(),
14748                                insert: lsp_range,
14749                                replace: lsp_range,
14750                            },
14751                        )),
14752                        filter_text: Some(snippet.body.clone()),
14753                        sort_text: Some(char::MAX.to_string()),
14754                        ..Default::default()
14755                    },
14756                    confirm: None,
14757                })
14758            })
14759            .collect();
14760
14761        Ok(result)
14762    })
14763}
14764
14765impl CompletionProvider for Entity<Project> {
14766    fn completions(
14767        &self,
14768        buffer: &Entity<Buffer>,
14769        buffer_position: text::Anchor,
14770        options: CompletionContext,
14771        _window: &mut Window,
14772        cx: &mut Context<Editor>,
14773    ) -> Task<Result<Vec<Completion>>> {
14774        self.update(cx, |project, cx| {
14775            let snippets = snippet_completions(project, buffer, buffer_position, cx);
14776            let project_completions = project.completions(buffer, buffer_position, options, cx);
14777            cx.background_executor().spawn(async move {
14778                let mut completions = project_completions.await?;
14779                let snippets_completions = snippets.await?;
14780                completions.extend(snippets_completions);
14781                Ok(completions)
14782            })
14783        })
14784    }
14785
14786    fn resolve_completions(
14787        &self,
14788        buffer: Entity<Buffer>,
14789        completion_indices: Vec<usize>,
14790        completions: Rc<RefCell<Box<[Completion]>>>,
14791        cx: &mut Context<Editor>,
14792    ) -> Task<Result<bool>> {
14793        self.update(cx, |project, cx| {
14794            project.lsp_store().update(cx, |lsp_store, cx| {
14795                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
14796            })
14797        })
14798    }
14799
14800    fn apply_additional_edits_for_completion(
14801        &self,
14802        buffer: Entity<Buffer>,
14803        completions: Rc<RefCell<Box<[Completion]>>>,
14804        completion_index: usize,
14805        push_to_history: bool,
14806        cx: &mut Context<Editor>,
14807    ) -> Task<Result<Option<language::Transaction>>> {
14808        self.update(cx, |project, cx| {
14809            project.lsp_store().update(cx, |lsp_store, cx| {
14810                lsp_store.apply_additional_edits_for_completion(
14811                    buffer,
14812                    completions,
14813                    completion_index,
14814                    push_to_history,
14815                    cx,
14816                )
14817            })
14818        })
14819    }
14820
14821    fn is_completion_trigger(
14822        &self,
14823        buffer: &Entity<Buffer>,
14824        position: language::Anchor,
14825        text: &str,
14826        trigger_in_words: bool,
14827        cx: &mut Context<Editor>,
14828    ) -> bool {
14829        let mut chars = text.chars();
14830        let char = if let Some(char) = chars.next() {
14831            char
14832        } else {
14833            return false;
14834        };
14835        if chars.next().is_some() {
14836            return false;
14837        }
14838
14839        let buffer = buffer.read(cx);
14840        let snapshot = buffer.snapshot();
14841        if !snapshot.settings_at(position, cx).show_completions_on_input {
14842            return false;
14843        }
14844        let classifier = snapshot.char_classifier_at(position).for_completion(true);
14845        if trigger_in_words && classifier.is_word(char) {
14846            return true;
14847        }
14848
14849        buffer.completion_triggers().contains(text)
14850    }
14851}
14852
14853impl SemanticsProvider for Entity<Project> {
14854    fn hover(
14855        &self,
14856        buffer: &Entity<Buffer>,
14857        position: text::Anchor,
14858        cx: &mut App,
14859    ) -> Option<Task<Vec<project::Hover>>> {
14860        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14861    }
14862
14863    fn document_highlights(
14864        &self,
14865        buffer: &Entity<Buffer>,
14866        position: text::Anchor,
14867        cx: &mut App,
14868    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14869        Some(self.update(cx, |project, cx| {
14870            project.document_highlights(buffer, position, cx)
14871        }))
14872    }
14873
14874    fn definitions(
14875        &self,
14876        buffer: &Entity<Buffer>,
14877        position: text::Anchor,
14878        kind: GotoDefinitionKind,
14879        cx: &mut App,
14880    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14881        Some(self.update(cx, |project, cx| match kind {
14882            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14883            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14884            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14885            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14886        }))
14887    }
14888
14889    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
14890        // TODO: make this work for remote projects
14891        self.read(cx)
14892            .language_servers_for_local_buffer(buffer.read(cx), cx)
14893            .any(
14894                |(_, server)| match server.capabilities().inlay_hint_provider {
14895                    Some(lsp::OneOf::Left(enabled)) => enabled,
14896                    Some(lsp::OneOf::Right(_)) => true,
14897                    None => false,
14898                },
14899            )
14900    }
14901
14902    fn inlay_hints(
14903        &self,
14904        buffer_handle: Entity<Buffer>,
14905        range: Range<text::Anchor>,
14906        cx: &mut App,
14907    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14908        Some(self.update(cx, |project, cx| {
14909            project.inlay_hints(buffer_handle, range, cx)
14910        }))
14911    }
14912
14913    fn resolve_inlay_hint(
14914        &self,
14915        hint: InlayHint,
14916        buffer_handle: Entity<Buffer>,
14917        server_id: LanguageServerId,
14918        cx: &mut App,
14919    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14920        Some(self.update(cx, |project, cx| {
14921            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14922        }))
14923    }
14924
14925    fn range_for_rename(
14926        &self,
14927        buffer: &Entity<Buffer>,
14928        position: text::Anchor,
14929        cx: &mut App,
14930    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14931        Some(self.update(cx, |project, cx| {
14932            let buffer = buffer.clone();
14933            let task = project.prepare_rename(buffer.clone(), position, cx);
14934            cx.spawn(|_, mut cx| async move {
14935                Ok(match task.await? {
14936                    PrepareRenameResponse::Success(range) => Some(range),
14937                    PrepareRenameResponse::InvalidPosition => None,
14938                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14939                        // Fallback on using TreeSitter info to determine identifier range
14940                        buffer.update(&mut cx, |buffer, _| {
14941                            let snapshot = buffer.snapshot();
14942                            let (range, kind) = snapshot.surrounding_word(position);
14943                            if kind != Some(CharKind::Word) {
14944                                return None;
14945                            }
14946                            Some(
14947                                snapshot.anchor_before(range.start)
14948                                    ..snapshot.anchor_after(range.end),
14949                            )
14950                        })?
14951                    }
14952                })
14953            })
14954        }))
14955    }
14956
14957    fn perform_rename(
14958        &self,
14959        buffer: &Entity<Buffer>,
14960        position: text::Anchor,
14961        new_name: String,
14962        cx: &mut App,
14963    ) -> Option<Task<Result<ProjectTransaction>>> {
14964        Some(self.update(cx, |project, cx| {
14965            project.perform_rename(buffer.clone(), position, new_name, cx)
14966        }))
14967    }
14968}
14969
14970fn inlay_hint_settings(
14971    location: Anchor,
14972    snapshot: &MultiBufferSnapshot,
14973    cx: &mut Context<Editor>,
14974) -> InlayHintSettings {
14975    let file = snapshot.file_at(location);
14976    let language = snapshot.language_at(location).map(|l| l.name());
14977    language_settings(language, file, cx).inlay_hints
14978}
14979
14980fn consume_contiguous_rows(
14981    contiguous_row_selections: &mut Vec<Selection<Point>>,
14982    selection: &Selection<Point>,
14983    display_map: &DisplaySnapshot,
14984    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14985) -> (MultiBufferRow, MultiBufferRow) {
14986    contiguous_row_selections.push(selection.clone());
14987    let start_row = MultiBufferRow(selection.start.row);
14988    let mut end_row = ending_row(selection, display_map);
14989
14990    while let Some(next_selection) = selections.peek() {
14991        if next_selection.start.row <= end_row.0 {
14992            end_row = ending_row(next_selection, display_map);
14993            contiguous_row_selections.push(selections.next().unwrap().clone());
14994        } else {
14995            break;
14996        }
14997    }
14998    (start_row, end_row)
14999}
15000
15001fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15002    if next_selection.end.column > 0 || next_selection.is_empty() {
15003        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15004    } else {
15005        MultiBufferRow(next_selection.end.row)
15006    }
15007}
15008
15009impl EditorSnapshot {
15010    pub fn remote_selections_in_range<'a>(
15011        &'a self,
15012        range: &'a Range<Anchor>,
15013        collaboration_hub: &dyn CollaborationHub,
15014        cx: &'a App,
15015    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15016        let participant_names = collaboration_hub.user_names(cx);
15017        let participant_indices = collaboration_hub.user_participant_indices(cx);
15018        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15019        let collaborators_by_replica_id = collaborators_by_peer_id
15020            .iter()
15021            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15022            .collect::<HashMap<_, _>>();
15023        self.buffer_snapshot
15024            .selections_in_range(range, false)
15025            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15026                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15027                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15028                let user_name = participant_names.get(&collaborator.user_id).cloned();
15029                Some(RemoteSelection {
15030                    replica_id,
15031                    selection,
15032                    cursor_shape,
15033                    line_mode,
15034                    participant_index,
15035                    peer_id: collaborator.peer_id,
15036                    user_name,
15037                })
15038            })
15039    }
15040
15041    pub fn hunks_for_ranges(
15042        &self,
15043        ranges: impl Iterator<Item = Range<Point>>,
15044    ) -> Vec<MultiBufferDiffHunk> {
15045        let mut hunks = Vec::new();
15046        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15047            HashMap::default();
15048        for query_range in ranges {
15049            let query_rows =
15050                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15051            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15052                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15053            ) {
15054                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15055                // when the caret is just above or just below the deleted hunk.
15056                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15057                let related_to_selection = if allow_adjacent {
15058                    hunk.row_range.overlaps(&query_rows)
15059                        || hunk.row_range.start == query_rows.end
15060                        || hunk.row_range.end == query_rows.start
15061                } else {
15062                    hunk.row_range.overlaps(&query_rows)
15063                };
15064                if related_to_selection {
15065                    if !processed_buffer_rows
15066                        .entry(hunk.buffer_id)
15067                        .or_default()
15068                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15069                    {
15070                        continue;
15071                    }
15072                    hunks.push(hunk);
15073                }
15074            }
15075        }
15076
15077        hunks
15078    }
15079
15080    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15081        self.display_snapshot.buffer_snapshot.language_at(position)
15082    }
15083
15084    pub fn is_focused(&self) -> bool {
15085        self.is_focused
15086    }
15087
15088    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15089        self.placeholder_text.as_ref()
15090    }
15091
15092    pub fn scroll_position(&self) -> gpui::Point<f32> {
15093        self.scroll_anchor.scroll_position(&self.display_snapshot)
15094    }
15095
15096    fn gutter_dimensions(
15097        &self,
15098        font_id: FontId,
15099        font_size: Pixels,
15100        max_line_number_width: Pixels,
15101        cx: &App,
15102    ) -> Option<GutterDimensions> {
15103        if !self.show_gutter {
15104            return None;
15105        }
15106
15107        let descent = cx.text_system().descent(font_id, font_size);
15108        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15109        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15110
15111        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15112            matches!(
15113                ProjectSettings::get_global(cx).git.git_gutter,
15114                Some(GitGutterSetting::TrackedFiles)
15115            )
15116        });
15117        let gutter_settings = EditorSettings::get_global(cx).gutter;
15118        let show_line_numbers = self
15119            .show_line_numbers
15120            .unwrap_or(gutter_settings.line_numbers);
15121        let line_gutter_width = if show_line_numbers {
15122            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15123            let min_width_for_number_on_gutter = em_advance * 4.0;
15124            max_line_number_width.max(min_width_for_number_on_gutter)
15125        } else {
15126            0.0.into()
15127        };
15128
15129        let show_code_actions = self
15130            .show_code_actions
15131            .unwrap_or(gutter_settings.code_actions);
15132
15133        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15134
15135        let git_blame_entries_width =
15136            self.git_blame_gutter_max_author_length
15137                .map(|max_author_length| {
15138                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15139
15140                    /// The number of characters to dedicate to gaps and margins.
15141                    const SPACING_WIDTH: usize = 4;
15142
15143                    let max_char_count = max_author_length
15144                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15145                        + ::git::SHORT_SHA_LENGTH
15146                        + MAX_RELATIVE_TIMESTAMP.len()
15147                        + SPACING_WIDTH;
15148
15149                    em_advance * max_char_count
15150                });
15151
15152        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15153        left_padding += if show_code_actions || show_runnables {
15154            em_width * 3.0
15155        } else if show_git_gutter && show_line_numbers {
15156            em_width * 2.0
15157        } else if show_git_gutter || show_line_numbers {
15158            em_width
15159        } else {
15160            px(0.)
15161        };
15162
15163        let right_padding = if gutter_settings.folds && show_line_numbers {
15164            em_width * 4.0
15165        } else if gutter_settings.folds {
15166            em_width * 3.0
15167        } else if show_line_numbers {
15168            em_width
15169        } else {
15170            px(0.)
15171        };
15172
15173        Some(GutterDimensions {
15174            left_padding,
15175            right_padding,
15176            width: line_gutter_width + left_padding + right_padding,
15177            margin: -descent,
15178            git_blame_entries_width,
15179        })
15180    }
15181
15182    pub fn render_crease_toggle(
15183        &self,
15184        buffer_row: MultiBufferRow,
15185        row_contains_cursor: bool,
15186        editor: Entity<Editor>,
15187        window: &mut Window,
15188        cx: &mut App,
15189    ) -> Option<AnyElement> {
15190        let folded = self.is_line_folded(buffer_row);
15191        let mut is_foldable = false;
15192
15193        if let Some(crease) = self
15194            .crease_snapshot
15195            .query_row(buffer_row, &self.buffer_snapshot)
15196        {
15197            is_foldable = true;
15198            match crease {
15199                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15200                    if let Some(render_toggle) = render_toggle {
15201                        let toggle_callback =
15202                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15203                                if folded {
15204                                    editor.update(cx, |editor, cx| {
15205                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15206                                    });
15207                                } else {
15208                                    editor.update(cx, |editor, cx| {
15209                                        editor.unfold_at(
15210                                            &crate::UnfoldAt { buffer_row },
15211                                            window,
15212                                            cx,
15213                                        )
15214                                    });
15215                                }
15216                            });
15217                        return Some((render_toggle)(
15218                            buffer_row,
15219                            folded,
15220                            toggle_callback,
15221                            window,
15222                            cx,
15223                        ));
15224                    }
15225                }
15226            }
15227        }
15228
15229        is_foldable |= self.starts_indent(buffer_row);
15230
15231        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15232            Some(
15233                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15234                    .toggle_state(folded)
15235                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15236                        if folded {
15237                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15238                        } else {
15239                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15240                        }
15241                    }))
15242                    .into_any_element(),
15243            )
15244        } else {
15245            None
15246        }
15247    }
15248
15249    pub fn render_crease_trailer(
15250        &self,
15251        buffer_row: MultiBufferRow,
15252        window: &mut Window,
15253        cx: &mut App,
15254    ) -> Option<AnyElement> {
15255        let folded = self.is_line_folded(buffer_row);
15256        if let Crease::Inline { render_trailer, .. } = self
15257            .crease_snapshot
15258            .query_row(buffer_row, &self.buffer_snapshot)?
15259        {
15260            let render_trailer = render_trailer.as_ref()?;
15261            Some(render_trailer(buffer_row, folded, window, cx))
15262        } else {
15263            None
15264        }
15265    }
15266}
15267
15268impl Deref for EditorSnapshot {
15269    type Target = DisplaySnapshot;
15270
15271    fn deref(&self) -> &Self::Target {
15272        &self.display_snapshot
15273    }
15274}
15275
15276#[derive(Clone, Debug, PartialEq, Eq)]
15277pub enum EditorEvent {
15278    InputIgnored {
15279        text: Arc<str>,
15280    },
15281    InputHandled {
15282        utf16_range_to_replace: Option<Range<isize>>,
15283        text: Arc<str>,
15284    },
15285    ExcerptsAdded {
15286        buffer: Entity<Buffer>,
15287        predecessor: ExcerptId,
15288        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15289    },
15290    ExcerptsRemoved {
15291        ids: Vec<ExcerptId>,
15292    },
15293    BufferFoldToggled {
15294        ids: Vec<ExcerptId>,
15295        folded: bool,
15296    },
15297    ExcerptsEdited {
15298        ids: Vec<ExcerptId>,
15299    },
15300    ExcerptsExpanded {
15301        ids: Vec<ExcerptId>,
15302    },
15303    BufferEdited,
15304    Edited {
15305        transaction_id: clock::Lamport,
15306    },
15307    Reparsed(BufferId),
15308    Focused,
15309    FocusedIn,
15310    Blurred,
15311    DirtyChanged,
15312    Saved,
15313    TitleChanged,
15314    DiffBaseChanged,
15315    SelectionsChanged {
15316        local: bool,
15317    },
15318    ScrollPositionChanged {
15319        local: bool,
15320        autoscroll: bool,
15321    },
15322    Closed,
15323    TransactionUndone {
15324        transaction_id: clock::Lamport,
15325    },
15326    TransactionBegun {
15327        transaction_id: clock::Lamport,
15328    },
15329    Reloaded,
15330    CursorShapeChanged,
15331}
15332
15333impl EventEmitter<EditorEvent> for Editor {}
15334
15335impl Focusable for Editor {
15336    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15337        self.focus_handle.clone()
15338    }
15339}
15340
15341impl Render for Editor {
15342    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15343        let settings = ThemeSettings::get_global(cx);
15344
15345        let mut text_style = match self.mode {
15346            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15347                color: cx.theme().colors().editor_foreground,
15348                font_family: settings.ui_font.family.clone(),
15349                font_features: settings.ui_font.features.clone(),
15350                font_fallbacks: settings.ui_font.fallbacks.clone(),
15351                font_size: rems(0.875).into(),
15352                font_weight: settings.ui_font.weight,
15353                line_height: relative(settings.buffer_line_height.value()),
15354                ..Default::default()
15355            },
15356            EditorMode::Full => TextStyle {
15357                color: cx.theme().colors().editor_foreground,
15358                font_family: settings.buffer_font.family.clone(),
15359                font_features: settings.buffer_font.features.clone(),
15360                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15361                font_size: settings.buffer_font_size().into(),
15362                font_weight: settings.buffer_font.weight,
15363                line_height: relative(settings.buffer_line_height.value()),
15364                ..Default::default()
15365            },
15366        };
15367        if let Some(text_style_refinement) = &self.text_style_refinement {
15368            text_style.refine(text_style_refinement)
15369        }
15370
15371        let background = match self.mode {
15372            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15373            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15374            EditorMode::Full => cx.theme().colors().editor_background,
15375        };
15376
15377        EditorElement::new(
15378            &cx.entity(),
15379            EditorStyle {
15380                background,
15381                local_player: cx.theme().players().local(),
15382                text: text_style,
15383                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15384                syntax: cx.theme().syntax().clone(),
15385                status: cx.theme().status().clone(),
15386                inlay_hints_style: make_inlay_hints_style(cx),
15387                inline_completion_styles: make_suggestion_styles(cx),
15388                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15389            },
15390        )
15391    }
15392}
15393
15394impl EntityInputHandler for Editor {
15395    fn text_for_range(
15396        &mut self,
15397        range_utf16: Range<usize>,
15398        adjusted_range: &mut Option<Range<usize>>,
15399        _: &mut Window,
15400        cx: &mut Context<Self>,
15401    ) -> Option<String> {
15402        let snapshot = self.buffer.read(cx).read(cx);
15403        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15404        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15405        if (start.0..end.0) != range_utf16 {
15406            adjusted_range.replace(start.0..end.0);
15407        }
15408        Some(snapshot.text_for_range(start..end).collect())
15409    }
15410
15411    fn selected_text_range(
15412        &mut self,
15413        ignore_disabled_input: bool,
15414        _: &mut Window,
15415        cx: &mut Context<Self>,
15416    ) -> Option<UTF16Selection> {
15417        // Prevent the IME menu from appearing when holding down an alphabetic key
15418        // while input is disabled.
15419        if !ignore_disabled_input && !self.input_enabled {
15420            return None;
15421        }
15422
15423        let selection = self.selections.newest::<OffsetUtf16>(cx);
15424        let range = selection.range();
15425
15426        Some(UTF16Selection {
15427            range: range.start.0..range.end.0,
15428            reversed: selection.reversed,
15429        })
15430    }
15431
15432    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15433        let snapshot = self.buffer.read(cx).read(cx);
15434        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15435        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15436    }
15437
15438    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15439        self.clear_highlights::<InputComposition>(cx);
15440        self.ime_transaction.take();
15441    }
15442
15443    fn replace_text_in_range(
15444        &mut self,
15445        range_utf16: Option<Range<usize>>,
15446        text: &str,
15447        window: &mut Window,
15448        cx: &mut Context<Self>,
15449    ) {
15450        if !self.input_enabled {
15451            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15452            return;
15453        }
15454
15455        self.transact(window, cx, |this, window, cx| {
15456            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15457                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15458                Some(this.selection_replacement_ranges(range_utf16, cx))
15459            } else {
15460                this.marked_text_ranges(cx)
15461            };
15462
15463            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15464                let newest_selection_id = this.selections.newest_anchor().id;
15465                this.selections
15466                    .all::<OffsetUtf16>(cx)
15467                    .iter()
15468                    .zip(ranges_to_replace.iter())
15469                    .find_map(|(selection, range)| {
15470                        if selection.id == newest_selection_id {
15471                            Some(
15472                                (range.start.0 as isize - selection.head().0 as isize)
15473                                    ..(range.end.0 as isize - selection.head().0 as isize),
15474                            )
15475                        } else {
15476                            None
15477                        }
15478                    })
15479            });
15480
15481            cx.emit(EditorEvent::InputHandled {
15482                utf16_range_to_replace: range_to_replace,
15483                text: text.into(),
15484            });
15485
15486            if let Some(new_selected_ranges) = new_selected_ranges {
15487                this.change_selections(None, window, cx, |selections| {
15488                    selections.select_ranges(new_selected_ranges)
15489                });
15490                this.backspace(&Default::default(), window, cx);
15491            }
15492
15493            this.handle_input(text, window, cx);
15494        });
15495
15496        if let Some(transaction) = self.ime_transaction {
15497            self.buffer.update(cx, |buffer, cx| {
15498                buffer.group_until_transaction(transaction, cx);
15499            });
15500        }
15501
15502        self.unmark_text(window, cx);
15503    }
15504
15505    fn replace_and_mark_text_in_range(
15506        &mut self,
15507        range_utf16: Option<Range<usize>>,
15508        text: &str,
15509        new_selected_range_utf16: Option<Range<usize>>,
15510        window: &mut Window,
15511        cx: &mut Context<Self>,
15512    ) {
15513        if !self.input_enabled {
15514            return;
15515        }
15516
15517        let transaction = self.transact(window, cx, |this, window, cx| {
15518            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15519                let snapshot = this.buffer.read(cx).read(cx);
15520                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15521                    for marked_range in &mut marked_ranges {
15522                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15523                        marked_range.start.0 += relative_range_utf16.start;
15524                        marked_range.start =
15525                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15526                        marked_range.end =
15527                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15528                    }
15529                }
15530                Some(marked_ranges)
15531            } else if let Some(range_utf16) = range_utf16 {
15532                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15533                Some(this.selection_replacement_ranges(range_utf16, cx))
15534            } else {
15535                None
15536            };
15537
15538            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15539                let newest_selection_id = this.selections.newest_anchor().id;
15540                this.selections
15541                    .all::<OffsetUtf16>(cx)
15542                    .iter()
15543                    .zip(ranges_to_replace.iter())
15544                    .find_map(|(selection, range)| {
15545                        if selection.id == newest_selection_id {
15546                            Some(
15547                                (range.start.0 as isize - selection.head().0 as isize)
15548                                    ..(range.end.0 as isize - selection.head().0 as isize),
15549                            )
15550                        } else {
15551                            None
15552                        }
15553                    })
15554            });
15555
15556            cx.emit(EditorEvent::InputHandled {
15557                utf16_range_to_replace: range_to_replace,
15558                text: text.into(),
15559            });
15560
15561            if let Some(ranges) = ranges_to_replace {
15562                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15563            }
15564
15565            let marked_ranges = {
15566                let snapshot = this.buffer.read(cx).read(cx);
15567                this.selections
15568                    .disjoint_anchors()
15569                    .iter()
15570                    .map(|selection| {
15571                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15572                    })
15573                    .collect::<Vec<_>>()
15574            };
15575
15576            if text.is_empty() {
15577                this.unmark_text(window, cx);
15578            } else {
15579                this.highlight_text::<InputComposition>(
15580                    marked_ranges.clone(),
15581                    HighlightStyle {
15582                        underline: Some(UnderlineStyle {
15583                            thickness: px(1.),
15584                            color: None,
15585                            wavy: false,
15586                        }),
15587                        ..Default::default()
15588                    },
15589                    cx,
15590                );
15591            }
15592
15593            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15594            let use_autoclose = this.use_autoclose;
15595            let use_auto_surround = this.use_auto_surround;
15596            this.set_use_autoclose(false);
15597            this.set_use_auto_surround(false);
15598            this.handle_input(text, window, cx);
15599            this.set_use_autoclose(use_autoclose);
15600            this.set_use_auto_surround(use_auto_surround);
15601
15602            if let Some(new_selected_range) = new_selected_range_utf16 {
15603                let snapshot = this.buffer.read(cx).read(cx);
15604                let new_selected_ranges = marked_ranges
15605                    .into_iter()
15606                    .map(|marked_range| {
15607                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15608                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15609                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15610                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15611                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15612                    })
15613                    .collect::<Vec<_>>();
15614
15615                drop(snapshot);
15616                this.change_selections(None, window, cx, |selections| {
15617                    selections.select_ranges(new_selected_ranges)
15618                });
15619            }
15620        });
15621
15622        self.ime_transaction = self.ime_transaction.or(transaction);
15623        if let Some(transaction) = self.ime_transaction {
15624            self.buffer.update(cx, |buffer, cx| {
15625                buffer.group_until_transaction(transaction, cx);
15626            });
15627        }
15628
15629        if self.text_highlights::<InputComposition>(cx).is_none() {
15630            self.ime_transaction.take();
15631        }
15632    }
15633
15634    fn bounds_for_range(
15635        &mut self,
15636        range_utf16: Range<usize>,
15637        element_bounds: gpui::Bounds<Pixels>,
15638        window: &mut Window,
15639        cx: &mut Context<Self>,
15640    ) -> Option<gpui::Bounds<Pixels>> {
15641        let text_layout_details = self.text_layout_details(window);
15642        let gpui::Point {
15643            x: em_width,
15644            y: line_height,
15645        } = self.character_size(window);
15646
15647        let snapshot = self.snapshot(window, cx);
15648        let scroll_position = snapshot.scroll_position();
15649        let scroll_left = scroll_position.x * em_width;
15650
15651        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15652        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15653            + self.gutter_dimensions.width
15654            + self.gutter_dimensions.margin;
15655        let y = line_height * (start.row().as_f32() - scroll_position.y);
15656
15657        Some(Bounds {
15658            origin: element_bounds.origin + point(x, y),
15659            size: size(em_width, line_height),
15660        })
15661    }
15662}
15663
15664trait SelectionExt {
15665    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15666    fn spanned_rows(
15667        &self,
15668        include_end_if_at_line_start: bool,
15669        map: &DisplaySnapshot,
15670    ) -> Range<MultiBufferRow>;
15671}
15672
15673impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15674    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15675        let start = self
15676            .start
15677            .to_point(&map.buffer_snapshot)
15678            .to_display_point(map);
15679        let end = self
15680            .end
15681            .to_point(&map.buffer_snapshot)
15682            .to_display_point(map);
15683        if self.reversed {
15684            end..start
15685        } else {
15686            start..end
15687        }
15688    }
15689
15690    fn spanned_rows(
15691        &self,
15692        include_end_if_at_line_start: bool,
15693        map: &DisplaySnapshot,
15694    ) -> Range<MultiBufferRow> {
15695        let start = self.start.to_point(&map.buffer_snapshot);
15696        let mut end = self.end.to_point(&map.buffer_snapshot);
15697        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15698            end.row -= 1;
15699        }
15700
15701        let buffer_start = map.prev_line_boundary(start).0;
15702        let buffer_end = map.next_line_boundary(end).0;
15703        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15704    }
15705}
15706
15707impl<T: InvalidationRegion> InvalidationStack<T> {
15708    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15709    where
15710        S: Clone + ToOffset,
15711    {
15712        while let Some(region) = self.last() {
15713            let all_selections_inside_invalidation_ranges =
15714                if selections.len() == region.ranges().len() {
15715                    selections
15716                        .iter()
15717                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15718                        .all(|(selection, invalidation_range)| {
15719                            let head = selection.head().to_offset(buffer);
15720                            invalidation_range.start <= head && invalidation_range.end >= head
15721                        })
15722                } else {
15723                    false
15724                };
15725
15726            if all_selections_inside_invalidation_ranges {
15727                break;
15728            } else {
15729                self.pop();
15730            }
15731        }
15732    }
15733}
15734
15735impl<T> Default for InvalidationStack<T> {
15736    fn default() -> Self {
15737        Self(Default::default())
15738    }
15739}
15740
15741impl<T> Deref for InvalidationStack<T> {
15742    type Target = Vec<T>;
15743
15744    fn deref(&self) -> &Self::Target {
15745        &self.0
15746    }
15747}
15748
15749impl<T> DerefMut for InvalidationStack<T> {
15750    fn deref_mut(&mut self) -> &mut Self::Target {
15751        &mut self.0
15752    }
15753}
15754
15755impl InvalidationRegion for SnippetState {
15756    fn ranges(&self) -> &[Range<Anchor>] {
15757        &self.ranges[self.active_index]
15758    }
15759}
15760
15761pub fn diagnostic_block_renderer(
15762    diagnostic: Diagnostic,
15763    max_message_rows: Option<u8>,
15764    allow_closing: bool,
15765    _is_valid: bool,
15766) -> RenderBlock {
15767    let (text_without_backticks, code_ranges) =
15768        highlight_diagnostic_message(&diagnostic, max_message_rows);
15769
15770    Arc::new(move |cx: &mut BlockContext| {
15771        let group_id: SharedString = cx.block_id.to_string().into();
15772
15773        let mut text_style = cx.window.text_style().clone();
15774        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15775        let theme_settings = ThemeSettings::get_global(cx);
15776        text_style.font_family = theme_settings.buffer_font.family.clone();
15777        text_style.font_style = theme_settings.buffer_font.style;
15778        text_style.font_features = theme_settings.buffer_font.features.clone();
15779        text_style.font_weight = theme_settings.buffer_font.weight;
15780
15781        let multi_line_diagnostic = diagnostic.message.contains('\n');
15782
15783        let buttons = |diagnostic: &Diagnostic| {
15784            if multi_line_diagnostic {
15785                v_flex()
15786            } else {
15787                h_flex()
15788            }
15789            .when(allow_closing, |div| {
15790                div.children(diagnostic.is_primary.then(|| {
15791                    IconButton::new("close-block", IconName::XCircle)
15792                        .icon_color(Color::Muted)
15793                        .size(ButtonSize::Compact)
15794                        .style(ButtonStyle::Transparent)
15795                        .visible_on_hover(group_id.clone())
15796                        .on_click(move |_click, window, cx| {
15797                            window.dispatch_action(Box::new(Cancel), cx)
15798                        })
15799                        .tooltip(|window, cx| {
15800                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
15801                        })
15802                }))
15803            })
15804            .child(
15805                IconButton::new("copy-block", IconName::Copy)
15806                    .icon_color(Color::Muted)
15807                    .size(ButtonSize::Compact)
15808                    .style(ButtonStyle::Transparent)
15809                    .visible_on_hover(group_id.clone())
15810                    .on_click({
15811                        let message = diagnostic.message.clone();
15812                        move |_click, _, cx| {
15813                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15814                        }
15815                    })
15816                    .tooltip(Tooltip::text("Copy diagnostic message")),
15817            )
15818        };
15819
15820        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
15821            AvailableSpace::min_size(),
15822            cx.window,
15823            cx.app,
15824        );
15825
15826        h_flex()
15827            .id(cx.block_id)
15828            .group(group_id.clone())
15829            .relative()
15830            .size_full()
15831            .block_mouse_down()
15832            .pl(cx.gutter_dimensions.width)
15833            .w(cx.max_width - cx.gutter_dimensions.full_width())
15834            .child(
15835                div()
15836                    .flex()
15837                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15838                    .flex_shrink(),
15839            )
15840            .child(buttons(&diagnostic))
15841            .child(div().flex().flex_shrink_0().child(
15842                StyledText::new(text_without_backticks.clone()).with_highlights(
15843                    &text_style,
15844                    code_ranges.iter().map(|range| {
15845                        (
15846                            range.clone(),
15847                            HighlightStyle {
15848                                font_weight: Some(FontWeight::BOLD),
15849                                ..Default::default()
15850                            },
15851                        )
15852                    }),
15853                ),
15854            ))
15855            .into_any_element()
15856    })
15857}
15858
15859fn inline_completion_edit_text(
15860    current_snapshot: &BufferSnapshot,
15861    edits: &[(Range<Anchor>, String)],
15862    edit_preview: &EditPreview,
15863    include_deletions: bool,
15864    cx: &App,
15865) -> Option<HighlightedText> {
15866    let edits = edits
15867        .iter()
15868        .map(|(anchor, text)| {
15869            (
15870                anchor.start.text_anchor..anchor.end.text_anchor,
15871                text.clone(),
15872            )
15873        })
15874        .collect::<Vec<_>>();
15875
15876    Some(edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx))
15877}
15878
15879pub fn highlight_diagnostic_message(
15880    diagnostic: &Diagnostic,
15881    mut max_message_rows: Option<u8>,
15882) -> (SharedString, Vec<Range<usize>>) {
15883    let mut text_without_backticks = String::new();
15884    let mut code_ranges = Vec::new();
15885
15886    if let Some(source) = &diagnostic.source {
15887        text_without_backticks.push_str(source);
15888        code_ranges.push(0..source.len());
15889        text_without_backticks.push_str(": ");
15890    }
15891
15892    let mut prev_offset = 0;
15893    let mut in_code_block = false;
15894    let has_row_limit = max_message_rows.is_some();
15895    let mut newline_indices = diagnostic
15896        .message
15897        .match_indices('\n')
15898        .filter(|_| has_row_limit)
15899        .map(|(ix, _)| ix)
15900        .fuse()
15901        .peekable();
15902
15903    for (quote_ix, _) in diagnostic
15904        .message
15905        .match_indices('`')
15906        .chain([(diagnostic.message.len(), "")])
15907    {
15908        let mut first_newline_ix = None;
15909        let mut last_newline_ix = None;
15910        while let Some(newline_ix) = newline_indices.peek() {
15911            if *newline_ix < quote_ix {
15912                if first_newline_ix.is_none() {
15913                    first_newline_ix = Some(*newline_ix);
15914                }
15915                last_newline_ix = Some(*newline_ix);
15916
15917                if let Some(rows_left) = &mut max_message_rows {
15918                    if *rows_left == 0 {
15919                        break;
15920                    } else {
15921                        *rows_left -= 1;
15922                    }
15923                }
15924                let _ = newline_indices.next();
15925            } else {
15926                break;
15927            }
15928        }
15929        let prev_len = text_without_backticks.len();
15930        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15931        text_without_backticks.push_str(new_text);
15932        if in_code_block {
15933            code_ranges.push(prev_len..text_without_backticks.len());
15934        }
15935        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15936        in_code_block = !in_code_block;
15937        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15938            text_without_backticks.push_str("...");
15939            break;
15940        }
15941    }
15942
15943    (text_without_backticks.into(), code_ranges)
15944}
15945
15946fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15947    match severity {
15948        DiagnosticSeverity::ERROR => colors.error,
15949        DiagnosticSeverity::WARNING => colors.warning,
15950        DiagnosticSeverity::INFORMATION => colors.info,
15951        DiagnosticSeverity::HINT => colors.info,
15952        _ => colors.ignored,
15953    }
15954}
15955
15956pub fn styled_runs_for_code_label<'a>(
15957    label: &'a CodeLabel,
15958    syntax_theme: &'a theme::SyntaxTheme,
15959) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15960    let fade_out = HighlightStyle {
15961        fade_out: Some(0.35),
15962        ..Default::default()
15963    };
15964
15965    let mut prev_end = label.filter_range.end;
15966    label
15967        .runs
15968        .iter()
15969        .enumerate()
15970        .flat_map(move |(ix, (range, highlight_id))| {
15971            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15972                style
15973            } else {
15974                return Default::default();
15975            };
15976            let mut muted_style = style;
15977            muted_style.highlight(fade_out);
15978
15979            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15980            if range.start >= label.filter_range.end {
15981                if range.start > prev_end {
15982                    runs.push((prev_end..range.start, fade_out));
15983                }
15984                runs.push((range.clone(), muted_style));
15985            } else if range.end <= label.filter_range.end {
15986                runs.push((range.clone(), style));
15987            } else {
15988                runs.push((range.start..label.filter_range.end, style));
15989                runs.push((label.filter_range.end..range.end, muted_style));
15990            }
15991            prev_end = cmp::max(prev_end, range.end);
15992
15993            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15994                runs.push((prev_end..label.text.len(), fade_out));
15995            }
15996
15997            runs
15998        })
15999}
16000
16001pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16002    let mut prev_index = 0;
16003    let mut prev_codepoint: Option<char> = None;
16004    text.char_indices()
16005        .chain([(text.len(), '\0')])
16006        .filter_map(move |(index, codepoint)| {
16007            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16008            let is_boundary = index == text.len()
16009                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16010                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16011            if is_boundary {
16012                let chunk = &text[prev_index..index];
16013                prev_index = index;
16014                Some(chunk)
16015            } else {
16016                None
16017            }
16018        })
16019}
16020
16021pub trait RangeToAnchorExt: Sized {
16022    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16023
16024    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16025        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16026        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16027    }
16028}
16029
16030impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16031    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16032        let start_offset = self.start.to_offset(snapshot);
16033        let end_offset = self.end.to_offset(snapshot);
16034        if start_offset == end_offset {
16035            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16036        } else {
16037            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16038        }
16039    }
16040}
16041
16042pub trait RowExt {
16043    fn as_f32(&self) -> f32;
16044
16045    fn next_row(&self) -> Self;
16046
16047    fn previous_row(&self) -> Self;
16048
16049    fn minus(&self, other: Self) -> u32;
16050}
16051
16052impl RowExt for DisplayRow {
16053    fn as_f32(&self) -> f32 {
16054        self.0 as f32
16055    }
16056
16057    fn next_row(&self) -> Self {
16058        Self(self.0 + 1)
16059    }
16060
16061    fn previous_row(&self) -> Self {
16062        Self(self.0.saturating_sub(1))
16063    }
16064
16065    fn minus(&self, other: Self) -> u32 {
16066        self.0 - other.0
16067    }
16068}
16069
16070impl RowExt for MultiBufferRow {
16071    fn as_f32(&self) -> f32 {
16072        self.0 as f32
16073    }
16074
16075    fn next_row(&self) -> Self {
16076        Self(self.0 + 1)
16077    }
16078
16079    fn previous_row(&self) -> Self {
16080        Self(self.0.saturating_sub(1))
16081    }
16082
16083    fn minus(&self, other: Self) -> u32 {
16084        self.0 - other.0
16085    }
16086}
16087
16088trait RowRangeExt {
16089    type Row;
16090
16091    fn len(&self) -> usize;
16092
16093    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16094}
16095
16096impl RowRangeExt for Range<MultiBufferRow> {
16097    type Row = MultiBufferRow;
16098
16099    fn len(&self) -> usize {
16100        (self.end.0 - self.start.0) as usize
16101    }
16102
16103    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16104        (self.start.0..self.end.0).map(MultiBufferRow)
16105    }
16106}
16107
16108impl RowRangeExt for Range<DisplayRow> {
16109    type Row = DisplayRow;
16110
16111    fn len(&self) -> usize {
16112        (self.end.0 - self.start.0) as usize
16113    }
16114
16115    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16116        (self.start.0..self.end.0).map(DisplayRow)
16117    }
16118}
16119
16120/// If select range has more than one line, we
16121/// just point the cursor to range.start.
16122fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16123    if range.start.row == range.end.row {
16124        range
16125    } else {
16126        range.start..range.start
16127    }
16128}
16129pub struct KillRing(ClipboardItem);
16130impl Global for KillRing {}
16131
16132const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16133
16134fn all_edits_insertions_or_deletions(
16135    edits: &Vec<(Range<Anchor>, String)>,
16136    snapshot: &MultiBufferSnapshot,
16137) -> bool {
16138    let mut all_insertions = true;
16139    let mut all_deletions = true;
16140
16141    for (range, new_text) in edits.iter() {
16142        let range_is_empty = range.to_offset(&snapshot).is_empty();
16143        let text_is_empty = new_text.is_empty();
16144
16145        if range_is_empty != text_is_empty {
16146            if range_is_empty {
16147                all_deletions = false;
16148            } else {
16149                all_insertions = false;
16150            }
16151        } else {
16152            return false;
16153        }
16154
16155        if !all_insertions && !all_deletions {
16156            return false;
16157        }
16158    }
16159    all_insertions || all_deletions
16160}