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 debounced_delay;
   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 hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod proposed_changes_editor;
   39mod rust_analyzer_ext;
   40pub mod scroll;
   41mod selections_collection;
   42pub mod tasks;
   43
   44#[cfg(test)]
   45mod editor_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   52pub(crate) use actions::*;
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use debounced_delay::DebouncedDelay;
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::{StringMatch, StringMatchCandidate};
   73use git::blame::GitBlame;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
   78    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   79    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   81    UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   82    VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86pub(crate) use hunk_diff::HoveredHunk;
   87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use task::{ResolvedTask, TaskTemplate, TaskVariables};
  106
  107use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  108pub use lsp::CompletionContext;
  109use lsp::{
  110    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  111    LanguageServerId,
  112};
  113use mouse_context_menu::MouseContextMenu;
  114use movement::TextLayoutDetails;
  115pub use multi_buffer::{
  116    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  117    ToPoint,
  118};
  119use multi_buffer::{
  120    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  121};
  122use ordered_float::OrderedFloat;
  123use parking_lot::{Mutex, RwLock};
  124use project::project_settings::{GitGutterSetting, ProjectSettings};
  125use project::{
  126    lsp_store::FormatTrigger, CodeAction, Completion, CompletionIntent, Item, Location, Project,
  127    ProjectPath, ProjectTransaction, TaskSourceKind,
  128};
  129use rand::prelude::*;
  130use rpc::{proto::*, ErrorExt};
  131use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  132use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  133use serde::{Deserialize, Serialize};
  134use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  135use smallvec::SmallVec;
  136use snippet::Snippet;
  137use std::{
  138    any::TypeId,
  139    borrow::Cow,
  140    cell::RefCell,
  141    cmp::{self, Ordering, Reverse},
  142    mem,
  143    num::NonZeroU32,
  144    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  145    path::{Path, PathBuf},
  146    rc::Rc,
  147    sync::Arc,
  148    time::{Duration, Instant},
  149};
  150pub use sum_tree::Bias;
  151use sum_tree::TreeMap;
  152use text::{BufferId, OffsetUtf16, Rope};
  153use theme::{
  154    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  155    ThemeColors, ThemeSettings,
  156};
  157use ui::{
  158    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  159    ListItem, Popover, PopoverMenuHandle, Tooltip,
  160};
  161use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  162use workspace::item::{ItemHandle, PreviewTabsSettings};
  163use workspace::notifications::{DetachAndPromptErr, NotificationId};
  164use workspace::{
  165    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  166};
  167use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  168
  169use crate::hover_links::find_url;
  170use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  171
  172pub const FILE_HEADER_HEIGHT: u32 = 1;
  173pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  174pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  175pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  176const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  177const MAX_LINE_LEN: usize = 1024;
  178const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  179const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  180pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  181#[doc(hidden)]
  182pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  183#[doc(hidden)]
  184pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  185
  186pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  187pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  188
  189pub fn render_parsed_markdown(
  190    element_id: impl Into<ElementId>,
  191    parsed: &language::ParsedMarkdown,
  192    editor_style: &EditorStyle,
  193    workspace: Option<WeakView<Workspace>>,
  194    cx: &mut WindowContext,
  195) -> InteractiveText {
  196    let code_span_background_color = cx
  197        .theme()
  198        .colors()
  199        .editor_document_highlight_read_background;
  200
  201    let highlights = gpui::combine_highlights(
  202        parsed.highlights.iter().filter_map(|(range, highlight)| {
  203            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  204            Some((range.clone(), highlight))
  205        }),
  206        parsed
  207            .regions
  208            .iter()
  209            .zip(&parsed.region_ranges)
  210            .filter_map(|(region, range)| {
  211                if region.code {
  212                    Some((
  213                        range.clone(),
  214                        HighlightStyle {
  215                            background_color: Some(code_span_background_color),
  216                            ..Default::default()
  217                        },
  218                    ))
  219                } else {
  220                    None
  221                }
  222            }),
  223    );
  224
  225    let mut links = Vec::new();
  226    let mut link_ranges = Vec::new();
  227    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  228        if let Some(link) = region.link.clone() {
  229            links.push(link);
  230            link_ranges.push(range.clone());
  231        }
  232    }
  233
  234    InteractiveText::new(
  235        element_id,
  236        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  237    )
  238    .on_click(link_ranges, move |clicked_range_ix, cx| {
  239        match &links[clicked_range_ix] {
  240            markdown::Link::Web { url } => cx.open_url(url),
  241            markdown::Link::Path { path } => {
  242                if let Some(workspace) = &workspace {
  243                    _ = workspace.update(cx, |workspace, cx| {
  244                        workspace.open_abs_path(path.clone(), false, cx).detach();
  245                    });
  246                }
  247            }
  248        }
  249    })
  250}
  251
  252#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  253pub(crate) enum InlayId {
  254    Suggestion(usize),
  255    Hint(usize),
  256}
  257
  258impl InlayId {
  259    fn id(&self) -> usize {
  260        match self {
  261            Self::Suggestion(id) => *id,
  262            Self::Hint(id) => *id,
  263        }
  264    }
  265}
  266
  267enum DiffRowHighlight {}
  268enum DocumentHighlightRead {}
  269enum DocumentHighlightWrite {}
  270enum InputComposition {}
  271
  272#[derive(Copy, Clone, PartialEq, Eq)]
  273pub enum Direction {
  274    Prev,
  275    Next,
  276}
  277
  278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  279pub enum Navigated {
  280    Yes,
  281    No,
  282}
  283
  284impl Navigated {
  285    pub fn from_bool(yes: bool) -> Navigated {
  286        if yes {
  287            Navigated::Yes
  288        } else {
  289            Navigated::No
  290        }
  291    }
  292}
  293
  294pub fn init_settings(cx: &mut AppContext) {
  295    EditorSettings::register(cx);
  296}
  297
  298pub fn init(cx: &mut AppContext) {
  299    init_settings(cx);
  300
  301    workspace::register_project_item::<Editor>(cx);
  302    workspace::FollowableViewRegistry::register::<Editor>(cx);
  303    workspace::register_serializable_item::<Editor>(cx);
  304
  305    cx.observe_new_views(
  306        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  307            workspace.register_action(Editor::new_file);
  308            workspace.register_action(Editor::new_file_vertical);
  309            workspace.register_action(Editor::new_file_horizontal);
  310        },
  311    )
  312    .detach();
  313
  314    cx.on_action(move |_: &workspace::NewFile, cx| {
  315        let app_state = workspace::AppState::global(cx);
  316        if let Some(app_state) = app_state.upgrade() {
  317            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  318                Editor::new_file(workspace, &Default::default(), cx)
  319            })
  320            .detach();
  321        }
  322    });
  323    cx.on_action(move |_: &workspace::NewWindow, cx| {
  324        let app_state = workspace::AppState::global(cx);
  325        if let Some(app_state) = app_state.upgrade() {
  326            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  327                Editor::new_file(workspace, &Default::default(), cx)
  328            })
  329            .detach();
  330        }
  331    });
  332}
  333
  334pub struct SearchWithinRange;
  335
  336trait InvalidationRegion {
  337    fn ranges(&self) -> &[Range<Anchor>];
  338}
  339
  340#[derive(Clone, Debug, PartialEq)]
  341pub enum SelectPhase {
  342    Begin {
  343        position: DisplayPoint,
  344        add: bool,
  345        click_count: usize,
  346    },
  347    BeginColumnar {
  348        position: DisplayPoint,
  349        reset: bool,
  350        goal_column: u32,
  351    },
  352    Extend {
  353        position: DisplayPoint,
  354        click_count: usize,
  355    },
  356    Update {
  357        position: DisplayPoint,
  358        goal_column: u32,
  359        scroll_delta: gpui::Point<f32>,
  360    },
  361    End,
  362}
  363
  364#[derive(Clone, Debug)]
  365pub enum SelectMode {
  366    Character,
  367    Word(Range<Anchor>),
  368    Line(Range<Anchor>),
  369    All,
  370}
  371
  372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  373pub enum EditorMode {
  374    SingleLine { auto_width: bool },
  375    AutoHeight { max_lines: usize },
  376    Full,
  377}
  378
  379#[derive(Copy, Clone, Debug)]
  380pub enum SoftWrap {
  381    /// Prefer not to wrap at all.
  382    ///
  383    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  384    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  385    GitDiff,
  386    /// Prefer a single line generally, unless an overly long line is encountered.
  387    None,
  388    /// Soft wrap lines that exceed the editor width.
  389    EditorWidth,
  390    /// Soft wrap lines at the preferred line length.
  391    Column(u32),
  392    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  393    Bounded(u32),
  394}
  395
  396#[derive(Clone)]
  397pub struct EditorStyle {
  398    pub background: Hsla,
  399    pub local_player: PlayerColor,
  400    pub text: TextStyle,
  401    pub scrollbar_width: Pixels,
  402    pub syntax: Arc<SyntaxTheme>,
  403    pub status: StatusColors,
  404    pub inlay_hints_style: HighlightStyle,
  405    pub suggestions_style: HighlightStyle,
  406    pub unnecessary_code_fade: f32,
  407}
  408
  409impl Default for EditorStyle {
  410    fn default() -> Self {
  411        Self {
  412            background: Hsla::default(),
  413            local_player: PlayerColor::default(),
  414            text: TextStyle::default(),
  415            scrollbar_width: Pixels::default(),
  416            syntax: Default::default(),
  417            // HACK: Status colors don't have a real default.
  418            // We should look into removing the status colors from the editor
  419            // style and retrieve them directly from the theme.
  420            status: StatusColors::dark(),
  421            inlay_hints_style: HighlightStyle::default(),
  422            suggestions_style: HighlightStyle::default(),
  423            unnecessary_code_fade: Default::default(),
  424        }
  425    }
  426}
  427
  428pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  429    let show_background = all_language_settings(None, cx)
  430        .language(None)
  431        .inlay_hints
  432        .show_background;
  433
  434    HighlightStyle {
  435        color: Some(cx.theme().status().hint),
  436        background_color: show_background.then(|| cx.theme().status().hint_background),
  437        ..HighlightStyle::default()
  438    }
  439}
  440
  441type CompletionId = usize;
  442
  443#[derive(Clone, Debug)]
  444struct CompletionState {
  445    // render_inlay_ids represents the inlay hints that are inserted
  446    // for rendering the inline completions. They may be discontinuous
  447    // in the event that the completion provider returns some intersection
  448    // with the existing content.
  449    render_inlay_ids: Vec<InlayId>,
  450    // text is the resulting rope that is inserted when the user accepts a completion.
  451    text: Rope,
  452    // position is the position of the cursor when the completion was triggered.
  453    position: multi_buffer::Anchor,
  454    // delete_range is the range of text that this completion state covers.
  455    // if the completion is accepted, this range should be deleted.
  456    delete_range: Option<Range<multi_buffer::Anchor>>,
  457}
  458
  459#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  460struct EditorActionId(usize);
  461
  462impl EditorActionId {
  463    pub fn post_inc(&mut self) -> Self {
  464        let answer = self.0;
  465
  466        *self = Self(answer + 1);
  467
  468        Self(answer)
  469    }
  470}
  471
  472// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  473// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  474
  475type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  476type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  477
  478#[derive(Default)]
  479struct ScrollbarMarkerState {
  480    scrollbar_size: Size<Pixels>,
  481    dirty: bool,
  482    markers: Arc<[PaintQuad]>,
  483    pending_refresh: Option<Task<Result<()>>>,
  484}
  485
  486impl ScrollbarMarkerState {
  487    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  488        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  489    }
  490}
  491
  492#[derive(Clone, Debug)]
  493struct RunnableTasks {
  494    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  495    offset: MultiBufferOffset,
  496    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  497    column: u32,
  498    // Values of all named captures, including those starting with '_'
  499    extra_variables: HashMap<String, String>,
  500    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  501    context_range: Range<BufferOffset>,
  502}
  503
  504#[derive(Clone)]
  505struct ResolvedTasks {
  506    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  507    position: Anchor,
  508}
  509#[derive(Copy, Clone, Debug)]
  510struct MultiBufferOffset(usize);
  511#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  512struct BufferOffset(usize);
  513
  514// Addons allow storing per-editor state in other crates (e.g. Vim)
  515pub trait Addon: 'static {
  516    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  517
  518    fn to_any(&self) -> &dyn std::any::Any;
  519}
  520
  521/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  522///
  523/// See the [module level documentation](self) for more information.
  524pub struct Editor {
  525    focus_handle: FocusHandle,
  526    last_focused_descendant: Option<WeakFocusHandle>,
  527    /// The text buffer being edited
  528    buffer: Model<MultiBuffer>,
  529    /// Map of how text in the buffer should be displayed.
  530    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  531    pub display_map: Model<DisplayMap>,
  532    pub selections: SelectionsCollection,
  533    pub scroll_manager: ScrollManager,
  534    /// When inline assist editors are linked, they all render cursors because
  535    /// typing enters text into each of them, even the ones that aren't focused.
  536    pub(crate) show_cursor_when_unfocused: bool,
  537    columnar_selection_tail: Option<Anchor>,
  538    add_selections_state: Option<AddSelectionsState>,
  539    select_next_state: Option<SelectNextState>,
  540    select_prev_state: Option<SelectNextState>,
  541    selection_history: SelectionHistory,
  542    autoclose_regions: Vec<AutocloseRegion>,
  543    snippet_stack: InvalidationStack<SnippetState>,
  544    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  545    ime_transaction: Option<TransactionId>,
  546    active_diagnostics: Option<ActiveDiagnosticGroup>,
  547    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  548    project: Option<Model<Project>>,
  549    completion_provider: Option<Box<dyn CompletionProvider>>,
  550    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  551    blink_manager: Model<BlinkManager>,
  552    show_cursor_names: bool,
  553    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  554    pub show_local_selections: bool,
  555    mode: EditorMode,
  556    show_breadcrumbs: bool,
  557    show_gutter: bool,
  558    show_line_numbers: Option<bool>,
  559    use_relative_line_numbers: Option<bool>,
  560    show_git_diff_gutter: Option<bool>,
  561    show_code_actions: Option<bool>,
  562    show_runnables: Option<bool>,
  563    show_wrap_guides: Option<bool>,
  564    show_indent_guides: Option<bool>,
  565    placeholder_text: Option<Arc<str>>,
  566    highlight_order: usize,
  567    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  568    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  569    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  570    scrollbar_marker_state: ScrollbarMarkerState,
  571    active_indent_guides_state: ActiveIndentGuidesState,
  572    nav_history: Option<ItemNavHistory>,
  573    context_menu: RwLock<Option<ContextMenu>>,
  574    mouse_context_menu: Option<MouseContextMenu>,
  575    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  576    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  577    signature_help_state: SignatureHelpState,
  578    auto_signature_help: Option<bool>,
  579    find_all_references_task_sources: Vec<Anchor>,
  580    next_completion_id: CompletionId,
  581    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  582    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  583    code_actions_task: Option<Task<Result<()>>>,
  584    document_highlights_task: Option<Task<()>>,
  585    linked_editing_range_task: Option<Task<Option<()>>>,
  586    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  587    pending_rename: Option<RenameState>,
  588    searchable: bool,
  589    cursor_shape: CursorShape,
  590    current_line_highlight: Option<CurrentLineHighlight>,
  591    collapse_matches: bool,
  592    autoindent_mode: Option<AutoindentMode>,
  593    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  594    input_enabled: bool,
  595    use_modal_editing: bool,
  596    read_only: bool,
  597    leader_peer_id: Option<PeerId>,
  598    remote_id: Option<ViewId>,
  599    hover_state: HoverState,
  600    gutter_hovered: bool,
  601    hovered_link_state: Option<HoveredLinkState>,
  602    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  603    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  604    active_inline_completion: Option<CompletionState>,
  605    // enable_inline_completions is a switch that Vim can use to disable
  606    // inline completions based on its mode.
  607    enable_inline_completions: bool,
  608    show_inline_completions_override: Option<bool>,
  609    inlay_hint_cache: InlayHintCache,
  610    expanded_hunks: ExpandedHunks,
  611    next_inlay_id: usize,
  612    _subscriptions: Vec<Subscription>,
  613    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  614    gutter_dimensions: GutterDimensions,
  615    style: Option<EditorStyle>,
  616    next_editor_action_id: EditorActionId,
  617    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  618    use_autoclose: bool,
  619    use_auto_surround: bool,
  620    auto_replace_emoji_shortcode: bool,
  621    show_git_blame_gutter: bool,
  622    show_git_blame_inline: bool,
  623    show_git_blame_inline_delay_task: Option<Task<()>>,
  624    git_blame_inline_enabled: bool,
  625    serialize_dirty_buffers: bool,
  626    show_selection_menu: Option<bool>,
  627    blame: Option<Model<GitBlame>>,
  628    blame_subscription: Option<Subscription>,
  629    custom_context_menu: Option<
  630        Box<
  631            dyn 'static
  632                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  633        >,
  634    >,
  635    last_bounds: Option<Bounds<Pixels>>,
  636    expect_bounds_change: Option<Bounds<Pixels>>,
  637    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  638    tasks_update_task: Option<Task<()>>,
  639    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  640    file_header_size: u32,
  641    breadcrumb_header: Option<String>,
  642    focused_block: Option<FocusedBlock>,
  643    next_scroll_position: NextScrollCursorCenterTopBottom,
  644    addons: HashMap<TypeId, Box<dyn Addon>>,
  645    _scroll_cursor_center_top_bottom_task: Task<()>,
  646}
  647
  648#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  649enum NextScrollCursorCenterTopBottom {
  650    #[default]
  651    Center,
  652    Top,
  653    Bottom,
  654}
  655
  656impl NextScrollCursorCenterTopBottom {
  657    fn next(&self) -> Self {
  658        match self {
  659            Self::Center => Self::Top,
  660            Self::Top => Self::Bottom,
  661            Self::Bottom => Self::Center,
  662        }
  663    }
  664}
  665
  666#[derive(Clone)]
  667pub struct EditorSnapshot {
  668    pub mode: EditorMode,
  669    show_gutter: bool,
  670    show_line_numbers: Option<bool>,
  671    show_git_diff_gutter: Option<bool>,
  672    show_code_actions: Option<bool>,
  673    show_runnables: Option<bool>,
  674    git_blame_gutter_max_author_length: Option<usize>,
  675    pub display_snapshot: DisplaySnapshot,
  676    pub placeholder_text: Option<Arc<str>>,
  677    is_focused: bool,
  678    scroll_anchor: ScrollAnchor,
  679    ongoing_scroll: OngoingScroll,
  680    current_line_highlight: CurrentLineHighlight,
  681    gutter_hovered: bool,
  682}
  683
  684const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  685
  686#[derive(Default, Debug, Clone, Copy)]
  687pub struct GutterDimensions {
  688    pub left_padding: Pixels,
  689    pub right_padding: Pixels,
  690    pub width: Pixels,
  691    pub margin: Pixels,
  692    pub git_blame_entries_width: Option<Pixels>,
  693}
  694
  695impl GutterDimensions {
  696    /// The full width of the space taken up by the gutter.
  697    pub fn full_width(&self) -> Pixels {
  698        self.margin + self.width
  699    }
  700
  701    /// The width of the space reserved for the fold indicators,
  702    /// use alongside 'justify_end' and `gutter_width` to
  703    /// right align content with the line numbers
  704    pub fn fold_area_width(&self) -> Pixels {
  705        self.margin + self.right_padding
  706    }
  707}
  708
  709#[derive(Debug)]
  710pub struct RemoteSelection {
  711    pub replica_id: ReplicaId,
  712    pub selection: Selection<Anchor>,
  713    pub cursor_shape: CursorShape,
  714    pub peer_id: PeerId,
  715    pub line_mode: bool,
  716    pub participant_index: Option<ParticipantIndex>,
  717    pub user_name: Option<SharedString>,
  718}
  719
  720#[derive(Clone, Debug)]
  721struct SelectionHistoryEntry {
  722    selections: Arc<[Selection<Anchor>]>,
  723    select_next_state: Option<SelectNextState>,
  724    select_prev_state: Option<SelectNextState>,
  725    add_selections_state: Option<AddSelectionsState>,
  726}
  727
  728enum SelectionHistoryMode {
  729    Normal,
  730    Undoing,
  731    Redoing,
  732}
  733
  734#[derive(Clone, PartialEq, Eq, Hash)]
  735struct HoveredCursor {
  736    replica_id: u16,
  737    selection_id: usize,
  738}
  739
  740impl Default for SelectionHistoryMode {
  741    fn default() -> Self {
  742        Self::Normal
  743    }
  744}
  745
  746#[derive(Default)]
  747struct SelectionHistory {
  748    #[allow(clippy::type_complexity)]
  749    selections_by_transaction:
  750        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  751    mode: SelectionHistoryMode,
  752    undo_stack: VecDeque<SelectionHistoryEntry>,
  753    redo_stack: VecDeque<SelectionHistoryEntry>,
  754}
  755
  756impl SelectionHistory {
  757    fn insert_transaction(
  758        &mut self,
  759        transaction_id: TransactionId,
  760        selections: Arc<[Selection<Anchor>]>,
  761    ) {
  762        self.selections_by_transaction
  763            .insert(transaction_id, (selections, None));
  764    }
  765
  766    #[allow(clippy::type_complexity)]
  767    fn transaction(
  768        &self,
  769        transaction_id: TransactionId,
  770    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  771        self.selections_by_transaction.get(&transaction_id)
  772    }
  773
  774    #[allow(clippy::type_complexity)]
  775    fn transaction_mut(
  776        &mut self,
  777        transaction_id: TransactionId,
  778    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  779        self.selections_by_transaction.get_mut(&transaction_id)
  780    }
  781
  782    fn push(&mut self, entry: SelectionHistoryEntry) {
  783        if !entry.selections.is_empty() {
  784            match self.mode {
  785                SelectionHistoryMode::Normal => {
  786                    self.push_undo(entry);
  787                    self.redo_stack.clear();
  788                }
  789                SelectionHistoryMode::Undoing => self.push_redo(entry),
  790                SelectionHistoryMode::Redoing => self.push_undo(entry),
  791            }
  792        }
  793    }
  794
  795    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  796        if self
  797            .undo_stack
  798            .back()
  799            .map_or(true, |e| e.selections != entry.selections)
  800        {
  801            self.undo_stack.push_back(entry);
  802            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  803                self.undo_stack.pop_front();
  804            }
  805        }
  806    }
  807
  808    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  809        if self
  810            .redo_stack
  811            .back()
  812            .map_or(true, |e| e.selections != entry.selections)
  813        {
  814            self.redo_stack.push_back(entry);
  815            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  816                self.redo_stack.pop_front();
  817            }
  818        }
  819    }
  820}
  821
  822struct RowHighlight {
  823    index: usize,
  824    range: Range<Anchor>,
  825    color: Hsla,
  826    should_autoscroll: bool,
  827}
  828
  829#[derive(Clone, Debug)]
  830struct AddSelectionsState {
  831    above: bool,
  832    stack: Vec<usize>,
  833}
  834
  835#[derive(Clone)]
  836struct SelectNextState {
  837    query: AhoCorasick,
  838    wordwise: bool,
  839    done: bool,
  840}
  841
  842impl std::fmt::Debug for SelectNextState {
  843    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  844        f.debug_struct(std::any::type_name::<Self>())
  845            .field("wordwise", &self.wordwise)
  846            .field("done", &self.done)
  847            .finish()
  848    }
  849}
  850
  851#[derive(Debug)]
  852struct AutocloseRegion {
  853    selection_id: usize,
  854    range: Range<Anchor>,
  855    pair: BracketPair,
  856}
  857
  858#[derive(Debug)]
  859struct SnippetState {
  860    ranges: Vec<Vec<Range<Anchor>>>,
  861    active_index: usize,
  862}
  863
  864#[doc(hidden)]
  865pub struct RenameState {
  866    pub range: Range<Anchor>,
  867    pub old_name: Arc<str>,
  868    pub editor: View<Editor>,
  869    block_id: CustomBlockId,
  870}
  871
  872struct InvalidationStack<T>(Vec<T>);
  873
  874struct RegisteredInlineCompletionProvider {
  875    provider: Arc<dyn InlineCompletionProviderHandle>,
  876    _subscription: Subscription,
  877}
  878
  879enum ContextMenu {
  880    Completions(CompletionsMenu),
  881    CodeActions(CodeActionsMenu),
  882}
  883
  884impl ContextMenu {
  885    fn select_first(
  886        &mut self,
  887        project: Option<&Model<Project>>,
  888        cx: &mut ViewContext<Editor>,
  889    ) -> bool {
  890        if self.visible() {
  891            match self {
  892                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  893                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  894            }
  895            true
  896        } else {
  897            false
  898        }
  899    }
  900
  901    fn select_prev(
  902        &mut self,
  903        project: Option<&Model<Project>>,
  904        cx: &mut ViewContext<Editor>,
  905    ) -> bool {
  906        if self.visible() {
  907            match self {
  908                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  909                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  910            }
  911            true
  912        } else {
  913            false
  914        }
  915    }
  916
  917    fn select_next(
  918        &mut self,
  919        project: Option<&Model<Project>>,
  920        cx: &mut ViewContext<Editor>,
  921    ) -> bool {
  922        if self.visible() {
  923            match self {
  924                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  925                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  926            }
  927            true
  928        } else {
  929            false
  930        }
  931    }
  932
  933    fn select_last(
  934        &mut self,
  935        project: Option<&Model<Project>>,
  936        cx: &mut ViewContext<Editor>,
  937    ) -> bool {
  938        if self.visible() {
  939            match self {
  940                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  941                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  942            }
  943            true
  944        } else {
  945            false
  946        }
  947    }
  948
  949    fn visible(&self) -> bool {
  950        match self {
  951            ContextMenu::Completions(menu) => menu.visible(),
  952            ContextMenu::CodeActions(menu) => menu.visible(),
  953        }
  954    }
  955
  956    fn render(
  957        &self,
  958        cursor_position: DisplayPoint,
  959        style: &EditorStyle,
  960        max_height: Pixels,
  961        workspace: Option<WeakView<Workspace>>,
  962        cx: &mut ViewContext<Editor>,
  963    ) -> (ContextMenuOrigin, AnyElement) {
  964        match self {
  965            ContextMenu::Completions(menu) => (
  966                ContextMenuOrigin::EditorPoint(cursor_position),
  967                menu.render(style, max_height, workspace, cx),
  968            ),
  969            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  970        }
  971    }
  972}
  973
  974enum ContextMenuOrigin {
  975    EditorPoint(DisplayPoint),
  976    GutterIndicator(DisplayRow),
  977}
  978
  979#[derive(Clone)]
  980struct CompletionsMenu {
  981    id: CompletionId,
  982    sort_completions: bool,
  983    initial_position: Anchor,
  984    buffer: Model<Buffer>,
  985    completions: Arc<RwLock<Box<[Completion]>>>,
  986    match_candidates: Arc<[StringMatchCandidate]>,
  987    matches: Arc<[StringMatch]>,
  988    selected_item: usize,
  989    scroll_handle: UniformListScrollHandle,
  990    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  991}
  992
  993impl CompletionsMenu {
  994    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  995        self.selected_item = 0;
  996        self.scroll_handle.scroll_to_item(self.selected_item);
  997        self.attempt_resolve_selected_completion_documentation(project, cx);
  998        cx.notify();
  999    }
 1000
 1001    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 1002        if self.selected_item > 0 {
 1003            self.selected_item -= 1;
 1004        } else {
 1005            self.selected_item = self.matches.len() - 1;
 1006        }
 1007        self.scroll_handle.scroll_to_item(self.selected_item);
 1008        self.attempt_resolve_selected_completion_documentation(project, cx);
 1009        cx.notify();
 1010    }
 1011
 1012    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 1013        if self.selected_item + 1 < self.matches.len() {
 1014            self.selected_item += 1;
 1015        } else {
 1016            self.selected_item = 0;
 1017        }
 1018        self.scroll_handle.scroll_to_item(self.selected_item);
 1019        self.attempt_resolve_selected_completion_documentation(project, cx);
 1020        cx.notify();
 1021    }
 1022
 1023    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 1024        self.selected_item = self.matches.len() - 1;
 1025        self.scroll_handle.scroll_to_item(self.selected_item);
 1026        self.attempt_resolve_selected_completion_documentation(project, cx);
 1027        cx.notify();
 1028    }
 1029
 1030    fn pre_resolve_completion_documentation(
 1031        buffer: Model<Buffer>,
 1032        completions: Arc<RwLock<Box<[Completion]>>>,
 1033        matches: Arc<[StringMatch]>,
 1034        editor: &Editor,
 1035        cx: &mut ViewContext<Editor>,
 1036    ) -> Task<()> {
 1037        let settings = EditorSettings::get_global(cx);
 1038        if !settings.show_completion_documentation {
 1039            return Task::ready(());
 1040        }
 1041
 1042        let Some(provider) = editor.completion_provider.as_ref() else {
 1043            return Task::ready(());
 1044        };
 1045
 1046        let resolve_task = provider.resolve_completions(
 1047            buffer,
 1048            matches.iter().map(|m| m.candidate_id).collect(),
 1049            completions.clone(),
 1050            cx,
 1051        );
 1052
 1053        cx.spawn(move |this, mut cx| async move {
 1054            if let Some(true) = resolve_task.await.log_err() {
 1055                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1056            }
 1057        })
 1058    }
 1059
 1060    fn attempt_resolve_selected_completion_documentation(
 1061        &mut self,
 1062        project: Option<&Model<Project>>,
 1063        cx: &mut ViewContext<Editor>,
 1064    ) {
 1065        let settings = EditorSettings::get_global(cx);
 1066        if !settings.show_completion_documentation {
 1067            return;
 1068        }
 1069
 1070        let completion_index = self.matches[self.selected_item].candidate_id;
 1071        let Some(project) = project else {
 1072            return;
 1073        };
 1074
 1075        let resolve_task = project.update(cx, |project, cx| {
 1076            project.resolve_completions(
 1077                self.buffer.clone(),
 1078                vec![completion_index],
 1079                self.completions.clone(),
 1080                cx,
 1081            )
 1082        });
 1083
 1084        let delay_ms =
 1085            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1086        let delay = Duration::from_millis(delay_ms);
 1087
 1088        self.selected_completion_documentation_resolve_debounce
 1089            .lock()
 1090            .fire_new(delay, cx, |_, cx| {
 1091                cx.spawn(move |this, mut cx| async move {
 1092                    if let Some(true) = resolve_task.await.log_err() {
 1093                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1094                    }
 1095                })
 1096            });
 1097    }
 1098
 1099    fn visible(&self) -> bool {
 1100        !self.matches.is_empty()
 1101    }
 1102
 1103    fn render(
 1104        &self,
 1105        style: &EditorStyle,
 1106        max_height: Pixels,
 1107        workspace: Option<WeakView<Workspace>>,
 1108        cx: &mut ViewContext<Editor>,
 1109    ) -> AnyElement {
 1110        let settings = EditorSettings::get_global(cx);
 1111        let show_completion_documentation = settings.show_completion_documentation;
 1112
 1113        let widest_completion_ix = self
 1114            .matches
 1115            .iter()
 1116            .enumerate()
 1117            .max_by_key(|(_, mat)| {
 1118                let completions = self.completions.read();
 1119                let completion = &completions[mat.candidate_id];
 1120                let documentation = &completion.documentation;
 1121
 1122                let mut len = completion.label.text.chars().count();
 1123                if let Some(Documentation::SingleLine(text)) = documentation {
 1124                    if show_completion_documentation {
 1125                        len += text.chars().count();
 1126                    }
 1127                }
 1128
 1129                len
 1130            })
 1131            .map(|(ix, _)| ix);
 1132
 1133        let completions = self.completions.clone();
 1134        let matches = self.matches.clone();
 1135        let selected_item = self.selected_item;
 1136        let style = style.clone();
 1137
 1138        let multiline_docs = if show_completion_documentation {
 1139            let mat = &self.matches[selected_item];
 1140            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1141                Some(Documentation::MultiLinePlainText(text)) => {
 1142                    Some(div().child(SharedString::from(text.clone())))
 1143                }
 1144                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1145                    Some(div().child(render_parsed_markdown(
 1146                        "completions_markdown",
 1147                        parsed,
 1148                        &style,
 1149                        workspace,
 1150                        cx,
 1151                    )))
 1152                }
 1153                _ => None,
 1154            };
 1155            multiline_docs.map(|div| {
 1156                div.id("multiline_docs")
 1157                    .max_h(max_height)
 1158                    .flex_1()
 1159                    .px_1p5()
 1160                    .py_1()
 1161                    .min_w(px(260.))
 1162                    .max_w(px(640.))
 1163                    .w(px(500.))
 1164                    .overflow_y_scroll()
 1165                    .occlude()
 1166            })
 1167        } else {
 1168            None
 1169        };
 1170
 1171        let list = uniform_list(
 1172            cx.view().clone(),
 1173            "completions",
 1174            matches.len(),
 1175            move |_editor, range, cx| {
 1176                let start_ix = range.start;
 1177                let completions_guard = completions.read();
 1178
 1179                matches[range]
 1180                    .iter()
 1181                    .enumerate()
 1182                    .map(|(ix, mat)| {
 1183                        let item_ix = start_ix + ix;
 1184                        let candidate_id = mat.candidate_id;
 1185                        let completion = &completions_guard[candidate_id];
 1186
 1187                        let documentation = if show_completion_documentation {
 1188                            &completion.documentation
 1189                        } else {
 1190                            &None
 1191                        };
 1192
 1193                        let highlights = gpui::combine_highlights(
 1194                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1195                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1196                                |(range, mut highlight)| {
 1197                                    // Ignore font weight for syntax highlighting, as we'll use it
 1198                                    // for fuzzy matches.
 1199                                    highlight.font_weight = None;
 1200
 1201                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1202                                        highlight.strikethrough = Some(StrikethroughStyle {
 1203                                            thickness: 1.0.into(),
 1204                                            ..Default::default()
 1205                                        });
 1206                                        highlight.color = Some(cx.theme().colors().text_muted);
 1207                                    }
 1208
 1209                                    (range, highlight)
 1210                                },
 1211                            ),
 1212                        );
 1213                        let completion_label = StyledText::new(completion.label.text.clone())
 1214                            .with_highlights(&style.text, highlights);
 1215                        let documentation_label =
 1216                            if let Some(Documentation::SingleLine(text)) = documentation {
 1217                                if text.trim().is_empty() {
 1218                                    None
 1219                                } else {
 1220                                    Some(
 1221                                        Label::new(text.clone())
 1222                                            .ml_4()
 1223                                            .size(LabelSize::Small)
 1224                                            .color(Color::Muted),
 1225                                    )
 1226                                }
 1227                            } else {
 1228                                None
 1229                            };
 1230
 1231                        div().min_w(px(220.)).max_w(px(540.)).child(
 1232                            ListItem::new(mat.candidate_id)
 1233                                .inset(true)
 1234                                .selected(item_ix == selected_item)
 1235                                .on_click(cx.listener(move |editor, _event, cx| {
 1236                                    cx.stop_propagation();
 1237                                    if let Some(task) = editor.confirm_completion(
 1238                                        &ConfirmCompletion {
 1239                                            item_ix: Some(item_ix),
 1240                                        },
 1241                                        cx,
 1242                                    ) {
 1243                                        task.detach_and_log_err(cx)
 1244                                    }
 1245                                }))
 1246                                .child(h_flex().overflow_hidden().child(completion_label))
 1247                                .end_slot::<Label>(documentation_label),
 1248                        )
 1249                    })
 1250                    .collect()
 1251            },
 1252        )
 1253        .occlude()
 1254        .max_h(max_height)
 1255        .track_scroll(self.scroll_handle.clone())
 1256        .with_width_from_item(widest_completion_ix)
 1257        .with_sizing_behavior(ListSizingBehavior::Infer);
 1258
 1259        Popover::new()
 1260            .child(list)
 1261            .when_some(multiline_docs, |popover, multiline_docs| {
 1262                popover.aside(multiline_docs)
 1263            })
 1264            .into_any_element()
 1265    }
 1266
 1267    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1268        let mut matches = if let Some(query) = query {
 1269            fuzzy::match_strings(
 1270                &self.match_candidates,
 1271                query,
 1272                query.chars().any(|c| c.is_uppercase()),
 1273                100,
 1274                &Default::default(),
 1275                executor,
 1276            )
 1277            .await
 1278        } else {
 1279            self.match_candidates
 1280                .iter()
 1281                .enumerate()
 1282                .map(|(candidate_id, candidate)| StringMatch {
 1283                    candidate_id,
 1284                    score: Default::default(),
 1285                    positions: Default::default(),
 1286                    string: candidate.string.clone(),
 1287                })
 1288                .collect()
 1289        };
 1290
 1291        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1292        if let Some(query) = query {
 1293            if let Some(query_start) = query.chars().next() {
 1294                matches.retain(|string_match| {
 1295                    split_words(&string_match.string).any(|word| {
 1296                        // Check that the first codepoint of the word as lowercase matches the first
 1297                        // codepoint of the query as lowercase
 1298                        word.chars()
 1299                            .flat_map(|codepoint| codepoint.to_lowercase())
 1300                            .zip(query_start.to_lowercase())
 1301                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1302                    })
 1303                });
 1304            }
 1305        }
 1306
 1307        let completions = self.completions.read();
 1308        if self.sort_completions {
 1309            matches.sort_unstable_by_key(|mat| {
 1310                // We do want to strike a balance here between what the language server tells us
 1311                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1312                // `Creat` and there is a local variable called `CreateComponent`).
 1313                // So what we do is: we bucket all matches into two buckets
 1314                // - Strong matches
 1315                // - Weak matches
 1316                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1317                // and the Weak matches are the rest.
 1318                //
 1319                // For the strong matches, we sort by the language-servers score first and for the weak
 1320                // matches, we prefer our fuzzy finder first.
 1321                //
 1322                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1323                // us into account when it's obviously a bad match.
 1324
 1325                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1326                enum MatchScore<'a> {
 1327                    Strong {
 1328                        sort_text: Option<&'a str>,
 1329                        score: Reverse<OrderedFloat<f64>>,
 1330                        sort_key: (usize, &'a str),
 1331                    },
 1332                    Weak {
 1333                        score: Reverse<OrderedFloat<f64>>,
 1334                        sort_text: Option<&'a str>,
 1335                        sort_key: (usize, &'a str),
 1336                    },
 1337                }
 1338
 1339                let completion = &completions[mat.candidate_id];
 1340                let sort_key = completion.sort_key();
 1341                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1342                let score = Reverse(OrderedFloat(mat.score));
 1343
 1344                if mat.score >= 0.2 {
 1345                    MatchScore::Strong {
 1346                        sort_text,
 1347                        score,
 1348                        sort_key,
 1349                    }
 1350                } else {
 1351                    MatchScore::Weak {
 1352                        score,
 1353                        sort_text,
 1354                        sort_key,
 1355                    }
 1356                }
 1357            });
 1358        }
 1359
 1360        for mat in &mut matches {
 1361            let completion = &completions[mat.candidate_id];
 1362            mat.string.clone_from(&completion.label.text);
 1363            for position in &mut mat.positions {
 1364                *position += completion.label.filter_range.start;
 1365            }
 1366        }
 1367        drop(completions);
 1368
 1369        self.matches = matches.into();
 1370        self.selected_item = 0;
 1371    }
 1372}
 1373
 1374struct AvailableCodeAction {
 1375    excerpt_id: ExcerptId,
 1376    action: CodeAction,
 1377    provider: Arc<dyn CodeActionProvider>,
 1378}
 1379
 1380#[derive(Clone)]
 1381struct CodeActionContents {
 1382    tasks: Option<Arc<ResolvedTasks>>,
 1383    actions: Option<Arc<[AvailableCodeAction]>>,
 1384}
 1385
 1386impl CodeActionContents {
 1387    fn len(&self) -> usize {
 1388        match (&self.tasks, &self.actions) {
 1389            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1390            (Some(tasks), None) => tasks.templates.len(),
 1391            (None, Some(actions)) => actions.len(),
 1392            (None, None) => 0,
 1393        }
 1394    }
 1395
 1396    fn is_empty(&self) -> bool {
 1397        match (&self.tasks, &self.actions) {
 1398            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1399            (Some(tasks), None) => tasks.templates.is_empty(),
 1400            (None, Some(actions)) => actions.is_empty(),
 1401            (None, None) => true,
 1402        }
 1403    }
 1404
 1405    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1406        self.tasks
 1407            .iter()
 1408            .flat_map(|tasks| {
 1409                tasks
 1410                    .templates
 1411                    .iter()
 1412                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1413            })
 1414            .chain(self.actions.iter().flat_map(|actions| {
 1415                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1416                    excerpt_id: available.excerpt_id,
 1417                    action: available.action.clone(),
 1418                    provider: available.provider.clone(),
 1419                })
 1420            }))
 1421    }
 1422    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1423        match (&self.tasks, &self.actions) {
 1424            (Some(tasks), Some(actions)) => {
 1425                if index < tasks.templates.len() {
 1426                    tasks
 1427                        .templates
 1428                        .get(index)
 1429                        .cloned()
 1430                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1431                } else {
 1432                    actions.get(index - tasks.templates.len()).map(|available| {
 1433                        CodeActionsItem::CodeAction {
 1434                            excerpt_id: available.excerpt_id,
 1435                            action: available.action.clone(),
 1436                            provider: available.provider.clone(),
 1437                        }
 1438                    })
 1439                }
 1440            }
 1441            (Some(tasks), None) => tasks
 1442                .templates
 1443                .get(index)
 1444                .cloned()
 1445                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1446            (None, Some(actions)) => {
 1447                actions
 1448                    .get(index)
 1449                    .map(|available| CodeActionsItem::CodeAction {
 1450                        excerpt_id: available.excerpt_id,
 1451                        action: available.action.clone(),
 1452                        provider: available.provider.clone(),
 1453                    })
 1454            }
 1455            (None, None) => None,
 1456        }
 1457    }
 1458}
 1459
 1460#[allow(clippy::large_enum_variant)]
 1461#[derive(Clone)]
 1462enum CodeActionsItem {
 1463    Task(TaskSourceKind, ResolvedTask),
 1464    CodeAction {
 1465        excerpt_id: ExcerptId,
 1466        action: CodeAction,
 1467        provider: Arc<dyn CodeActionProvider>,
 1468    },
 1469}
 1470
 1471impl CodeActionsItem {
 1472    fn as_task(&self) -> Option<&ResolvedTask> {
 1473        let Self::Task(_, task) = self else {
 1474            return None;
 1475        };
 1476        Some(task)
 1477    }
 1478    fn as_code_action(&self) -> Option<&CodeAction> {
 1479        let Self::CodeAction { action, .. } = self else {
 1480            return None;
 1481        };
 1482        Some(action)
 1483    }
 1484    fn label(&self) -> String {
 1485        match self {
 1486            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1487            Self::Task(_, task) => task.resolved_label.clone(),
 1488        }
 1489    }
 1490}
 1491
 1492struct CodeActionsMenu {
 1493    actions: CodeActionContents,
 1494    buffer: Model<Buffer>,
 1495    selected_item: usize,
 1496    scroll_handle: UniformListScrollHandle,
 1497    deployed_from_indicator: Option<DisplayRow>,
 1498}
 1499
 1500impl CodeActionsMenu {
 1501    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1502        self.selected_item = 0;
 1503        self.scroll_handle.scroll_to_item(self.selected_item);
 1504        cx.notify()
 1505    }
 1506
 1507    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1508        if self.selected_item > 0 {
 1509            self.selected_item -= 1;
 1510        } else {
 1511            self.selected_item = self.actions.len() - 1;
 1512        }
 1513        self.scroll_handle.scroll_to_item(self.selected_item);
 1514        cx.notify();
 1515    }
 1516
 1517    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1518        if self.selected_item + 1 < self.actions.len() {
 1519            self.selected_item += 1;
 1520        } else {
 1521            self.selected_item = 0;
 1522        }
 1523        self.scroll_handle.scroll_to_item(self.selected_item);
 1524        cx.notify();
 1525    }
 1526
 1527    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1528        self.selected_item = self.actions.len() - 1;
 1529        self.scroll_handle.scroll_to_item(self.selected_item);
 1530        cx.notify()
 1531    }
 1532
 1533    fn visible(&self) -> bool {
 1534        !self.actions.is_empty()
 1535    }
 1536
 1537    fn render(
 1538        &self,
 1539        cursor_position: DisplayPoint,
 1540        _style: &EditorStyle,
 1541        max_height: Pixels,
 1542        cx: &mut ViewContext<Editor>,
 1543    ) -> (ContextMenuOrigin, AnyElement) {
 1544        let actions = self.actions.clone();
 1545        let selected_item = self.selected_item;
 1546        let element = uniform_list(
 1547            cx.view().clone(),
 1548            "code_actions_menu",
 1549            self.actions.len(),
 1550            move |_this, range, cx| {
 1551                actions
 1552                    .iter()
 1553                    .skip(range.start)
 1554                    .take(range.end - range.start)
 1555                    .enumerate()
 1556                    .map(|(ix, action)| {
 1557                        let item_ix = range.start + ix;
 1558                        let selected = selected_item == item_ix;
 1559                        let colors = cx.theme().colors();
 1560                        div()
 1561                            .px_1()
 1562                            .rounded_md()
 1563                            .text_color(colors.text)
 1564                            .when(selected, |style| {
 1565                                style
 1566                                    .bg(colors.element_active)
 1567                                    .text_color(colors.text_accent)
 1568                            })
 1569                            .hover(|style| {
 1570                                style
 1571                                    .bg(colors.element_hover)
 1572                                    .text_color(colors.text_accent)
 1573                            })
 1574                            .whitespace_nowrap()
 1575                            .when_some(action.as_code_action(), |this, action| {
 1576                                this.on_mouse_down(
 1577                                    MouseButton::Left,
 1578                                    cx.listener(move |editor, _, cx| {
 1579                                        cx.stop_propagation();
 1580                                        if let Some(task) = editor.confirm_code_action(
 1581                                            &ConfirmCodeAction {
 1582                                                item_ix: Some(item_ix),
 1583                                            },
 1584                                            cx,
 1585                                        ) {
 1586                                            task.detach_and_log_err(cx)
 1587                                        }
 1588                                    }),
 1589                                )
 1590                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1591                                .child(SharedString::from(action.lsp_action.title.clone()))
 1592                            })
 1593                            .when_some(action.as_task(), |this, task| {
 1594                                this.on_mouse_down(
 1595                                    MouseButton::Left,
 1596                                    cx.listener(move |editor, _, cx| {
 1597                                        cx.stop_propagation();
 1598                                        if let Some(task) = editor.confirm_code_action(
 1599                                            &ConfirmCodeAction {
 1600                                                item_ix: Some(item_ix),
 1601                                            },
 1602                                            cx,
 1603                                        ) {
 1604                                            task.detach_and_log_err(cx)
 1605                                        }
 1606                                    }),
 1607                                )
 1608                                .child(SharedString::from(task.resolved_label.clone()))
 1609                            })
 1610                    })
 1611                    .collect()
 1612            },
 1613        )
 1614        .elevation_1(cx)
 1615        .p_1()
 1616        .max_h(max_height)
 1617        .occlude()
 1618        .track_scroll(self.scroll_handle.clone())
 1619        .with_width_from_item(
 1620            self.actions
 1621                .iter()
 1622                .enumerate()
 1623                .max_by_key(|(_, action)| match action {
 1624                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1625                    CodeActionsItem::CodeAction { action, .. } => {
 1626                        action.lsp_action.title.chars().count()
 1627                    }
 1628                })
 1629                .map(|(ix, _)| ix),
 1630        )
 1631        .with_sizing_behavior(ListSizingBehavior::Infer)
 1632        .into_any_element();
 1633
 1634        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1635            ContextMenuOrigin::GutterIndicator(row)
 1636        } else {
 1637            ContextMenuOrigin::EditorPoint(cursor_position)
 1638        };
 1639
 1640        (cursor_position, element)
 1641    }
 1642}
 1643
 1644#[derive(Debug)]
 1645struct ActiveDiagnosticGroup {
 1646    primary_range: Range<Anchor>,
 1647    primary_message: String,
 1648    group_id: usize,
 1649    blocks: HashMap<CustomBlockId, Diagnostic>,
 1650    is_valid: bool,
 1651}
 1652
 1653#[derive(Serialize, Deserialize, Clone, Debug)]
 1654pub struct ClipboardSelection {
 1655    pub len: usize,
 1656    pub is_entire_line: bool,
 1657    pub first_line_indent: u32,
 1658}
 1659
 1660#[derive(Debug)]
 1661pub(crate) struct NavigationData {
 1662    cursor_anchor: Anchor,
 1663    cursor_position: Point,
 1664    scroll_anchor: ScrollAnchor,
 1665    scroll_top_row: u32,
 1666}
 1667
 1668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1669enum GotoDefinitionKind {
 1670    Symbol,
 1671    Declaration,
 1672    Type,
 1673    Implementation,
 1674}
 1675
 1676#[derive(Debug, Clone)]
 1677enum InlayHintRefreshReason {
 1678    Toggle(bool),
 1679    SettingsChange(InlayHintSettings),
 1680    NewLinesShown,
 1681    BufferEdited(HashSet<Arc<Language>>),
 1682    RefreshRequested,
 1683    ExcerptsRemoved(Vec<ExcerptId>),
 1684}
 1685
 1686impl InlayHintRefreshReason {
 1687    fn description(&self) -> &'static str {
 1688        match self {
 1689            Self::Toggle(_) => "toggle",
 1690            Self::SettingsChange(_) => "settings change",
 1691            Self::NewLinesShown => "new lines shown",
 1692            Self::BufferEdited(_) => "buffer edited",
 1693            Self::RefreshRequested => "refresh requested",
 1694            Self::ExcerptsRemoved(_) => "excerpts removed",
 1695        }
 1696    }
 1697}
 1698
 1699pub(crate) struct FocusedBlock {
 1700    id: BlockId,
 1701    focus_handle: WeakFocusHandle,
 1702}
 1703
 1704impl Editor {
 1705    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1706        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1707        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1708        Self::new(
 1709            EditorMode::SingleLine { auto_width: false },
 1710            buffer,
 1711            None,
 1712            false,
 1713            cx,
 1714        )
 1715    }
 1716
 1717    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1718        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1719        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1720        Self::new(EditorMode::Full, buffer, None, false, cx)
 1721    }
 1722
 1723    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1724        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1725        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1726        Self::new(
 1727            EditorMode::SingleLine { auto_width: true },
 1728            buffer,
 1729            None,
 1730            false,
 1731            cx,
 1732        )
 1733    }
 1734
 1735    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1736        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1737        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1738        Self::new(
 1739            EditorMode::AutoHeight { max_lines },
 1740            buffer,
 1741            None,
 1742            false,
 1743            cx,
 1744        )
 1745    }
 1746
 1747    pub fn for_buffer(
 1748        buffer: Model<Buffer>,
 1749        project: Option<Model<Project>>,
 1750        cx: &mut ViewContext<Self>,
 1751    ) -> Self {
 1752        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1753        Self::new(EditorMode::Full, buffer, project, false, cx)
 1754    }
 1755
 1756    pub fn for_multibuffer(
 1757        buffer: Model<MultiBuffer>,
 1758        project: Option<Model<Project>>,
 1759        show_excerpt_controls: bool,
 1760        cx: &mut ViewContext<Self>,
 1761    ) -> Self {
 1762        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1763    }
 1764
 1765    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1766        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1767        let mut clone = Self::new(
 1768            self.mode,
 1769            self.buffer.clone(),
 1770            self.project.clone(),
 1771            show_excerpt_controls,
 1772            cx,
 1773        );
 1774        self.display_map.update(cx, |display_map, cx| {
 1775            let snapshot = display_map.snapshot(cx);
 1776            clone.display_map.update(cx, |display_map, cx| {
 1777                display_map.set_state(&snapshot, cx);
 1778            });
 1779        });
 1780        clone.selections.clone_state(&self.selections);
 1781        clone.scroll_manager.clone_state(&self.scroll_manager);
 1782        clone.searchable = self.searchable;
 1783        clone
 1784    }
 1785
 1786    pub fn new(
 1787        mode: EditorMode,
 1788        buffer: Model<MultiBuffer>,
 1789        project: Option<Model<Project>>,
 1790        show_excerpt_controls: bool,
 1791        cx: &mut ViewContext<Self>,
 1792    ) -> Self {
 1793        let style = cx.text_style();
 1794        let font_size = style.font_size.to_pixels(cx.rem_size());
 1795        let editor = cx.view().downgrade();
 1796        let fold_placeholder = FoldPlaceholder {
 1797            constrain_width: true,
 1798            render: Arc::new(move |fold_id, fold_range, cx| {
 1799                let editor = editor.clone();
 1800                div()
 1801                    .id(fold_id)
 1802                    .bg(cx.theme().colors().ghost_element_background)
 1803                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1804                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1805                    .rounded_sm()
 1806                    .size_full()
 1807                    .cursor_pointer()
 1808                    .child("")
 1809                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1810                    .on_click(move |_, cx| {
 1811                        editor
 1812                            .update(cx, |editor, cx| {
 1813                                editor.unfold_ranges(
 1814                                    [fold_range.start..fold_range.end],
 1815                                    true,
 1816                                    false,
 1817                                    cx,
 1818                                );
 1819                                cx.stop_propagation();
 1820                            })
 1821                            .ok();
 1822                    })
 1823                    .into_any()
 1824            }),
 1825            merge_adjacent: true,
 1826        };
 1827        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1828        let display_map = cx.new_model(|cx| {
 1829            DisplayMap::new(
 1830                buffer.clone(),
 1831                style.font(),
 1832                font_size,
 1833                None,
 1834                show_excerpt_controls,
 1835                file_header_size,
 1836                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1837                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1838                fold_placeholder,
 1839                cx,
 1840            )
 1841        });
 1842
 1843        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1844
 1845        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1846
 1847        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1848            .then(|| language_settings::SoftWrap::None);
 1849
 1850        let mut project_subscriptions = Vec::new();
 1851        if mode == EditorMode::Full {
 1852            if let Some(project) = project.as_ref() {
 1853                if buffer.read(cx).is_singleton() {
 1854                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1855                        cx.emit(EditorEvent::TitleChanged);
 1856                    }));
 1857                }
 1858                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1859                    if let project::Event::RefreshInlayHints = event {
 1860                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1861                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1862                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1863                            let focus_handle = editor.focus_handle(cx);
 1864                            if focus_handle.is_focused(cx) {
 1865                                let snapshot = buffer.read(cx).snapshot();
 1866                                for (range, snippet) in snippet_edits {
 1867                                    let editor_range =
 1868                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1869                                    editor
 1870                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1871                                        .ok();
 1872                                }
 1873                            }
 1874                        }
 1875                    }
 1876                }));
 1877                let task_inventory = project.read(cx).task_inventory().clone();
 1878                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1879                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1880                }));
 1881            }
 1882        }
 1883
 1884        let inlay_hint_settings = inlay_hint_settings(
 1885            selections.newest_anchor().head(),
 1886            &buffer.read(cx).snapshot(cx),
 1887            cx,
 1888        );
 1889        let focus_handle = cx.focus_handle();
 1890        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1891        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1892            .detach();
 1893        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1894            .detach();
 1895        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1896
 1897        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1898            Some(false)
 1899        } else {
 1900            None
 1901        };
 1902
 1903        let mut code_action_providers = Vec::new();
 1904        if let Some(project) = project.clone() {
 1905            code_action_providers.push(Arc::new(project) as Arc<_>);
 1906        }
 1907
 1908        let mut this = Self {
 1909            focus_handle,
 1910            show_cursor_when_unfocused: false,
 1911            last_focused_descendant: None,
 1912            buffer: buffer.clone(),
 1913            display_map: display_map.clone(),
 1914            selections,
 1915            scroll_manager: ScrollManager::new(cx),
 1916            columnar_selection_tail: None,
 1917            add_selections_state: None,
 1918            select_next_state: None,
 1919            select_prev_state: None,
 1920            selection_history: Default::default(),
 1921            autoclose_regions: Default::default(),
 1922            snippet_stack: Default::default(),
 1923            select_larger_syntax_node_stack: Vec::new(),
 1924            ime_transaction: Default::default(),
 1925            active_diagnostics: None,
 1926            soft_wrap_mode_override,
 1927            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1928            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1929            project,
 1930            blink_manager: blink_manager.clone(),
 1931            show_local_selections: true,
 1932            mode,
 1933            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1934            show_gutter: mode == EditorMode::Full,
 1935            show_line_numbers: None,
 1936            use_relative_line_numbers: None,
 1937            show_git_diff_gutter: None,
 1938            show_code_actions: None,
 1939            show_runnables: None,
 1940            show_wrap_guides: None,
 1941            show_indent_guides,
 1942            placeholder_text: None,
 1943            highlight_order: 0,
 1944            highlighted_rows: HashMap::default(),
 1945            background_highlights: Default::default(),
 1946            gutter_highlights: TreeMap::default(),
 1947            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1948            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1949            nav_history: None,
 1950            context_menu: RwLock::new(None),
 1951            mouse_context_menu: None,
 1952            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1953            completion_tasks: Default::default(),
 1954            signature_help_state: SignatureHelpState::default(),
 1955            auto_signature_help: None,
 1956            find_all_references_task_sources: Vec::new(),
 1957            next_completion_id: 0,
 1958            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1959            next_inlay_id: 0,
 1960            code_action_providers,
 1961            available_code_actions: Default::default(),
 1962            code_actions_task: Default::default(),
 1963            document_highlights_task: Default::default(),
 1964            linked_editing_range_task: Default::default(),
 1965            pending_rename: Default::default(),
 1966            searchable: true,
 1967            cursor_shape: EditorSettings::get_global(cx)
 1968                .cursor_shape
 1969                .unwrap_or_default(),
 1970            current_line_highlight: None,
 1971            autoindent_mode: Some(AutoindentMode::EachLine),
 1972            collapse_matches: false,
 1973            workspace: None,
 1974            input_enabled: true,
 1975            use_modal_editing: mode == EditorMode::Full,
 1976            read_only: false,
 1977            use_autoclose: true,
 1978            use_auto_surround: true,
 1979            auto_replace_emoji_shortcode: false,
 1980            leader_peer_id: None,
 1981            remote_id: None,
 1982            hover_state: Default::default(),
 1983            hovered_link_state: Default::default(),
 1984            inline_completion_provider: None,
 1985            active_inline_completion: None,
 1986            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1987            expanded_hunks: ExpandedHunks::default(),
 1988            gutter_hovered: false,
 1989            pixel_position_of_newest_cursor: None,
 1990            last_bounds: None,
 1991            expect_bounds_change: None,
 1992            gutter_dimensions: GutterDimensions::default(),
 1993            style: None,
 1994            show_cursor_names: false,
 1995            hovered_cursors: Default::default(),
 1996            next_editor_action_id: EditorActionId::default(),
 1997            editor_actions: Rc::default(),
 1998            show_inline_completions_override: None,
 1999            enable_inline_completions: true,
 2000            custom_context_menu: None,
 2001            show_git_blame_gutter: false,
 2002            show_git_blame_inline: false,
 2003            show_selection_menu: None,
 2004            show_git_blame_inline_delay_task: None,
 2005            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2006            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2007                .session
 2008                .restore_unsaved_buffers,
 2009            blame: None,
 2010            blame_subscription: None,
 2011            file_header_size,
 2012            tasks: Default::default(),
 2013            _subscriptions: vec![
 2014                cx.observe(&buffer, Self::on_buffer_changed),
 2015                cx.subscribe(&buffer, Self::on_buffer_event),
 2016                cx.observe(&display_map, Self::on_display_map_changed),
 2017                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2018                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2019                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2020                cx.observe_window_activation(|editor, cx| {
 2021                    let active = cx.is_window_active();
 2022                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2023                        if active {
 2024                            blink_manager.enable(cx);
 2025                        } else {
 2026                            blink_manager.disable(cx);
 2027                        }
 2028                    });
 2029                }),
 2030            ],
 2031            tasks_update_task: None,
 2032            linked_edit_ranges: Default::default(),
 2033            previous_search_ranges: None,
 2034            breadcrumb_header: None,
 2035            focused_block: None,
 2036            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2037            addons: HashMap::default(),
 2038            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2039        };
 2040        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2041        this._subscriptions.extend(project_subscriptions);
 2042
 2043        this.end_selection(cx);
 2044        this.scroll_manager.show_scrollbar(cx);
 2045
 2046        if mode == EditorMode::Full {
 2047            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2048            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2049
 2050            if this.git_blame_inline_enabled {
 2051                this.git_blame_inline_enabled = true;
 2052                this.start_git_blame_inline(false, cx);
 2053            }
 2054        }
 2055
 2056        this.report_editor_event("open", None, cx);
 2057        this
 2058    }
 2059
 2060    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2061        self.mouse_context_menu
 2062            .as_ref()
 2063            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2064    }
 2065
 2066    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2067        let mut key_context = KeyContext::new_with_defaults();
 2068        key_context.add("Editor");
 2069        let mode = match self.mode {
 2070            EditorMode::SingleLine { .. } => "single_line",
 2071            EditorMode::AutoHeight { .. } => "auto_height",
 2072            EditorMode::Full => "full",
 2073        };
 2074
 2075        if EditorSettings::jupyter_enabled(cx) {
 2076            key_context.add("jupyter");
 2077        }
 2078
 2079        key_context.set("mode", mode);
 2080        if self.pending_rename.is_some() {
 2081            key_context.add("renaming");
 2082        }
 2083        if self.context_menu_visible() {
 2084            match self.context_menu.read().as_ref() {
 2085                Some(ContextMenu::Completions(_)) => {
 2086                    key_context.add("menu");
 2087                    key_context.add("showing_completions")
 2088                }
 2089                Some(ContextMenu::CodeActions(_)) => {
 2090                    key_context.add("menu");
 2091                    key_context.add("showing_code_actions")
 2092                }
 2093                None => {}
 2094            }
 2095        }
 2096
 2097        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2098        if !self.focus_handle(cx).contains_focused(cx)
 2099            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2100        {
 2101            for addon in self.addons.values() {
 2102                addon.extend_key_context(&mut key_context, cx)
 2103            }
 2104        }
 2105
 2106        if let Some(extension) = self
 2107            .buffer
 2108            .read(cx)
 2109            .as_singleton()
 2110            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2111        {
 2112            key_context.set("extension", extension.to_string());
 2113        }
 2114
 2115        if self.has_active_inline_completion(cx) {
 2116            key_context.add("copilot_suggestion");
 2117            key_context.add("inline_completion");
 2118        }
 2119
 2120        key_context
 2121    }
 2122
 2123    pub fn new_file(
 2124        workspace: &mut Workspace,
 2125        _: &workspace::NewFile,
 2126        cx: &mut ViewContext<Workspace>,
 2127    ) {
 2128        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2129            "Failed to create buffer",
 2130            cx,
 2131            |e, _| match e.error_code() {
 2132                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2133                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2134                e.error_tag("required").unwrap_or("the latest version")
 2135            )),
 2136                _ => None,
 2137            },
 2138        );
 2139    }
 2140
 2141    pub fn new_in_workspace(
 2142        workspace: &mut Workspace,
 2143        cx: &mut ViewContext<Workspace>,
 2144    ) -> Task<Result<View<Editor>>> {
 2145        let project = workspace.project().clone();
 2146        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2147
 2148        cx.spawn(|workspace, mut cx| async move {
 2149            let buffer = create.await?;
 2150            workspace.update(&mut cx, |workspace, cx| {
 2151                let editor =
 2152                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2153                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2154                editor
 2155            })
 2156        })
 2157    }
 2158
 2159    fn new_file_vertical(
 2160        workspace: &mut Workspace,
 2161        _: &workspace::NewFileSplitVertical,
 2162        cx: &mut ViewContext<Workspace>,
 2163    ) {
 2164        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2165    }
 2166
 2167    fn new_file_horizontal(
 2168        workspace: &mut Workspace,
 2169        _: &workspace::NewFileSplitHorizontal,
 2170        cx: &mut ViewContext<Workspace>,
 2171    ) {
 2172        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2173    }
 2174
 2175    fn new_file_in_direction(
 2176        workspace: &mut Workspace,
 2177        direction: SplitDirection,
 2178        cx: &mut ViewContext<Workspace>,
 2179    ) {
 2180        let project = workspace.project().clone();
 2181        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2182
 2183        cx.spawn(|workspace, mut cx| async move {
 2184            let buffer = create.await?;
 2185            workspace.update(&mut cx, move |workspace, cx| {
 2186                workspace.split_item(
 2187                    direction,
 2188                    Box::new(
 2189                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2190                    ),
 2191                    cx,
 2192                )
 2193            })?;
 2194            anyhow::Ok(())
 2195        })
 2196        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2197            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2198                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2199                e.error_tag("required").unwrap_or("the latest version")
 2200            )),
 2201            _ => None,
 2202        });
 2203    }
 2204
 2205    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2206        self.leader_peer_id
 2207    }
 2208
 2209    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2210        &self.buffer
 2211    }
 2212
 2213    pub fn workspace(&self) -> Option<View<Workspace>> {
 2214        self.workspace.as_ref()?.0.upgrade()
 2215    }
 2216
 2217    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2218        self.buffer().read(cx).title(cx)
 2219    }
 2220
 2221    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2222        let git_blame_gutter_max_author_length = self
 2223            .render_git_blame_gutter(cx)
 2224            .then(|| {
 2225                if let Some(blame) = self.blame.as_ref() {
 2226                    let max_author_length =
 2227                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2228                    Some(max_author_length)
 2229                } else {
 2230                    None
 2231                }
 2232            })
 2233            .flatten();
 2234
 2235        EditorSnapshot {
 2236            mode: self.mode,
 2237            show_gutter: self.show_gutter,
 2238            show_line_numbers: self.show_line_numbers,
 2239            show_git_diff_gutter: self.show_git_diff_gutter,
 2240            show_code_actions: self.show_code_actions,
 2241            show_runnables: self.show_runnables,
 2242            git_blame_gutter_max_author_length,
 2243            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2244            scroll_anchor: self.scroll_manager.anchor(),
 2245            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2246            placeholder_text: self.placeholder_text.clone(),
 2247            is_focused: self.focus_handle.is_focused(cx),
 2248            current_line_highlight: self
 2249                .current_line_highlight
 2250                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2251            gutter_hovered: self.gutter_hovered,
 2252        }
 2253    }
 2254
 2255    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2256        self.buffer.read(cx).language_at(point, cx)
 2257    }
 2258
 2259    pub fn file_at<T: ToOffset>(
 2260        &self,
 2261        point: T,
 2262        cx: &AppContext,
 2263    ) -> Option<Arc<dyn language::File>> {
 2264        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2265    }
 2266
 2267    pub fn active_excerpt(
 2268        &self,
 2269        cx: &AppContext,
 2270    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2271        self.buffer
 2272            .read(cx)
 2273            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2274    }
 2275
 2276    pub fn mode(&self) -> EditorMode {
 2277        self.mode
 2278    }
 2279
 2280    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2281        self.collaboration_hub.as_deref()
 2282    }
 2283
 2284    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2285        self.collaboration_hub = Some(hub);
 2286    }
 2287
 2288    pub fn set_custom_context_menu(
 2289        &mut self,
 2290        f: impl 'static
 2291            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2292    ) {
 2293        self.custom_context_menu = Some(Box::new(f))
 2294    }
 2295
 2296    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2297        self.completion_provider = Some(provider);
 2298    }
 2299
 2300    pub fn set_inline_completion_provider<T>(
 2301        &mut self,
 2302        provider: Option<Model<T>>,
 2303        cx: &mut ViewContext<Self>,
 2304    ) where
 2305        T: InlineCompletionProvider,
 2306    {
 2307        self.inline_completion_provider =
 2308            provider.map(|provider| RegisteredInlineCompletionProvider {
 2309                _subscription: cx.observe(&provider, |this, _, cx| {
 2310                    if this.focus_handle.is_focused(cx) {
 2311                        this.update_visible_inline_completion(cx);
 2312                    }
 2313                }),
 2314                provider: Arc::new(provider),
 2315            });
 2316        self.refresh_inline_completion(false, false, cx);
 2317    }
 2318
 2319    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2320        self.placeholder_text.as_deref()
 2321    }
 2322
 2323    pub fn set_placeholder_text(
 2324        &mut self,
 2325        placeholder_text: impl Into<Arc<str>>,
 2326        cx: &mut ViewContext<Self>,
 2327    ) {
 2328        let placeholder_text = Some(placeholder_text.into());
 2329        if self.placeholder_text != placeholder_text {
 2330            self.placeholder_text = placeholder_text;
 2331            cx.notify();
 2332        }
 2333    }
 2334
 2335    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2336        self.cursor_shape = cursor_shape;
 2337
 2338        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2339        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2340
 2341        cx.notify();
 2342    }
 2343
 2344    pub fn set_current_line_highlight(
 2345        &mut self,
 2346        current_line_highlight: Option<CurrentLineHighlight>,
 2347    ) {
 2348        self.current_line_highlight = current_line_highlight;
 2349    }
 2350
 2351    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2352        self.collapse_matches = collapse_matches;
 2353    }
 2354
 2355    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2356        if self.collapse_matches {
 2357            return range.start..range.start;
 2358        }
 2359        range.clone()
 2360    }
 2361
 2362    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2363        if self.display_map.read(cx).clip_at_line_ends != clip {
 2364            self.display_map
 2365                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2366        }
 2367    }
 2368
 2369    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2370        self.input_enabled = input_enabled;
 2371    }
 2372
 2373    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2374        self.enable_inline_completions = enabled;
 2375    }
 2376
 2377    pub fn set_autoindent(&mut self, autoindent: bool) {
 2378        if autoindent {
 2379            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2380        } else {
 2381            self.autoindent_mode = None;
 2382        }
 2383    }
 2384
 2385    pub fn read_only(&self, cx: &AppContext) -> bool {
 2386        self.read_only || self.buffer.read(cx).read_only()
 2387    }
 2388
 2389    pub fn set_read_only(&mut self, read_only: bool) {
 2390        self.read_only = read_only;
 2391    }
 2392
 2393    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2394        self.use_autoclose = autoclose;
 2395    }
 2396
 2397    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2398        self.use_auto_surround = auto_surround;
 2399    }
 2400
 2401    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2402        self.auto_replace_emoji_shortcode = auto_replace;
 2403    }
 2404
 2405    pub fn toggle_inline_completions(
 2406        &mut self,
 2407        _: &ToggleInlineCompletions,
 2408        cx: &mut ViewContext<Self>,
 2409    ) {
 2410        if self.show_inline_completions_override.is_some() {
 2411            self.set_show_inline_completions(None, cx);
 2412        } else {
 2413            let cursor = self.selections.newest_anchor().head();
 2414            if let Some((buffer, cursor_buffer_position)) =
 2415                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2416            {
 2417                let show_inline_completions =
 2418                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2419                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2420            }
 2421        }
 2422    }
 2423
 2424    pub fn set_show_inline_completions(
 2425        &mut self,
 2426        show_inline_completions: Option<bool>,
 2427        cx: &mut ViewContext<Self>,
 2428    ) {
 2429        self.show_inline_completions_override = show_inline_completions;
 2430        self.refresh_inline_completion(false, true, cx);
 2431    }
 2432
 2433    fn should_show_inline_completions(
 2434        &self,
 2435        buffer: &Model<Buffer>,
 2436        buffer_position: language::Anchor,
 2437        cx: &AppContext,
 2438    ) -> bool {
 2439        if let Some(provider) = self.inline_completion_provider() {
 2440            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2441                show_inline_completions
 2442            } else {
 2443                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2444            }
 2445        } else {
 2446            false
 2447        }
 2448    }
 2449
 2450    pub fn set_use_modal_editing(&mut self, to: bool) {
 2451        self.use_modal_editing = to;
 2452    }
 2453
 2454    pub fn use_modal_editing(&self) -> bool {
 2455        self.use_modal_editing
 2456    }
 2457
 2458    fn selections_did_change(
 2459        &mut self,
 2460        local: bool,
 2461        old_cursor_position: &Anchor,
 2462        show_completions: bool,
 2463        cx: &mut ViewContext<Self>,
 2464    ) {
 2465        cx.invalidate_character_coordinates();
 2466
 2467        // Copy selections to primary selection buffer
 2468        #[cfg(target_os = "linux")]
 2469        if local {
 2470            let selections = self.selections.all::<usize>(cx);
 2471            let buffer_handle = self.buffer.read(cx).read(cx);
 2472
 2473            let mut text = String::new();
 2474            for (index, selection) in selections.iter().enumerate() {
 2475                let text_for_selection = buffer_handle
 2476                    .text_for_range(selection.start..selection.end)
 2477                    .collect::<String>();
 2478
 2479                text.push_str(&text_for_selection);
 2480                if index != selections.len() - 1 {
 2481                    text.push('\n');
 2482                }
 2483            }
 2484
 2485            if !text.is_empty() {
 2486                cx.write_to_primary(ClipboardItem::new_string(text));
 2487            }
 2488        }
 2489
 2490        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2491            self.buffer.update(cx, |buffer, cx| {
 2492                buffer.set_active_selections(
 2493                    &self.selections.disjoint_anchors(),
 2494                    self.selections.line_mode,
 2495                    self.cursor_shape,
 2496                    cx,
 2497                )
 2498            });
 2499        }
 2500        let display_map = self
 2501            .display_map
 2502            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2503        let buffer = &display_map.buffer_snapshot;
 2504        self.add_selections_state = None;
 2505        self.select_next_state = None;
 2506        self.select_prev_state = None;
 2507        self.select_larger_syntax_node_stack.clear();
 2508        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2509        self.snippet_stack
 2510            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2511        self.take_rename(false, cx);
 2512
 2513        let new_cursor_position = self.selections.newest_anchor().head();
 2514
 2515        self.push_to_nav_history(
 2516            *old_cursor_position,
 2517            Some(new_cursor_position.to_point(buffer)),
 2518            cx,
 2519        );
 2520
 2521        if local {
 2522            let new_cursor_position = self.selections.newest_anchor().head();
 2523            let mut context_menu = self.context_menu.write();
 2524            let completion_menu = match context_menu.as_ref() {
 2525                Some(ContextMenu::Completions(menu)) => Some(menu),
 2526
 2527                _ => {
 2528                    *context_menu = None;
 2529                    None
 2530                }
 2531            };
 2532
 2533            if let Some(completion_menu) = completion_menu {
 2534                let cursor_position = new_cursor_position.to_offset(buffer);
 2535                let (word_range, kind) =
 2536                    buffer.surrounding_word(completion_menu.initial_position, true);
 2537                if kind == Some(CharKind::Word)
 2538                    && word_range.to_inclusive().contains(&cursor_position)
 2539                {
 2540                    let mut completion_menu = completion_menu.clone();
 2541                    drop(context_menu);
 2542
 2543                    let query = Self::completion_query(buffer, cursor_position);
 2544                    cx.spawn(move |this, mut cx| async move {
 2545                        completion_menu
 2546                            .filter(query.as_deref(), cx.background_executor().clone())
 2547                            .await;
 2548
 2549                        this.update(&mut cx, |this, cx| {
 2550                            let mut context_menu = this.context_menu.write();
 2551                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2552                                return;
 2553                            };
 2554
 2555                            if menu.id > completion_menu.id {
 2556                                return;
 2557                            }
 2558
 2559                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2560                            drop(context_menu);
 2561                            cx.notify();
 2562                        })
 2563                    })
 2564                    .detach();
 2565
 2566                    if show_completions {
 2567                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2568                    }
 2569                } else {
 2570                    drop(context_menu);
 2571                    self.hide_context_menu(cx);
 2572                }
 2573            } else {
 2574                drop(context_menu);
 2575            }
 2576
 2577            hide_hover(self, cx);
 2578
 2579            if old_cursor_position.to_display_point(&display_map).row()
 2580                != new_cursor_position.to_display_point(&display_map).row()
 2581            {
 2582                self.available_code_actions.take();
 2583            }
 2584            self.refresh_code_actions(cx);
 2585            self.refresh_document_highlights(cx);
 2586            refresh_matching_bracket_highlights(self, cx);
 2587            self.discard_inline_completion(false, cx);
 2588            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2589            if self.git_blame_inline_enabled {
 2590                self.start_inline_blame_timer(cx);
 2591            }
 2592        }
 2593
 2594        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2595        cx.emit(EditorEvent::SelectionsChanged { local });
 2596
 2597        if self.selections.disjoint_anchors().len() == 1 {
 2598            cx.emit(SearchEvent::ActiveMatchChanged)
 2599        }
 2600        cx.notify();
 2601    }
 2602
 2603    pub fn change_selections<R>(
 2604        &mut self,
 2605        autoscroll: Option<Autoscroll>,
 2606        cx: &mut ViewContext<Self>,
 2607        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2608    ) -> R {
 2609        self.change_selections_inner(autoscroll, true, cx, change)
 2610    }
 2611
 2612    pub fn change_selections_inner<R>(
 2613        &mut self,
 2614        autoscroll: Option<Autoscroll>,
 2615        request_completions: bool,
 2616        cx: &mut ViewContext<Self>,
 2617        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2618    ) -> R {
 2619        let old_cursor_position = self.selections.newest_anchor().head();
 2620        self.push_to_selection_history();
 2621
 2622        let (changed, result) = self.selections.change_with(cx, change);
 2623
 2624        if changed {
 2625            if let Some(autoscroll) = autoscroll {
 2626                self.request_autoscroll(autoscroll, cx);
 2627            }
 2628            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2629
 2630            if self.should_open_signature_help_automatically(
 2631                &old_cursor_position,
 2632                self.signature_help_state.backspace_pressed(),
 2633                cx,
 2634            ) {
 2635                self.show_signature_help(&ShowSignatureHelp, cx);
 2636            }
 2637            self.signature_help_state.set_backspace_pressed(false);
 2638        }
 2639
 2640        result
 2641    }
 2642
 2643    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2644    where
 2645        I: IntoIterator<Item = (Range<S>, T)>,
 2646        S: ToOffset,
 2647        T: Into<Arc<str>>,
 2648    {
 2649        if self.read_only(cx) {
 2650            return;
 2651        }
 2652
 2653        self.buffer
 2654            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2655    }
 2656
 2657    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2658    where
 2659        I: IntoIterator<Item = (Range<S>, T)>,
 2660        S: ToOffset,
 2661        T: Into<Arc<str>>,
 2662    {
 2663        if self.read_only(cx) {
 2664            return;
 2665        }
 2666
 2667        self.buffer.update(cx, |buffer, cx| {
 2668            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2669        });
 2670    }
 2671
 2672    pub fn edit_with_block_indent<I, S, T>(
 2673        &mut self,
 2674        edits: I,
 2675        original_indent_columns: Vec<u32>,
 2676        cx: &mut ViewContext<Self>,
 2677    ) where
 2678        I: IntoIterator<Item = (Range<S>, T)>,
 2679        S: ToOffset,
 2680        T: Into<Arc<str>>,
 2681    {
 2682        if self.read_only(cx) {
 2683            return;
 2684        }
 2685
 2686        self.buffer.update(cx, |buffer, cx| {
 2687            buffer.edit(
 2688                edits,
 2689                Some(AutoindentMode::Block {
 2690                    original_indent_columns,
 2691                }),
 2692                cx,
 2693            )
 2694        });
 2695    }
 2696
 2697    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2698        self.hide_context_menu(cx);
 2699
 2700        match phase {
 2701            SelectPhase::Begin {
 2702                position,
 2703                add,
 2704                click_count,
 2705            } => self.begin_selection(position, add, click_count, cx),
 2706            SelectPhase::BeginColumnar {
 2707                position,
 2708                goal_column,
 2709                reset,
 2710            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2711            SelectPhase::Extend {
 2712                position,
 2713                click_count,
 2714            } => self.extend_selection(position, click_count, cx),
 2715            SelectPhase::Update {
 2716                position,
 2717                goal_column,
 2718                scroll_delta,
 2719            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2720            SelectPhase::End => self.end_selection(cx),
 2721        }
 2722    }
 2723
 2724    fn extend_selection(
 2725        &mut self,
 2726        position: DisplayPoint,
 2727        click_count: usize,
 2728        cx: &mut ViewContext<Self>,
 2729    ) {
 2730        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2731        let tail = self.selections.newest::<usize>(cx).tail();
 2732        self.begin_selection(position, false, click_count, cx);
 2733
 2734        let position = position.to_offset(&display_map, Bias::Left);
 2735        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2736
 2737        let mut pending_selection = self
 2738            .selections
 2739            .pending_anchor()
 2740            .expect("extend_selection not called with pending selection");
 2741        if position >= tail {
 2742            pending_selection.start = tail_anchor;
 2743        } else {
 2744            pending_selection.end = tail_anchor;
 2745            pending_selection.reversed = true;
 2746        }
 2747
 2748        let mut pending_mode = self.selections.pending_mode().unwrap();
 2749        match &mut pending_mode {
 2750            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2751            _ => {}
 2752        }
 2753
 2754        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2755            s.set_pending(pending_selection, pending_mode)
 2756        });
 2757    }
 2758
 2759    fn begin_selection(
 2760        &mut self,
 2761        position: DisplayPoint,
 2762        add: bool,
 2763        click_count: usize,
 2764        cx: &mut ViewContext<Self>,
 2765    ) {
 2766        if !self.focus_handle.is_focused(cx) {
 2767            self.last_focused_descendant = None;
 2768            cx.focus(&self.focus_handle);
 2769        }
 2770
 2771        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2772        let buffer = &display_map.buffer_snapshot;
 2773        let newest_selection = self.selections.newest_anchor().clone();
 2774        let position = display_map.clip_point(position, Bias::Left);
 2775
 2776        let start;
 2777        let end;
 2778        let mode;
 2779        let auto_scroll;
 2780        match click_count {
 2781            1 => {
 2782                start = buffer.anchor_before(position.to_point(&display_map));
 2783                end = start;
 2784                mode = SelectMode::Character;
 2785                auto_scroll = true;
 2786            }
 2787            2 => {
 2788                let range = movement::surrounding_word(&display_map, position);
 2789                start = buffer.anchor_before(range.start.to_point(&display_map));
 2790                end = buffer.anchor_before(range.end.to_point(&display_map));
 2791                mode = SelectMode::Word(start..end);
 2792                auto_scroll = true;
 2793            }
 2794            3 => {
 2795                let position = display_map
 2796                    .clip_point(position, Bias::Left)
 2797                    .to_point(&display_map);
 2798                let line_start = display_map.prev_line_boundary(position).0;
 2799                let next_line_start = buffer.clip_point(
 2800                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2801                    Bias::Left,
 2802                );
 2803                start = buffer.anchor_before(line_start);
 2804                end = buffer.anchor_before(next_line_start);
 2805                mode = SelectMode::Line(start..end);
 2806                auto_scroll = true;
 2807            }
 2808            _ => {
 2809                start = buffer.anchor_before(0);
 2810                end = buffer.anchor_before(buffer.len());
 2811                mode = SelectMode::All;
 2812                auto_scroll = false;
 2813            }
 2814        }
 2815
 2816        let point_to_delete: Option<usize> = {
 2817            let selected_points: Vec<Selection<Point>> =
 2818                self.selections.disjoint_in_range(start..end, cx);
 2819
 2820            if !add || click_count > 1 {
 2821                None
 2822            } else if !selected_points.is_empty() {
 2823                Some(selected_points[0].id)
 2824            } else {
 2825                let clicked_point_already_selected =
 2826                    self.selections.disjoint.iter().find(|selection| {
 2827                        selection.start.to_point(buffer) == start.to_point(buffer)
 2828                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2829                    });
 2830
 2831                clicked_point_already_selected.map(|selection| selection.id)
 2832            }
 2833        };
 2834
 2835        let selections_count = self.selections.count();
 2836
 2837        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2838            if let Some(point_to_delete) = point_to_delete {
 2839                s.delete(point_to_delete);
 2840
 2841                if selections_count == 1 {
 2842                    s.set_pending_anchor_range(start..end, mode);
 2843                }
 2844            } else {
 2845                if !add {
 2846                    s.clear_disjoint();
 2847                } else if click_count > 1 {
 2848                    s.delete(newest_selection.id)
 2849                }
 2850
 2851                s.set_pending_anchor_range(start..end, mode);
 2852            }
 2853        });
 2854    }
 2855
 2856    fn begin_columnar_selection(
 2857        &mut self,
 2858        position: DisplayPoint,
 2859        goal_column: u32,
 2860        reset: bool,
 2861        cx: &mut ViewContext<Self>,
 2862    ) {
 2863        if !self.focus_handle.is_focused(cx) {
 2864            self.last_focused_descendant = None;
 2865            cx.focus(&self.focus_handle);
 2866        }
 2867
 2868        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2869
 2870        if reset {
 2871            let pointer_position = display_map
 2872                .buffer_snapshot
 2873                .anchor_before(position.to_point(&display_map));
 2874
 2875            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2876                s.clear_disjoint();
 2877                s.set_pending_anchor_range(
 2878                    pointer_position..pointer_position,
 2879                    SelectMode::Character,
 2880                );
 2881            });
 2882        }
 2883
 2884        let tail = self.selections.newest::<Point>(cx).tail();
 2885        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2886
 2887        if !reset {
 2888            self.select_columns(
 2889                tail.to_display_point(&display_map),
 2890                position,
 2891                goal_column,
 2892                &display_map,
 2893                cx,
 2894            );
 2895        }
 2896    }
 2897
 2898    fn update_selection(
 2899        &mut self,
 2900        position: DisplayPoint,
 2901        goal_column: u32,
 2902        scroll_delta: gpui::Point<f32>,
 2903        cx: &mut ViewContext<Self>,
 2904    ) {
 2905        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2906
 2907        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2908            let tail = tail.to_display_point(&display_map);
 2909            self.select_columns(tail, position, goal_column, &display_map, cx);
 2910        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2911            let buffer = self.buffer.read(cx).snapshot(cx);
 2912            let head;
 2913            let tail;
 2914            let mode = self.selections.pending_mode().unwrap();
 2915            match &mode {
 2916                SelectMode::Character => {
 2917                    head = position.to_point(&display_map);
 2918                    tail = pending.tail().to_point(&buffer);
 2919                }
 2920                SelectMode::Word(original_range) => {
 2921                    let original_display_range = original_range.start.to_display_point(&display_map)
 2922                        ..original_range.end.to_display_point(&display_map);
 2923                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2924                        ..original_display_range.end.to_point(&display_map);
 2925                    if movement::is_inside_word(&display_map, position)
 2926                        || original_display_range.contains(&position)
 2927                    {
 2928                        let word_range = movement::surrounding_word(&display_map, position);
 2929                        if word_range.start < original_display_range.start {
 2930                            head = word_range.start.to_point(&display_map);
 2931                        } else {
 2932                            head = word_range.end.to_point(&display_map);
 2933                        }
 2934                    } else {
 2935                        head = position.to_point(&display_map);
 2936                    }
 2937
 2938                    if head <= original_buffer_range.start {
 2939                        tail = original_buffer_range.end;
 2940                    } else {
 2941                        tail = original_buffer_range.start;
 2942                    }
 2943                }
 2944                SelectMode::Line(original_range) => {
 2945                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2946
 2947                    let position = display_map
 2948                        .clip_point(position, Bias::Left)
 2949                        .to_point(&display_map);
 2950                    let line_start = display_map.prev_line_boundary(position).0;
 2951                    let next_line_start = buffer.clip_point(
 2952                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2953                        Bias::Left,
 2954                    );
 2955
 2956                    if line_start < original_range.start {
 2957                        head = line_start
 2958                    } else {
 2959                        head = next_line_start
 2960                    }
 2961
 2962                    if head <= original_range.start {
 2963                        tail = original_range.end;
 2964                    } else {
 2965                        tail = original_range.start;
 2966                    }
 2967                }
 2968                SelectMode::All => {
 2969                    return;
 2970                }
 2971            };
 2972
 2973            if head < tail {
 2974                pending.start = buffer.anchor_before(head);
 2975                pending.end = buffer.anchor_before(tail);
 2976                pending.reversed = true;
 2977            } else {
 2978                pending.start = buffer.anchor_before(tail);
 2979                pending.end = buffer.anchor_before(head);
 2980                pending.reversed = false;
 2981            }
 2982
 2983            self.change_selections(None, cx, |s| {
 2984                s.set_pending(pending, mode);
 2985            });
 2986        } else {
 2987            log::error!("update_selection dispatched with no pending selection");
 2988            return;
 2989        }
 2990
 2991        self.apply_scroll_delta(scroll_delta, cx);
 2992        cx.notify();
 2993    }
 2994
 2995    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2996        self.columnar_selection_tail.take();
 2997        if self.selections.pending_anchor().is_some() {
 2998            let selections = self.selections.all::<usize>(cx);
 2999            self.change_selections(None, cx, |s| {
 3000                s.select(selections);
 3001                s.clear_pending();
 3002            });
 3003        }
 3004    }
 3005
 3006    fn select_columns(
 3007        &mut self,
 3008        tail: DisplayPoint,
 3009        head: DisplayPoint,
 3010        goal_column: u32,
 3011        display_map: &DisplaySnapshot,
 3012        cx: &mut ViewContext<Self>,
 3013    ) {
 3014        let start_row = cmp::min(tail.row(), head.row());
 3015        let end_row = cmp::max(tail.row(), head.row());
 3016        let start_column = cmp::min(tail.column(), goal_column);
 3017        let end_column = cmp::max(tail.column(), goal_column);
 3018        let reversed = start_column < tail.column();
 3019
 3020        let selection_ranges = (start_row.0..=end_row.0)
 3021            .map(DisplayRow)
 3022            .filter_map(|row| {
 3023                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3024                    let start = display_map
 3025                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3026                        .to_point(display_map);
 3027                    let end = display_map
 3028                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3029                        .to_point(display_map);
 3030                    if reversed {
 3031                        Some(end..start)
 3032                    } else {
 3033                        Some(start..end)
 3034                    }
 3035                } else {
 3036                    None
 3037                }
 3038            })
 3039            .collect::<Vec<_>>();
 3040
 3041        self.change_selections(None, cx, |s| {
 3042            s.select_ranges(selection_ranges);
 3043        });
 3044        cx.notify();
 3045    }
 3046
 3047    pub fn has_pending_nonempty_selection(&self) -> bool {
 3048        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3049            Some(Selection { start, end, .. }) => start != end,
 3050            None => false,
 3051        };
 3052
 3053        pending_nonempty_selection
 3054            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3055    }
 3056
 3057    pub fn has_pending_selection(&self) -> bool {
 3058        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3059    }
 3060
 3061    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3062        if self.clear_clicked_diff_hunks(cx) {
 3063            cx.notify();
 3064            return;
 3065        }
 3066        if self.dismiss_menus_and_popups(true, cx) {
 3067            return;
 3068        }
 3069
 3070        if self.mode == EditorMode::Full
 3071            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3072        {
 3073            return;
 3074        }
 3075
 3076        cx.propagate();
 3077    }
 3078
 3079    pub fn dismiss_menus_and_popups(
 3080        &mut self,
 3081        should_report_inline_completion_event: bool,
 3082        cx: &mut ViewContext<Self>,
 3083    ) -> bool {
 3084        if self.take_rename(false, cx).is_some() {
 3085            return true;
 3086        }
 3087
 3088        if hide_hover(self, cx) {
 3089            return true;
 3090        }
 3091
 3092        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3093            return true;
 3094        }
 3095
 3096        if self.hide_context_menu(cx).is_some() {
 3097            return true;
 3098        }
 3099
 3100        if self.mouse_context_menu.take().is_some() {
 3101            return true;
 3102        }
 3103
 3104        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3105            return true;
 3106        }
 3107
 3108        if self.snippet_stack.pop().is_some() {
 3109            return true;
 3110        }
 3111
 3112        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3113            self.dismiss_diagnostics(cx);
 3114            return true;
 3115        }
 3116
 3117        false
 3118    }
 3119
 3120    fn linked_editing_ranges_for(
 3121        &self,
 3122        selection: Range<text::Anchor>,
 3123        cx: &AppContext,
 3124    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3125        if self.linked_edit_ranges.is_empty() {
 3126            return None;
 3127        }
 3128        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3129            selection.end.buffer_id.and_then(|end_buffer_id| {
 3130                if selection.start.buffer_id != Some(end_buffer_id) {
 3131                    return None;
 3132                }
 3133                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3134                let snapshot = buffer.read(cx).snapshot();
 3135                self.linked_edit_ranges
 3136                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3137                    .map(|ranges| (ranges, snapshot, buffer))
 3138            })?;
 3139        use text::ToOffset as TO;
 3140        // find offset from the start of current range to current cursor position
 3141        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3142
 3143        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3144        let start_difference = start_offset - start_byte_offset;
 3145        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3146        let end_difference = end_offset - start_byte_offset;
 3147        // Current range has associated linked ranges.
 3148        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3149        for range in linked_ranges.iter() {
 3150            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3151            let end_offset = start_offset + end_difference;
 3152            let start_offset = start_offset + start_difference;
 3153            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3154                continue;
 3155            }
 3156            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3157                if s.start.buffer_id != selection.start.buffer_id
 3158                    || s.end.buffer_id != selection.end.buffer_id
 3159                {
 3160                    return false;
 3161                }
 3162                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3163                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3164            }) {
 3165                continue;
 3166            }
 3167            let start = buffer_snapshot.anchor_after(start_offset);
 3168            let end = buffer_snapshot.anchor_after(end_offset);
 3169            linked_edits
 3170                .entry(buffer.clone())
 3171                .or_default()
 3172                .push(start..end);
 3173        }
 3174        Some(linked_edits)
 3175    }
 3176
 3177    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3178        let text: Arc<str> = text.into();
 3179
 3180        if self.read_only(cx) {
 3181            return;
 3182        }
 3183
 3184        let selections = self.selections.all_adjusted(cx);
 3185        let mut bracket_inserted = false;
 3186        let mut edits = Vec::new();
 3187        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3188        let mut new_selections = Vec::with_capacity(selections.len());
 3189        let mut new_autoclose_regions = Vec::new();
 3190        let snapshot = self.buffer.read(cx).read(cx);
 3191
 3192        for (selection, autoclose_region) in
 3193            self.selections_with_autoclose_regions(selections, &snapshot)
 3194        {
 3195            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3196                // Determine if the inserted text matches the opening or closing
 3197                // bracket of any of this language's bracket pairs.
 3198                let mut bracket_pair = None;
 3199                let mut is_bracket_pair_start = false;
 3200                let mut is_bracket_pair_end = false;
 3201                if !text.is_empty() {
 3202                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3203                    //  and they are removing the character that triggered IME popup.
 3204                    for (pair, enabled) in scope.brackets() {
 3205                        if !pair.close && !pair.surround {
 3206                            continue;
 3207                        }
 3208
 3209                        if enabled && pair.start.ends_with(text.as_ref()) {
 3210                            bracket_pair = Some(pair.clone());
 3211                            is_bracket_pair_start = true;
 3212                            break;
 3213                        }
 3214                        if pair.end.as_str() == text.as_ref() {
 3215                            bracket_pair = Some(pair.clone());
 3216                            is_bracket_pair_end = true;
 3217                            break;
 3218                        }
 3219                    }
 3220                }
 3221
 3222                if let Some(bracket_pair) = bracket_pair {
 3223                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3224                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3225                    let auto_surround =
 3226                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3227                    if selection.is_empty() {
 3228                        if is_bracket_pair_start {
 3229                            let prefix_len = bracket_pair.start.len() - text.len();
 3230
 3231                            // If the inserted text is a suffix of an opening bracket and the
 3232                            // selection is preceded by the rest of the opening bracket, then
 3233                            // insert the closing bracket.
 3234                            let following_text_allows_autoclose = snapshot
 3235                                .chars_at(selection.start)
 3236                                .next()
 3237                                .map_or(true, |c| scope.should_autoclose_before(c));
 3238                            let preceding_text_matches_prefix = prefix_len == 0
 3239                                || (selection.start.column >= (prefix_len as u32)
 3240                                    && snapshot.contains_str_at(
 3241                                        Point::new(
 3242                                            selection.start.row,
 3243                                            selection.start.column - (prefix_len as u32),
 3244                                        ),
 3245                                        &bracket_pair.start[..prefix_len],
 3246                                    ));
 3247
 3248                            if autoclose
 3249                                && bracket_pair.close
 3250                                && following_text_allows_autoclose
 3251                                && preceding_text_matches_prefix
 3252                            {
 3253                                let anchor = snapshot.anchor_before(selection.end);
 3254                                new_selections.push((selection.map(|_| anchor), text.len()));
 3255                                new_autoclose_regions.push((
 3256                                    anchor,
 3257                                    text.len(),
 3258                                    selection.id,
 3259                                    bracket_pair.clone(),
 3260                                ));
 3261                                edits.push((
 3262                                    selection.range(),
 3263                                    format!("{}{}", text, bracket_pair.end).into(),
 3264                                ));
 3265                                bracket_inserted = true;
 3266                                continue;
 3267                            }
 3268                        }
 3269
 3270                        if let Some(region) = autoclose_region {
 3271                            // If the selection is followed by an auto-inserted closing bracket,
 3272                            // then don't insert that closing bracket again; just move the selection
 3273                            // past the closing bracket.
 3274                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3275                                && text.as_ref() == region.pair.end.as_str();
 3276                            if should_skip {
 3277                                let anchor = snapshot.anchor_after(selection.end);
 3278                                new_selections
 3279                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3280                                continue;
 3281                            }
 3282                        }
 3283
 3284                        let always_treat_brackets_as_autoclosed = snapshot
 3285                            .settings_at(selection.start, cx)
 3286                            .always_treat_brackets_as_autoclosed;
 3287                        if always_treat_brackets_as_autoclosed
 3288                            && is_bracket_pair_end
 3289                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3290                        {
 3291                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3292                            // and the inserted text is a closing bracket and the selection is followed
 3293                            // by the closing bracket then move the selection past the closing bracket.
 3294                            let anchor = snapshot.anchor_after(selection.end);
 3295                            new_selections.push((selection.map(|_| anchor), text.len()));
 3296                            continue;
 3297                        }
 3298                    }
 3299                    // If an opening bracket is 1 character long and is typed while
 3300                    // text is selected, then surround that text with the bracket pair.
 3301                    else if auto_surround
 3302                        && bracket_pair.surround
 3303                        && is_bracket_pair_start
 3304                        && bracket_pair.start.chars().count() == 1
 3305                    {
 3306                        edits.push((selection.start..selection.start, text.clone()));
 3307                        edits.push((
 3308                            selection.end..selection.end,
 3309                            bracket_pair.end.as_str().into(),
 3310                        ));
 3311                        bracket_inserted = true;
 3312                        new_selections.push((
 3313                            Selection {
 3314                                id: selection.id,
 3315                                start: snapshot.anchor_after(selection.start),
 3316                                end: snapshot.anchor_before(selection.end),
 3317                                reversed: selection.reversed,
 3318                                goal: selection.goal,
 3319                            },
 3320                            0,
 3321                        ));
 3322                        continue;
 3323                    }
 3324                }
 3325            }
 3326
 3327            if self.auto_replace_emoji_shortcode
 3328                && selection.is_empty()
 3329                && text.as_ref().ends_with(':')
 3330            {
 3331                if let Some(possible_emoji_short_code) =
 3332                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3333                {
 3334                    if !possible_emoji_short_code.is_empty() {
 3335                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3336                            let emoji_shortcode_start = Point::new(
 3337                                selection.start.row,
 3338                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3339                            );
 3340
 3341                            // Remove shortcode from buffer
 3342                            edits.push((
 3343                                emoji_shortcode_start..selection.start,
 3344                                "".to_string().into(),
 3345                            ));
 3346                            new_selections.push((
 3347                                Selection {
 3348                                    id: selection.id,
 3349                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3350                                    end: snapshot.anchor_before(selection.start),
 3351                                    reversed: selection.reversed,
 3352                                    goal: selection.goal,
 3353                                },
 3354                                0,
 3355                            ));
 3356
 3357                            // Insert emoji
 3358                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3359                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3360                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3361
 3362                            continue;
 3363                        }
 3364                    }
 3365                }
 3366            }
 3367
 3368            // If not handling any auto-close operation, then just replace the selected
 3369            // text with the given input and move the selection to the end of the
 3370            // newly inserted text.
 3371            let anchor = snapshot.anchor_after(selection.end);
 3372            if !self.linked_edit_ranges.is_empty() {
 3373                let start_anchor = snapshot.anchor_before(selection.start);
 3374
 3375                let is_word_char = text.chars().next().map_or(true, |char| {
 3376                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3377                    classifier.is_word(char)
 3378                });
 3379
 3380                if is_word_char {
 3381                    if let Some(ranges) = self
 3382                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3383                    {
 3384                        for (buffer, edits) in ranges {
 3385                            linked_edits
 3386                                .entry(buffer.clone())
 3387                                .or_default()
 3388                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3389                        }
 3390                    }
 3391                }
 3392            }
 3393
 3394            new_selections.push((selection.map(|_| anchor), 0));
 3395            edits.push((selection.start..selection.end, text.clone()));
 3396        }
 3397
 3398        drop(snapshot);
 3399
 3400        self.transact(cx, |this, cx| {
 3401            this.buffer.update(cx, |buffer, cx| {
 3402                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3403            });
 3404            for (buffer, edits) in linked_edits {
 3405                buffer.update(cx, |buffer, cx| {
 3406                    let snapshot = buffer.snapshot();
 3407                    let edits = edits
 3408                        .into_iter()
 3409                        .map(|(range, text)| {
 3410                            use text::ToPoint as TP;
 3411                            let end_point = TP::to_point(&range.end, &snapshot);
 3412                            let start_point = TP::to_point(&range.start, &snapshot);
 3413                            (start_point..end_point, text)
 3414                        })
 3415                        .sorted_by_key(|(range, _)| range.start)
 3416                        .collect::<Vec<_>>();
 3417                    buffer.edit(edits, None, cx);
 3418                })
 3419            }
 3420            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3421            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3422            let snapshot = this.buffer.read(cx).read(cx);
 3423            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3424                .zip(new_selection_deltas)
 3425                .map(|(selection, delta)| Selection {
 3426                    id: selection.id,
 3427                    start: selection.start + delta,
 3428                    end: selection.end + delta,
 3429                    reversed: selection.reversed,
 3430                    goal: SelectionGoal::None,
 3431                })
 3432                .collect::<Vec<_>>();
 3433
 3434            let mut i = 0;
 3435            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3436                let position = position.to_offset(&snapshot) + delta;
 3437                let start = snapshot.anchor_before(position);
 3438                let end = snapshot.anchor_after(position);
 3439                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3440                    match existing_state.range.start.cmp(&start, &snapshot) {
 3441                        Ordering::Less => i += 1,
 3442                        Ordering::Greater => break,
 3443                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3444                            Ordering::Less => i += 1,
 3445                            Ordering::Equal => break,
 3446                            Ordering::Greater => break,
 3447                        },
 3448                    }
 3449                }
 3450                this.autoclose_regions.insert(
 3451                    i,
 3452                    AutocloseRegion {
 3453                        selection_id,
 3454                        range: start..end,
 3455                        pair,
 3456                    },
 3457                );
 3458            }
 3459
 3460            drop(snapshot);
 3461            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3462            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3463                s.select(new_selections)
 3464            });
 3465
 3466            if !bracket_inserted {
 3467                if let Some(on_type_format_task) =
 3468                    this.trigger_on_type_formatting(text.to_string(), cx)
 3469                {
 3470                    on_type_format_task.detach_and_log_err(cx);
 3471                }
 3472            }
 3473
 3474            let editor_settings = EditorSettings::get_global(cx);
 3475            if bracket_inserted
 3476                && (editor_settings.auto_signature_help
 3477                    || editor_settings.show_signature_help_after_edits)
 3478            {
 3479                this.show_signature_help(&ShowSignatureHelp, cx);
 3480            }
 3481
 3482            let trigger_in_words = !had_active_inline_completion;
 3483            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3484            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3485            this.refresh_inline_completion(true, false, cx);
 3486        });
 3487    }
 3488
 3489    fn find_possible_emoji_shortcode_at_position(
 3490        snapshot: &MultiBufferSnapshot,
 3491        position: Point,
 3492    ) -> Option<String> {
 3493        let mut chars = Vec::new();
 3494        let mut found_colon = false;
 3495        for char in snapshot.reversed_chars_at(position).take(100) {
 3496            // Found a possible emoji shortcode in the middle of the buffer
 3497            if found_colon {
 3498                if char.is_whitespace() {
 3499                    chars.reverse();
 3500                    return Some(chars.iter().collect());
 3501                }
 3502                // If the previous character is not a whitespace, we are in the middle of a word
 3503                // and we only want to complete the shortcode if the word is made up of other emojis
 3504                let mut containing_word = String::new();
 3505                for ch in snapshot
 3506                    .reversed_chars_at(position)
 3507                    .skip(chars.len() + 1)
 3508                    .take(100)
 3509                {
 3510                    if ch.is_whitespace() {
 3511                        break;
 3512                    }
 3513                    containing_word.push(ch);
 3514                }
 3515                let containing_word = containing_word.chars().rev().collect::<String>();
 3516                if util::word_consists_of_emojis(containing_word.as_str()) {
 3517                    chars.reverse();
 3518                    return Some(chars.iter().collect());
 3519                }
 3520            }
 3521
 3522            if char.is_whitespace() || !char.is_ascii() {
 3523                return None;
 3524            }
 3525            if char == ':' {
 3526                found_colon = true;
 3527            } else {
 3528                chars.push(char);
 3529            }
 3530        }
 3531        // Found a possible emoji shortcode at the beginning of the buffer
 3532        chars.reverse();
 3533        Some(chars.iter().collect())
 3534    }
 3535
 3536    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3537        self.transact(cx, |this, cx| {
 3538            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3539                let selections = this.selections.all::<usize>(cx);
 3540                let multi_buffer = this.buffer.read(cx);
 3541                let buffer = multi_buffer.snapshot(cx);
 3542                selections
 3543                    .iter()
 3544                    .map(|selection| {
 3545                        let start_point = selection.start.to_point(&buffer);
 3546                        let mut indent =
 3547                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3548                        indent.len = cmp::min(indent.len, start_point.column);
 3549                        let start = selection.start;
 3550                        let end = selection.end;
 3551                        let selection_is_empty = start == end;
 3552                        let language_scope = buffer.language_scope_at(start);
 3553                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3554                            &language_scope
 3555                        {
 3556                            let leading_whitespace_len = buffer
 3557                                .reversed_chars_at(start)
 3558                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3559                                .map(|c| c.len_utf8())
 3560                                .sum::<usize>();
 3561
 3562                            let trailing_whitespace_len = buffer
 3563                                .chars_at(end)
 3564                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3565                                .map(|c| c.len_utf8())
 3566                                .sum::<usize>();
 3567
 3568                            let insert_extra_newline =
 3569                                language.brackets().any(|(pair, enabled)| {
 3570                                    let pair_start = pair.start.trim_end();
 3571                                    let pair_end = pair.end.trim_start();
 3572
 3573                                    enabled
 3574                                        && pair.newline
 3575                                        && buffer.contains_str_at(
 3576                                            end + trailing_whitespace_len,
 3577                                            pair_end,
 3578                                        )
 3579                                        && buffer.contains_str_at(
 3580                                            (start - leading_whitespace_len)
 3581                                                .saturating_sub(pair_start.len()),
 3582                                            pair_start,
 3583                                        )
 3584                                });
 3585
 3586                            // Comment extension on newline is allowed only for cursor selections
 3587                            let comment_delimiter = maybe!({
 3588                                if !selection_is_empty {
 3589                                    return None;
 3590                                }
 3591
 3592                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3593                                    return None;
 3594                                }
 3595
 3596                                let delimiters = language.line_comment_prefixes();
 3597                                let max_len_of_delimiter =
 3598                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3599                                let (snapshot, range) =
 3600                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3601
 3602                                let mut index_of_first_non_whitespace = 0;
 3603                                let comment_candidate = snapshot
 3604                                    .chars_for_range(range)
 3605                                    .skip_while(|c| {
 3606                                        let should_skip = c.is_whitespace();
 3607                                        if should_skip {
 3608                                            index_of_first_non_whitespace += 1;
 3609                                        }
 3610                                        should_skip
 3611                                    })
 3612                                    .take(max_len_of_delimiter)
 3613                                    .collect::<String>();
 3614                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3615                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3616                                })?;
 3617                                let cursor_is_placed_after_comment_marker =
 3618                                    index_of_first_non_whitespace + comment_prefix.len()
 3619                                        <= start_point.column as usize;
 3620                                if cursor_is_placed_after_comment_marker {
 3621                                    Some(comment_prefix.clone())
 3622                                } else {
 3623                                    None
 3624                                }
 3625                            });
 3626                            (comment_delimiter, insert_extra_newline)
 3627                        } else {
 3628                            (None, false)
 3629                        };
 3630
 3631                        let capacity_for_delimiter = comment_delimiter
 3632                            .as_deref()
 3633                            .map(str::len)
 3634                            .unwrap_or_default();
 3635                        let mut new_text =
 3636                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3637                        new_text.push('\n');
 3638                        new_text.extend(indent.chars());
 3639                        if let Some(delimiter) = &comment_delimiter {
 3640                            new_text.push_str(delimiter);
 3641                        }
 3642                        if insert_extra_newline {
 3643                            new_text = new_text.repeat(2);
 3644                        }
 3645
 3646                        let anchor = buffer.anchor_after(end);
 3647                        let new_selection = selection.map(|_| anchor);
 3648                        (
 3649                            (start..end, new_text),
 3650                            (insert_extra_newline, new_selection),
 3651                        )
 3652                    })
 3653                    .unzip()
 3654            };
 3655
 3656            this.edit_with_autoindent(edits, cx);
 3657            let buffer = this.buffer.read(cx).snapshot(cx);
 3658            let new_selections = selection_fixup_info
 3659                .into_iter()
 3660                .map(|(extra_newline_inserted, new_selection)| {
 3661                    let mut cursor = new_selection.end.to_point(&buffer);
 3662                    if extra_newline_inserted {
 3663                        cursor.row -= 1;
 3664                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3665                    }
 3666                    new_selection.map(|_| cursor)
 3667                })
 3668                .collect();
 3669
 3670            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3671            this.refresh_inline_completion(true, false, cx);
 3672        });
 3673    }
 3674
 3675    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3676        let buffer = self.buffer.read(cx);
 3677        let snapshot = buffer.snapshot(cx);
 3678
 3679        let mut edits = Vec::new();
 3680        let mut rows = Vec::new();
 3681
 3682        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3683            let cursor = selection.head();
 3684            let row = cursor.row;
 3685
 3686            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3687
 3688            let newline = "\n".to_string();
 3689            edits.push((start_of_line..start_of_line, newline));
 3690
 3691            rows.push(row + rows_inserted as u32);
 3692        }
 3693
 3694        self.transact(cx, |editor, cx| {
 3695            editor.edit(edits, cx);
 3696
 3697            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3698                let mut index = 0;
 3699                s.move_cursors_with(|map, _, _| {
 3700                    let row = rows[index];
 3701                    index += 1;
 3702
 3703                    let point = Point::new(row, 0);
 3704                    let boundary = map.next_line_boundary(point).1;
 3705                    let clipped = map.clip_point(boundary, Bias::Left);
 3706
 3707                    (clipped, SelectionGoal::None)
 3708                });
 3709            });
 3710
 3711            let mut indent_edits = Vec::new();
 3712            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3713            for row in rows {
 3714                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3715                for (row, indent) in indents {
 3716                    if indent.len == 0 {
 3717                        continue;
 3718                    }
 3719
 3720                    let text = match indent.kind {
 3721                        IndentKind::Space => " ".repeat(indent.len as usize),
 3722                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3723                    };
 3724                    let point = Point::new(row.0, 0);
 3725                    indent_edits.push((point..point, text));
 3726                }
 3727            }
 3728            editor.edit(indent_edits, cx);
 3729        });
 3730    }
 3731
 3732    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3733        let buffer = self.buffer.read(cx);
 3734        let snapshot = buffer.snapshot(cx);
 3735
 3736        let mut edits = Vec::new();
 3737        let mut rows = Vec::new();
 3738        let mut rows_inserted = 0;
 3739
 3740        for selection in self.selections.all_adjusted(cx) {
 3741            let cursor = selection.head();
 3742            let row = cursor.row;
 3743
 3744            let point = Point::new(row + 1, 0);
 3745            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3746
 3747            let newline = "\n".to_string();
 3748            edits.push((start_of_line..start_of_line, newline));
 3749
 3750            rows_inserted += 1;
 3751            rows.push(row + rows_inserted);
 3752        }
 3753
 3754        self.transact(cx, |editor, cx| {
 3755            editor.edit(edits, cx);
 3756
 3757            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3758                let mut index = 0;
 3759                s.move_cursors_with(|map, _, _| {
 3760                    let row = rows[index];
 3761                    index += 1;
 3762
 3763                    let point = Point::new(row, 0);
 3764                    let boundary = map.next_line_boundary(point).1;
 3765                    let clipped = map.clip_point(boundary, Bias::Left);
 3766
 3767                    (clipped, SelectionGoal::None)
 3768                });
 3769            });
 3770
 3771            let mut indent_edits = Vec::new();
 3772            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3773            for row in rows {
 3774                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3775                for (row, indent) in indents {
 3776                    if indent.len == 0 {
 3777                        continue;
 3778                    }
 3779
 3780                    let text = match indent.kind {
 3781                        IndentKind::Space => " ".repeat(indent.len as usize),
 3782                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3783                    };
 3784                    let point = Point::new(row.0, 0);
 3785                    indent_edits.push((point..point, text));
 3786                }
 3787            }
 3788            editor.edit(indent_edits, cx);
 3789        });
 3790    }
 3791
 3792    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3793        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3794            original_indent_columns: Vec::new(),
 3795        });
 3796        self.insert_with_autoindent_mode(text, autoindent, cx);
 3797    }
 3798
 3799    fn insert_with_autoindent_mode(
 3800        &mut self,
 3801        text: &str,
 3802        autoindent_mode: Option<AutoindentMode>,
 3803        cx: &mut ViewContext<Self>,
 3804    ) {
 3805        if self.read_only(cx) {
 3806            return;
 3807        }
 3808
 3809        let text: Arc<str> = text.into();
 3810        self.transact(cx, |this, cx| {
 3811            let old_selections = this.selections.all_adjusted(cx);
 3812            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3813                let anchors = {
 3814                    let snapshot = buffer.read(cx);
 3815                    old_selections
 3816                        .iter()
 3817                        .map(|s| {
 3818                            let anchor = snapshot.anchor_after(s.head());
 3819                            s.map(|_| anchor)
 3820                        })
 3821                        .collect::<Vec<_>>()
 3822                };
 3823                buffer.edit(
 3824                    old_selections
 3825                        .iter()
 3826                        .map(|s| (s.start..s.end, text.clone())),
 3827                    autoindent_mode,
 3828                    cx,
 3829                );
 3830                anchors
 3831            });
 3832
 3833            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3834                s.select_anchors(selection_anchors);
 3835            })
 3836        });
 3837    }
 3838
 3839    fn trigger_completion_on_input(
 3840        &mut self,
 3841        text: &str,
 3842        trigger_in_words: bool,
 3843        cx: &mut ViewContext<Self>,
 3844    ) {
 3845        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3846            self.show_completions(
 3847                &ShowCompletions {
 3848                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3849                },
 3850                cx,
 3851            );
 3852        } else {
 3853            self.hide_context_menu(cx);
 3854        }
 3855    }
 3856
 3857    fn is_completion_trigger(
 3858        &self,
 3859        text: &str,
 3860        trigger_in_words: bool,
 3861        cx: &mut ViewContext<Self>,
 3862    ) -> bool {
 3863        let position = self.selections.newest_anchor().head();
 3864        let multibuffer = self.buffer.read(cx);
 3865        let Some(buffer) = position
 3866            .buffer_id
 3867            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3868        else {
 3869            return false;
 3870        };
 3871
 3872        if let Some(completion_provider) = &self.completion_provider {
 3873            completion_provider.is_completion_trigger(
 3874                &buffer,
 3875                position.text_anchor,
 3876                text,
 3877                trigger_in_words,
 3878                cx,
 3879            )
 3880        } else {
 3881            false
 3882        }
 3883    }
 3884
 3885    /// If any empty selections is touching the start of its innermost containing autoclose
 3886    /// region, expand it to select the brackets.
 3887    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3888        let selections = self.selections.all::<usize>(cx);
 3889        let buffer = self.buffer.read(cx).read(cx);
 3890        let new_selections = self
 3891            .selections_with_autoclose_regions(selections, &buffer)
 3892            .map(|(mut selection, region)| {
 3893                if !selection.is_empty() {
 3894                    return selection;
 3895                }
 3896
 3897                if let Some(region) = region {
 3898                    let mut range = region.range.to_offset(&buffer);
 3899                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3900                        range.start -= region.pair.start.len();
 3901                        if buffer.contains_str_at(range.start, &region.pair.start)
 3902                            && buffer.contains_str_at(range.end, &region.pair.end)
 3903                        {
 3904                            range.end += region.pair.end.len();
 3905                            selection.start = range.start;
 3906                            selection.end = range.end;
 3907
 3908                            return selection;
 3909                        }
 3910                    }
 3911                }
 3912
 3913                let always_treat_brackets_as_autoclosed = buffer
 3914                    .settings_at(selection.start, cx)
 3915                    .always_treat_brackets_as_autoclosed;
 3916
 3917                if !always_treat_brackets_as_autoclosed {
 3918                    return selection;
 3919                }
 3920
 3921                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3922                    for (pair, enabled) in scope.brackets() {
 3923                        if !enabled || !pair.close {
 3924                            continue;
 3925                        }
 3926
 3927                        if buffer.contains_str_at(selection.start, &pair.end) {
 3928                            let pair_start_len = pair.start.len();
 3929                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3930                            {
 3931                                selection.start -= pair_start_len;
 3932                                selection.end += pair.end.len();
 3933
 3934                                return selection;
 3935                            }
 3936                        }
 3937                    }
 3938                }
 3939
 3940                selection
 3941            })
 3942            .collect();
 3943
 3944        drop(buffer);
 3945        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3946    }
 3947
 3948    /// Iterate the given selections, and for each one, find the smallest surrounding
 3949    /// autoclose region. This uses the ordering of the selections and the autoclose
 3950    /// regions to avoid repeated comparisons.
 3951    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3952        &'a self,
 3953        selections: impl IntoIterator<Item = Selection<D>>,
 3954        buffer: &'a MultiBufferSnapshot,
 3955    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3956        let mut i = 0;
 3957        let mut regions = self.autoclose_regions.as_slice();
 3958        selections.into_iter().map(move |selection| {
 3959            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3960
 3961            let mut enclosing = None;
 3962            while let Some(pair_state) = regions.get(i) {
 3963                if pair_state.range.end.to_offset(buffer) < range.start {
 3964                    regions = &regions[i + 1..];
 3965                    i = 0;
 3966                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3967                    break;
 3968                } else {
 3969                    if pair_state.selection_id == selection.id {
 3970                        enclosing = Some(pair_state);
 3971                    }
 3972                    i += 1;
 3973                }
 3974            }
 3975
 3976            (selection.clone(), enclosing)
 3977        })
 3978    }
 3979
 3980    /// Remove any autoclose regions that no longer contain their selection.
 3981    fn invalidate_autoclose_regions(
 3982        &mut self,
 3983        mut selections: &[Selection<Anchor>],
 3984        buffer: &MultiBufferSnapshot,
 3985    ) {
 3986        self.autoclose_regions.retain(|state| {
 3987            let mut i = 0;
 3988            while let Some(selection) = selections.get(i) {
 3989                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3990                    selections = &selections[1..];
 3991                    continue;
 3992                }
 3993                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3994                    break;
 3995                }
 3996                if selection.id == state.selection_id {
 3997                    return true;
 3998                } else {
 3999                    i += 1;
 4000                }
 4001            }
 4002            false
 4003        });
 4004    }
 4005
 4006    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4007        let offset = position.to_offset(buffer);
 4008        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4009        if offset > word_range.start && kind == Some(CharKind::Word) {
 4010            Some(
 4011                buffer
 4012                    .text_for_range(word_range.start..offset)
 4013                    .collect::<String>(),
 4014            )
 4015        } else {
 4016            None
 4017        }
 4018    }
 4019
 4020    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4021        self.refresh_inlay_hints(
 4022            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4023            cx,
 4024        );
 4025    }
 4026
 4027    pub fn inlay_hints_enabled(&self) -> bool {
 4028        self.inlay_hint_cache.enabled
 4029    }
 4030
 4031    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4032        if self.project.is_none() || self.mode != EditorMode::Full {
 4033            return;
 4034        }
 4035
 4036        let reason_description = reason.description();
 4037        let ignore_debounce = matches!(
 4038            reason,
 4039            InlayHintRefreshReason::SettingsChange(_)
 4040                | InlayHintRefreshReason::Toggle(_)
 4041                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4042        );
 4043        let (invalidate_cache, required_languages) = match reason {
 4044            InlayHintRefreshReason::Toggle(enabled) => {
 4045                self.inlay_hint_cache.enabled = enabled;
 4046                if enabled {
 4047                    (InvalidationStrategy::RefreshRequested, None)
 4048                } else {
 4049                    self.inlay_hint_cache.clear();
 4050                    self.splice_inlays(
 4051                        self.visible_inlay_hints(cx)
 4052                            .iter()
 4053                            .map(|inlay| inlay.id)
 4054                            .collect(),
 4055                        Vec::new(),
 4056                        cx,
 4057                    );
 4058                    return;
 4059                }
 4060            }
 4061            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4062                match self.inlay_hint_cache.update_settings(
 4063                    &self.buffer,
 4064                    new_settings,
 4065                    self.visible_inlay_hints(cx),
 4066                    cx,
 4067                ) {
 4068                    ControlFlow::Break(Some(InlaySplice {
 4069                        to_remove,
 4070                        to_insert,
 4071                    })) => {
 4072                        self.splice_inlays(to_remove, to_insert, cx);
 4073                        return;
 4074                    }
 4075                    ControlFlow::Break(None) => return,
 4076                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4077                }
 4078            }
 4079            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4080                if let Some(InlaySplice {
 4081                    to_remove,
 4082                    to_insert,
 4083                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4084                {
 4085                    self.splice_inlays(to_remove, to_insert, cx);
 4086                }
 4087                return;
 4088            }
 4089            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4090            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4091                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4092            }
 4093            InlayHintRefreshReason::RefreshRequested => {
 4094                (InvalidationStrategy::RefreshRequested, None)
 4095            }
 4096        };
 4097
 4098        if let Some(InlaySplice {
 4099            to_remove,
 4100            to_insert,
 4101        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4102            reason_description,
 4103            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4104            invalidate_cache,
 4105            ignore_debounce,
 4106            cx,
 4107        ) {
 4108            self.splice_inlays(to_remove, to_insert, cx);
 4109        }
 4110    }
 4111
 4112    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4113        self.display_map
 4114            .read(cx)
 4115            .current_inlays()
 4116            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4117            .cloned()
 4118            .collect()
 4119    }
 4120
 4121    pub fn excerpts_for_inlay_hints_query(
 4122        &self,
 4123        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4124        cx: &mut ViewContext<Editor>,
 4125    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4126        let Some(project) = self.project.as_ref() else {
 4127            return HashMap::default();
 4128        };
 4129        let project = project.read(cx);
 4130        let multi_buffer = self.buffer().read(cx);
 4131        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4132        let multi_buffer_visible_start = self
 4133            .scroll_manager
 4134            .anchor()
 4135            .anchor
 4136            .to_point(&multi_buffer_snapshot);
 4137        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4138            multi_buffer_visible_start
 4139                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4140            Bias::Left,
 4141        );
 4142        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4143        multi_buffer
 4144            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4145            .into_iter()
 4146            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4147            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4148                let buffer = buffer_handle.read(cx);
 4149                let buffer_file = project::File::from_dyn(buffer.file())?;
 4150                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4151                let worktree_entry = buffer_worktree
 4152                    .read(cx)
 4153                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4154                if worktree_entry.is_ignored {
 4155                    return None;
 4156                }
 4157
 4158                let language = buffer.language()?;
 4159                if let Some(restrict_to_languages) = restrict_to_languages {
 4160                    if !restrict_to_languages.contains(language) {
 4161                        return None;
 4162                    }
 4163                }
 4164                Some((
 4165                    excerpt_id,
 4166                    (
 4167                        buffer_handle,
 4168                        buffer.version().clone(),
 4169                        excerpt_visible_range,
 4170                    ),
 4171                ))
 4172            })
 4173            .collect()
 4174    }
 4175
 4176    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4177        TextLayoutDetails {
 4178            text_system: cx.text_system().clone(),
 4179            editor_style: self.style.clone().unwrap(),
 4180            rem_size: cx.rem_size(),
 4181            scroll_anchor: self.scroll_manager.anchor(),
 4182            visible_rows: self.visible_line_count(),
 4183            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4184        }
 4185    }
 4186
 4187    fn splice_inlays(
 4188        &self,
 4189        to_remove: Vec<InlayId>,
 4190        to_insert: Vec<Inlay>,
 4191        cx: &mut ViewContext<Self>,
 4192    ) {
 4193        self.display_map.update(cx, |display_map, cx| {
 4194            display_map.splice_inlays(to_remove, to_insert, cx);
 4195        });
 4196        cx.notify();
 4197    }
 4198
 4199    fn trigger_on_type_formatting(
 4200        &self,
 4201        input: String,
 4202        cx: &mut ViewContext<Self>,
 4203    ) -> Option<Task<Result<()>>> {
 4204        if input.len() != 1 {
 4205            return None;
 4206        }
 4207
 4208        let project = self.project.as_ref()?;
 4209        let position = self.selections.newest_anchor().head();
 4210        let (buffer, buffer_position) = self
 4211            .buffer
 4212            .read(cx)
 4213            .text_anchor_for_position(position, cx)?;
 4214
 4215        let settings = language_settings::language_settings(
 4216            buffer.read(cx).language_at(buffer_position).as_ref(),
 4217            buffer.read(cx).file(),
 4218            cx,
 4219        );
 4220        if !settings.use_on_type_format {
 4221            return None;
 4222        }
 4223
 4224        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4225        // hence we do LSP request & edit on host side only — add formats to host's history.
 4226        let push_to_lsp_host_history = true;
 4227        // If this is not the host, append its history with new edits.
 4228        let push_to_client_history = project.read(cx).is_via_collab();
 4229
 4230        let on_type_formatting = project.update(cx, |project, cx| {
 4231            project.on_type_format(
 4232                buffer.clone(),
 4233                buffer_position,
 4234                input,
 4235                push_to_lsp_host_history,
 4236                cx,
 4237            )
 4238        });
 4239        Some(cx.spawn(|editor, mut cx| async move {
 4240            if let Some(transaction) = on_type_formatting.await? {
 4241                if push_to_client_history {
 4242                    buffer
 4243                        .update(&mut cx, |buffer, _| {
 4244                            buffer.push_transaction(transaction, Instant::now());
 4245                        })
 4246                        .ok();
 4247                }
 4248                editor.update(&mut cx, |editor, cx| {
 4249                    editor.refresh_document_highlights(cx);
 4250                })?;
 4251            }
 4252            Ok(())
 4253        }))
 4254    }
 4255
 4256    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4257        if self.pending_rename.is_some() {
 4258            return;
 4259        }
 4260
 4261        let Some(provider) = self.completion_provider.as_ref() else {
 4262            return;
 4263        };
 4264
 4265        let position = self.selections.newest_anchor().head();
 4266        let (buffer, buffer_position) =
 4267            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4268                output
 4269            } else {
 4270                return;
 4271            };
 4272
 4273        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4274        let is_followup_invoke = {
 4275            let context_menu_state = self.context_menu.read();
 4276            matches!(
 4277                context_menu_state.deref(),
 4278                Some(ContextMenu::Completions(_))
 4279            )
 4280        };
 4281        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4282            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4283            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4284                CompletionTriggerKind::TRIGGER_CHARACTER
 4285            }
 4286
 4287            _ => CompletionTriggerKind::INVOKED,
 4288        };
 4289        let completion_context = CompletionContext {
 4290            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4291                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4292                    Some(String::from(trigger))
 4293                } else {
 4294                    None
 4295                }
 4296            }),
 4297            trigger_kind,
 4298        };
 4299        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4300        let sort_completions = provider.sort_completions();
 4301
 4302        let id = post_inc(&mut self.next_completion_id);
 4303        let task = cx.spawn(|this, mut cx| {
 4304            async move {
 4305                this.update(&mut cx, |this, _| {
 4306                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4307                })?;
 4308                let completions = completions.await.log_err();
 4309                let menu = if let Some(completions) = completions {
 4310                    let mut menu = CompletionsMenu {
 4311                        id,
 4312                        sort_completions,
 4313                        initial_position: position,
 4314                        match_candidates: completions
 4315                            .iter()
 4316                            .enumerate()
 4317                            .map(|(id, completion)| {
 4318                                StringMatchCandidate::new(
 4319                                    id,
 4320                                    completion.label.text[completion.label.filter_range.clone()]
 4321                                        .into(),
 4322                                )
 4323                            })
 4324                            .collect(),
 4325                        buffer: buffer.clone(),
 4326                        completions: Arc::new(RwLock::new(completions.into())),
 4327                        matches: Vec::new().into(),
 4328                        selected_item: 0,
 4329                        scroll_handle: UniformListScrollHandle::new(),
 4330                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4331                            DebouncedDelay::new(),
 4332                        )),
 4333                    };
 4334                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4335                        .await;
 4336
 4337                    if menu.matches.is_empty() {
 4338                        None
 4339                    } else {
 4340                        this.update(&mut cx, |editor, cx| {
 4341                            let completions = menu.completions.clone();
 4342                            let matches = menu.matches.clone();
 4343
 4344                            let delay_ms = EditorSettings::get_global(cx)
 4345                                .completion_documentation_secondary_query_debounce;
 4346                            let delay = Duration::from_millis(delay_ms);
 4347                            editor
 4348                                .completion_documentation_pre_resolve_debounce
 4349                                .fire_new(delay, cx, |editor, cx| {
 4350                                    CompletionsMenu::pre_resolve_completion_documentation(
 4351                                        buffer,
 4352                                        completions,
 4353                                        matches,
 4354                                        editor,
 4355                                        cx,
 4356                                    )
 4357                                });
 4358                        })
 4359                        .ok();
 4360                        Some(menu)
 4361                    }
 4362                } else {
 4363                    None
 4364                };
 4365
 4366                this.update(&mut cx, |this, cx| {
 4367                    let mut context_menu = this.context_menu.write();
 4368                    match context_menu.as_ref() {
 4369                        None => {}
 4370
 4371                        Some(ContextMenu::Completions(prev_menu)) => {
 4372                            if prev_menu.id > id {
 4373                                return;
 4374                            }
 4375                        }
 4376
 4377                        _ => return,
 4378                    }
 4379
 4380                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4381                        let menu = menu.unwrap();
 4382                        *context_menu = Some(ContextMenu::Completions(menu));
 4383                        drop(context_menu);
 4384                        this.discard_inline_completion(false, cx);
 4385                        cx.notify();
 4386                    } else if this.completion_tasks.len() <= 1 {
 4387                        // If there are no more completion tasks and the last menu was
 4388                        // empty, we should hide it. If it was already hidden, we should
 4389                        // also show the copilot completion when available.
 4390                        drop(context_menu);
 4391                        if this.hide_context_menu(cx).is_none() {
 4392                            this.update_visible_inline_completion(cx);
 4393                        }
 4394                    }
 4395                })?;
 4396
 4397                Ok::<_, anyhow::Error>(())
 4398            }
 4399            .log_err()
 4400        });
 4401
 4402        self.completion_tasks.push((id, task));
 4403    }
 4404
 4405    pub fn confirm_completion(
 4406        &mut self,
 4407        action: &ConfirmCompletion,
 4408        cx: &mut ViewContext<Self>,
 4409    ) -> Option<Task<Result<()>>> {
 4410        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4411    }
 4412
 4413    pub fn compose_completion(
 4414        &mut self,
 4415        action: &ComposeCompletion,
 4416        cx: &mut ViewContext<Self>,
 4417    ) -> Option<Task<Result<()>>> {
 4418        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4419    }
 4420
 4421    fn do_completion(
 4422        &mut self,
 4423        item_ix: Option<usize>,
 4424        intent: CompletionIntent,
 4425        cx: &mut ViewContext<Editor>,
 4426    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4427        use language::ToOffset as _;
 4428
 4429        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4430            menu
 4431        } else {
 4432            return None;
 4433        };
 4434
 4435        let mat = completions_menu
 4436            .matches
 4437            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4438        let buffer_handle = completions_menu.buffer;
 4439        let completions = completions_menu.completions.read();
 4440        let completion = completions.get(mat.candidate_id)?;
 4441        cx.stop_propagation();
 4442
 4443        let snippet;
 4444        let text;
 4445
 4446        if completion.is_snippet() {
 4447            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4448            text = snippet.as_ref().unwrap().text.clone();
 4449        } else {
 4450            snippet = None;
 4451            text = completion.new_text.clone();
 4452        };
 4453        let selections = self.selections.all::<usize>(cx);
 4454        let buffer = buffer_handle.read(cx);
 4455        let old_range = completion.old_range.to_offset(buffer);
 4456        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4457
 4458        let newest_selection = self.selections.newest_anchor();
 4459        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4460            return None;
 4461        }
 4462
 4463        let lookbehind = newest_selection
 4464            .start
 4465            .text_anchor
 4466            .to_offset(buffer)
 4467            .saturating_sub(old_range.start);
 4468        let lookahead = old_range
 4469            .end
 4470            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4471        let mut common_prefix_len = old_text
 4472            .bytes()
 4473            .zip(text.bytes())
 4474            .take_while(|(a, b)| a == b)
 4475            .count();
 4476
 4477        let snapshot = self.buffer.read(cx).snapshot(cx);
 4478        let mut range_to_replace: Option<Range<isize>> = None;
 4479        let mut ranges = Vec::new();
 4480        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4481        for selection in &selections {
 4482            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4483                let start = selection.start.saturating_sub(lookbehind);
 4484                let end = selection.end + lookahead;
 4485                if selection.id == newest_selection.id {
 4486                    range_to_replace = Some(
 4487                        ((start + common_prefix_len) as isize - selection.start as isize)
 4488                            ..(end as isize - selection.start as isize),
 4489                    );
 4490                }
 4491                ranges.push(start + common_prefix_len..end);
 4492            } else {
 4493                common_prefix_len = 0;
 4494                ranges.clear();
 4495                ranges.extend(selections.iter().map(|s| {
 4496                    if s.id == newest_selection.id {
 4497                        range_to_replace = Some(
 4498                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4499                                - selection.start as isize
 4500                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4501                                    - selection.start as isize,
 4502                        );
 4503                        old_range.clone()
 4504                    } else {
 4505                        s.start..s.end
 4506                    }
 4507                }));
 4508                break;
 4509            }
 4510            if !self.linked_edit_ranges.is_empty() {
 4511                let start_anchor = snapshot.anchor_before(selection.head());
 4512                let end_anchor = snapshot.anchor_after(selection.tail());
 4513                if let Some(ranges) = self
 4514                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4515                {
 4516                    for (buffer, edits) in ranges {
 4517                        linked_edits.entry(buffer.clone()).or_default().extend(
 4518                            edits
 4519                                .into_iter()
 4520                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4521                        );
 4522                    }
 4523                }
 4524            }
 4525        }
 4526        let text = &text[common_prefix_len..];
 4527
 4528        cx.emit(EditorEvent::InputHandled {
 4529            utf16_range_to_replace: range_to_replace,
 4530            text: text.into(),
 4531        });
 4532
 4533        self.transact(cx, |this, cx| {
 4534            if let Some(mut snippet) = snippet {
 4535                snippet.text = text.to_string();
 4536                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4537                    tabstop.start -= common_prefix_len as isize;
 4538                    tabstop.end -= common_prefix_len as isize;
 4539                }
 4540
 4541                this.insert_snippet(&ranges, snippet, cx).log_err();
 4542            } else {
 4543                this.buffer.update(cx, |buffer, cx| {
 4544                    buffer.edit(
 4545                        ranges.iter().map(|range| (range.clone(), text)),
 4546                        this.autoindent_mode.clone(),
 4547                        cx,
 4548                    );
 4549                });
 4550            }
 4551            for (buffer, edits) in linked_edits {
 4552                buffer.update(cx, |buffer, cx| {
 4553                    let snapshot = buffer.snapshot();
 4554                    let edits = edits
 4555                        .into_iter()
 4556                        .map(|(range, text)| {
 4557                            use text::ToPoint as TP;
 4558                            let end_point = TP::to_point(&range.end, &snapshot);
 4559                            let start_point = TP::to_point(&range.start, &snapshot);
 4560                            (start_point..end_point, text)
 4561                        })
 4562                        .sorted_by_key(|(range, _)| range.start)
 4563                        .collect::<Vec<_>>();
 4564                    buffer.edit(edits, None, cx);
 4565                })
 4566            }
 4567
 4568            this.refresh_inline_completion(true, false, cx);
 4569        });
 4570
 4571        let show_new_completions_on_confirm = completion
 4572            .confirm
 4573            .as_ref()
 4574            .map_or(false, |confirm| confirm(intent, cx));
 4575        if show_new_completions_on_confirm {
 4576            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4577        }
 4578
 4579        let provider = self.completion_provider.as_ref()?;
 4580        let apply_edits = provider.apply_additional_edits_for_completion(
 4581            buffer_handle,
 4582            completion.clone(),
 4583            true,
 4584            cx,
 4585        );
 4586
 4587        let editor_settings = EditorSettings::get_global(cx);
 4588        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4589            // After the code completion is finished, users often want to know what signatures are needed.
 4590            // so we should automatically call signature_help
 4591            self.show_signature_help(&ShowSignatureHelp, cx);
 4592        }
 4593
 4594        Some(cx.foreground_executor().spawn(async move {
 4595            apply_edits.await?;
 4596            Ok(())
 4597        }))
 4598    }
 4599
 4600    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4601        let mut context_menu = self.context_menu.write();
 4602        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4603            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4604                // Toggle if we're selecting the same one
 4605                *context_menu = None;
 4606                cx.notify();
 4607                return;
 4608            } else {
 4609                // Otherwise, clear it and start a new one
 4610                *context_menu = None;
 4611                cx.notify();
 4612            }
 4613        }
 4614        drop(context_menu);
 4615        let snapshot = self.snapshot(cx);
 4616        let deployed_from_indicator = action.deployed_from_indicator;
 4617        let mut task = self.code_actions_task.take();
 4618        let action = action.clone();
 4619        cx.spawn(|editor, mut cx| async move {
 4620            while let Some(prev_task) = task {
 4621                prev_task.await.log_err();
 4622                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4623            }
 4624
 4625            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4626                if editor.focus_handle.is_focused(cx) {
 4627                    let multibuffer_point = action
 4628                        .deployed_from_indicator
 4629                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4630                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4631                    let (buffer, buffer_row) = snapshot
 4632                        .buffer_snapshot
 4633                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4634                        .and_then(|(buffer_snapshot, range)| {
 4635                            editor
 4636                                .buffer
 4637                                .read(cx)
 4638                                .buffer(buffer_snapshot.remote_id())
 4639                                .map(|buffer| (buffer, range.start.row))
 4640                        })?;
 4641                    let (_, code_actions) = editor
 4642                        .available_code_actions
 4643                        .clone()
 4644                        .and_then(|(location, code_actions)| {
 4645                            let snapshot = location.buffer.read(cx).snapshot();
 4646                            let point_range = location.range.to_point(&snapshot);
 4647                            let point_range = point_range.start.row..=point_range.end.row;
 4648                            if point_range.contains(&buffer_row) {
 4649                                Some((location, code_actions))
 4650                            } else {
 4651                                None
 4652                            }
 4653                        })
 4654                        .unzip();
 4655                    let buffer_id = buffer.read(cx).remote_id();
 4656                    let tasks = editor
 4657                        .tasks
 4658                        .get(&(buffer_id, buffer_row))
 4659                        .map(|t| Arc::new(t.to_owned()));
 4660                    if tasks.is_none() && code_actions.is_none() {
 4661                        return None;
 4662                    }
 4663
 4664                    editor.completion_tasks.clear();
 4665                    editor.discard_inline_completion(false, cx);
 4666                    let task_context =
 4667                        tasks
 4668                            .as_ref()
 4669                            .zip(editor.project.clone())
 4670                            .map(|(tasks, project)| {
 4671                                let position = Point::new(buffer_row, tasks.column);
 4672                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4673                                let location = Location {
 4674                                    buffer: buffer.clone(),
 4675                                    range: range_start..range_start,
 4676                                };
 4677                                // Fill in the environmental variables from the tree-sitter captures
 4678                                let mut captured_task_variables = TaskVariables::default();
 4679                                for (capture_name, value) in tasks.extra_variables.clone() {
 4680                                    captured_task_variables.insert(
 4681                                        task::VariableName::Custom(capture_name.into()),
 4682                                        value.clone(),
 4683                                    );
 4684                                }
 4685                                project.update(cx, |project, cx| {
 4686                                    project.task_context_for_location(
 4687                                        captured_task_variables,
 4688                                        location,
 4689                                        cx,
 4690                                    )
 4691                                })
 4692                            });
 4693
 4694                    Some(cx.spawn(|editor, mut cx| async move {
 4695                        let task_context = match task_context {
 4696                            Some(task_context) => task_context.await,
 4697                            None => None,
 4698                        };
 4699                        let resolved_tasks =
 4700                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4701                                Arc::new(ResolvedTasks {
 4702                                    templates: tasks
 4703                                        .templates
 4704                                        .iter()
 4705                                        .filter_map(|(kind, template)| {
 4706                                            template
 4707                                                .resolve_task(&kind.to_id_base(), &task_context)
 4708                                                .map(|task| (kind.clone(), task))
 4709                                        })
 4710                                        .collect(),
 4711                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4712                                        multibuffer_point.row,
 4713                                        tasks.column,
 4714                                    )),
 4715                                })
 4716                            });
 4717                        let spawn_straight_away = resolved_tasks
 4718                            .as_ref()
 4719                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4720                            && code_actions
 4721                                .as_ref()
 4722                                .map_or(true, |actions| actions.is_empty());
 4723                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4724                            *editor.context_menu.write() =
 4725                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4726                                    buffer,
 4727                                    actions: CodeActionContents {
 4728                                        tasks: resolved_tasks,
 4729                                        actions: code_actions,
 4730                                    },
 4731                                    selected_item: Default::default(),
 4732                                    scroll_handle: UniformListScrollHandle::default(),
 4733                                    deployed_from_indicator,
 4734                                }));
 4735                            if spawn_straight_away {
 4736                                if let Some(task) = editor.confirm_code_action(
 4737                                    &ConfirmCodeAction { item_ix: Some(0) },
 4738                                    cx,
 4739                                ) {
 4740                                    cx.notify();
 4741                                    return task;
 4742                                }
 4743                            }
 4744                            cx.notify();
 4745                            Task::ready(Ok(()))
 4746                        }) {
 4747                            task.await
 4748                        } else {
 4749                            Ok(())
 4750                        }
 4751                    }))
 4752                } else {
 4753                    Some(Task::ready(Ok(())))
 4754                }
 4755            })?;
 4756            if let Some(task) = spawned_test_task {
 4757                task.await?;
 4758            }
 4759
 4760            Ok::<_, anyhow::Error>(())
 4761        })
 4762        .detach_and_log_err(cx);
 4763    }
 4764
 4765    pub fn confirm_code_action(
 4766        &mut self,
 4767        action: &ConfirmCodeAction,
 4768        cx: &mut ViewContext<Self>,
 4769    ) -> Option<Task<Result<()>>> {
 4770        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4771            menu
 4772        } else {
 4773            return None;
 4774        };
 4775        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4776        let action = actions_menu.actions.get(action_ix)?;
 4777        let title = action.label();
 4778        let buffer = actions_menu.buffer;
 4779        let workspace = self.workspace()?;
 4780
 4781        match action {
 4782            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4783                workspace.update(cx, |workspace, cx| {
 4784                    workspace::tasks::schedule_resolved_task(
 4785                        workspace,
 4786                        task_source_kind,
 4787                        resolved_task,
 4788                        false,
 4789                        cx,
 4790                    );
 4791
 4792                    Some(Task::ready(Ok(())))
 4793                })
 4794            }
 4795            CodeActionsItem::CodeAction {
 4796                excerpt_id,
 4797                action,
 4798                provider,
 4799            } => {
 4800                let apply_code_action =
 4801                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4802                let workspace = workspace.downgrade();
 4803                Some(cx.spawn(|editor, cx| async move {
 4804                    let project_transaction = apply_code_action.await?;
 4805                    Self::open_project_transaction(
 4806                        &editor,
 4807                        workspace,
 4808                        project_transaction,
 4809                        title,
 4810                        cx,
 4811                    )
 4812                    .await
 4813                }))
 4814            }
 4815        }
 4816    }
 4817
 4818    pub async fn open_project_transaction(
 4819        this: &WeakView<Editor>,
 4820        workspace: WeakView<Workspace>,
 4821        transaction: ProjectTransaction,
 4822        title: String,
 4823        mut cx: AsyncWindowContext,
 4824    ) -> Result<()> {
 4825        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4826        cx.update(|cx| {
 4827            entries.sort_unstable_by_key(|(buffer, _)| {
 4828                buffer.read(cx).file().map(|f| f.path().clone())
 4829            });
 4830        })?;
 4831
 4832        // If the project transaction's edits are all contained within this editor, then
 4833        // avoid opening a new editor to display them.
 4834
 4835        if let Some((buffer, transaction)) = entries.first() {
 4836            if entries.len() == 1 {
 4837                let excerpt = this.update(&mut cx, |editor, cx| {
 4838                    editor
 4839                        .buffer()
 4840                        .read(cx)
 4841                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4842                })?;
 4843                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4844                    if excerpted_buffer == *buffer {
 4845                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4846                            let excerpt_range = excerpt_range.to_offset(buffer);
 4847                            buffer
 4848                                .edited_ranges_for_transaction::<usize>(transaction)
 4849                                .all(|range| {
 4850                                    excerpt_range.start <= range.start
 4851                                        && excerpt_range.end >= range.end
 4852                                })
 4853                        })?;
 4854
 4855                        if all_edits_within_excerpt {
 4856                            return Ok(());
 4857                        }
 4858                    }
 4859                }
 4860            }
 4861        } else {
 4862            return Ok(());
 4863        }
 4864
 4865        let mut ranges_to_highlight = Vec::new();
 4866        let excerpt_buffer = cx.new_model(|cx| {
 4867            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4868            for (buffer_handle, transaction) in &entries {
 4869                let buffer = buffer_handle.read(cx);
 4870                ranges_to_highlight.extend(
 4871                    multibuffer.push_excerpts_with_context_lines(
 4872                        buffer_handle.clone(),
 4873                        buffer
 4874                            .edited_ranges_for_transaction::<usize>(transaction)
 4875                            .collect(),
 4876                        DEFAULT_MULTIBUFFER_CONTEXT,
 4877                        cx,
 4878                    ),
 4879                );
 4880            }
 4881            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4882            multibuffer
 4883        })?;
 4884
 4885        workspace.update(&mut cx, |workspace, cx| {
 4886            let project = workspace.project().clone();
 4887            let editor =
 4888                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4889            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4890            editor.update(cx, |editor, cx| {
 4891                editor.highlight_background::<Self>(
 4892                    &ranges_to_highlight,
 4893                    |theme| theme.editor_highlighted_line_background,
 4894                    cx,
 4895                );
 4896            });
 4897        })?;
 4898
 4899        Ok(())
 4900    }
 4901
 4902    pub fn push_code_action_provider(
 4903        &mut self,
 4904        provider: Arc<dyn CodeActionProvider>,
 4905        cx: &mut ViewContext<Self>,
 4906    ) {
 4907        self.code_action_providers.push(provider);
 4908        self.refresh_code_actions(cx);
 4909    }
 4910
 4911    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4912        let buffer = self.buffer.read(cx);
 4913        let newest_selection = self.selections.newest_anchor().clone();
 4914        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4915        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4916        if start_buffer != end_buffer {
 4917            return None;
 4918        }
 4919
 4920        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4921            cx.background_executor()
 4922                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4923                .await;
 4924
 4925            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4926                let providers = this.code_action_providers.clone();
 4927                let tasks = this
 4928                    .code_action_providers
 4929                    .iter()
 4930                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4931                    .collect::<Vec<_>>();
 4932                (providers, tasks)
 4933            })?;
 4934
 4935            let mut actions = Vec::new();
 4936            for (provider, provider_actions) in
 4937                providers.into_iter().zip(future::join_all(tasks).await)
 4938            {
 4939                if let Some(provider_actions) = provider_actions.log_err() {
 4940                    actions.extend(provider_actions.into_iter().map(|action| {
 4941                        AvailableCodeAction {
 4942                            excerpt_id: newest_selection.start.excerpt_id,
 4943                            action,
 4944                            provider: provider.clone(),
 4945                        }
 4946                    }));
 4947                }
 4948            }
 4949
 4950            this.update(&mut cx, |this, cx| {
 4951                this.available_code_actions = if actions.is_empty() {
 4952                    None
 4953                } else {
 4954                    Some((
 4955                        Location {
 4956                            buffer: start_buffer,
 4957                            range: start..end,
 4958                        },
 4959                        actions.into(),
 4960                    ))
 4961                };
 4962                cx.notify();
 4963            })
 4964        }));
 4965        None
 4966    }
 4967
 4968    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4969        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4970            self.show_git_blame_inline = false;
 4971
 4972            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4973                cx.background_executor().timer(delay).await;
 4974
 4975                this.update(&mut cx, |this, cx| {
 4976                    this.show_git_blame_inline = true;
 4977                    cx.notify();
 4978                })
 4979                .log_err();
 4980            }));
 4981        }
 4982    }
 4983
 4984    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4985        if self.pending_rename.is_some() {
 4986            return None;
 4987        }
 4988
 4989        let project = self.project.clone()?;
 4990        let buffer = self.buffer.read(cx);
 4991        let newest_selection = self.selections.newest_anchor().clone();
 4992        let cursor_position = newest_selection.head();
 4993        let (cursor_buffer, cursor_buffer_position) =
 4994            buffer.text_anchor_for_position(cursor_position, cx)?;
 4995        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4996        if cursor_buffer != tail_buffer {
 4997            return None;
 4998        }
 4999
 5000        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5001            cx.background_executor()
 5002                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5003                .await;
 5004
 5005            let highlights = if let Some(highlights) = project
 5006                .update(&mut cx, |project, cx| {
 5007                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5008                })
 5009                .log_err()
 5010            {
 5011                highlights.await.log_err()
 5012            } else {
 5013                None
 5014            };
 5015
 5016            if let Some(highlights) = highlights {
 5017                this.update(&mut cx, |this, cx| {
 5018                    if this.pending_rename.is_some() {
 5019                        return;
 5020                    }
 5021
 5022                    let buffer_id = cursor_position.buffer_id;
 5023                    let buffer = this.buffer.read(cx);
 5024                    if !buffer
 5025                        .text_anchor_for_position(cursor_position, cx)
 5026                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5027                    {
 5028                        return;
 5029                    }
 5030
 5031                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5032                    let mut write_ranges = Vec::new();
 5033                    let mut read_ranges = Vec::new();
 5034                    for highlight in highlights {
 5035                        for (excerpt_id, excerpt_range) in
 5036                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5037                        {
 5038                            let start = highlight
 5039                                .range
 5040                                .start
 5041                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5042                            let end = highlight
 5043                                .range
 5044                                .end
 5045                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5046                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5047                                continue;
 5048                            }
 5049
 5050                            let range = Anchor {
 5051                                buffer_id,
 5052                                excerpt_id,
 5053                                text_anchor: start,
 5054                            }..Anchor {
 5055                                buffer_id,
 5056                                excerpt_id,
 5057                                text_anchor: end,
 5058                            };
 5059                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5060                                write_ranges.push(range);
 5061                            } else {
 5062                                read_ranges.push(range);
 5063                            }
 5064                        }
 5065                    }
 5066
 5067                    this.highlight_background::<DocumentHighlightRead>(
 5068                        &read_ranges,
 5069                        |theme| theme.editor_document_highlight_read_background,
 5070                        cx,
 5071                    );
 5072                    this.highlight_background::<DocumentHighlightWrite>(
 5073                        &write_ranges,
 5074                        |theme| theme.editor_document_highlight_write_background,
 5075                        cx,
 5076                    );
 5077                    cx.notify();
 5078                })
 5079                .log_err();
 5080            }
 5081        }));
 5082        None
 5083    }
 5084
 5085    pub fn refresh_inline_completion(
 5086        &mut self,
 5087        debounce: bool,
 5088        user_requested: bool,
 5089        cx: &mut ViewContext<Self>,
 5090    ) -> Option<()> {
 5091        let provider = self.inline_completion_provider()?;
 5092        let cursor = self.selections.newest_anchor().head();
 5093        let (buffer, cursor_buffer_position) =
 5094            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5095
 5096        if !user_requested
 5097            && (!self.enable_inline_completions
 5098                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5099        {
 5100            self.discard_inline_completion(false, cx);
 5101            return None;
 5102        }
 5103
 5104        self.update_visible_inline_completion(cx);
 5105        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5106        Some(())
 5107    }
 5108
 5109    fn cycle_inline_completion(
 5110        &mut self,
 5111        direction: Direction,
 5112        cx: &mut ViewContext<Self>,
 5113    ) -> Option<()> {
 5114        let provider = self.inline_completion_provider()?;
 5115        let cursor = self.selections.newest_anchor().head();
 5116        let (buffer, cursor_buffer_position) =
 5117            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5118        if !self.enable_inline_completions
 5119            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5120        {
 5121            return None;
 5122        }
 5123
 5124        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5125        self.update_visible_inline_completion(cx);
 5126
 5127        Some(())
 5128    }
 5129
 5130    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5131        if !self.has_active_inline_completion(cx) {
 5132            self.refresh_inline_completion(false, true, cx);
 5133            return;
 5134        }
 5135
 5136        self.update_visible_inline_completion(cx);
 5137    }
 5138
 5139    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5140        self.show_cursor_names(cx);
 5141    }
 5142
 5143    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5144        self.show_cursor_names = true;
 5145        cx.notify();
 5146        cx.spawn(|this, mut cx| async move {
 5147            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5148            this.update(&mut cx, |this, cx| {
 5149                this.show_cursor_names = false;
 5150                cx.notify()
 5151            })
 5152            .ok()
 5153        })
 5154        .detach();
 5155    }
 5156
 5157    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5158        if self.has_active_inline_completion(cx) {
 5159            self.cycle_inline_completion(Direction::Next, cx);
 5160        } else {
 5161            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5162            if is_copilot_disabled {
 5163                cx.propagate();
 5164            }
 5165        }
 5166    }
 5167
 5168    pub fn previous_inline_completion(
 5169        &mut self,
 5170        _: &PreviousInlineCompletion,
 5171        cx: &mut ViewContext<Self>,
 5172    ) {
 5173        if self.has_active_inline_completion(cx) {
 5174            self.cycle_inline_completion(Direction::Prev, cx);
 5175        } else {
 5176            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5177            if is_copilot_disabled {
 5178                cx.propagate();
 5179            }
 5180        }
 5181    }
 5182
 5183    pub fn accept_inline_completion(
 5184        &mut self,
 5185        _: &AcceptInlineCompletion,
 5186        cx: &mut ViewContext<Self>,
 5187    ) {
 5188        let Some(completion) = self.take_active_inline_completion(cx) else {
 5189            return;
 5190        };
 5191        if let Some(provider) = self.inline_completion_provider() {
 5192            provider.accept(cx);
 5193        }
 5194
 5195        cx.emit(EditorEvent::InputHandled {
 5196            utf16_range_to_replace: None,
 5197            text: completion.text.to_string().into(),
 5198        });
 5199
 5200        if let Some(range) = completion.delete_range {
 5201            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5202        }
 5203        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5204        self.refresh_inline_completion(true, true, cx);
 5205        cx.notify();
 5206    }
 5207
 5208    pub fn accept_partial_inline_completion(
 5209        &mut self,
 5210        _: &AcceptPartialInlineCompletion,
 5211        cx: &mut ViewContext<Self>,
 5212    ) {
 5213        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5214            if let Some(completion) = self.take_active_inline_completion(cx) {
 5215                let mut partial_completion = completion
 5216                    .text
 5217                    .chars()
 5218                    .by_ref()
 5219                    .take_while(|c| c.is_alphabetic())
 5220                    .collect::<String>();
 5221                if partial_completion.is_empty() {
 5222                    partial_completion = completion
 5223                        .text
 5224                        .chars()
 5225                        .by_ref()
 5226                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5227                        .collect::<String>();
 5228                }
 5229
 5230                cx.emit(EditorEvent::InputHandled {
 5231                    utf16_range_to_replace: None,
 5232                    text: partial_completion.clone().into(),
 5233                });
 5234
 5235                if let Some(range) = completion.delete_range {
 5236                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5237                }
 5238                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5239
 5240                self.refresh_inline_completion(true, true, cx);
 5241                cx.notify();
 5242            }
 5243        }
 5244    }
 5245
 5246    fn discard_inline_completion(
 5247        &mut self,
 5248        should_report_inline_completion_event: bool,
 5249        cx: &mut ViewContext<Self>,
 5250    ) -> bool {
 5251        if let Some(provider) = self.inline_completion_provider() {
 5252            provider.discard(should_report_inline_completion_event, cx);
 5253        }
 5254
 5255        self.take_active_inline_completion(cx).is_some()
 5256    }
 5257
 5258    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5259        if let Some(completion) = self.active_inline_completion.as_ref() {
 5260            let buffer = self.buffer.read(cx).read(cx);
 5261            completion.position.is_valid(&buffer)
 5262        } else {
 5263            false
 5264        }
 5265    }
 5266
 5267    fn take_active_inline_completion(
 5268        &mut self,
 5269        cx: &mut ViewContext<Self>,
 5270    ) -> Option<CompletionState> {
 5271        let completion = self.active_inline_completion.take()?;
 5272        let render_inlay_ids = completion.render_inlay_ids.clone();
 5273        self.display_map.update(cx, |map, cx| {
 5274            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5275        });
 5276        let buffer = self.buffer.read(cx).read(cx);
 5277
 5278        if completion.position.is_valid(&buffer) {
 5279            Some(completion)
 5280        } else {
 5281            None
 5282        }
 5283    }
 5284
 5285    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5286        let selection = self.selections.newest_anchor();
 5287        let cursor = selection.head();
 5288
 5289        let excerpt_id = cursor.excerpt_id;
 5290
 5291        if self.context_menu.read().is_none()
 5292            && self.completion_tasks.is_empty()
 5293            && selection.start == selection.end
 5294        {
 5295            if let Some(provider) = self.inline_completion_provider() {
 5296                if let Some((buffer, cursor_buffer_position)) =
 5297                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5298                {
 5299                    if let Some(proposal) =
 5300                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5301                    {
 5302                        let mut to_remove = Vec::new();
 5303                        if let Some(completion) = self.active_inline_completion.take() {
 5304                            to_remove.extend(completion.render_inlay_ids.iter());
 5305                        }
 5306
 5307                        let to_add = proposal
 5308                            .inlays
 5309                            .iter()
 5310                            .filter_map(|inlay| {
 5311                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5312                                let id = post_inc(&mut self.next_inlay_id);
 5313                                match inlay {
 5314                                    InlayProposal::Hint(position, hint) => {
 5315                                        let position =
 5316                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5317                                        Some(Inlay::hint(id, position, hint))
 5318                                    }
 5319                                    InlayProposal::Suggestion(position, text) => {
 5320                                        let position =
 5321                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5322                                        Some(Inlay::suggestion(id, position, text.clone()))
 5323                                    }
 5324                                }
 5325                            })
 5326                            .collect_vec();
 5327
 5328                        self.active_inline_completion = Some(CompletionState {
 5329                            position: cursor,
 5330                            text: proposal.text,
 5331                            delete_range: proposal.delete_range.and_then(|range| {
 5332                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5333                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5334                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5335                                Some(start?..end?)
 5336                            }),
 5337                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5338                        });
 5339
 5340                        self.display_map
 5341                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5342
 5343                        cx.notify();
 5344                        return;
 5345                    }
 5346                }
 5347            }
 5348        }
 5349
 5350        self.discard_inline_completion(false, cx);
 5351    }
 5352
 5353    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5354        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5355    }
 5356
 5357    fn render_code_actions_indicator(
 5358        &self,
 5359        _style: &EditorStyle,
 5360        row: DisplayRow,
 5361        is_active: bool,
 5362        cx: &mut ViewContext<Self>,
 5363    ) -> Option<IconButton> {
 5364        if self.available_code_actions.is_some() {
 5365            Some(
 5366                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5367                    .shape(ui::IconButtonShape::Square)
 5368                    .icon_size(IconSize::XSmall)
 5369                    .icon_color(Color::Muted)
 5370                    .selected(is_active)
 5371                    .on_click(cx.listener(move |editor, _e, cx| {
 5372                        editor.focus(cx);
 5373                        editor.toggle_code_actions(
 5374                            &ToggleCodeActions {
 5375                                deployed_from_indicator: Some(row),
 5376                            },
 5377                            cx,
 5378                        );
 5379                    })),
 5380            )
 5381        } else {
 5382            None
 5383        }
 5384    }
 5385
 5386    fn clear_tasks(&mut self) {
 5387        self.tasks.clear()
 5388    }
 5389
 5390    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5391        if self.tasks.insert(key, value).is_some() {
 5392            // This case should hopefully be rare, but just in case...
 5393            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5394        }
 5395    }
 5396
 5397    fn render_run_indicator(
 5398        &self,
 5399        _style: &EditorStyle,
 5400        is_active: bool,
 5401        row: DisplayRow,
 5402        cx: &mut ViewContext<Self>,
 5403    ) -> IconButton {
 5404        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5405            .shape(ui::IconButtonShape::Square)
 5406            .icon_size(IconSize::XSmall)
 5407            .icon_color(Color::Muted)
 5408            .selected(is_active)
 5409            .on_click(cx.listener(move |editor, _e, cx| {
 5410                editor.focus(cx);
 5411                editor.toggle_code_actions(
 5412                    &ToggleCodeActions {
 5413                        deployed_from_indicator: Some(row),
 5414                    },
 5415                    cx,
 5416                );
 5417            }))
 5418    }
 5419
 5420    pub fn context_menu_visible(&self) -> bool {
 5421        self.context_menu
 5422            .read()
 5423            .as_ref()
 5424            .map_or(false, |menu| menu.visible())
 5425    }
 5426
 5427    fn render_context_menu(
 5428        &self,
 5429        cursor_position: DisplayPoint,
 5430        style: &EditorStyle,
 5431        max_height: Pixels,
 5432        cx: &mut ViewContext<Editor>,
 5433    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5434        self.context_menu.read().as_ref().map(|menu| {
 5435            menu.render(
 5436                cursor_position,
 5437                style,
 5438                max_height,
 5439                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5440                cx,
 5441            )
 5442        })
 5443    }
 5444
 5445    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5446        cx.notify();
 5447        self.completion_tasks.clear();
 5448        let context_menu = self.context_menu.write().take();
 5449        if context_menu.is_some() {
 5450            self.update_visible_inline_completion(cx);
 5451        }
 5452        context_menu
 5453    }
 5454
 5455    pub fn insert_snippet(
 5456        &mut self,
 5457        insertion_ranges: &[Range<usize>],
 5458        snippet: Snippet,
 5459        cx: &mut ViewContext<Self>,
 5460    ) -> Result<()> {
 5461        struct Tabstop<T> {
 5462            is_end_tabstop: bool,
 5463            ranges: Vec<Range<T>>,
 5464        }
 5465
 5466        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5467            let snippet_text: Arc<str> = snippet.text.clone().into();
 5468            buffer.edit(
 5469                insertion_ranges
 5470                    .iter()
 5471                    .cloned()
 5472                    .map(|range| (range, snippet_text.clone())),
 5473                Some(AutoindentMode::EachLine),
 5474                cx,
 5475            );
 5476
 5477            let snapshot = &*buffer.read(cx);
 5478            let snippet = &snippet;
 5479            snippet
 5480                .tabstops
 5481                .iter()
 5482                .map(|tabstop| {
 5483                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5484                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5485                    });
 5486                    let mut tabstop_ranges = tabstop
 5487                        .iter()
 5488                        .flat_map(|tabstop_range| {
 5489                            let mut delta = 0_isize;
 5490                            insertion_ranges.iter().map(move |insertion_range| {
 5491                                let insertion_start = insertion_range.start as isize + delta;
 5492                                delta +=
 5493                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5494
 5495                                let start = ((insertion_start + tabstop_range.start) as usize)
 5496                                    .min(snapshot.len());
 5497                                let end = ((insertion_start + tabstop_range.end) as usize)
 5498                                    .min(snapshot.len());
 5499                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5500                            })
 5501                        })
 5502                        .collect::<Vec<_>>();
 5503                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5504
 5505                    Tabstop {
 5506                        is_end_tabstop,
 5507                        ranges: tabstop_ranges,
 5508                    }
 5509                })
 5510                .collect::<Vec<_>>()
 5511        });
 5512        if let Some(tabstop) = tabstops.first() {
 5513            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5514                s.select_ranges(tabstop.ranges.iter().cloned());
 5515            });
 5516
 5517            // If we're already at the last tabstop and it's at the end of the snippet,
 5518            // we're done, we don't need to keep the state around.
 5519            if !tabstop.is_end_tabstop {
 5520                let ranges = tabstops
 5521                    .into_iter()
 5522                    .map(|tabstop| tabstop.ranges)
 5523                    .collect::<Vec<_>>();
 5524                self.snippet_stack.push(SnippetState {
 5525                    active_index: 0,
 5526                    ranges,
 5527                });
 5528            }
 5529
 5530            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5531            if self.autoclose_regions.is_empty() {
 5532                let snapshot = self.buffer.read(cx).snapshot(cx);
 5533                for selection in &mut self.selections.all::<Point>(cx) {
 5534                    let selection_head = selection.head();
 5535                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5536                        continue;
 5537                    };
 5538
 5539                    let mut bracket_pair = None;
 5540                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5541                    let prev_chars = snapshot
 5542                        .reversed_chars_at(selection_head)
 5543                        .collect::<String>();
 5544                    for (pair, enabled) in scope.brackets() {
 5545                        if enabled
 5546                            && pair.close
 5547                            && prev_chars.starts_with(pair.start.as_str())
 5548                            && next_chars.starts_with(pair.end.as_str())
 5549                        {
 5550                            bracket_pair = Some(pair.clone());
 5551                            break;
 5552                        }
 5553                    }
 5554                    if let Some(pair) = bracket_pair {
 5555                        let start = snapshot.anchor_after(selection_head);
 5556                        let end = snapshot.anchor_after(selection_head);
 5557                        self.autoclose_regions.push(AutocloseRegion {
 5558                            selection_id: selection.id,
 5559                            range: start..end,
 5560                            pair,
 5561                        });
 5562                    }
 5563                }
 5564            }
 5565        }
 5566        Ok(())
 5567    }
 5568
 5569    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5570        self.move_to_snippet_tabstop(Bias::Right, cx)
 5571    }
 5572
 5573    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5574        self.move_to_snippet_tabstop(Bias::Left, cx)
 5575    }
 5576
 5577    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5578        if let Some(mut snippet) = self.snippet_stack.pop() {
 5579            match bias {
 5580                Bias::Left => {
 5581                    if snippet.active_index > 0 {
 5582                        snippet.active_index -= 1;
 5583                    } else {
 5584                        self.snippet_stack.push(snippet);
 5585                        return false;
 5586                    }
 5587                }
 5588                Bias::Right => {
 5589                    if snippet.active_index + 1 < snippet.ranges.len() {
 5590                        snippet.active_index += 1;
 5591                    } else {
 5592                        self.snippet_stack.push(snippet);
 5593                        return false;
 5594                    }
 5595                }
 5596            }
 5597            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5598                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5599                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5600                });
 5601                // If snippet state is not at the last tabstop, push it back on the stack
 5602                if snippet.active_index + 1 < snippet.ranges.len() {
 5603                    self.snippet_stack.push(snippet);
 5604                }
 5605                return true;
 5606            }
 5607        }
 5608
 5609        false
 5610    }
 5611
 5612    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5613        self.transact(cx, |this, cx| {
 5614            this.select_all(&SelectAll, cx);
 5615            this.insert("", cx);
 5616        });
 5617    }
 5618
 5619    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5620        self.transact(cx, |this, cx| {
 5621            this.select_autoclose_pair(cx);
 5622            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5623            if !this.linked_edit_ranges.is_empty() {
 5624                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5625                let snapshot = this.buffer.read(cx).snapshot(cx);
 5626
 5627                for selection in selections.iter() {
 5628                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5629                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5630                    if selection_start.buffer_id != selection_end.buffer_id {
 5631                        continue;
 5632                    }
 5633                    if let Some(ranges) =
 5634                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5635                    {
 5636                        for (buffer, entries) in ranges {
 5637                            linked_ranges.entry(buffer).or_default().extend(entries);
 5638                        }
 5639                    }
 5640                }
 5641            }
 5642
 5643            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5644            if !this.selections.line_mode {
 5645                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5646                for selection in &mut selections {
 5647                    if selection.is_empty() {
 5648                        let old_head = selection.head();
 5649                        let mut new_head =
 5650                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5651                                .to_point(&display_map);
 5652                        if let Some((buffer, line_buffer_range)) = display_map
 5653                            .buffer_snapshot
 5654                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5655                        {
 5656                            let indent_size =
 5657                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5658                            let indent_len = match indent_size.kind {
 5659                                IndentKind::Space => {
 5660                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5661                                }
 5662                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5663                            };
 5664                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5665                                let indent_len = indent_len.get();
 5666                                new_head = cmp::min(
 5667                                    new_head,
 5668                                    MultiBufferPoint::new(
 5669                                        old_head.row,
 5670                                        ((old_head.column - 1) / indent_len) * indent_len,
 5671                                    ),
 5672                                );
 5673                            }
 5674                        }
 5675
 5676                        selection.set_head(new_head, SelectionGoal::None);
 5677                    }
 5678                }
 5679            }
 5680
 5681            this.signature_help_state.set_backspace_pressed(true);
 5682            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5683            this.insert("", cx);
 5684            let empty_str: Arc<str> = Arc::from("");
 5685            for (buffer, edits) in linked_ranges {
 5686                let snapshot = buffer.read(cx).snapshot();
 5687                use text::ToPoint as TP;
 5688
 5689                let edits = edits
 5690                    .into_iter()
 5691                    .map(|range| {
 5692                        let end_point = TP::to_point(&range.end, &snapshot);
 5693                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5694
 5695                        if end_point == start_point {
 5696                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5697                                .saturating_sub(1);
 5698                            start_point = TP::to_point(&offset, &snapshot);
 5699                        };
 5700
 5701                        (start_point..end_point, empty_str.clone())
 5702                    })
 5703                    .sorted_by_key(|(range, _)| range.start)
 5704                    .collect::<Vec<_>>();
 5705                buffer.update(cx, |this, cx| {
 5706                    this.edit(edits, None, cx);
 5707                })
 5708            }
 5709            this.refresh_inline_completion(true, false, cx);
 5710            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5711        });
 5712    }
 5713
 5714    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5715        self.transact(cx, |this, cx| {
 5716            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5717                let line_mode = s.line_mode;
 5718                s.move_with(|map, selection| {
 5719                    if selection.is_empty() && !line_mode {
 5720                        let cursor = movement::right(map, selection.head());
 5721                        selection.end = cursor;
 5722                        selection.reversed = true;
 5723                        selection.goal = SelectionGoal::None;
 5724                    }
 5725                })
 5726            });
 5727            this.insert("", cx);
 5728            this.refresh_inline_completion(true, false, cx);
 5729        });
 5730    }
 5731
 5732    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5733        if self.move_to_prev_snippet_tabstop(cx) {
 5734            return;
 5735        }
 5736
 5737        self.outdent(&Outdent, cx);
 5738    }
 5739
 5740    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5741        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5742            return;
 5743        }
 5744
 5745        let mut selections = self.selections.all_adjusted(cx);
 5746        let buffer = self.buffer.read(cx);
 5747        let snapshot = buffer.snapshot(cx);
 5748        let rows_iter = selections.iter().map(|s| s.head().row);
 5749        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5750
 5751        let mut edits = Vec::new();
 5752        let mut prev_edited_row = 0;
 5753        let mut row_delta = 0;
 5754        for selection in &mut selections {
 5755            if selection.start.row != prev_edited_row {
 5756                row_delta = 0;
 5757            }
 5758            prev_edited_row = selection.end.row;
 5759
 5760            // If the selection is non-empty, then increase the indentation of the selected lines.
 5761            if !selection.is_empty() {
 5762                row_delta =
 5763                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5764                continue;
 5765            }
 5766
 5767            // If the selection is empty and the cursor is in the leading whitespace before the
 5768            // suggested indentation, then auto-indent the line.
 5769            let cursor = selection.head();
 5770            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5771            if let Some(suggested_indent) =
 5772                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5773            {
 5774                if cursor.column < suggested_indent.len
 5775                    && cursor.column <= current_indent.len
 5776                    && current_indent.len <= suggested_indent.len
 5777                {
 5778                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5779                    selection.end = selection.start;
 5780                    if row_delta == 0 {
 5781                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5782                            cursor.row,
 5783                            current_indent,
 5784                            suggested_indent,
 5785                        ));
 5786                        row_delta = suggested_indent.len - current_indent.len;
 5787                    }
 5788                    continue;
 5789                }
 5790            }
 5791
 5792            // Otherwise, insert a hard or soft tab.
 5793            let settings = buffer.settings_at(cursor, cx);
 5794            let tab_size = if settings.hard_tabs {
 5795                IndentSize::tab()
 5796            } else {
 5797                let tab_size = settings.tab_size.get();
 5798                let char_column = snapshot
 5799                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5800                    .flat_map(str::chars)
 5801                    .count()
 5802                    + row_delta as usize;
 5803                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5804                IndentSize::spaces(chars_to_next_tab_stop)
 5805            };
 5806            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5807            selection.end = selection.start;
 5808            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5809            row_delta += tab_size.len;
 5810        }
 5811
 5812        self.transact(cx, |this, cx| {
 5813            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5814            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5815            this.refresh_inline_completion(true, false, cx);
 5816        });
 5817    }
 5818
 5819    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5820        if self.read_only(cx) {
 5821            return;
 5822        }
 5823        let mut selections = self.selections.all::<Point>(cx);
 5824        let mut prev_edited_row = 0;
 5825        let mut row_delta = 0;
 5826        let mut edits = Vec::new();
 5827        let buffer = self.buffer.read(cx);
 5828        let snapshot = buffer.snapshot(cx);
 5829        for selection in &mut selections {
 5830            if selection.start.row != prev_edited_row {
 5831                row_delta = 0;
 5832            }
 5833            prev_edited_row = selection.end.row;
 5834
 5835            row_delta =
 5836                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5837        }
 5838
 5839        self.transact(cx, |this, cx| {
 5840            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5841            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5842        });
 5843    }
 5844
 5845    fn indent_selection(
 5846        buffer: &MultiBuffer,
 5847        snapshot: &MultiBufferSnapshot,
 5848        selection: &mut Selection<Point>,
 5849        edits: &mut Vec<(Range<Point>, String)>,
 5850        delta_for_start_row: u32,
 5851        cx: &AppContext,
 5852    ) -> u32 {
 5853        let settings = buffer.settings_at(selection.start, cx);
 5854        let tab_size = settings.tab_size.get();
 5855        let indent_kind = if settings.hard_tabs {
 5856            IndentKind::Tab
 5857        } else {
 5858            IndentKind::Space
 5859        };
 5860        let mut start_row = selection.start.row;
 5861        let mut end_row = selection.end.row + 1;
 5862
 5863        // If a selection ends at the beginning of a line, don't indent
 5864        // that last line.
 5865        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5866            end_row -= 1;
 5867        }
 5868
 5869        // Avoid re-indenting a row that has already been indented by a
 5870        // previous selection, but still update this selection's column
 5871        // to reflect that indentation.
 5872        if delta_for_start_row > 0 {
 5873            start_row += 1;
 5874            selection.start.column += delta_for_start_row;
 5875            if selection.end.row == selection.start.row {
 5876                selection.end.column += delta_for_start_row;
 5877            }
 5878        }
 5879
 5880        let mut delta_for_end_row = 0;
 5881        let has_multiple_rows = start_row + 1 != end_row;
 5882        for row in start_row..end_row {
 5883            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5884            let indent_delta = match (current_indent.kind, indent_kind) {
 5885                (IndentKind::Space, IndentKind::Space) => {
 5886                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5887                    IndentSize::spaces(columns_to_next_tab_stop)
 5888                }
 5889                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5890                (_, IndentKind::Tab) => IndentSize::tab(),
 5891            };
 5892
 5893            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5894                0
 5895            } else {
 5896                selection.start.column
 5897            };
 5898            let row_start = Point::new(row, start);
 5899            edits.push((
 5900                row_start..row_start,
 5901                indent_delta.chars().collect::<String>(),
 5902            ));
 5903
 5904            // Update this selection's endpoints to reflect the indentation.
 5905            if row == selection.start.row {
 5906                selection.start.column += indent_delta.len;
 5907            }
 5908            if row == selection.end.row {
 5909                selection.end.column += indent_delta.len;
 5910                delta_for_end_row = indent_delta.len;
 5911            }
 5912        }
 5913
 5914        if selection.start.row == selection.end.row {
 5915            delta_for_start_row + delta_for_end_row
 5916        } else {
 5917            delta_for_end_row
 5918        }
 5919    }
 5920
 5921    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5922        if self.read_only(cx) {
 5923            return;
 5924        }
 5925        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5926        let selections = self.selections.all::<Point>(cx);
 5927        let mut deletion_ranges = Vec::new();
 5928        let mut last_outdent = None;
 5929        {
 5930            let buffer = self.buffer.read(cx);
 5931            let snapshot = buffer.snapshot(cx);
 5932            for selection in &selections {
 5933                let settings = buffer.settings_at(selection.start, cx);
 5934                let tab_size = settings.tab_size.get();
 5935                let mut rows = selection.spanned_rows(false, &display_map);
 5936
 5937                // Avoid re-outdenting a row that has already been outdented by a
 5938                // previous selection.
 5939                if let Some(last_row) = last_outdent {
 5940                    if last_row == rows.start {
 5941                        rows.start = rows.start.next_row();
 5942                    }
 5943                }
 5944                let has_multiple_rows = rows.len() > 1;
 5945                for row in rows.iter_rows() {
 5946                    let indent_size = snapshot.indent_size_for_line(row);
 5947                    if indent_size.len > 0 {
 5948                        let deletion_len = match indent_size.kind {
 5949                            IndentKind::Space => {
 5950                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5951                                if columns_to_prev_tab_stop == 0 {
 5952                                    tab_size
 5953                                } else {
 5954                                    columns_to_prev_tab_stop
 5955                                }
 5956                            }
 5957                            IndentKind::Tab => 1,
 5958                        };
 5959                        let start = if has_multiple_rows
 5960                            || deletion_len > selection.start.column
 5961                            || indent_size.len < selection.start.column
 5962                        {
 5963                            0
 5964                        } else {
 5965                            selection.start.column - deletion_len
 5966                        };
 5967                        deletion_ranges.push(
 5968                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5969                        );
 5970                        last_outdent = Some(row);
 5971                    }
 5972                }
 5973            }
 5974        }
 5975
 5976        self.transact(cx, |this, cx| {
 5977            this.buffer.update(cx, |buffer, cx| {
 5978                let empty_str: Arc<str> = Arc::default();
 5979                buffer.edit(
 5980                    deletion_ranges
 5981                        .into_iter()
 5982                        .map(|range| (range, empty_str.clone())),
 5983                    None,
 5984                    cx,
 5985                );
 5986            });
 5987            let selections = this.selections.all::<usize>(cx);
 5988            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5989        });
 5990    }
 5991
 5992    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5993        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5994        let selections = self.selections.all::<Point>(cx);
 5995
 5996        let mut new_cursors = Vec::new();
 5997        let mut edit_ranges = Vec::new();
 5998        let mut selections = selections.iter().peekable();
 5999        while let Some(selection) = selections.next() {
 6000            let mut rows = selection.spanned_rows(false, &display_map);
 6001            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6002
 6003            // Accumulate contiguous regions of rows that we want to delete.
 6004            while let Some(next_selection) = selections.peek() {
 6005                let next_rows = next_selection.spanned_rows(false, &display_map);
 6006                if next_rows.start <= rows.end {
 6007                    rows.end = next_rows.end;
 6008                    selections.next().unwrap();
 6009                } else {
 6010                    break;
 6011                }
 6012            }
 6013
 6014            let buffer = &display_map.buffer_snapshot;
 6015            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6016            let edit_end;
 6017            let cursor_buffer_row;
 6018            if buffer.max_point().row >= rows.end.0 {
 6019                // If there's a line after the range, delete the \n from the end of the row range
 6020                // and position the cursor on the next line.
 6021                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6022                cursor_buffer_row = rows.end;
 6023            } else {
 6024                // If there isn't a line after the range, delete the \n from the line before the
 6025                // start of the row range and position the cursor there.
 6026                edit_start = edit_start.saturating_sub(1);
 6027                edit_end = buffer.len();
 6028                cursor_buffer_row = rows.start.previous_row();
 6029            }
 6030
 6031            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6032            *cursor.column_mut() =
 6033                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6034
 6035            new_cursors.push((
 6036                selection.id,
 6037                buffer.anchor_after(cursor.to_point(&display_map)),
 6038            ));
 6039            edit_ranges.push(edit_start..edit_end);
 6040        }
 6041
 6042        self.transact(cx, |this, cx| {
 6043            let buffer = this.buffer.update(cx, |buffer, cx| {
 6044                let empty_str: Arc<str> = Arc::default();
 6045                buffer.edit(
 6046                    edit_ranges
 6047                        .into_iter()
 6048                        .map(|range| (range, empty_str.clone())),
 6049                    None,
 6050                    cx,
 6051                );
 6052                buffer.snapshot(cx)
 6053            });
 6054            let new_selections = new_cursors
 6055                .into_iter()
 6056                .map(|(id, cursor)| {
 6057                    let cursor = cursor.to_point(&buffer);
 6058                    Selection {
 6059                        id,
 6060                        start: cursor,
 6061                        end: cursor,
 6062                        reversed: false,
 6063                        goal: SelectionGoal::None,
 6064                    }
 6065                })
 6066                .collect();
 6067
 6068            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6069                s.select(new_selections);
 6070            });
 6071        });
 6072    }
 6073
 6074    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6075        if self.read_only(cx) {
 6076            return;
 6077        }
 6078        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6079        for selection in self.selections.all::<Point>(cx) {
 6080            let start = MultiBufferRow(selection.start.row);
 6081            let end = if selection.start.row == selection.end.row {
 6082                MultiBufferRow(selection.start.row + 1)
 6083            } else {
 6084                MultiBufferRow(selection.end.row)
 6085            };
 6086
 6087            if let Some(last_row_range) = row_ranges.last_mut() {
 6088                if start <= last_row_range.end {
 6089                    last_row_range.end = end;
 6090                    continue;
 6091                }
 6092            }
 6093            row_ranges.push(start..end);
 6094        }
 6095
 6096        let snapshot = self.buffer.read(cx).snapshot(cx);
 6097        let mut cursor_positions = Vec::new();
 6098        for row_range in &row_ranges {
 6099            let anchor = snapshot.anchor_before(Point::new(
 6100                row_range.end.previous_row().0,
 6101                snapshot.line_len(row_range.end.previous_row()),
 6102            ));
 6103            cursor_positions.push(anchor..anchor);
 6104        }
 6105
 6106        self.transact(cx, |this, cx| {
 6107            for row_range in row_ranges.into_iter().rev() {
 6108                for row in row_range.iter_rows().rev() {
 6109                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6110                    let next_line_row = row.next_row();
 6111                    let indent = snapshot.indent_size_for_line(next_line_row);
 6112                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6113
 6114                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6115                        " "
 6116                    } else {
 6117                        ""
 6118                    };
 6119
 6120                    this.buffer.update(cx, |buffer, cx| {
 6121                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6122                    });
 6123                }
 6124            }
 6125
 6126            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6127                s.select_anchor_ranges(cursor_positions)
 6128            });
 6129        });
 6130    }
 6131
 6132    pub fn sort_lines_case_sensitive(
 6133        &mut self,
 6134        _: &SortLinesCaseSensitive,
 6135        cx: &mut ViewContext<Self>,
 6136    ) {
 6137        self.manipulate_lines(cx, |lines| lines.sort())
 6138    }
 6139
 6140    pub fn sort_lines_case_insensitive(
 6141        &mut self,
 6142        _: &SortLinesCaseInsensitive,
 6143        cx: &mut ViewContext<Self>,
 6144    ) {
 6145        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6146    }
 6147
 6148    pub fn unique_lines_case_insensitive(
 6149        &mut self,
 6150        _: &UniqueLinesCaseInsensitive,
 6151        cx: &mut ViewContext<Self>,
 6152    ) {
 6153        self.manipulate_lines(cx, |lines| {
 6154            let mut seen = HashSet::default();
 6155            lines.retain(|line| seen.insert(line.to_lowercase()));
 6156        })
 6157    }
 6158
 6159    pub fn unique_lines_case_sensitive(
 6160        &mut self,
 6161        _: &UniqueLinesCaseSensitive,
 6162        cx: &mut ViewContext<Self>,
 6163    ) {
 6164        self.manipulate_lines(cx, |lines| {
 6165            let mut seen = HashSet::default();
 6166            lines.retain(|line| seen.insert(*line));
 6167        })
 6168    }
 6169
 6170    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6171        let mut revert_changes = HashMap::default();
 6172        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6173        for hunk in hunks_for_rows(
 6174            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6175            &multi_buffer_snapshot,
 6176        ) {
 6177            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6178        }
 6179        if !revert_changes.is_empty() {
 6180            self.transact(cx, |editor, cx| {
 6181                editor.revert(revert_changes, cx);
 6182            });
 6183        }
 6184    }
 6185
 6186    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6187        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6188        if !revert_changes.is_empty() {
 6189            self.transact(cx, |editor, cx| {
 6190                editor.revert(revert_changes, cx);
 6191            });
 6192        }
 6193    }
 6194
 6195    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6196        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6197            let project_path = buffer.read(cx).project_path(cx)?;
 6198            let project = self.project.as_ref()?.read(cx);
 6199            let entry = project.entry_for_path(&project_path, cx)?;
 6200            let abs_path = project.absolute_path(&project_path, cx)?;
 6201            let parent = if entry.is_symlink {
 6202                abs_path.canonicalize().ok()?
 6203            } else {
 6204                abs_path
 6205            }
 6206            .parent()?
 6207            .to_path_buf();
 6208            Some(parent)
 6209        }) {
 6210            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6211        }
 6212    }
 6213
 6214    fn gather_revert_changes(
 6215        &mut self,
 6216        selections: &[Selection<Anchor>],
 6217        cx: &mut ViewContext<'_, Editor>,
 6218    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6219        let mut revert_changes = HashMap::default();
 6220        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6221        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6222            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6223        }
 6224        revert_changes
 6225    }
 6226
 6227    pub fn prepare_revert_change(
 6228        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6229        multi_buffer: &Model<MultiBuffer>,
 6230        hunk: &MultiBufferDiffHunk,
 6231        cx: &AppContext,
 6232    ) -> Option<()> {
 6233        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6234        let buffer = buffer.read(cx);
 6235        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6236        let buffer_snapshot = buffer.snapshot();
 6237        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6238        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6239            probe
 6240                .0
 6241                .start
 6242                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6243                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6244        }) {
 6245            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6246            Some(())
 6247        } else {
 6248            None
 6249        }
 6250    }
 6251
 6252    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6253        self.manipulate_lines(cx, |lines| lines.reverse())
 6254    }
 6255
 6256    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6257        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6258    }
 6259
 6260    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6261    where
 6262        Fn: FnMut(&mut Vec<&str>),
 6263    {
 6264        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6265        let buffer = self.buffer.read(cx).snapshot(cx);
 6266
 6267        let mut edits = Vec::new();
 6268
 6269        let selections = self.selections.all::<Point>(cx);
 6270        let mut selections = selections.iter().peekable();
 6271        let mut contiguous_row_selections = Vec::new();
 6272        let mut new_selections = Vec::new();
 6273        let mut added_lines = 0;
 6274        let mut removed_lines = 0;
 6275
 6276        while let Some(selection) = selections.next() {
 6277            let (start_row, end_row) = consume_contiguous_rows(
 6278                &mut contiguous_row_selections,
 6279                selection,
 6280                &display_map,
 6281                &mut selections,
 6282            );
 6283
 6284            let start_point = Point::new(start_row.0, 0);
 6285            let end_point = Point::new(
 6286                end_row.previous_row().0,
 6287                buffer.line_len(end_row.previous_row()),
 6288            );
 6289            let text = buffer
 6290                .text_for_range(start_point..end_point)
 6291                .collect::<String>();
 6292
 6293            let mut lines = text.split('\n').collect_vec();
 6294
 6295            let lines_before = lines.len();
 6296            callback(&mut lines);
 6297            let lines_after = lines.len();
 6298
 6299            edits.push((start_point..end_point, lines.join("\n")));
 6300
 6301            // Selections must change based on added and removed line count
 6302            let start_row =
 6303                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6304            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6305            new_selections.push(Selection {
 6306                id: selection.id,
 6307                start: start_row,
 6308                end: end_row,
 6309                goal: SelectionGoal::None,
 6310                reversed: selection.reversed,
 6311            });
 6312
 6313            if lines_after > lines_before {
 6314                added_lines += lines_after - lines_before;
 6315            } else if lines_before > lines_after {
 6316                removed_lines += lines_before - lines_after;
 6317            }
 6318        }
 6319
 6320        self.transact(cx, |this, cx| {
 6321            let buffer = this.buffer.update(cx, |buffer, cx| {
 6322                buffer.edit(edits, None, cx);
 6323                buffer.snapshot(cx)
 6324            });
 6325
 6326            // Recalculate offsets on newly edited buffer
 6327            let new_selections = new_selections
 6328                .iter()
 6329                .map(|s| {
 6330                    let start_point = Point::new(s.start.0, 0);
 6331                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6332                    Selection {
 6333                        id: s.id,
 6334                        start: buffer.point_to_offset(start_point),
 6335                        end: buffer.point_to_offset(end_point),
 6336                        goal: s.goal,
 6337                        reversed: s.reversed,
 6338                    }
 6339                })
 6340                .collect();
 6341
 6342            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6343                s.select(new_selections);
 6344            });
 6345
 6346            this.request_autoscroll(Autoscroll::fit(), cx);
 6347        });
 6348    }
 6349
 6350    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6351        self.manipulate_text(cx, |text| text.to_uppercase())
 6352    }
 6353
 6354    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6355        self.manipulate_text(cx, |text| text.to_lowercase())
 6356    }
 6357
 6358    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6359        self.manipulate_text(cx, |text| {
 6360            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6361            // https://github.com/rutrum/convert-case/issues/16
 6362            text.split('\n')
 6363                .map(|line| line.to_case(Case::Title))
 6364                .join("\n")
 6365        })
 6366    }
 6367
 6368    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6369        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6370    }
 6371
 6372    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6373        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6374    }
 6375
 6376    pub fn convert_to_upper_camel_case(
 6377        &mut self,
 6378        _: &ConvertToUpperCamelCase,
 6379        cx: &mut ViewContext<Self>,
 6380    ) {
 6381        self.manipulate_text(cx, |text| {
 6382            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6383            // https://github.com/rutrum/convert-case/issues/16
 6384            text.split('\n')
 6385                .map(|line| line.to_case(Case::UpperCamel))
 6386                .join("\n")
 6387        })
 6388    }
 6389
 6390    pub fn convert_to_lower_camel_case(
 6391        &mut self,
 6392        _: &ConvertToLowerCamelCase,
 6393        cx: &mut ViewContext<Self>,
 6394    ) {
 6395        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6396    }
 6397
 6398    pub fn convert_to_opposite_case(
 6399        &mut self,
 6400        _: &ConvertToOppositeCase,
 6401        cx: &mut ViewContext<Self>,
 6402    ) {
 6403        self.manipulate_text(cx, |text| {
 6404            text.chars()
 6405                .fold(String::with_capacity(text.len()), |mut t, c| {
 6406                    if c.is_uppercase() {
 6407                        t.extend(c.to_lowercase());
 6408                    } else {
 6409                        t.extend(c.to_uppercase());
 6410                    }
 6411                    t
 6412                })
 6413        })
 6414    }
 6415
 6416    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6417    where
 6418        Fn: FnMut(&str) -> String,
 6419    {
 6420        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6421        let buffer = self.buffer.read(cx).snapshot(cx);
 6422
 6423        let mut new_selections = Vec::new();
 6424        let mut edits = Vec::new();
 6425        let mut selection_adjustment = 0i32;
 6426
 6427        for selection in self.selections.all::<usize>(cx) {
 6428            let selection_is_empty = selection.is_empty();
 6429
 6430            let (start, end) = if selection_is_empty {
 6431                let word_range = movement::surrounding_word(
 6432                    &display_map,
 6433                    selection.start.to_display_point(&display_map),
 6434                );
 6435                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6436                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6437                (start, end)
 6438            } else {
 6439                (selection.start, selection.end)
 6440            };
 6441
 6442            let text = buffer.text_for_range(start..end).collect::<String>();
 6443            let old_length = text.len() as i32;
 6444            let text = callback(&text);
 6445
 6446            new_selections.push(Selection {
 6447                start: (start as i32 - selection_adjustment) as usize,
 6448                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6449                goal: SelectionGoal::None,
 6450                ..selection
 6451            });
 6452
 6453            selection_adjustment += old_length - text.len() as i32;
 6454
 6455            edits.push((start..end, text));
 6456        }
 6457
 6458        self.transact(cx, |this, cx| {
 6459            this.buffer.update(cx, |buffer, cx| {
 6460                buffer.edit(edits, None, cx);
 6461            });
 6462
 6463            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6464                s.select(new_selections);
 6465            });
 6466
 6467            this.request_autoscroll(Autoscroll::fit(), cx);
 6468        });
 6469    }
 6470
 6471    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6472        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6473        let buffer = &display_map.buffer_snapshot;
 6474        let selections = self.selections.all::<Point>(cx);
 6475
 6476        let mut edits = Vec::new();
 6477        let mut selections_iter = selections.iter().peekable();
 6478        while let Some(selection) = selections_iter.next() {
 6479            // Avoid duplicating the same lines twice.
 6480            let mut rows = selection.spanned_rows(false, &display_map);
 6481
 6482            while let Some(next_selection) = selections_iter.peek() {
 6483                let next_rows = next_selection.spanned_rows(false, &display_map);
 6484                if next_rows.start < rows.end {
 6485                    rows.end = next_rows.end;
 6486                    selections_iter.next().unwrap();
 6487                } else {
 6488                    break;
 6489                }
 6490            }
 6491
 6492            // Copy the text from the selected row region and splice it either at the start
 6493            // or end of the region.
 6494            let start = Point::new(rows.start.0, 0);
 6495            let end = Point::new(
 6496                rows.end.previous_row().0,
 6497                buffer.line_len(rows.end.previous_row()),
 6498            );
 6499            let text = buffer
 6500                .text_for_range(start..end)
 6501                .chain(Some("\n"))
 6502                .collect::<String>();
 6503            let insert_location = if upwards {
 6504                Point::new(rows.end.0, 0)
 6505            } else {
 6506                start
 6507            };
 6508            edits.push((insert_location..insert_location, text));
 6509        }
 6510
 6511        self.transact(cx, |this, cx| {
 6512            this.buffer.update(cx, |buffer, cx| {
 6513                buffer.edit(edits, None, cx);
 6514            });
 6515
 6516            this.request_autoscroll(Autoscroll::fit(), cx);
 6517        });
 6518    }
 6519
 6520    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6521        self.duplicate_line(true, cx);
 6522    }
 6523
 6524    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6525        self.duplicate_line(false, cx);
 6526    }
 6527
 6528    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6530        let buffer = self.buffer.read(cx).snapshot(cx);
 6531
 6532        let mut edits = Vec::new();
 6533        let mut unfold_ranges = Vec::new();
 6534        let mut refold_ranges = Vec::new();
 6535
 6536        let selections = self.selections.all::<Point>(cx);
 6537        let mut selections = selections.iter().peekable();
 6538        let mut contiguous_row_selections = Vec::new();
 6539        let mut new_selections = Vec::new();
 6540
 6541        while let Some(selection) = selections.next() {
 6542            // Find all the selections that span a contiguous row range
 6543            let (start_row, end_row) = consume_contiguous_rows(
 6544                &mut contiguous_row_selections,
 6545                selection,
 6546                &display_map,
 6547                &mut selections,
 6548            );
 6549
 6550            // Move the text spanned by the row range to be before the line preceding the row range
 6551            if start_row.0 > 0 {
 6552                let range_to_move = Point::new(
 6553                    start_row.previous_row().0,
 6554                    buffer.line_len(start_row.previous_row()),
 6555                )
 6556                    ..Point::new(
 6557                        end_row.previous_row().0,
 6558                        buffer.line_len(end_row.previous_row()),
 6559                    );
 6560                let insertion_point = display_map
 6561                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6562                    .0;
 6563
 6564                // Don't move lines across excerpts
 6565                if buffer
 6566                    .excerpt_boundaries_in_range((
 6567                        Bound::Excluded(insertion_point),
 6568                        Bound::Included(range_to_move.end),
 6569                    ))
 6570                    .next()
 6571                    .is_none()
 6572                {
 6573                    let text = buffer
 6574                        .text_for_range(range_to_move.clone())
 6575                        .flat_map(|s| s.chars())
 6576                        .skip(1)
 6577                        .chain(['\n'])
 6578                        .collect::<String>();
 6579
 6580                    edits.push((
 6581                        buffer.anchor_after(range_to_move.start)
 6582                            ..buffer.anchor_before(range_to_move.end),
 6583                        String::new(),
 6584                    ));
 6585                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6586                    edits.push((insertion_anchor..insertion_anchor, text));
 6587
 6588                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6589
 6590                    // Move selections up
 6591                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6592                        |mut selection| {
 6593                            selection.start.row -= row_delta;
 6594                            selection.end.row -= row_delta;
 6595                            selection
 6596                        },
 6597                    ));
 6598
 6599                    // Move folds up
 6600                    unfold_ranges.push(range_to_move.clone());
 6601                    for fold in display_map.folds_in_range(
 6602                        buffer.anchor_before(range_to_move.start)
 6603                            ..buffer.anchor_after(range_to_move.end),
 6604                    ) {
 6605                        let mut start = fold.range.start.to_point(&buffer);
 6606                        let mut end = fold.range.end.to_point(&buffer);
 6607                        start.row -= row_delta;
 6608                        end.row -= row_delta;
 6609                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6610                    }
 6611                }
 6612            }
 6613
 6614            // If we didn't move line(s), preserve the existing selections
 6615            new_selections.append(&mut contiguous_row_selections);
 6616        }
 6617
 6618        self.transact(cx, |this, cx| {
 6619            this.unfold_ranges(unfold_ranges, true, true, cx);
 6620            this.buffer.update(cx, |buffer, cx| {
 6621                for (range, text) in edits {
 6622                    buffer.edit([(range, text)], None, cx);
 6623                }
 6624            });
 6625            this.fold_ranges(refold_ranges, true, cx);
 6626            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6627                s.select(new_selections);
 6628            })
 6629        });
 6630    }
 6631
 6632    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6634        let buffer = self.buffer.read(cx).snapshot(cx);
 6635
 6636        let mut edits = Vec::new();
 6637        let mut unfold_ranges = Vec::new();
 6638        let mut refold_ranges = Vec::new();
 6639
 6640        let selections = self.selections.all::<Point>(cx);
 6641        let mut selections = selections.iter().peekable();
 6642        let mut contiguous_row_selections = Vec::new();
 6643        let mut new_selections = Vec::new();
 6644
 6645        while let Some(selection) = selections.next() {
 6646            // Find all the selections that span a contiguous row range
 6647            let (start_row, end_row) = consume_contiguous_rows(
 6648                &mut contiguous_row_selections,
 6649                selection,
 6650                &display_map,
 6651                &mut selections,
 6652            );
 6653
 6654            // Move the text spanned by the row range to be after the last line of the row range
 6655            if end_row.0 <= buffer.max_point().row {
 6656                let range_to_move =
 6657                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6658                let insertion_point = display_map
 6659                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6660                    .0;
 6661
 6662                // Don't move lines across excerpt boundaries
 6663                if buffer
 6664                    .excerpt_boundaries_in_range((
 6665                        Bound::Excluded(range_to_move.start),
 6666                        Bound::Included(insertion_point),
 6667                    ))
 6668                    .next()
 6669                    .is_none()
 6670                {
 6671                    let mut text = String::from("\n");
 6672                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6673                    text.pop(); // Drop trailing newline
 6674                    edits.push((
 6675                        buffer.anchor_after(range_to_move.start)
 6676                            ..buffer.anchor_before(range_to_move.end),
 6677                        String::new(),
 6678                    ));
 6679                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6680                    edits.push((insertion_anchor..insertion_anchor, text));
 6681
 6682                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6683
 6684                    // Move selections down
 6685                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6686                        |mut selection| {
 6687                            selection.start.row += row_delta;
 6688                            selection.end.row += row_delta;
 6689                            selection
 6690                        },
 6691                    ));
 6692
 6693                    // Move folds down
 6694                    unfold_ranges.push(range_to_move.clone());
 6695                    for fold in display_map.folds_in_range(
 6696                        buffer.anchor_before(range_to_move.start)
 6697                            ..buffer.anchor_after(range_to_move.end),
 6698                    ) {
 6699                        let mut start = fold.range.start.to_point(&buffer);
 6700                        let mut end = fold.range.end.to_point(&buffer);
 6701                        start.row += row_delta;
 6702                        end.row += row_delta;
 6703                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6704                    }
 6705                }
 6706            }
 6707
 6708            // If we didn't move line(s), preserve the existing selections
 6709            new_selections.append(&mut contiguous_row_selections);
 6710        }
 6711
 6712        self.transact(cx, |this, cx| {
 6713            this.unfold_ranges(unfold_ranges, true, true, cx);
 6714            this.buffer.update(cx, |buffer, cx| {
 6715                for (range, text) in edits {
 6716                    buffer.edit([(range, text)], None, cx);
 6717                }
 6718            });
 6719            this.fold_ranges(refold_ranges, true, cx);
 6720            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6721        });
 6722    }
 6723
 6724    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6725        let text_layout_details = &self.text_layout_details(cx);
 6726        self.transact(cx, |this, cx| {
 6727            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6728                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6729                let line_mode = s.line_mode;
 6730                s.move_with(|display_map, selection| {
 6731                    if !selection.is_empty() || line_mode {
 6732                        return;
 6733                    }
 6734
 6735                    let mut head = selection.head();
 6736                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6737                    if head.column() == display_map.line_len(head.row()) {
 6738                        transpose_offset = display_map
 6739                            .buffer_snapshot
 6740                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6741                    }
 6742
 6743                    if transpose_offset == 0 {
 6744                        return;
 6745                    }
 6746
 6747                    *head.column_mut() += 1;
 6748                    head = display_map.clip_point(head, Bias::Right);
 6749                    let goal = SelectionGoal::HorizontalPosition(
 6750                        display_map
 6751                            .x_for_display_point(head, text_layout_details)
 6752                            .into(),
 6753                    );
 6754                    selection.collapse_to(head, goal);
 6755
 6756                    let transpose_start = display_map
 6757                        .buffer_snapshot
 6758                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6759                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6760                        let transpose_end = display_map
 6761                            .buffer_snapshot
 6762                            .clip_offset(transpose_offset + 1, Bias::Right);
 6763                        if let Some(ch) =
 6764                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6765                        {
 6766                            edits.push((transpose_start..transpose_offset, String::new()));
 6767                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6768                        }
 6769                    }
 6770                });
 6771                edits
 6772            });
 6773            this.buffer
 6774                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6775            let selections = this.selections.all::<usize>(cx);
 6776            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6777                s.select(selections);
 6778            });
 6779        });
 6780    }
 6781
 6782    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6783        self.rewrap_impl(true, cx)
 6784    }
 6785
 6786    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6787        let buffer = self.buffer.read(cx).snapshot(cx);
 6788        let selections = self.selections.all::<Point>(cx);
 6789        let mut selections = selections.iter().peekable();
 6790
 6791        let mut edits = Vec::new();
 6792        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6793
 6794        while let Some(selection) = selections.next() {
 6795            let mut start_row = selection.start.row;
 6796            let mut end_row = selection.end.row;
 6797
 6798            // Skip selections that overlap with a range that has already been rewrapped.
 6799            let selection_range = start_row..end_row;
 6800            if rewrapped_row_ranges
 6801                .iter()
 6802                .any(|range| range.overlaps(&selection_range))
 6803            {
 6804                continue;
 6805            }
 6806
 6807            let mut should_rewrap = !only_text;
 6808
 6809            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6810                match language_scope.language_name().0.as_ref() {
 6811                    "Markdown" | "Plain Text" => {
 6812                        should_rewrap = true;
 6813                    }
 6814                    _ => {}
 6815                }
 6816            }
 6817
 6818            // Since not all lines in the selection may be at the same indent
 6819            // level, choose the indent size that is the most common between all
 6820            // of the lines.
 6821            //
 6822            // If there is a tie, we use the deepest indent.
 6823            let (indent_size, indent_end) = {
 6824                let mut indent_size_occurrences = HashMap::default();
 6825                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6826
 6827                for row in start_row..=end_row {
 6828                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6829                    rows_by_indent_size.entry(indent).or_default().push(row);
 6830                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6831                }
 6832
 6833                let indent_size = indent_size_occurrences
 6834                    .into_iter()
 6835                    .max_by_key(|(indent, count)| (*count, indent.len))
 6836                    .map(|(indent, _)| indent)
 6837                    .unwrap_or_default();
 6838                let row = rows_by_indent_size[&indent_size][0];
 6839                let indent_end = Point::new(row, indent_size.len);
 6840
 6841                (indent_size, indent_end)
 6842            };
 6843
 6844            let mut line_prefix = indent_size.chars().collect::<String>();
 6845
 6846            if let Some(comment_prefix) =
 6847                buffer
 6848                    .language_scope_at(selection.head())
 6849                    .and_then(|language| {
 6850                        language
 6851                            .line_comment_prefixes()
 6852                            .iter()
 6853                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6854                            .cloned()
 6855                    })
 6856            {
 6857                line_prefix.push_str(&comment_prefix);
 6858                should_rewrap = true;
 6859            }
 6860
 6861            if selection.is_empty() {
 6862                'expand_upwards: while start_row > 0 {
 6863                    let prev_row = start_row - 1;
 6864                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6865                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6866                    {
 6867                        start_row = prev_row;
 6868                    } else {
 6869                        break 'expand_upwards;
 6870                    }
 6871                }
 6872
 6873                'expand_downwards: while end_row < buffer.max_point().row {
 6874                    let next_row = end_row + 1;
 6875                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6876                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6877                    {
 6878                        end_row = next_row;
 6879                    } else {
 6880                        break 'expand_downwards;
 6881                    }
 6882                }
 6883            }
 6884
 6885            if !should_rewrap {
 6886                continue;
 6887            }
 6888
 6889            let start = Point::new(start_row, 0);
 6890            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6891            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6892            let Some(lines_without_prefixes) = selection_text
 6893                .lines()
 6894                .map(|line| {
 6895                    line.strip_prefix(&line_prefix)
 6896                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6897                        .ok_or_else(|| {
 6898                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6899                        })
 6900                })
 6901                .collect::<Result<Vec<_>, _>>()
 6902                .log_err()
 6903            else {
 6904                continue;
 6905            };
 6906
 6907            let unwrapped_text = lines_without_prefixes.join(" ");
 6908            let wrap_column = buffer
 6909                .settings_at(Point::new(start_row, 0), cx)
 6910                .preferred_line_length as usize;
 6911            let mut wrapped_text = String::new();
 6912            let mut current_line = line_prefix.clone();
 6913            for word in unwrapped_text.split_whitespace() {
 6914                if current_line.len() + word.len() >= wrap_column {
 6915                    wrapped_text.push_str(&current_line);
 6916                    wrapped_text.push('\n');
 6917                    current_line.truncate(line_prefix.len());
 6918                }
 6919
 6920                if current_line.len() > line_prefix.len() {
 6921                    current_line.push(' ');
 6922                }
 6923
 6924                current_line.push_str(word);
 6925            }
 6926
 6927            if !current_line.is_empty() {
 6928                wrapped_text.push_str(&current_line);
 6929            }
 6930
 6931            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 6932            let mut offset = start.to_offset(&buffer);
 6933            let mut moved_since_edit = true;
 6934
 6935            for change in diff.iter_all_changes() {
 6936                let value = change.value();
 6937                match change.tag() {
 6938                    ChangeTag::Equal => {
 6939                        offset += value.len();
 6940                        moved_since_edit = true;
 6941                    }
 6942                    ChangeTag::Delete => {
 6943                        let start = buffer.anchor_after(offset);
 6944                        let end = buffer.anchor_before(offset + value.len());
 6945
 6946                        if moved_since_edit {
 6947                            edits.push((start..end, String::new()));
 6948                        } else {
 6949                            edits.last_mut().unwrap().0.end = end;
 6950                        }
 6951
 6952                        offset += value.len();
 6953                        moved_since_edit = false;
 6954                    }
 6955                    ChangeTag::Insert => {
 6956                        if moved_since_edit {
 6957                            let anchor = buffer.anchor_after(offset);
 6958                            edits.push((anchor..anchor, value.to_string()));
 6959                        } else {
 6960                            edits.last_mut().unwrap().1.push_str(value);
 6961                        }
 6962
 6963                        moved_since_edit = false;
 6964                    }
 6965                }
 6966            }
 6967
 6968            rewrapped_row_ranges.push(start_row..=end_row);
 6969        }
 6970
 6971        self.buffer
 6972            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6973    }
 6974
 6975    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6976        let mut text = String::new();
 6977        let buffer = self.buffer.read(cx).snapshot(cx);
 6978        let mut selections = self.selections.all::<Point>(cx);
 6979        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6980        {
 6981            let max_point = buffer.max_point();
 6982            let mut is_first = true;
 6983            for selection in &mut selections {
 6984                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6985                if is_entire_line {
 6986                    selection.start = Point::new(selection.start.row, 0);
 6987                    if !selection.is_empty() && selection.end.column == 0 {
 6988                        selection.end = cmp::min(max_point, selection.end);
 6989                    } else {
 6990                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6991                    }
 6992                    selection.goal = SelectionGoal::None;
 6993                }
 6994                if is_first {
 6995                    is_first = false;
 6996                } else {
 6997                    text += "\n";
 6998                }
 6999                let mut len = 0;
 7000                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7001                    text.push_str(chunk);
 7002                    len += chunk.len();
 7003                }
 7004                clipboard_selections.push(ClipboardSelection {
 7005                    len,
 7006                    is_entire_line,
 7007                    first_line_indent: buffer
 7008                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7009                        .len,
 7010                });
 7011            }
 7012        }
 7013
 7014        self.transact(cx, |this, cx| {
 7015            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7016                s.select(selections);
 7017            });
 7018            this.insert("", cx);
 7019            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7020                text,
 7021                clipboard_selections,
 7022            ));
 7023        });
 7024    }
 7025
 7026    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7027        let selections = self.selections.all::<Point>(cx);
 7028        let buffer = self.buffer.read(cx).read(cx);
 7029        let mut text = String::new();
 7030
 7031        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7032        {
 7033            let max_point = buffer.max_point();
 7034            let mut is_first = true;
 7035            for selection in selections.iter() {
 7036                let mut start = selection.start;
 7037                let mut end = selection.end;
 7038                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7039                if is_entire_line {
 7040                    start = Point::new(start.row, 0);
 7041                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7042                }
 7043                if is_first {
 7044                    is_first = false;
 7045                } else {
 7046                    text += "\n";
 7047                }
 7048                let mut len = 0;
 7049                for chunk in buffer.text_for_range(start..end) {
 7050                    text.push_str(chunk);
 7051                    len += chunk.len();
 7052                }
 7053                clipboard_selections.push(ClipboardSelection {
 7054                    len,
 7055                    is_entire_line,
 7056                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7057                });
 7058            }
 7059        }
 7060
 7061        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7062            text,
 7063            clipboard_selections,
 7064        ));
 7065    }
 7066
 7067    pub fn do_paste(
 7068        &mut self,
 7069        text: &String,
 7070        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7071        handle_entire_lines: bool,
 7072        cx: &mut ViewContext<Self>,
 7073    ) {
 7074        if self.read_only(cx) {
 7075            return;
 7076        }
 7077
 7078        let clipboard_text = Cow::Borrowed(text);
 7079
 7080        self.transact(cx, |this, cx| {
 7081            if let Some(mut clipboard_selections) = clipboard_selections {
 7082                let old_selections = this.selections.all::<usize>(cx);
 7083                let all_selections_were_entire_line =
 7084                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7085                let first_selection_indent_column =
 7086                    clipboard_selections.first().map(|s| s.first_line_indent);
 7087                if clipboard_selections.len() != old_selections.len() {
 7088                    clipboard_selections.drain(..);
 7089                }
 7090
 7091                this.buffer.update(cx, |buffer, cx| {
 7092                    let snapshot = buffer.read(cx);
 7093                    let mut start_offset = 0;
 7094                    let mut edits = Vec::new();
 7095                    let mut original_indent_columns = Vec::new();
 7096                    for (ix, selection) in old_selections.iter().enumerate() {
 7097                        let to_insert;
 7098                        let entire_line;
 7099                        let original_indent_column;
 7100                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7101                            let end_offset = start_offset + clipboard_selection.len;
 7102                            to_insert = &clipboard_text[start_offset..end_offset];
 7103                            entire_line = clipboard_selection.is_entire_line;
 7104                            start_offset = end_offset + 1;
 7105                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7106                        } else {
 7107                            to_insert = clipboard_text.as_str();
 7108                            entire_line = all_selections_were_entire_line;
 7109                            original_indent_column = first_selection_indent_column
 7110                        }
 7111
 7112                        // If the corresponding selection was empty when this slice of the
 7113                        // clipboard text was written, then the entire line containing the
 7114                        // selection was copied. If this selection is also currently empty,
 7115                        // then paste the line before the current line of the buffer.
 7116                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7117                            let column = selection.start.to_point(&snapshot).column as usize;
 7118                            let line_start = selection.start - column;
 7119                            line_start..line_start
 7120                        } else {
 7121                            selection.range()
 7122                        };
 7123
 7124                        edits.push((range, to_insert));
 7125                        original_indent_columns.extend(original_indent_column);
 7126                    }
 7127                    drop(snapshot);
 7128
 7129                    buffer.edit(
 7130                        edits,
 7131                        Some(AutoindentMode::Block {
 7132                            original_indent_columns,
 7133                        }),
 7134                        cx,
 7135                    );
 7136                });
 7137
 7138                let selections = this.selections.all::<usize>(cx);
 7139                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7140            } else {
 7141                this.insert(&clipboard_text, cx);
 7142            }
 7143        });
 7144    }
 7145
 7146    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7147        if let Some(item) = cx.read_from_clipboard() {
 7148            let entries = item.entries();
 7149
 7150            match entries.first() {
 7151                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7152                // of all the pasted entries.
 7153                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7154                    .do_paste(
 7155                        clipboard_string.text(),
 7156                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7157                        true,
 7158                        cx,
 7159                    ),
 7160                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7161            }
 7162        }
 7163    }
 7164
 7165    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7166        if self.read_only(cx) {
 7167            return;
 7168        }
 7169
 7170        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7171            if let Some((selections, _)) =
 7172                self.selection_history.transaction(transaction_id).cloned()
 7173            {
 7174                self.change_selections(None, cx, |s| {
 7175                    s.select_anchors(selections.to_vec());
 7176                });
 7177            }
 7178            self.request_autoscroll(Autoscroll::fit(), cx);
 7179            self.unmark_text(cx);
 7180            self.refresh_inline_completion(true, false, cx);
 7181            cx.emit(EditorEvent::Edited { transaction_id });
 7182            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7183        }
 7184    }
 7185
 7186    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7187        if self.read_only(cx) {
 7188            return;
 7189        }
 7190
 7191        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7192            if let Some((_, Some(selections))) =
 7193                self.selection_history.transaction(transaction_id).cloned()
 7194            {
 7195                self.change_selections(None, cx, |s| {
 7196                    s.select_anchors(selections.to_vec());
 7197                });
 7198            }
 7199            self.request_autoscroll(Autoscroll::fit(), cx);
 7200            self.unmark_text(cx);
 7201            self.refresh_inline_completion(true, false, cx);
 7202            cx.emit(EditorEvent::Edited { transaction_id });
 7203        }
 7204    }
 7205
 7206    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7207        self.buffer
 7208            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7209    }
 7210
 7211    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7212        self.buffer
 7213            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7214    }
 7215
 7216    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7217        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7218            let line_mode = s.line_mode;
 7219            s.move_with(|map, selection| {
 7220                let cursor = if selection.is_empty() && !line_mode {
 7221                    movement::left(map, selection.start)
 7222                } else {
 7223                    selection.start
 7224                };
 7225                selection.collapse_to(cursor, SelectionGoal::None);
 7226            });
 7227        })
 7228    }
 7229
 7230    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7231        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7232            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7233        })
 7234    }
 7235
 7236    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7237        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7238            let line_mode = s.line_mode;
 7239            s.move_with(|map, selection| {
 7240                let cursor = if selection.is_empty() && !line_mode {
 7241                    movement::right(map, selection.end)
 7242                } else {
 7243                    selection.end
 7244                };
 7245                selection.collapse_to(cursor, SelectionGoal::None)
 7246            });
 7247        })
 7248    }
 7249
 7250    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7251        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7252            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7253        })
 7254    }
 7255
 7256    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7257        if self.take_rename(true, cx).is_some() {
 7258            return;
 7259        }
 7260
 7261        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7262            cx.propagate();
 7263            return;
 7264        }
 7265
 7266        let text_layout_details = &self.text_layout_details(cx);
 7267        let selection_count = self.selections.count();
 7268        let first_selection = self.selections.first_anchor();
 7269
 7270        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7271            let line_mode = s.line_mode;
 7272            s.move_with(|map, selection| {
 7273                if !selection.is_empty() && !line_mode {
 7274                    selection.goal = SelectionGoal::None;
 7275                }
 7276                let (cursor, goal) = movement::up(
 7277                    map,
 7278                    selection.start,
 7279                    selection.goal,
 7280                    false,
 7281                    text_layout_details,
 7282                );
 7283                selection.collapse_to(cursor, goal);
 7284            });
 7285        });
 7286
 7287        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7288        {
 7289            cx.propagate();
 7290        }
 7291    }
 7292
 7293    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7294        if self.take_rename(true, cx).is_some() {
 7295            return;
 7296        }
 7297
 7298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7299            cx.propagate();
 7300            return;
 7301        }
 7302
 7303        let text_layout_details = &self.text_layout_details(cx);
 7304
 7305        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7306            let line_mode = s.line_mode;
 7307            s.move_with(|map, selection| {
 7308                if !selection.is_empty() && !line_mode {
 7309                    selection.goal = SelectionGoal::None;
 7310                }
 7311                let (cursor, goal) = movement::up_by_rows(
 7312                    map,
 7313                    selection.start,
 7314                    action.lines,
 7315                    selection.goal,
 7316                    false,
 7317                    text_layout_details,
 7318                );
 7319                selection.collapse_to(cursor, goal);
 7320            });
 7321        })
 7322    }
 7323
 7324    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7325        if self.take_rename(true, cx).is_some() {
 7326            return;
 7327        }
 7328
 7329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7330            cx.propagate();
 7331            return;
 7332        }
 7333
 7334        let text_layout_details = &self.text_layout_details(cx);
 7335
 7336        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7337            let line_mode = s.line_mode;
 7338            s.move_with(|map, selection| {
 7339                if !selection.is_empty() && !line_mode {
 7340                    selection.goal = SelectionGoal::None;
 7341                }
 7342                let (cursor, goal) = movement::down_by_rows(
 7343                    map,
 7344                    selection.start,
 7345                    action.lines,
 7346                    selection.goal,
 7347                    false,
 7348                    text_layout_details,
 7349                );
 7350                selection.collapse_to(cursor, goal);
 7351            });
 7352        })
 7353    }
 7354
 7355    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7356        let text_layout_details = &self.text_layout_details(cx);
 7357        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7358            s.move_heads_with(|map, head, goal| {
 7359                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7360            })
 7361        })
 7362    }
 7363
 7364    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7365        let text_layout_details = &self.text_layout_details(cx);
 7366        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7367            s.move_heads_with(|map, head, goal| {
 7368                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7369            })
 7370        })
 7371    }
 7372
 7373    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7374        let Some(row_count) = self.visible_row_count() else {
 7375            return;
 7376        };
 7377
 7378        let text_layout_details = &self.text_layout_details(cx);
 7379
 7380        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7381            s.move_heads_with(|map, head, goal| {
 7382                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7383            })
 7384        })
 7385    }
 7386
 7387    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7388        if self.take_rename(true, cx).is_some() {
 7389            return;
 7390        }
 7391
 7392        if self
 7393            .context_menu
 7394            .write()
 7395            .as_mut()
 7396            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 7397            .unwrap_or(false)
 7398        {
 7399            return;
 7400        }
 7401
 7402        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7403            cx.propagate();
 7404            return;
 7405        }
 7406
 7407        let Some(row_count) = self.visible_row_count() else {
 7408            return;
 7409        };
 7410
 7411        let autoscroll = if action.center_cursor {
 7412            Autoscroll::center()
 7413        } else {
 7414            Autoscroll::fit()
 7415        };
 7416
 7417        let text_layout_details = &self.text_layout_details(cx);
 7418
 7419        self.change_selections(Some(autoscroll), cx, |s| {
 7420            let line_mode = s.line_mode;
 7421            s.move_with(|map, selection| {
 7422                if !selection.is_empty() && !line_mode {
 7423                    selection.goal = SelectionGoal::None;
 7424                }
 7425                let (cursor, goal) = movement::up_by_rows(
 7426                    map,
 7427                    selection.end,
 7428                    row_count,
 7429                    selection.goal,
 7430                    false,
 7431                    text_layout_details,
 7432                );
 7433                selection.collapse_to(cursor, goal);
 7434            });
 7435        });
 7436    }
 7437
 7438    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7439        let text_layout_details = &self.text_layout_details(cx);
 7440        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7441            s.move_heads_with(|map, head, goal| {
 7442                movement::up(map, head, goal, false, text_layout_details)
 7443            })
 7444        })
 7445    }
 7446
 7447    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7448        self.take_rename(true, cx);
 7449
 7450        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7451            cx.propagate();
 7452            return;
 7453        }
 7454
 7455        let text_layout_details = &self.text_layout_details(cx);
 7456        let selection_count = self.selections.count();
 7457        let first_selection = self.selections.first_anchor();
 7458
 7459        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7460            let line_mode = s.line_mode;
 7461            s.move_with(|map, selection| {
 7462                if !selection.is_empty() && !line_mode {
 7463                    selection.goal = SelectionGoal::None;
 7464                }
 7465                let (cursor, goal) = movement::down(
 7466                    map,
 7467                    selection.end,
 7468                    selection.goal,
 7469                    false,
 7470                    text_layout_details,
 7471                );
 7472                selection.collapse_to(cursor, goal);
 7473            });
 7474        });
 7475
 7476        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7477        {
 7478            cx.propagate();
 7479        }
 7480    }
 7481
 7482    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7483        let Some(row_count) = self.visible_row_count() else {
 7484            return;
 7485        };
 7486
 7487        let text_layout_details = &self.text_layout_details(cx);
 7488
 7489        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7490            s.move_heads_with(|map, head, goal| {
 7491                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7492            })
 7493        })
 7494    }
 7495
 7496    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7497        if self.take_rename(true, cx).is_some() {
 7498            return;
 7499        }
 7500
 7501        if self
 7502            .context_menu
 7503            .write()
 7504            .as_mut()
 7505            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7506            .unwrap_or(false)
 7507        {
 7508            return;
 7509        }
 7510
 7511        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7512            cx.propagate();
 7513            return;
 7514        }
 7515
 7516        let Some(row_count) = self.visible_row_count() else {
 7517            return;
 7518        };
 7519
 7520        let autoscroll = if action.center_cursor {
 7521            Autoscroll::center()
 7522        } else {
 7523            Autoscroll::fit()
 7524        };
 7525
 7526        let text_layout_details = &self.text_layout_details(cx);
 7527        self.change_selections(Some(autoscroll), cx, |s| {
 7528            let line_mode = s.line_mode;
 7529            s.move_with(|map, selection| {
 7530                if !selection.is_empty() && !line_mode {
 7531                    selection.goal = SelectionGoal::None;
 7532                }
 7533                let (cursor, goal) = movement::down_by_rows(
 7534                    map,
 7535                    selection.end,
 7536                    row_count,
 7537                    selection.goal,
 7538                    false,
 7539                    text_layout_details,
 7540                );
 7541                selection.collapse_to(cursor, goal);
 7542            });
 7543        });
 7544    }
 7545
 7546    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7547        let text_layout_details = &self.text_layout_details(cx);
 7548        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7549            s.move_heads_with(|map, head, goal| {
 7550                movement::down(map, head, goal, false, text_layout_details)
 7551            })
 7552        });
 7553    }
 7554
 7555    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7556        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7557            context_menu.select_first(self.project.as_ref(), cx);
 7558        }
 7559    }
 7560
 7561    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7562        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7563            context_menu.select_prev(self.project.as_ref(), cx);
 7564        }
 7565    }
 7566
 7567    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7568        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7569            context_menu.select_next(self.project.as_ref(), cx);
 7570        }
 7571    }
 7572
 7573    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7574        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7575            context_menu.select_last(self.project.as_ref(), cx);
 7576        }
 7577    }
 7578
 7579    pub fn move_to_previous_word_start(
 7580        &mut self,
 7581        _: &MoveToPreviousWordStart,
 7582        cx: &mut ViewContext<Self>,
 7583    ) {
 7584        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7585            s.move_cursors_with(|map, head, _| {
 7586                (
 7587                    movement::previous_word_start(map, head),
 7588                    SelectionGoal::None,
 7589                )
 7590            });
 7591        })
 7592    }
 7593
 7594    pub fn move_to_previous_subword_start(
 7595        &mut self,
 7596        _: &MoveToPreviousSubwordStart,
 7597        cx: &mut ViewContext<Self>,
 7598    ) {
 7599        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7600            s.move_cursors_with(|map, head, _| {
 7601                (
 7602                    movement::previous_subword_start(map, head),
 7603                    SelectionGoal::None,
 7604                )
 7605            });
 7606        })
 7607    }
 7608
 7609    pub fn select_to_previous_word_start(
 7610        &mut self,
 7611        _: &SelectToPreviousWordStart,
 7612        cx: &mut ViewContext<Self>,
 7613    ) {
 7614        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7615            s.move_heads_with(|map, head, _| {
 7616                (
 7617                    movement::previous_word_start(map, head),
 7618                    SelectionGoal::None,
 7619                )
 7620            });
 7621        })
 7622    }
 7623
 7624    pub fn select_to_previous_subword_start(
 7625        &mut self,
 7626        _: &SelectToPreviousSubwordStart,
 7627        cx: &mut ViewContext<Self>,
 7628    ) {
 7629        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7630            s.move_heads_with(|map, head, _| {
 7631                (
 7632                    movement::previous_subword_start(map, head),
 7633                    SelectionGoal::None,
 7634                )
 7635            });
 7636        })
 7637    }
 7638
 7639    pub fn delete_to_previous_word_start(
 7640        &mut self,
 7641        action: &DeleteToPreviousWordStart,
 7642        cx: &mut ViewContext<Self>,
 7643    ) {
 7644        self.transact(cx, |this, cx| {
 7645            this.select_autoclose_pair(cx);
 7646            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7647                let line_mode = s.line_mode;
 7648                s.move_with(|map, selection| {
 7649                    if selection.is_empty() && !line_mode {
 7650                        let cursor = if action.ignore_newlines {
 7651                            movement::previous_word_start(map, selection.head())
 7652                        } else {
 7653                            movement::previous_word_start_or_newline(map, selection.head())
 7654                        };
 7655                        selection.set_head(cursor, SelectionGoal::None);
 7656                    }
 7657                });
 7658            });
 7659            this.insert("", cx);
 7660        });
 7661    }
 7662
 7663    pub fn delete_to_previous_subword_start(
 7664        &mut self,
 7665        _: &DeleteToPreviousSubwordStart,
 7666        cx: &mut ViewContext<Self>,
 7667    ) {
 7668        self.transact(cx, |this, cx| {
 7669            this.select_autoclose_pair(cx);
 7670            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7671                let line_mode = s.line_mode;
 7672                s.move_with(|map, selection| {
 7673                    if selection.is_empty() && !line_mode {
 7674                        let cursor = movement::previous_subword_start(map, selection.head());
 7675                        selection.set_head(cursor, SelectionGoal::None);
 7676                    }
 7677                });
 7678            });
 7679            this.insert("", cx);
 7680        });
 7681    }
 7682
 7683    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7684        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7685            s.move_cursors_with(|map, head, _| {
 7686                (movement::next_word_end(map, head), SelectionGoal::None)
 7687            });
 7688        })
 7689    }
 7690
 7691    pub fn move_to_next_subword_end(
 7692        &mut self,
 7693        _: &MoveToNextSubwordEnd,
 7694        cx: &mut ViewContext<Self>,
 7695    ) {
 7696        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7697            s.move_cursors_with(|map, head, _| {
 7698                (movement::next_subword_end(map, head), SelectionGoal::None)
 7699            });
 7700        })
 7701    }
 7702
 7703    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7704        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7705            s.move_heads_with(|map, head, _| {
 7706                (movement::next_word_end(map, head), SelectionGoal::None)
 7707            });
 7708        })
 7709    }
 7710
 7711    pub fn select_to_next_subword_end(
 7712        &mut self,
 7713        _: &SelectToNextSubwordEnd,
 7714        cx: &mut ViewContext<Self>,
 7715    ) {
 7716        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7717            s.move_heads_with(|map, head, _| {
 7718                (movement::next_subword_end(map, head), SelectionGoal::None)
 7719            });
 7720        })
 7721    }
 7722
 7723    pub fn delete_to_next_word_end(
 7724        &mut self,
 7725        action: &DeleteToNextWordEnd,
 7726        cx: &mut ViewContext<Self>,
 7727    ) {
 7728        self.transact(cx, |this, cx| {
 7729            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7730                let line_mode = s.line_mode;
 7731                s.move_with(|map, selection| {
 7732                    if selection.is_empty() && !line_mode {
 7733                        let cursor = if action.ignore_newlines {
 7734                            movement::next_word_end(map, selection.head())
 7735                        } else {
 7736                            movement::next_word_end_or_newline(map, selection.head())
 7737                        };
 7738                        selection.set_head(cursor, SelectionGoal::None);
 7739                    }
 7740                });
 7741            });
 7742            this.insert("", cx);
 7743        });
 7744    }
 7745
 7746    pub fn delete_to_next_subword_end(
 7747        &mut self,
 7748        _: &DeleteToNextSubwordEnd,
 7749        cx: &mut ViewContext<Self>,
 7750    ) {
 7751        self.transact(cx, |this, cx| {
 7752            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7753                s.move_with(|map, selection| {
 7754                    if selection.is_empty() {
 7755                        let cursor = movement::next_subword_end(map, selection.head());
 7756                        selection.set_head(cursor, SelectionGoal::None);
 7757                    }
 7758                });
 7759            });
 7760            this.insert("", cx);
 7761        });
 7762    }
 7763
 7764    pub fn move_to_beginning_of_line(
 7765        &mut self,
 7766        action: &MoveToBeginningOfLine,
 7767        cx: &mut ViewContext<Self>,
 7768    ) {
 7769        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7770            s.move_cursors_with(|map, head, _| {
 7771                (
 7772                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7773                    SelectionGoal::None,
 7774                )
 7775            });
 7776        })
 7777    }
 7778
 7779    pub fn select_to_beginning_of_line(
 7780        &mut self,
 7781        action: &SelectToBeginningOfLine,
 7782        cx: &mut ViewContext<Self>,
 7783    ) {
 7784        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7785            s.move_heads_with(|map, head, _| {
 7786                (
 7787                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7788                    SelectionGoal::None,
 7789                )
 7790            });
 7791        });
 7792    }
 7793
 7794    pub fn delete_to_beginning_of_line(
 7795        &mut self,
 7796        _: &DeleteToBeginningOfLine,
 7797        cx: &mut ViewContext<Self>,
 7798    ) {
 7799        self.transact(cx, |this, cx| {
 7800            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7801                s.move_with(|_, selection| {
 7802                    selection.reversed = true;
 7803                });
 7804            });
 7805
 7806            this.select_to_beginning_of_line(
 7807                &SelectToBeginningOfLine {
 7808                    stop_at_soft_wraps: false,
 7809                },
 7810                cx,
 7811            );
 7812            this.backspace(&Backspace, cx);
 7813        });
 7814    }
 7815
 7816    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7817        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7818            s.move_cursors_with(|map, head, _| {
 7819                (
 7820                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7821                    SelectionGoal::None,
 7822                )
 7823            });
 7824        })
 7825    }
 7826
 7827    pub fn select_to_end_of_line(
 7828        &mut self,
 7829        action: &SelectToEndOfLine,
 7830        cx: &mut ViewContext<Self>,
 7831    ) {
 7832        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7833            s.move_heads_with(|map, head, _| {
 7834                (
 7835                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7836                    SelectionGoal::None,
 7837                )
 7838            });
 7839        })
 7840    }
 7841
 7842    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7843        self.transact(cx, |this, cx| {
 7844            this.select_to_end_of_line(
 7845                &SelectToEndOfLine {
 7846                    stop_at_soft_wraps: false,
 7847                },
 7848                cx,
 7849            );
 7850            this.delete(&Delete, cx);
 7851        });
 7852    }
 7853
 7854    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7855        self.transact(cx, |this, cx| {
 7856            this.select_to_end_of_line(
 7857                &SelectToEndOfLine {
 7858                    stop_at_soft_wraps: false,
 7859                },
 7860                cx,
 7861            );
 7862            this.cut(&Cut, cx);
 7863        });
 7864    }
 7865
 7866    pub fn move_to_start_of_paragraph(
 7867        &mut self,
 7868        _: &MoveToStartOfParagraph,
 7869        cx: &mut ViewContext<Self>,
 7870    ) {
 7871        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7872            cx.propagate();
 7873            return;
 7874        }
 7875
 7876        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7877            s.move_with(|map, selection| {
 7878                selection.collapse_to(
 7879                    movement::start_of_paragraph(map, selection.head(), 1),
 7880                    SelectionGoal::None,
 7881                )
 7882            });
 7883        })
 7884    }
 7885
 7886    pub fn move_to_end_of_paragraph(
 7887        &mut self,
 7888        _: &MoveToEndOfParagraph,
 7889        cx: &mut ViewContext<Self>,
 7890    ) {
 7891        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7892            cx.propagate();
 7893            return;
 7894        }
 7895
 7896        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7897            s.move_with(|map, selection| {
 7898                selection.collapse_to(
 7899                    movement::end_of_paragraph(map, selection.head(), 1),
 7900                    SelectionGoal::None,
 7901                )
 7902            });
 7903        })
 7904    }
 7905
 7906    pub fn select_to_start_of_paragraph(
 7907        &mut self,
 7908        _: &SelectToStartOfParagraph,
 7909        cx: &mut ViewContext<Self>,
 7910    ) {
 7911        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7912            cx.propagate();
 7913            return;
 7914        }
 7915
 7916        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7917            s.move_heads_with(|map, head, _| {
 7918                (
 7919                    movement::start_of_paragraph(map, head, 1),
 7920                    SelectionGoal::None,
 7921                )
 7922            });
 7923        })
 7924    }
 7925
 7926    pub fn select_to_end_of_paragraph(
 7927        &mut self,
 7928        _: &SelectToEndOfParagraph,
 7929        cx: &mut ViewContext<Self>,
 7930    ) {
 7931        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7932            cx.propagate();
 7933            return;
 7934        }
 7935
 7936        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7937            s.move_heads_with(|map, head, _| {
 7938                (
 7939                    movement::end_of_paragraph(map, head, 1),
 7940                    SelectionGoal::None,
 7941                )
 7942            });
 7943        })
 7944    }
 7945
 7946    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7947        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7948            cx.propagate();
 7949            return;
 7950        }
 7951
 7952        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7953            s.select_ranges(vec![0..0]);
 7954        });
 7955    }
 7956
 7957    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7958        let mut selection = self.selections.last::<Point>(cx);
 7959        selection.set_head(Point::zero(), SelectionGoal::None);
 7960
 7961        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7962            s.select(vec![selection]);
 7963        });
 7964    }
 7965
 7966    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7967        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7968            cx.propagate();
 7969            return;
 7970        }
 7971
 7972        let cursor = self.buffer.read(cx).read(cx).len();
 7973        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7974            s.select_ranges(vec![cursor..cursor])
 7975        });
 7976    }
 7977
 7978    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7979        self.nav_history = nav_history;
 7980    }
 7981
 7982    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7983        self.nav_history.as_ref()
 7984    }
 7985
 7986    fn push_to_nav_history(
 7987        &mut self,
 7988        cursor_anchor: Anchor,
 7989        new_position: Option<Point>,
 7990        cx: &mut ViewContext<Self>,
 7991    ) {
 7992        if let Some(nav_history) = self.nav_history.as_mut() {
 7993            let buffer = self.buffer.read(cx).read(cx);
 7994            let cursor_position = cursor_anchor.to_point(&buffer);
 7995            let scroll_state = self.scroll_manager.anchor();
 7996            let scroll_top_row = scroll_state.top_row(&buffer);
 7997            drop(buffer);
 7998
 7999            if let Some(new_position) = new_position {
 8000                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8001                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8002                    return;
 8003                }
 8004            }
 8005
 8006            nav_history.push(
 8007                Some(NavigationData {
 8008                    cursor_anchor,
 8009                    cursor_position,
 8010                    scroll_anchor: scroll_state,
 8011                    scroll_top_row,
 8012                }),
 8013                cx,
 8014            );
 8015        }
 8016    }
 8017
 8018    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8019        let buffer = self.buffer.read(cx).snapshot(cx);
 8020        let mut selection = self.selections.first::<usize>(cx);
 8021        selection.set_head(buffer.len(), SelectionGoal::None);
 8022        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8023            s.select(vec![selection]);
 8024        });
 8025    }
 8026
 8027    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8028        let end = self.buffer.read(cx).read(cx).len();
 8029        self.change_selections(None, cx, |s| {
 8030            s.select_ranges(vec![0..end]);
 8031        });
 8032    }
 8033
 8034    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8035        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8036        let mut selections = self.selections.all::<Point>(cx);
 8037        let max_point = display_map.buffer_snapshot.max_point();
 8038        for selection in &mut selections {
 8039            let rows = selection.spanned_rows(true, &display_map);
 8040            selection.start = Point::new(rows.start.0, 0);
 8041            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8042            selection.reversed = false;
 8043        }
 8044        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8045            s.select(selections);
 8046        });
 8047    }
 8048
 8049    pub fn split_selection_into_lines(
 8050        &mut self,
 8051        _: &SplitSelectionIntoLines,
 8052        cx: &mut ViewContext<Self>,
 8053    ) {
 8054        let mut to_unfold = Vec::new();
 8055        let mut new_selection_ranges = Vec::new();
 8056        {
 8057            let selections = self.selections.all::<Point>(cx);
 8058            let buffer = self.buffer.read(cx).read(cx);
 8059            for selection in selections {
 8060                for row in selection.start.row..selection.end.row {
 8061                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8062                    new_selection_ranges.push(cursor..cursor);
 8063                }
 8064                new_selection_ranges.push(selection.end..selection.end);
 8065                to_unfold.push(selection.start..selection.end);
 8066            }
 8067        }
 8068        self.unfold_ranges(to_unfold, true, true, cx);
 8069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8070            s.select_ranges(new_selection_ranges);
 8071        });
 8072    }
 8073
 8074    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8075        self.add_selection(true, cx);
 8076    }
 8077
 8078    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8079        self.add_selection(false, cx);
 8080    }
 8081
 8082    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8083        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8084        let mut selections = self.selections.all::<Point>(cx);
 8085        let text_layout_details = self.text_layout_details(cx);
 8086        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8087            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8088            let range = oldest_selection.display_range(&display_map).sorted();
 8089
 8090            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8091            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8092            let positions = start_x.min(end_x)..start_x.max(end_x);
 8093
 8094            selections.clear();
 8095            let mut stack = Vec::new();
 8096            for row in range.start.row().0..=range.end.row().0 {
 8097                if let Some(selection) = self.selections.build_columnar_selection(
 8098                    &display_map,
 8099                    DisplayRow(row),
 8100                    &positions,
 8101                    oldest_selection.reversed,
 8102                    &text_layout_details,
 8103                ) {
 8104                    stack.push(selection.id);
 8105                    selections.push(selection);
 8106                }
 8107            }
 8108
 8109            if above {
 8110                stack.reverse();
 8111            }
 8112
 8113            AddSelectionsState { above, stack }
 8114        });
 8115
 8116        let last_added_selection = *state.stack.last().unwrap();
 8117        let mut new_selections = Vec::new();
 8118        if above == state.above {
 8119            let end_row = if above {
 8120                DisplayRow(0)
 8121            } else {
 8122                display_map.max_point().row()
 8123            };
 8124
 8125            'outer: for selection in selections {
 8126                if selection.id == last_added_selection {
 8127                    let range = selection.display_range(&display_map).sorted();
 8128                    debug_assert_eq!(range.start.row(), range.end.row());
 8129                    let mut row = range.start.row();
 8130                    let positions =
 8131                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8132                            px(start)..px(end)
 8133                        } else {
 8134                            let start_x =
 8135                                display_map.x_for_display_point(range.start, &text_layout_details);
 8136                            let end_x =
 8137                                display_map.x_for_display_point(range.end, &text_layout_details);
 8138                            start_x.min(end_x)..start_x.max(end_x)
 8139                        };
 8140
 8141                    while row != end_row {
 8142                        if above {
 8143                            row.0 -= 1;
 8144                        } else {
 8145                            row.0 += 1;
 8146                        }
 8147
 8148                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8149                            &display_map,
 8150                            row,
 8151                            &positions,
 8152                            selection.reversed,
 8153                            &text_layout_details,
 8154                        ) {
 8155                            state.stack.push(new_selection.id);
 8156                            if above {
 8157                                new_selections.push(new_selection);
 8158                                new_selections.push(selection);
 8159                            } else {
 8160                                new_selections.push(selection);
 8161                                new_selections.push(new_selection);
 8162                            }
 8163
 8164                            continue 'outer;
 8165                        }
 8166                    }
 8167                }
 8168
 8169                new_selections.push(selection);
 8170            }
 8171        } else {
 8172            new_selections = selections;
 8173            new_selections.retain(|s| s.id != last_added_selection);
 8174            state.stack.pop();
 8175        }
 8176
 8177        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8178            s.select(new_selections);
 8179        });
 8180        if state.stack.len() > 1 {
 8181            self.add_selections_state = Some(state);
 8182        }
 8183    }
 8184
 8185    pub fn select_next_match_internal(
 8186        &mut self,
 8187        display_map: &DisplaySnapshot,
 8188        replace_newest: bool,
 8189        autoscroll: Option<Autoscroll>,
 8190        cx: &mut ViewContext<Self>,
 8191    ) -> Result<()> {
 8192        fn select_next_match_ranges(
 8193            this: &mut Editor,
 8194            range: Range<usize>,
 8195            replace_newest: bool,
 8196            auto_scroll: Option<Autoscroll>,
 8197            cx: &mut ViewContext<Editor>,
 8198        ) {
 8199            this.unfold_ranges([range.clone()], false, true, cx);
 8200            this.change_selections(auto_scroll, cx, |s| {
 8201                if replace_newest {
 8202                    s.delete(s.newest_anchor().id);
 8203                }
 8204                s.insert_range(range.clone());
 8205            });
 8206        }
 8207
 8208        let buffer = &display_map.buffer_snapshot;
 8209        let mut selections = self.selections.all::<usize>(cx);
 8210        if let Some(mut select_next_state) = self.select_next_state.take() {
 8211            let query = &select_next_state.query;
 8212            if !select_next_state.done {
 8213                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8214                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8215                let mut next_selected_range = None;
 8216
 8217                let bytes_after_last_selection =
 8218                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8219                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8220                let query_matches = query
 8221                    .stream_find_iter(bytes_after_last_selection)
 8222                    .map(|result| (last_selection.end, result))
 8223                    .chain(
 8224                        query
 8225                            .stream_find_iter(bytes_before_first_selection)
 8226                            .map(|result| (0, result)),
 8227                    );
 8228
 8229                for (start_offset, query_match) in query_matches {
 8230                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8231                    let offset_range =
 8232                        start_offset + query_match.start()..start_offset + query_match.end();
 8233                    let display_range = offset_range.start.to_display_point(display_map)
 8234                        ..offset_range.end.to_display_point(display_map);
 8235
 8236                    if !select_next_state.wordwise
 8237                        || (!movement::is_inside_word(display_map, display_range.start)
 8238                            && !movement::is_inside_word(display_map, display_range.end))
 8239                    {
 8240                        // TODO: This is n^2, because we might check all the selections
 8241                        if !selections
 8242                            .iter()
 8243                            .any(|selection| selection.range().overlaps(&offset_range))
 8244                        {
 8245                            next_selected_range = Some(offset_range);
 8246                            break;
 8247                        }
 8248                    }
 8249                }
 8250
 8251                if let Some(next_selected_range) = next_selected_range {
 8252                    select_next_match_ranges(
 8253                        self,
 8254                        next_selected_range,
 8255                        replace_newest,
 8256                        autoscroll,
 8257                        cx,
 8258                    );
 8259                } else {
 8260                    select_next_state.done = true;
 8261                }
 8262            }
 8263
 8264            self.select_next_state = Some(select_next_state);
 8265        } else {
 8266            let mut only_carets = true;
 8267            let mut same_text_selected = true;
 8268            let mut selected_text = None;
 8269
 8270            let mut selections_iter = selections.iter().peekable();
 8271            while let Some(selection) = selections_iter.next() {
 8272                if selection.start != selection.end {
 8273                    only_carets = false;
 8274                }
 8275
 8276                if same_text_selected {
 8277                    if selected_text.is_none() {
 8278                        selected_text =
 8279                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8280                    }
 8281
 8282                    if let Some(next_selection) = selections_iter.peek() {
 8283                        if next_selection.range().len() == selection.range().len() {
 8284                            let next_selected_text = buffer
 8285                                .text_for_range(next_selection.range())
 8286                                .collect::<String>();
 8287                            if Some(next_selected_text) != selected_text {
 8288                                same_text_selected = false;
 8289                                selected_text = None;
 8290                            }
 8291                        } else {
 8292                            same_text_selected = false;
 8293                            selected_text = None;
 8294                        }
 8295                    }
 8296                }
 8297            }
 8298
 8299            if only_carets {
 8300                for selection in &mut selections {
 8301                    let word_range = movement::surrounding_word(
 8302                        display_map,
 8303                        selection.start.to_display_point(display_map),
 8304                    );
 8305                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8306                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8307                    selection.goal = SelectionGoal::None;
 8308                    selection.reversed = false;
 8309                    select_next_match_ranges(
 8310                        self,
 8311                        selection.start..selection.end,
 8312                        replace_newest,
 8313                        autoscroll,
 8314                        cx,
 8315                    );
 8316                }
 8317
 8318                if selections.len() == 1 {
 8319                    let selection = selections
 8320                        .last()
 8321                        .expect("ensured that there's only one selection");
 8322                    let query = buffer
 8323                        .text_for_range(selection.start..selection.end)
 8324                        .collect::<String>();
 8325                    let is_empty = query.is_empty();
 8326                    let select_state = SelectNextState {
 8327                        query: AhoCorasick::new(&[query])?,
 8328                        wordwise: true,
 8329                        done: is_empty,
 8330                    };
 8331                    self.select_next_state = Some(select_state);
 8332                } else {
 8333                    self.select_next_state = None;
 8334                }
 8335            } else if let Some(selected_text) = selected_text {
 8336                self.select_next_state = Some(SelectNextState {
 8337                    query: AhoCorasick::new(&[selected_text])?,
 8338                    wordwise: false,
 8339                    done: false,
 8340                });
 8341                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8342            }
 8343        }
 8344        Ok(())
 8345    }
 8346
 8347    pub fn select_all_matches(
 8348        &mut self,
 8349        _action: &SelectAllMatches,
 8350        cx: &mut ViewContext<Self>,
 8351    ) -> Result<()> {
 8352        self.push_to_selection_history();
 8353        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8354
 8355        self.select_next_match_internal(&display_map, false, None, cx)?;
 8356        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8357            return Ok(());
 8358        };
 8359        if select_next_state.done {
 8360            return Ok(());
 8361        }
 8362
 8363        let mut new_selections = self.selections.all::<usize>(cx);
 8364
 8365        let buffer = &display_map.buffer_snapshot;
 8366        let query_matches = select_next_state
 8367            .query
 8368            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8369
 8370        for query_match in query_matches {
 8371            let query_match = query_match.unwrap(); // can only fail due to I/O
 8372            let offset_range = query_match.start()..query_match.end();
 8373            let display_range = offset_range.start.to_display_point(&display_map)
 8374                ..offset_range.end.to_display_point(&display_map);
 8375
 8376            if !select_next_state.wordwise
 8377                || (!movement::is_inside_word(&display_map, display_range.start)
 8378                    && !movement::is_inside_word(&display_map, display_range.end))
 8379            {
 8380                self.selections.change_with(cx, |selections| {
 8381                    new_selections.push(Selection {
 8382                        id: selections.new_selection_id(),
 8383                        start: offset_range.start,
 8384                        end: offset_range.end,
 8385                        reversed: false,
 8386                        goal: SelectionGoal::None,
 8387                    });
 8388                });
 8389            }
 8390        }
 8391
 8392        new_selections.sort_by_key(|selection| selection.start);
 8393        let mut ix = 0;
 8394        while ix + 1 < new_selections.len() {
 8395            let current_selection = &new_selections[ix];
 8396            let next_selection = &new_selections[ix + 1];
 8397            if current_selection.range().overlaps(&next_selection.range()) {
 8398                if current_selection.id < next_selection.id {
 8399                    new_selections.remove(ix + 1);
 8400                } else {
 8401                    new_selections.remove(ix);
 8402                }
 8403            } else {
 8404                ix += 1;
 8405            }
 8406        }
 8407
 8408        select_next_state.done = true;
 8409        self.unfold_ranges(
 8410            new_selections.iter().map(|selection| selection.range()),
 8411            false,
 8412            false,
 8413            cx,
 8414        );
 8415        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8416            selections.select(new_selections)
 8417        });
 8418
 8419        Ok(())
 8420    }
 8421
 8422    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8423        self.push_to_selection_history();
 8424        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8425        self.select_next_match_internal(
 8426            &display_map,
 8427            action.replace_newest,
 8428            Some(Autoscroll::newest()),
 8429            cx,
 8430        )?;
 8431        Ok(())
 8432    }
 8433
 8434    pub fn select_previous(
 8435        &mut self,
 8436        action: &SelectPrevious,
 8437        cx: &mut ViewContext<Self>,
 8438    ) -> Result<()> {
 8439        self.push_to_selection_history();
 8440        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8441        let buffer = &display_map.buffer_snapshot;
 8442        let mut selections = self.selections.all::<usize>(cx);
 8443        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8444            let query = &select_prev_state.query;
 8445            if !select_prev_state.done {
 8446                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8447                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8448                let mut next_selected_range = None;
 8449                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8450                let bytes_before_last_selection =
 8451                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8452                let bytes_after_first_selection =
 8453                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8454                let query_matches = query
 8455                    .stream_find_iter(bytes_before_last_selection)
 8456                    .map(|result| (last_selection.start, result))
 8457                    .chain(
 8458                        query
 8459                            .stream_find_iter(bytes_after_first_selection)
 8460                            .map(|result| (buffer.len(), result)),
 8461                    );
 8462                for (end_offset, query_match) in query_matches {
 8463                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8464                    let offset_range =
 8465                        end_offset - query_match.end()..end_offset - query_match.start();
 8466                    let display_range = offset_range.start.to_display_point(&display_map)
 8467                        ..offset_range.end.to_display_point(&display_map);
 8468
 8469                    if !select_prev_state.wordwise
 8470                        || (!movement::is_inside_word(&display_map, display_range.start)
 8471                            && !movement::is_inside_word(&display_map, display_range.end))
 8472                    {
 8473                        next_selected_range = Some(offset_range);
 8474                        break;
 8475                    }
 8476                }
 8477
 8478                if let Some(next_selected_range) = next_selected_range {
 8479                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8480                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8481                        if action.replace_newest {
 8482                            s.delete(s.newest_anchor().id);
 8483                        }
 8484                        s.insert_range(next_selected_range);
 8485                    });
 8486                } else {
 8487                    select_prev_state.done = true;
 8488                }
 8489            }
 8490
 8491            self.select_prev_state = Some(select_prev_state);
 8492        } else {
 8493            let mut only_carets = true;
 8494            let mut same_text_selected = true;
 8495            let mut selected_text = None;
 8496
 8497            let mut selections_iter = selections.iter().peekable();
 8498            while let Some(selection) = selections_iter.next() {
 8499                if selection.start != selection.end {
 8500                    only_carets = false;
 8501                }
 8502
 8503                if same_text_selected {
 8504                    if selected_text.is_none() {
 8505                        selected_text =
 8506                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8507                    }
 8508
 8509                    if let Some(next_selection) = selections_iter.peek() {
 8510                        if next_selection.range().len() == selection.range().len() {
 8511                            let next_selected_text = buffer
 8512                                .text_for_range(next_selection.range())
 8513                                .collect::<String>();
 8514                            if Some(next_selected_text) != selected_text {
 8515                                same_text_selected = false;
 8516                                selected_text = None;
 8517                            }
 8518                        } else {
 8519                            same_text_selected = false;
 8520                            selected_text = None;
 8521                        }
 8522                    }
 8523                }
 8524            }
 8525
 8526            if only_carets {
 8527                for selection in &mut selections {
 8528                    let word_range = movement::surrounding_word(
 8529                        &display_map,
 8530                        selection.start.to_display_point(&display_map),
 8531                    );
 8532                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8533                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8534                    selection.goal = SelectionGoal::None;
 8535                    selection.reversed = false;
 8536                }
 8537                if selections.len() == 1 {
 8538                    let selection = selections
 8539                        .last()
 8540                        .expect("ensured that there's only one selection");
 8541                    let query = buffer
 8542                        .text_for_range(selection.start..selection.end)
 8543                        .collect::<String>();
 8544                    let is_empty = query.is_empty();
 8545                    let select_state = SelectNextState {
 8546                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8547                        wordwise: true,
 8548                        done: is_empty,
 8549                    };
 8550                    self.select_prev_state = Some(select_state);
 8551                } else {
 8552                    self.select_prev_state = None;
 8553                }
 8554
 8555                self.unfold_ranges(
 8556                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8557                    false,
 8558                    true,
 8559                    cx,
 8560                );
 8561                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8562                    s.select(selections);
 8563                });
 8564            } else if let Some(selected_text) = selected_text {
 8565                self.select_prev_state = Some(SelectNextState {
 8566                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8567                    wordwise: false,
 8568                    done: false,
 8569                });
 8570                self.select_previous(action, cx)?;
 8571            }
 8572        }
 8573        Ok(())
 8574    }
 8575
 8576    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8577        let text_layout_details = &self.text_layout_details(cx);
 8578        self.transact(cx, |this, cx| {
 8579            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8580            let mut edits = Vec::new();
 8581            let mut selection_edit_ranges = Vec::new();
 8582            let mut last_toggled_row = None;
 8583            let snapshot = this.buffer.read(cx).read(cx);
 8584            let empty_str: Arc<str> = Arc::default();
 8585            let mut suffixes_inserted = Vec::new();
 8586
 8587            fn comment_prefix_range(
 8588                snapshot: &MultiBufferSnapshot,
 8589                row: MultiBufferRow,
 8590                comment_prefix: &str,
 8591                comment_prefix_whitespace: &str,
 8592            ) -> Range<Point> {
 8593                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8594
 8595                let mut line_bytes = snapshot
 8596                    .bytes_in_range(start..snapshot.max_point())
 8597                    .flatten()
 8598                    .copied();
 8599
 8600                // If this line currently begins with the line comment prefix, then record
 8601                // the range containing the prefix.
 8602                if line_bytes
 8603                    .by_ref()
 8604                    .take(comment_prefix.len())
 8605                    .eq(comment_prefix.bytes())
 8606                {
 8607                    // Include any whitespace that matches the comment prefix.
 8608                    let matching_whitespace_len = line_bytes
 8609                        .zip(comment_prefix_whitespace.bytes())
 8610                        .take_while(|(a, b)| a == b)
 8611                        .count() as u32;
 8612                    let end = Point::new(
 8613                        start.row,
 8614                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8615                    );
 8616                    start..end
 8617                } else {
 8618                    start..start
 8619                }
 8620            }
 8621
 8622            fn comment_suffix_range(
 8623                snapshot: &MultiBufferSnapshot,
 8624                row: MultiBufferRow,
 8625                comment_suffix: &str,
 8626                comment_suffix_has_leading_space: bool,
 8627            ) -> Range<Point> {
 8628                let end = Point::new(row.0, snapshot.line_len(row));
 8629                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8630
 8631                let mut line_end_bytes = snapshot
 8632                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8633                    .flatten()
 8634                    .copied();
 8635
 8636                let leading_space_len = if suffix_start_column > 0
 8637                    && line_end_bytes.next() == Some(b' ')
 8638                    && comment_suffix_has_leading_space
 8639                {
 8640                    1
 8641                } else {
 8642                    0
 8643                };
 8644
 8645                // If this line currently begins with the line comment prefix, then record
 8646                // the range containing the prefix.
 8647                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8648                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8649                    start..end
 8650                } else {
 8651                    end..end
 8652                }
 8653            }
 8654
 8655            // TODO: Handle selections that cross excerpts
 8656            for selection in &mut selections {
 8657                let start_column = snapshot
 8658                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8659                    .len;
 8660                let language = if let Some(language) =
 8661                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8662                {
 8663                    language
 8664                } else {
 8665                    continue;
 8666                };
 8667
 8668                selection_edit_ranges.clear();
 8669
 8670                // If multiple selections contain a given row, avoid processing that
 8671                // row more than once.
 8672                let mut start_row = MultiBufferRow(selection.start.row);
 8673                if last_toggled_row == Some(start_row) {
 8674                    start_row = start_row.next_row();
 8675                }
 8676                let end_row =
 8677                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8678                        MultiBufferRow(selection.end.row - 1)
 8679                    } else {
 8680                        MultiBufferRow(selection.end.row)
 8681                    };
 8682                last_toggled_row = Some(end_row);
 8683
 8684                if start_row > end_row {
 8685                    continue;
 8686                }
 8687
 8688                // If the language has line comments, toggle those.
 8689                let full_comment_prefixes = language.line_comment_prefixes();
 8690                if !full_comment_prefixes.is_empty() {
 8691                    let first_prefix = full_comment_prefixes
 8692                        .first()
 8693                        .expect("prefixes is non-empty");
 8694                    let prefix_trimmed_lengths = full_comment_prefixes
 8695                        .iter()
 8696                        .map(|p| p.trim_end_matches(' ').len())
 8697                        .collect::<SmallVec<[usize; 4]>>();
 8698
 8699                    let mut all_selection_lines_are_comments = true;
 8700
 8701                    for row in start_row.0..=end_row.0 {
 8702                        let row = MultiBufferRow(row);
 8703                        if start_row < end_row && snapshot.is_line_blank(row) {
 8704                            continue;
 8705                        }
 8706
 8707                        let prefix_range = full_comment_prefixes
 8708                            .iter()
 8709                            .zip(prefix_trimmed_lengths.iter().copied())
 8710                            .map(|(prefix, trimmed_prefix_len)| {
 8711                                comment_prefix_range(
 8712                                    snapshot.deref(),
 8713                                    row,
 8714                                    &prefix[..trimmed_prefix_len],
 8715                                    &prefix[trimmed_prefix_len..],
 8716                                )
 8717                            })
 8718                            .max_by_key(|range| range.end.column - range.start.column)
 8719                            .expect("prefixes is non-empty");
 8720
 8721                        if prefix_range.is_empty() {
 8722                            all_selection_lines_are_comments = false;
 8723                        }
 8724
 8725                        selection_edit_ranges.push(prefix_range);
 8726                    }
 8727
 8728                    if all_selection_lines_are_comments {
 8729                        edits.extend(
 8730                            selection_edit_ranges
 8731                                .iter()
 8732                                .cloned()
 8733                                .map(|range| (range, empty_str.clone())),
 8734                        );
 8735                    } else {
 8736                        let min_column = selection_edit_ranges
 8737                            .iter()
 8738                            .map(|range| range.start.column)
 8739                            .min()
 8740                            .unwrap_or(0);
 8741                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8742                            let position = Point::new(range.start.row, min_column);
 8743                            (position..position, first_prefix.clone())
 8744                        }));
 8745                    }
 8746                } else if let Some((full_comment_prefix, comment_suffix)) =
 8747                    language.block_comment_delimiters()
 8748                {
 8749                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8750                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8751                    let prefix_range = comment_prefix_range(
 8752                        snapshot.deref(),
 8753                        start_row,
 8754                        comment_prefix,
 8755                        comment_prefix_whitespace,
 8756                    );
 8757                    let suffix_range = comment_suffix_range(
 8758                        snapshot.deref(),
 8759                        end_row,
 8760                        comment_suffix.trim_start_matches(' '),
 8761                        comment_suffix.starts_with(' '),
 8762                    );
 8763
 8764                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8765                        edits.push((
 8766                            prefix_range.start..prefix_range.start,
 8767                            full_comment_prefix.clone(),
 8768                        ));
 8769                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8770                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8771                    } else {
 8772                        edits.push((prefix_range, empty_str.clone()));
 8773                        edits.push((suffix_range, empty_str.clone()));
 8774                    }
 8775                } else {
 8776                    continue;
 8777                }
 8778            }
 8779
 8780            drop(snapshot);
 8781            this.buffer.update(cx, |buffer, cx| {
 8782                buffer.edit(edits, None, cx);
 8783            });
 8784
 8785            // Adjust selections so that they end before any comment suffixes that
 8786            // were inserted.
 8787            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8788            let mut selections = this.selections.all::<Point>(cx);
 8789            let snapshot = this.buffer.read(cx).read(cx);
 8790            for selection in &mut selections {
 8791                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8792                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8793                        Ordering::Less => {
 8794                            suffixes_inserted.next();
 8795                            continue;
 8796                        }
 8797                        Ordering::Greater => break,
 8798                        Ordering::Equal => {
 8799                            if selection.end.column == snapshot.line_len(row) {
 8800                                if selection.is_empty() {
 8801                                    selection.start.column -= suffix_len as u32;
 8802                                }
 8803                                selection.end.column -= suffix_len as u32;
 8804                            }
 8805                            break;
 8806                        }
 8807                    }
 8808                }
 8809            }
 8810
 8811            drop(snapshot);
 8812            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8813
 8814            let selections = this.selections.all::<Point>(cx);
 8815            let selections_on_single_row = selections.windows(2).all(|selections| {
 8816                selections[0].start.row == selections[1].start.row
 8817                    && selections[0].end.row == selections[1].end.row
 8818                    && selections[0].start.row == selections[0].end.row
 8819            });
 8820            let selections_selecting = selections
 8821                .iter()
 8822                .any(|selection| selection.start != selection.end);
 8823            let advance_downwards = action.advance_downwards
 8824                && selections_on_single_row
 8825                && !selections_selecting
 8826                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8827
 8828            if advance_downwards {
 8829                let snapshot = this.buffer.read(cx).snapshot(cx);
 8830
 8831                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8832                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8833                        let mut point = display_point.to_point(display_snapshot);
 8834                        point.row += 1;
 8835                        point = snapshot.clip_point(point, Bias::Left);
 8836                        let display_point = point.to_display_point(display_snapshot);
 8837                        let goal = SelectionGoal::HorizontalPosition(
 8838                            display_snapshot
 8839                                .x_for_display_point(display_point, text_layout_details)
 8840                                .into(),
 8841                        );
 8842                        (display_point, goal)
 8843                    })
 8844                });
 8845            }
 8846        });
 8847    }
 8848
 8849    pub fn select_enclosing_symbol(
 8850        &mut self,
 8851        _: &SelectEnclosingSymbol,
 8852        cx: &mut ViewContext<Self>,
 8853    ) {
 8854        let buffer = self.buffer.read(cx).snapshot(cx);
 8855        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8856
 8857        fn update_selection(
 8858            selection: &Selection<usize>,
 8859            buffer_snap: &MultiBufferSnapshot,
 8860        ) -> Option<Selection<usize>> {
 8861            let cursor = selection.head();
 8862            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8863            for symbol in symbols.iter().rev() {
 8864                let start = symbol.range.start.to_offset(buffer_snap);
 8865                let end = symbol.range.end.to_offset(buffer_snap);
 8866                let new_range = start..end;
 8867                if start < selection.start || end > selection.end {
 8868                    return Some(Selection {
 8869                        id: selection.id,
 8870                        start: new_range.start,
 8871                        end: new_range.end,
 8872                        goal: SelectionGoal::None,
 8873                        reversed: selection.reversed,
 8874                    });
 8875                }
 8876            }
 8877            None
 8878        }
 8879
 8880        let mut selected_larger_symbol = false;
 8881        let new_selections = old_selections
 8882            .iter()
 8883            .map(|selection| match update_selection(selection, &buffer) {
 8884                Some(new_selection) => {
 8885                    if new_selection.range() != selection.range() {
 8886                        selected_larger_symbol = true;
 8887                    }
 8888                    new_selection
 8889                }
 8890                None => selection.clone(),
 8891            })
 8892            .collect::<Vec<_>>();
 8893
 8894        if selected_larger_symbol {
 8895            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8896                s.select(new_selections);
 8897            });
 8898        }
 8899    }
 8900
 8901    pub fn select_larger_syntax_node(
 8902        &mut self,
 8903        _: &SelectLargerSyntaxNode,
 8904        cx: &mut ViewContext<Self>,
 8905    ) {
 8906        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8907        let buffer = self.buffer.read(cx).snapshot(cx);
 8908        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8909
 8910        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8911        let mut selected_larger_node = false;
 8912        let new_selections = old_selections
 8913            .iter()
 8914            .map(|selection| {
 8915                let old_range = selection.start..selection.end;
 8916                let mut new_range = old_range.clone();
 8917                while let Some(containing_range) =
 8918                    buffer.range_for_syntax_ancestor(new_range.clone())
 8919                {
 8920                    new_range = containing_range;
 8921                    if !display_map.intersects_fold(new_range.start)
 8922                        && !display_map.intersects_fold(new_range.end)
 8923                    {
 8924                        break;
 8925                    }
 8926                }
 8927
 8928                selected_larger_node |= new_range != old_range;
 8929                Selection {
 8930                    id: selection.id,
 8931                    start: new_range.start,
 8932                    end: new_range.end,
 8933                    goal: SelectionGoal::None,
 8934                    reversed: selection.reversed,
 8935                }
 8936            })
 8937            .collect::<Vec<_>>();
 8938
 8939        if selected_larger_node {
 8940            stack.push(old_selections);
 8941            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8942                s.select(new_selections);
 8943            });
 8944        }
 8945        self.select_larger_syntax_node_stack = stack;
 8946    }
 8947
 8948    pub fn select_smaller_syntax_node(
 8949        &mut self,
 8950        _: &SelectSmallerSyntaxNode,
 8951        cx: &mut ViewContext<Self>,
 8952    ) {
 8953        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8954        if let Some(selections) = stack.pop() {
 8955            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8956                s.select(selections.to_vec());
 8957            });
 8958        }
 8959        self.select_larger_syntax_node_stack = stack;
 8960    }
 8961
 8962    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8963        if !EditorSettings::get_global(cx).gutter.runnables {
 8964            self.clear_tasks();
 8965            return Task::ready(());
 8966        }
 8967        let project = self.project.clone();
 8968        cx.spawn(|this, mut cx| async move {
 8969            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8970                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8971            }) else {
 8972                return;
 8973            };
 8974
 8975            let Some(project) = project else {
 8976                return;
 8977            };
 8978
 8979            let hide_runnables = project
 8980                .update(&mut cx, |project, cx| {
 8981                    // Do not display any test indicators in non-dev server remote projects.
 8982                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8983                })
 8984                .unwrap_or(true);
 8985            if hide_runnables {
 8986                return;
 8987            }
 8988            let new_rows =
 8989                cx.background_executor()
 8990                    .spawn({
 8991                        let snapshot = display_snapshot.clone();
 8992                        async move {
 8993                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8994                        }
 8995                    })
 8996                    .await;
 8997            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8998
 8999            this.update(&mut cx, |this, _| {
 9000                this.clear_tasks();
 9001                for (key, value) in rows {
 9002                    this.insert_tasks(key, value);
 9003                }
 9004            })
 9005            .ok();
 9006        })
 9007    }
 9008    fn fetch_runnable_ranges(
 9009        snapshot: &DisplaySnapshot,
 9010        range: Range<Anchor>,
 9011    ) -> Vec<language::RunnableRange> {
 9012        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9013    }
 9014
 9015    fn runnable_rows(
 9016        project: Model<Project>,
 9017        snapshot: DisplaySnapshot,
 9018        runnable_ranges: Vec<RunnableRange>,
 9019        mut cx: AsyncWindowContext,
 9020    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9021        runnable_ranges
 9022            .into_iter()
 9023            .filter_map(|mut runnable| {
 9024                let tasks = cx
 9025                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9026                    .ok()?;
 9027                if tasks.is_empty() {
 9028                    return None;
 9029                }
 9030
 9031                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9032
 9033                let row = snapshot
 9034                    .buffer_snapshot
 9035                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9036                    .1
 9037                    .start
 9038                    .row;
 9039
 9040                let context_range =
 9041                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9042                Some((
 9043                    (runnable.buffer_id, row),
 9044                    RunnableTasks {
 9045                        templates: tasks,
 9046                        offset: MultiBufferOffset(runnable.run_range.start),
 9047                        context_range,
 9048                        column: point.column,
 9049                        extra_variables: runnable.extra_captures,
 9050                    },
 9051                ))
 9052            })
 9053            .collect()
 9054    }
 9055
 9056    fn templates_with_tags(
 9057        project: &Model<Project>,
 9058        runnable: &mut Runnable,
 9059        cx: &WindowContext<'_>,
 9060    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9061        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9062            let (worktree_id, file) = project
 9063                .buffer_for_id(runnable.buffer, cx)
 9064                .and_then(|buffer| buffer.read(cx).file())
 9065                .map(|file| (file.worktree_id(cx), file.clone()))
 9066                .unzip();
 9067
 9068            (project.task_inventory().clone(), worktree_id, file)
 9069        });
 9070
 9071        let inventory = inventory.read(cx);
 9072        let tags = mem::take(&mut runnable.tags);
 9073        let mut tags: Vec<_> = tags
 9074            .into_iter()
 9075            .flat_map(|tag| {
 9076                let tag = tag.0.clone();
 9077                inventory
 9078                    .list_tasks(
 9079                        file.clone(),
 9080                        Some(runnable.language.clone()),
 9081                        worktree_id,
 9082                        cx,
 9083                    )
 9084                    .into_iter()
 9085                    .filter(move |(_, template)| {
 9086                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9087                    })
 9088            })
 9089            .sorted_by_key(|(kind, _)| kind.to_owned())
 9090            .collect();
 9091        if let Some((leading_tag_source, _)) = tags.first() {
 9092            // Strongest source wins; if we have worktree tag binding, prefer that to
 9093            // global and language bindings;
 9094            // if we have a global binding, prefer that to language binding.
 9095            let first_mismatch = tags
 9096                .iter()
 9097                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9098            if let Some(index) = first_mismatch {
 9099                tags.truncate(index);
 9100            }
 9101        }
 9102
 9103        tags
 9104    }
 9105
 9106    pub fn move_to_enclosing_bracket(
 9107        &mut self,
 9108        _: &MoveToEnclosingBracket,
 9109        cx: &mut ViewContext<Self>,
 9110    ) {
 9111        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9112            s.move_offsets_with(|snapshot, selection| {
 9113                let Some(enclosing_bracket_ranges) =
 9114                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9115                else {
 9116                    return;
 9117                };
 9118
 9119                let mut best_length = usize::MAX;
 9120                let mut best_inside = false;
 9121                let mut best_in_bracket_range = false;
 9122                let mut best_destination = None;
 9123                for (open, close) in enclosing_bracket_ranges {
 9124                    let close = close.to_inclusive();
 9125                    let length = close.end() - open.start;
 9126                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9127                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9128                        || close.contains(&selection.head());
 9129
 9130                    // If best is next to a bracket and current isn't, skip
 9131                    if !in_bracket_range && best_in_bracket_range {
 9132                        continue;
 9133                    }
 9134
 9135                    // Prefer smaller lengths unless best is inside and current isn't
 9136                    if length > best_length && (best_inside || !inside) {
 9137                        continue;
 9138                    }
 9139
 9140                    best_length = length;
 9141                    best_inside = inside;
 9142                    best_in_bracket_range = in_bracket_range;
 9143                    best_destination = Some(
 9144                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9145                            if inside {
 9146                                open.end
 9147                            } else {
 9148                                open.start
 9149                            }
 9150                        } else if inside {
 9151                            *close.start()
 9152                        } else {
 9153                            *close.end()
 9154                        },
 9155                    );
 9156                }
 9157
 9158                if let Some(destination) = best_destination {
 9159                    selection.collapse_to(destination, SelectionGoal::None);
 9160                }
 9161            })
 9162        });
 9163    }
 9164
 9165    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9166        self.end_selection(cx);
 9167        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9168        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9169            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9170            self.select_next_state = entry.select_next_state;
 9171            self.select_prev_state = entry.select_prev_state;
 9172            self.add_selections_state = entry.add_selections_state;
 9173            self.request_autoscroll(Autoscroll::newest(), cx);
 9174        }
 9175        self.selection_history.mode = SelectionHistoryMode::Normal;
 9176    }
 9177
 9178    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9179        self.end_selection(cx);
 9180        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9181        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9182            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9183            self.select_next_state = entry.select_next_state;
 9184            self.select_prev_state = entry.select_prev_state;
 9185            self.add_selections_state = entry.add_selections_state;
 9186            self.request_autoscroll(Autoscroll::newest(), cx);
 9187        }
 9188        self.selection_history.mode = SelectionHistoryMode::Normal;
 9189    }
 9190
 9191    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9192        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9193    }
 9194
 9195    pub fn expand_excerpts_down(
 9196        &mut self,
 9197        action: &ExpandExcerptsDown,
 9198        cx: &mut ViewContext<Self>,
 9199    ) {
 9200        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9201    }
 9202
 9203    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9204        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9205    }
 9206
 9207    pub fn expand_excerpts_for_direction(
 9208        &mut self,
 9209        lines: u32,
 9210        direction: ExpandExcerptDirection,
 9211        cx: &mut ViewContext<Self>,
 9212    ) {
 9213        let selections = self.selections.disjoint_anchors();
 9214
 9215        let lines = if lines == 0 {
 9216            EditorSettings::get_global(cx).expand_excerpt_lines
 9217        } else {
 9218            lines
 9219        };
 9220
 9221        self.buffer.update(cx, |buffer, cx| {
 9222            buffer.expand_excerpts(
 9223                selections
 9224                    .iter()
 9225                    .map(|selection| selection.head().excerpt_id)
 9226                    .dedup(),
 9227                lines,
 9228                direction,
 9229                cx,
 9230            )
 9231        })
 9232    }
 9233
 9234    pub fn expand_excerpt(
 9235        &mut self,
 9236        excerpt: ExcerptId,
 9237        direction: ExpandExcerptDirection,
 9238        cx: &mut ViewContext<Self>,
 9239    ) {
 9240        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9241        self.buffer.update(cx, |buffer, cx| {
 9242            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9243        })
 9244    }
 9245
 9246    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9247        self.go_to_diagnostic_impl(Direction::Next, cx)
 9248    }
 9249
 9250    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9251        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9252    }
 9253
 9254    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9255        let buffer = self.buffer.read(cx).snapshot(cx);
 9256        let selection = self.selections.newest::<usize>(cx);
 9257
 9258        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9259        if direction == Direction::Next {
 9260            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9261                let (group_id, jump_to) = popover.activation_info();
 9262                if self.activate_diagnostics(group_id, cx) {
 9263                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9264                        let mut new_selection = s.newest_anchor().clone();
 9265                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9266                        s.select_anchors(vec![new_selection.clone()]);
 9267                    });
 9268                }
 9269                return;
 9270            }
 9271        }
 9272
 9273        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9274            active_diagnostics
 9275                .primary_range
 9276                .to_offset(&buffer)
 9277                .to_inclusive()
 9278        });
 9279        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9280            if active_primary_range.contains(&selection.head()) {
 9281                *active_primary_range.start()
 9282            } else {
 9283                selection.head()
 9284            }
 9285        } else {
 9286            selection.head()
 9287        };
 9288        let snapshot = self.snapshot(cx);
 9289        loop {
 9290            let diagnostics = if direction == Direction::Prev {
 9291                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9292            } else {
 9293                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9294            }
 9295            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9296            let group = diagnostics
 9297                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9298                // be sorted in a stable way
 9299                // skip until we are at current active diagnostic, if it exists
 9300                .skip_while(|entry| {
 9301                    (match direction {
 9302                        Direction::Prev => entry.range.start >= search_start,
 9303                        Direction::Next => entry.range.start <= search_start,
 9304                    }) && self
 9305                        .active_diagnostics
 9306                        .as_ref()
 9307                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9308                })
 9309                .find_map(|entry| {
 9310                    if entry.diagnostic.is_primary
 9311                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9312                        && !entry.range.is_empty()
 9313                        // if we match with the active diagnostic, skip it
 9314                        && Some(entry.diagnostic.group_id)
 9315                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9316                    {
 9317                        Some((entry.range, entry.diagnostic.group_id))
 9318                    } else {
 9319                        None
 9320                    }
 9321                });
 9322
 9323            if let Some((primary_range, group_id)) = group {
 9324                if self.activate_diagnostics(group_id, cx) {
 9325                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9326                        s.select(vec![Selection {
 9327                            id: selection.id,
 9328                            start: primary_range.start,
 9329                            end: primary_range.start,
 9330                            reversed: false,
 9331                            goal: SelectionGoal::None,
 9332                        }]);
 9333                    });
 9334                }
 9335                break;
 9336            } else {
 9337                // Cycle around to the start of the buffer, potentially moving back to the start of
 9338                // the currently active diagnostic.
 9339                active_primary_range.take();
 9340                if direction == Direction::Prev {
 9341                    if search_start == buffer.len() {
 9342                        break;
 9343                    } else {
 9344                        search_start = buffer.len();
 9345                    }
 9346                } else if search_start == 0 {
 9347                    break;
 9348                } else {
 9349                    search_start = 0;
 9350                }
 9351            }
 9352        }
 9353    }
 9354
 9355    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9356        let snapshot = self
 9357            .display_map
 9358            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9359        let selection = self.selections.newest::<Point>(cx);
 9360        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9361    }
 9362
 9363    fn go_to_hunk_after_position(
 9364        &mut self,
 9365        snapshot: &DisplaySnapshot,
 9366        position: Point,
 9367        cx: &mut ViewContext<'_, Editor>,
 9368    ) -> Option<MultiBufferDiffHunk> {
 9369        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9370            snapshot,
 9371            position,
 9372            false,
 9373            snapshot
 9374                .buffer_snapshot
 9375                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9376            cx,
 9377        ) {
 9378            return Some(hunk);
 9379        }
 9380
 9381        let wrapped_point = Point::zero();
 9382        self.go_to_next_hunk_in_direction(
 9383            snapshot,
 9384            wrapped_point,
 9385            true,
 9386            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9387                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9388            ),
 9389            cx,
 9390        )
 9391    }
 9392
 9393    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9394        let snapshot = self
 9395            .display_map
 9396            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9397        let selection = self.selections.newest::<Point>(cx);
 9398
 9399        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9400    }
 9401
 9402    fn go_to_hunk_before_position(
 9403        &mut self,
 9404        snapshot: &DisplaySnapshot,
 9405        position: Point,
 9406        cx: &mut ViewContext<'_, Editor>,
 9407    ) -> Option<MultiBufferDiffHunk> {
 9408        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9409            snapshot,
 9410            position,
 9411            false,
 9412            snapshot
 9413                .buffer_snapshot
 9414                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9415            cx,
 9416        ) {
 9417            return Some(hunk);
 9418        }
 9419
 9420        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9421        self.go_to_next_hunk_in_direction(
 9422            snapshot,
 9423            wrapped_point,
 9424            true,
 9425            snapshot
 9426                .buffer_snapshot
 9427                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9428            cx,
 9429        )
 9430    }
 9431
 9432    fn go_to_next_hunk_in_direction(
 9433        &mut self,
 9434        snapshot: &DisplaySnapshot,
 9435        initial_point: Point,
 9436        is_wrapped: bool,
 9437        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9438        cx: &mut ViewContext<Editor>,
 9439    ) -> Option<MultiBufferDiffHunk> {
 9440        let display_point = initial_point.to_display_point(snapshot);
 9441        let mut hunks = hunks
 9442            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9443            .filter(|(display_hunk, _)| {
 9444                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9445            })
 9446            .dedup();
 9447
 9448        if let Some((display_hunk, hunk)) = hunks.next() {
 9449            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9450                let row = display_hunk.start_display_row();
 9451                let point = DisplayPoint::new(row, 0);
 9452                s.select_display_ranges([point..point]);
 9453            });
 9454
 9455            Some(hunk)
 9456        } else {
 9457            None
 9458        }
 9459    }
 9460
 9461    pub fn go_to_definition(
 9462        &mut self,
 9463        _: &GoToDefinition,
 9464        cx: &mut ViewContext<Self>,
 9465    ) -> Task<Result<Navigated>> {
 9466        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9467        cx.spawn(|editor, mut cx| async move {
 9468            if definition.await? == Navigated::Yes {
 9469                return Ok(Navigated::Yes);
 9470            }
 9471            match editor.update(&mut cx, |editor, cx| {
 9472                editor.find_all_references(&FindAllReferences, cx)
 9473            })? {
 9474                Some(references) => references.await,
 9475                None => Ok(Navigated::No),
 9476            }
 9477        })
 9478    }
 9479
 9480    pub fn go_to_declaration(
 9481        &mut self,
 9482        _: &GoToDeclaration,
 9483        cx: &mut ViewContext<Self>,
 9484    ) -> Task<Result<Navigated>> {
 9485        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9486    }
 9487
 9488    pub fn go_to_declaration_split(
 9489        &mut self,
 9490        _: &GoToDeclaration,
 9491        cx: &mut ViewContext<Self>,
 9492    ) -> Task<Result<Navigated>> {
 9493        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9494    }
 9495
 9496    pub fn go_to_implementation(
 9497        &mut self,
 9498        _: &GoToImplementation,
 9499        cx: &mut ViewContext<Self>,
 9500    ) -> Task<Result<Navigated>> {
 9501        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9502    }
 9503
 9504    pub fn go_to_implementation_split(
 9505        &mut self,
 9506        _: &GoToImplementationSplit,
 9507        cx: &mut ViewContext<Self>,
 9508    ) -> Task<Result<Navigated>> {
 9509        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9510    }
 9511
 9512    pub fn go_to_type_definition(
 9513        &mut self,
 9514        _: &GoToTypeDefinition,
 9515        cx: &mut ViewContext<Self>,
 9516    ) -> Task<Result<Navigated>> {
 9517        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9518    }
 9519
 9520    pub fn go_to_definition_split(
 9521        &mut self,
 9522        _: &GoToDefinitionSplit,
 9523        cx: &mut ViewContext<Self>,
 9524    ) -> Task<Result<Navigated>> {
 9525        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9526    }
 9527
 9528    pub fn go_to_type_definition_split(
 9529        &mut self,
 9530        _: &GoToTypeDefinitionSplit,
 9531        cx: &mut ViewContext<Self>,
 9532    ) -> Task<Result<Navigated>> {
 9533        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9534    }
 9535
 9536    fn go_to_definition_of_kind(
 9537        &mut self,
 9538        kind: GotoDefinitionKind,
 9539        split: bool,
 9540        cx: &mut ViewContext<Self>,
 9541    ) -> Task<Result<Navigated>> {
 9542        let Some(workspace) = self.workspace() else {
 9543            return Task::ready(Ok(Navigated::No));
 9544        };
 9545        let buffer = self.buffer.read(cx);
 9546        let head = self.selections.newest::<usize>(cx).head();
 9547        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9548            text_anchor
 9549        } else {
 9550            return Task::ready(Ok(Navigated::No));
 9551        };
 9552
 9553        let project = workspace.read(cx).project().clone();
 9554        let definitions = project.update(cx, |project, cx| match kind {
 9555            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9556            GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
 9557            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9558            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9559        });
 9560
 9561        cx.spawn(|editor, mut cx| async move {
 9562            let definitions = definitions.await?;
 9563            let navigated = editor
 9564                .update(&mut cx, |editor, cx| {
 9565                    editor.navigate_to_hover_links(
 9566                        Some(kind),
 9567                        definitions
 9568                            .into_iter()
 9569                            .filter(|location| {
 9570                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9571                            })
 9572                            .map(HoverLink::Text)
 9573                            .collect::<Vec<_>>(),
 9574                        split,
 9575                        cx,
 9576                    )
 9577                })?
 9578                .await?;
 9579            anyhow::Ok(navigated)
 9580        })
 9581    }
 9582
 9583    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9584        let position = self.selections.newest_anchor().head();
 9585        let Some((buffer, buffer_position)) =
 9586            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9587        else {
 9588            return;
 9589        };
 9590
 9591        cx.spawn(|editor, mut cx| async move {
 9592            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9593                editor.update(&mut cx, |_, cx| {
 9594                    cx.open_url(&url);
 9595                })
 9596            } else {
 9597                Ok(())
 9598            }
 9599        })
 9600        .detach();
 9601    }
 9602
 9603    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9604        let Some(workspace) = self.workspace() else {
 9605            return;
 9606        };
 9607
 9608        let position = self.selections.newest_anchor().head();
 9609
 9610        let Some((buffer, buffer_position)) =
 9611            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9612        else {
 9613            return;
 9614        };
 9615
 9616        let Some(project) = self.project.clone() else {
 9617            return;
 9618        };
 9619
 9620        cx.spawn(|_, mut cx| async move {
 9621            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9622
 9623            if let Some((_, path)) = result {
 9624                workspace
 9625                    .update(&mut cx, |workspace, cx| {
 9626                        workspace.open_resolved_path(path, cx)
 9627                    })?
 9628                    .await?;
 9629            }
 9630            anyhow::Ok(())
 9631        })
 9632        .detach();
 9633    }
 9634
 9635    pub(crate) fn navigate_to_hover_links(
 9636        &mut self,
 9637        kind: Option<GotoDefinitionKind>,
 9638        mut definitions: Vec<HoverLink>,
 9639        split: bool,
 9640        cx: &mut ViewContext<Editor>,
 9641    ) -> Task<Result<Navigated>> {
 9642        // If there is one definition, just open it directly
 9643        if definitions.len() == 1 {
 9644            let definition = definitions.pop().unwrap();
 9645
 9646            enum TargetTaskResult {
 9647                Location(Option<Location>),
 9648                AlreadyNavigated,
 9649            }
 9650
 9651            let target_task = match definition {
 9652                HoverLink::Text(link) => {
 9653                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9654                }
 9655                HoverLink::InlayHint(lsp_location, server_id) => {
 9656                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9657                    cx.background_executor().spawn(async move {
 9658                        let location = computation.await?;
 9659                        Ok(TargetTaskResult::Location(location))
 9660                    })
 9661                }
 9662                HoverLink::Url(url) => {
 9663                    cx.open_url(&url);
 9664                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9665                }
 9666                HoverLink::File(path) => {
 9667                    if let Some(workspace) = self.workspace() {
 9668                        cx.spawn(|_, mut cx| async move {
 9669                            workspace
 9670                                .update(&mut cx, |workspace, cx| {
 9671                                    workspace.open_resolved_path(path, cx)
 9672                                })?
 9673                                .await
 9674                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9675                        })
 9676                    } else {
 9677                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9678                    }
 9679                }
 9680            };
 9681            cx.spawn(|editor, mut cx| async move {
 9682                let target = match target_task.await.context("target resolution task")? {
 9683                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9684                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9685                    TargetTaskResult::Location(Some(target)) => target,
 9686                };
 9687
 9688                editor.update(&mut cx, |editor, cx| {
 9689                    let Some(workspace) = editor.workspace() else {
 9690                        return Navigated::No;
 9691                    };
 9692                    let pane = workspace.read(cx).active_pane().clone();
 9693
 9694                    let range = target.range.to_offset(target.buffer.read(cx));
 9695                    let range = editor.range_for_match(&range);
 9696
 9697                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9698                        let buffer = target.buffer.read(cx);
 9699                        let range = check_multiline_range(buffer, range);
 9700                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9701                            s.select_ranges([range]);
 9702                        });
 9703                    } else {
 9704                        cx.window_context().defer(move |cx| {
 9705                            let target_editor: View<Self> =
 9706                                workspace.update(cx, |workspace, cx| {
 9707                                    let pane = if split {
 9708                                        workspace.adjacent_pane(cx)
 9709                                    } else {
 9710                                        workspace.active_pane().clone()
 9711                                    };
 9712
 9713                                    workspace.open_project_item(
 9714                                        pane,
 9715                                        target.buffer.clone(),
 9716                                        true,
 9717                                        true,
 9718                                        cx,
 9719                                    )
 9720                                });
 9721                            target_editor.update(cx, |target_editor, cx| {
 9722                                // When selecting a definition in a different buffer, disable the nav history
 9723                                // to avoid creating a history entry at the previous cursor location.
 9724                                pane.update(cx, |pane, _| pane.disable_history());
 9725                                let buffer = target.buffer.read(cx);
 9726                                let range = check_multiline_range(buffer, range);
 9727                                target_editor.change_selections(
 9728                                    Some(Autoscroll::focused()),
 9729                                    cx,
 9730                                    |s| {
 9731                                        s.select_ranges([range]);
 9732                                    },
 9733                                );
 9734                                pane.update(cx, |pane, _| pane.enable_history());
 9735                            });
 9736                        });
 9737                    }
 9738                    Navigated::Yes
 9739                })
 9740            })
 9741        } else if !definitions.is_empty() {
 9742            cx.spawn(|editor, mut cx| async move {
 9743                let (title, location_tasks, workspace) = editor
 9744                    .update(&mut cx, |editor, cx| {
 9745                        let tab_kind = match kind {
 9746                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9747                            _ => "Definitions",
 9748                        };
 9749                        let title = definitions
 9750                            .iter()
 9751                            .find_map(|definition| match definition {
 9752                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9753                                    let buffer = origin.buffer.read(cx);
 9754                                    format!(
 9755                                        "{} for {}",
 9756                                        tab_kind,
 9757                                        buffer
 9758                                            .text_for_range(origin.range.clone())
 9759                                            .collect::<String>()
 9760                                    )
 9761                                }),
 9762                                HoverLink::InlayHint(_, _) => None,
 9763                                HoverLink::Url(_) => None,
 9764                                HoverLink::File(_) => None,
 9765                            })
 9766                            .unwrap_or(tab_kind.to_string());
 9767                        let location_tasks = definitions
 9768                            .into_iter()
 9769                            .map(|definition| match definition {
 9770                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9771                                HoverLink::InlayHint(lsp_location, server_id) => {
 9772                                    editor.compute_target_location(lsp_location, server_id, cx)
 9773                                }
 9774                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9775                                HoverLink::File(_) => Task::ready(Ok(None)),
 9776                            })
 9777                            .collect::<Vec<_>>();
 9778                        (title, location_tasks, editor.workspace().clone())
 9779                    })
 9780                    .context("location tasks preparation")?;
 9781
 9782                let locations = future::join_all(location_tasks)
 9783                    .await
 9784                    .into_iter()
 9785                    .filter_map(|location| location.transpose())
 9786                    .collect::<Result<_>>()
 9787                    .context("location tasks")?;
 9788
 9789                let Some(workspace) = workspace else {
 9790                    return Ok(Navigated::No);
 9791                };
 9792                let opened = workspace
 9793                    .update(&mut cx, |workspace, cx| {
 9794                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9795                    })
 9796                    .ok();
 9797
 9798                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9799            })
 9800        } else {
 9801            Task::ready(Ok(Navigated::No))
 9802        }
 9803    }
 9804
 9805    fn compute_target_location(
 9806        &self,
 9807        lsp_location: lsp::Location,
 9808        server_id: LanguageServerId,
 9809        cx: &mut ViewContext<Editor>,
 9810    ) -> Task<anyhow::Result<Option<Location>>> {
 9811        let Some(project) = self.project.clone() else {
 9812            return Task::Ready(Some(Ok(None)));
 9813        };
 9814
 9815        cx.spawn(move |editor, mut cx| async move {
 9816            let location_task = editor.update(&mut cx, |editor, cx| {
 9817                project.update(cx, |project, cx| {
 9818                    let language_server_name =
 9819                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9820                            project
 9821                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9822                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9823                        });
 9824                    language_server_name.map(|language_server_name| {
 9825                        project.open_local_buffer_via_lsp(
 9826                            lsp_location.uri.clone(),
 9827                            server_id,
 9828                            language_server_name,
 9829                            cx,
 9830                        )
 9831                    })
 9832                })
 9833            })?;
 9834            let location = match location_task {
 9835                Some(task) => Some({
 9836                    let target_buffer_handle = task.await.context("open local buffer")?;
 9837                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9838                        let target_start = target_buffer
 9839                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9840                        let target_end = target_buffer
 9841                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9842                        target_buffer.anchor_after(target_start)
 9843                            ..target_buffer.anchor_before(target_end)
 9844                    })?;
 9845                    Location {
 9846                        buffer: target_buffer_handle,
 9847                        range,
 9848                    }
 9849                }),
 9850                None => None,
 9851            };
 9852            Ok(location)
 9853        })
 9854    }
 9855
 9856    pub fn find_all_references(
 9857        &mut self,
 9858        _: &FindAllReferences,
 9859        cx: &mut ViewContext<Self>,
 9860    ) -> Option<Task<Result<Navigated>>> {
 9861        let multi_buffer = self.buffer.read(cx);
 9862        let selection = self.selections.newest::<usize>(cx);
 9863        let head = selection.head();
 9864
 9865        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9866        let head_anchor = multi_buffer_snapshot.anchor_at(
 9867            head,
 9868            if head < selection.tail() {
 9869                Bias::Right
 9870            } else {
 9871                Bias::Left
 9872            },
 9873        );
 9874
 9875        match self
 9876            .find_all_references_task_sources
 9877            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9878        {
 9879            Ok(_) => {
 9880                log::info!(
 9881                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9882                );
 9883                return None;
 9884            }
 9885            Err(i) => {
 9886                self.find_all_references_task_sources.insert(i, head_anchor);
 9887            }
 9888        }
 9889
 9890        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9891        let workspace = self.workspace()?;
 9892        let project = workspace.read(cx).project().clone();
 9893        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9894        Some(cx.spawn(|editor, mut cx| async move {
 9895            let _cleanup = defer({
 9896                let mut cx = cx.clone();
 9897                move || {
 9898                    let _ = editor.update(&mut cx, |editor, _| {
 9899                        if let Ok(i) =
 9900                            editor
 9901                                .find_all_references_task_sources
 9902                                .binary_search_by(|anchor| {
 9903                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9904                                })
 9905                        {
 9906                            editor.find_all_references_task_sources.remove(i);
 9907                        }
 9908                    });
 9909                }
 9910            });
 9911
 9912            let locations = references.await?;
 9913            if locations.is_empty() {
 9914                return anyhow::Ok(Navigated::No);
 9915            }
 9916
 9917            workspace.update(&mut cx, |workspace, cx| {
 9918                let title = locations
 9919                    .first()
 9920                    .as_ref()
 9921                    .map(|location| {
 9922                        let buffer = location.buffer.read(cx);
 9923                        format!(
 9924                            "References to `{}`",
 9925                            buffer
 9926                                .text_for_range(location.range.clone())
 9927                                .collect::<String>()
 9928                        )
 9929                    })
 9930                    .unwrap();
 9931                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9932                Navigated::Yes
 9933            })
 9934        }))
 9935    }
 9936
 9937    /// Opens a multibuffer with the given project locations in it
 9938    pub fn open_locations_in_multibuffer(
 9939        workspace: &mut Workspace,
 9940        mut locations: Vec<Location>,
 9941        title: String,
 9942        split: bool,
 9943        cx: &mut ViewContext<Workspace>,
 9944    ) {
 9945        // If there are multiple definitions, open them in a multibuffer
 9946        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9947        let mut locations = locations.into_iter().peekable();
 9948        let mut ranges_to_highlight = Vec::new();
 9949        let capability = workspace.project().read(cx).capability();
 9950
 9951        let excerpt_buffer = cx.new_model(|cx| {
 9952            let mut multibuffer = MultiBuffer::new(capability);
 9953            while let Some(location) = locations.next() {
 9954                let buffer = location.buffer.read(cx);
 9955                let mut ranges_for_buffer = Vec::new();
 9956                let range = location.range.to_offset(buffer);
 9957                ranges_for_buffer.push(range.clone());
 9958
 9959                while let Some(next_location) = locations.peek() {
 9960                    if next_location.buffer == location.buffer {
 9961                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9962                        locations.next();
 9963                    } else {
 9964                        break;
 9965                    }
 9966                }
 9967
 9968                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9969                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9970                    location.buffer.clone(),
 9971                    ranges_for_buffer,
 9972                    DEFAULT_MULTIBUFFER_CONTEXT,
 9973                    cx,
 9974                ))
 9975            }
 9976
 9977            multibuffer.with_title(title)
 9978        });
 9979
 9980        let editor = cx.new_view(|cx| {
 9981            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9982        });
 9983        editor.update(cx, |editor, cx| {
 9984            if let Some(first_range) = ranges_to_highlight.first() {
 9985                editor.change_selections(None, cx, |selections| {
 9986                    selections.clear_disjoint();
 9987                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9988                });
 9989            }
 9990            editor.highlight_background::<Self>(
 9991                &ranges_to_highlight,
 9992                |theme| theme.editor_highlighted_line_background,
 9993                cx,
 9994            );
 9995        });
 9996
 9997        let item = Box::new(editor);
 9998        let item_id = item.item_id();
 9999
10000        if split {
10001            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10002        } else {
10003            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10004                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10005                    pane.close_current_preview_item(cx)
10006                } else {
10007                    None
10008                }
10009            });
10010            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10011        }
10012        workspace.active_pane().update(cx, |pane, cx| {
10013            pane.set_preview_item_id(Some(item_id), cx);
10014        });
10015    }
10016
10017    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10018        use language::ToOffset as _;
10019
10020        let project = self.project.clone()?;
10021        let selection = self.selections.newest_anchor().clone();
10022        let (cursor_buffer, cursor_buffer_position) = self
10023            .buffer
10024            .read(cx)
10025            .text_anchor_for_position(selection.head(), cx)?;
10026        let (tail_buffer, cursor_buffer_position_end) = self
10027            .buffer
10028            .read(cx)
10029            .text_anchor_for_position(selection.tail(), cx)?;
10030        if tail_buffer != cursor_buffer {
10031            return None;
10032        }
10033
10034        let snapshot = cursor_buffer.read(cx).snapshot();
10035        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10036        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10037        let prepare_rename = project.update(cx, |project, cx| {
10038            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10039        });
10040        drop(snapshot);
10041
10042        Some(cx.spawn(|this, mut cx| async move {
10043            let rename_range = if let Some(range) = prepare_rename.await? {
10044                Some(range)
10045            } else {
10046                this.update(&mut cx, |this, cx| {
10047                    let buffer = this.buffer.read(cx).snapshot(cx);
10048                    let mut buffer_highlights = this
10049                        .document_highlights_for_position(selection.head(), &buffer)
10050                        .filter(|highlight| {
10051                            highlight.start.excerpt_id == selection.head().excerpt_id
10052                                && highlight.end.excerpt_id == selection.head().excerpt_id
10053                        });
10054                    buffer_highlights
10055                        .next()
10056                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10057                })?
10058            };
10059            if let Some(rename_range) = rename_range {
10060                this.update(&mut cx, |this, cx| {
10061                    let snapshot = cursor_buffer.read(cx).snapshot();
10062                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10063                    let cursor_offset_in_rename_range =
10064                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10065                    let cursor_offset_in_rename_range_end =
10066                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10067
10068                    this.take_rename(false, cx);
10069                    let buffer = this.buffer.read(cx).read(cx);
10070                    let cursor_offset = selection.head().to_offset(&buffer);
10071                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10072                    let rename_end = rename_start + rename_buffer_range.len();
10073                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10074                    let mut old_highlight_id = None;
10075                    let old_name: Arc<str> = buffer
10076                        .chunks(rename_start..rename_end, true)
10077                        .map(|chunk| {
10078                            if old_highlight_id.is_none() {
10079                                old_highlight_id = chunk.syntax_highlight_id;
10080                            }
10081                            chunk.text
10082                        })
10083                        .collect::<String>()
10084                        .into();
10085
10086                    drop(buffer);
10087
10088                    // Position the selection in the rename editor so that it matches the current selection.
10089                    this.show_local_selections = false;
10090                    let rename_editor = cx.new_view(|cx| {
10091                        let mut editor = Editor::single_line(cx);
10092                        editor.buffer.update(cx, |buffer, cx| {
10093                            buffer.edit([(0..0, old_name.clone())], None, cx)
10094                        });
10095                        let rename_selection_range = match cursor_offset_in_rename_range
10096                            .cmp(&cursor_offset_in_rename_range_end)
10097                        {
10098                            Ordering::Equal => {
10099                                editor.select_all(&SelectAll, cx);
10100                                return editor;
10101                            }
10102                            Ordering::Less => {
10103                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10104                            }
10105                            Ordering::Greater => {
10106                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10107                            }
10108                        };
10109                        if rename_selection_range.end > old_name.len() {
10110                            editor.select_all(&SelectAll, cx);
10111                        } else {
10112                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10113                                s.select_ranges([rename_selection_range]);
10114                            });
10115                        }
10116                        editor
10117                    });
10118                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10119                        if e == &EditorEvent::Focused {
10120                            cx.emit(EditorEvent::FocusedIn)
10121                        }
10122                    })
10123                    .detach();
10124
10125                    let write_highlights =
10126                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10127                    let read_highlights =
10128                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10129                    let ranges = write_highlights
10130                        .iter()
10131                        .flat_map(|(_, ranges)| ranges.iter())
10132                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10133                        .cloned()
10134                        .collect();
10135
10136                    this.highlight_text::<Rename>(
10137                        ranges,
10138                        HighlightStyle {
10139                            fade_out: Some(0.6),
10140                            ..Default::default()
10141                        },
10142                        cx,
10143                    );
10144                    let rename_focus_handle = rename_editor.focus_handle(cx);
10145                    cx.focus(&rename_focus_handle);
10146                    let block_id = this.insert_blocks(
10147                        [BlockProperties {
10148                            style: BlockStyle::Flex,
10149                            position: range.start,
10150                            height: 1,
10151                            render: Box::new({
10152                                let rename_editor = rename_editor.clone();
10153                                move |cx: &mut BlockContext| {
10154                                    let mut text_style = cx.editor_style.text.clone();
10155                                    if let Some(highlight_style) = old_highlight_id
10156                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10157                                    {
10158                                        text_style = text_style.highlight(highlight_style);
10159                                    }
10160                                    div()
10161                                        .pl(cx.anchor_x)
10162                                        .child(EditorElement::new(
10163                                            &rename_editor,
10164                                            EditorStyle {
10165                                                background: cx.theme().system().transparent,
10166                                                local_player: cx.editor_style.local_player,
10167                                                text: text_style,
10168                                                scrollbar_width: cx.editor_style.scrollbar_width,
10169                                                syntax: cx.editor_style.syntax.clone(),
10170                                                status: cx.editor_style.status.clone(),
10171                                                inlay_hints_style: HighlightStyle {
10172                                                    font_weight: Some(FontWeight::BOLD),
10173                                                    ..make_inlay_hints_style(cx)
10174                                                },
10175                                                suggestions_style: HighlightStyle {
10176                                                    color: Some(cx.theme().status().predictive),
10177                                                    ..HighlightStyle::default()
10178                                                },
10179                                                ..EditorStyle::default()
10180                                            },
10181                                        ))
10182                                        .into_any_element()
10183                                }
10184                            }),
10185                            disposition: BlockDisposition::Below,
10186                            priority: 0,
10187                        }],
10188                        Some(Autoscroll::fit()),
10189                        cx,
10190                    )[0];
10191                    this.pending_rename = Some(RenameState {
10192                        range,
10193                        old_name,
10194                        editor: rename_editor,
10195                        block_id,
10196                    });
10197                })?;
10198            }
10199
10200            Ok(())
10201        }))
10202    }
10203
10204    pub fn confirm_rename(
10205        &mut self,
10206        _: &ConfirmRename,
10207        cx: &mut ViewContext<Self>,
10208    ) -> Option<Task<Result<()>>> {
10209        let rename = self.take_rename(false, cx)?;
10210        let workspace = self.workspace()?;
10211        let (start_buffer, start) = self
10212            .buffer
10213            .read(cx)
10214            .text_anchor_for_position(rename.range.start, cx)?;
10215        let (end_buffer, end) = self
10216            .buffer
10217            .read(cx)
10218            .text_anchor_for_position(rename.range.end, cx)?;
10219        if start_buffer != end_buffer {
10220            return None;
10221        }
10222
10223        let buffer = start_buffer;
10224        let range = start..end;
10225        let old_name = rename.old_name;
10226        let new_name = rename.editor.read(cx).text(cx);
10227
10228        let rename = workspace
10229            .read(cx)
10230            .project()
10231            .clone()
10232            .update(cx, |project, cx| {
10233                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10234            });
10235        let workspace = workspace.downgrade();
10236
10237        Some(cx.spawn(|editor, mut cx| async move {
10238            let project_transaction = rename.await?;
10239            Self::open_project_transaction(
10240                &editor,
10241                workspace,
10242                project_transaction,
10243                format!("Rename: {}{}", old_name, new_name),
10244                cx.clone(),
10245            )
10246            .await?;
10247
10248            editor.update(&mut cx, |editor, cx| {
10249                editor.refresh_document_highlights(cx);
10250            })?;
10251            Ok(())
10252        }))
10253    }
10254
10255    fn take_rename(
10256        &mut self,
10257        moving_cursor: bool,
10258        cx: &mut ViewContext<Self>,
10259    ) -> Option<RenameState> {
10260        let rename = self.pending_rename.take()?;
10261        if rename.editor.focus_handle(cx).is_focused(cx) {
10262            cx.focus(&self.focus_handle);
10263        }
10264
10265        self.remove_blocks(
10266            [rename.block_id].into_iter().collect(),
10267            Some(Autoscroll::fit()),
10268            cx,
10269        );
10270        self.clear_highlights::<Rename>(cx);
10271        self.show_local_selections = true;
10272
10273        if moving_cursor {
10274            let rename_editor = rename.editor.read(cx);
10275            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10276
10277            // Update the selection to match the position of the selection inside
10278            // the rename editor.
10279            let snapshot = self.buffer.read(cx).read(cx);
10280            let rename_range = rename.range.to_offset(&snapshot);
10281            let cursor_in_editor = snapshot
10282                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10283                .min(rename_range.end);
10284            drop(snapshot);
10285
10286            self.change_selections(None, cx, |s| {
10287                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10288            });
10289        } else {
10290            self.refresh_document_highlights(cx);
10291        }
10292
10293        Some(rename)
10294    }
10295
10296    pub fn pending_rename(&self) -> Option<&RenameState> {
10297        self.pending_rename.as_ref()
10298    }
10299
10300    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10301        let project = match &self.project {
10302            Some(project) => project.clone(),
10303            None => return None,
10304        };
10305
10306        Some(self.perform_format(project, FormatTrigger::Manual, cx))
10307    }
10308
10309    fn perform_format(
10310        &mut self,
10311        project: Model<Project>,
10312        trigger: FormatTrigger,
10313        cx: &mut ViewContext<Self>,
10314    ) -> Task<Result<()>> {
10315        let buffer = self.buffer().clone();
10316        let mut buffers = buffer.read(cx).all_buffers();
10317        if trigger == FormatTrigger::Save {
10318            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10319        }
10320
10321        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10322        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10323
10324        cx.spawn(|_, mut cx| async move {
10325            let transaction = futures::select_biased! {
10326                () = timeout => {
10327                    log::warn!("timed out waiting for formatting");
10328                    None
10329                }
10330                transaction = format.log_err().fuse() => transaction,
10331            };
10332
10333            buffer
10334                .update(&mut cx, |buffer, cx| {
10335                    if let Some(transaction) = transaction {
10336                        if !buffer.is_singleton() {
10337                            buffer.push_transaction(&transaction.0, cx);
10338                        }
10339                    }
10340
10341                    cx.notify();
10342                })
10343                .ok();
10344
10345            Ok(())
10346        })
10347    }
10348
10349    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10350        if let Some(project) = self.project.clone() {
10351            self.buffer.update(cx, |multi_buffer, cx| {
10352                project.update(cx, |project, cx| {
10353                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10354                });
10355            })
10356        }
10357    }
10358
10359    fn cancel_language_server_work(
10360        &mut self,
10361        _: &CancelLanguageServerWork,
10362        cx: &mut ViewContext<Self>,
10363    ) {
10364        if let Some(project) = self.project.clone() {
10365            self.buffer.update(cx, |multi_buffer, cx| {
10366                project.update(cx, |project, cx| {
10367                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10368                });
10369            })
10370        }
10371    }
10372
10373    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10374        cx.show_character_palette();
10375    }
10376
10377    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10378        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10379            let buffer = self.buffer.read(cx).snapshot(cx);
10380            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10381            let is_valid = buffer
10382                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10383                .any(|entry| {
10384                    entry.diagnostic.is_primary
10385                        && !entry.range.is_empty()
10386                        && entry.range.start == primary_range_start
10387                        && entry.diagnostic.message == active_diagnostics.primary_message
10388                });
10389
10390            if is_valid != active_diagnostics.is_valid {
10391                active_diagnostics.is_valid = is_valid;
10392                let mut new_styles = HashMap::default();
10393                for (block_id, diagnostic) in &active_diagnostics.blocks {
10394                    new_styles.insert(
10395                        *block_id,
10396                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10397                    );
10398                }
10399                self.display_map.update(cx, |display_map, _cx| {
10400                    display_map.replace_blocks(new_styles)
10401                });
10402            }
10403        }
10404    }
10405
10406    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10407        self.dismiss_diagnostics(cx);
10408        let snapshot = self.snapshot(cx);
10409        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10410            let buffer = self.buffer.read(cx).snapshot(cx);
10411
10412            let mut primary_range = None;
10413            let mut primary_message = None;
10414            let mut group_end = Point::zero();
10415            let diagnostic_group = buffer
10416                .diagnostic_group::<MultiBufferPoint>(group_id)
10417                .filter_map(|entry| {
10418                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10419                        && (entry.range.start.row == entry.range.end.row
10420                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10421                    {
10422                        return None;
10423                    }
10424                    if entry.range.end > group_end {
10425                        group_end = entry.range.end;
10426                    }
10427                    if entry.diagnostic.is_primary {
10428                        primary_range = Some(entry.range.clone());
10429                        primary_message = Some(entry.diagnostic.message.clone());
10430                    }
10431                    Some(entry)
10432                })
10433                .collect::<Vec<_>>();
10434            let primary_range = primary_range?;
10435            let primary_message = primary_message?;
10436            let primary_range =
10437                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10438
10439            let blocks = display_map
10440                .insert_blocks(
10441                    diagnostic_group.iter().map(|entry| {
10442                        let diagnostic = entry.diagnostic.clone();
10443                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10444                        BlockProperties {
10445                            style: BlockStyle::Fixed,
10446                            position: buffer.anchor_after(entry.range.start),
10447                            height: message_height,
10448                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10449                            disposition: BlockDisposition::Below,
10450                            priority: 0,
10451                        }
10452                    }),
10453                    cx,
10454                )
10455                .into_iter()
10456                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10457                .collect();
10458
10459            Some(ActiveDiagnosticGroup {
10460                primary_range,
10461                primary_message,
10462                group_id,
10463                blocks,
10464                is_valid: true,
10465            })
10466        });
10467        self.active_diagnostics.is_some()
10468    }
10469
10470    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10471        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10472            self.display_map.update(cx, |display_map, cx| {
10473                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10474            });
10475            cx.notify();
10476        }
10477    }
10478
10479    pub fn set_selections_from_remote(
10480        &mut self,
10481        selections: Vec<Selection<Anchor>>,
10482        pending_selection: Option<Selection<Anchor>>,
10483        cx: &mut ViewContext<Self>,
10484    ) {
10485        let old_cursor_position = self.selections.newest_anchor().head();
10486        self.selections.change_with(cx, |s| {
10487            s.select_anchors(selections);
10488            if let Some(pending_selection) = pending_selection {
10489                s.set_pending(pending_selection, SelectMode::Character);
10490            } else {
10491                s.clear_pending();
10492            }
10493        });
10494        self.selections_did_change(false, &old_cursor_position, true, cx);
10495    }
10496
10497    fn push_to_selection_history(&mut self) {
10498        self.selection_history.push(SelectionHistoryEntry {
10499            selections: self.selections.disjoint_anchors(),
10500            select_next_state: self.select_next_state.clone(),
10501            select_prev_state: self.select_prev_state.clone(),
10502            add_selections_state: self.add_selections_state.clone(),
10503        });
10504    }
10505
10506    pub fn transact(
10507        &mut self,
10508        cx: &mut ViewContext<Self>,
10509        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10510    ) -> Option<TransactionId> {
10511        self.start_transaction_at(Instant::now(), cx);
10512        update(self, cx);
10513        self.end_transaction_at(Instant::now(), cx)
10514    }
10515
10516    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10517        self.end_selection(cx);
10518        if let Some(tx_id) = self
10519            .buffer
10520            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10521        {
10522            self.selection_history
10523                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10524            cx.emit(EditorEvent::TransactionBegun {
10525                transaction_id: tx_id,
10526            })
10527        }
10528    }
10529
10530    fn end_transaction_at(
10531        &mut self,
10532        now: Instant,
10533        cx: &mut ViewContext<Self>,
10534    ) -> Option<TransactionId> {
10535        if let Some(transaction_id) = self
10536            .buffer
10537            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10538        {
10539            if let Some((_, end_selections)) =
10540                self.selection_history.transaction_mut(transaction_id)
10541            {
10542                *end_selections = Some(self.selections.disjoint_anchors());
10543            } else {
10544                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10545            }
10546
10547            cx.emit(EditorEvent::Edited { transaction_id });
10548            Some(transaction_id)
10549        } else {
10550            None
10551        }
10552    }
10553
10554    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10555        let selection = self.selections.newest::<Point>(cx);
10556
10557        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10558        let range = if selection.is_empty() {
10559            let point = selection.head().to_display_point(&display_map);
10560            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10561            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10562                .to_point(&display_map);
10563            start..end
10564        } else {
10565            selection.range()
10566        };
10567        if display_map.folds_in_range(range).next().is_some() {
10568            self.unfold_lines(&Default::default(), cx)
10569        } else {
10570            self.fold(&Default::default(), cx)
10571        }
10572    }
10573
10574    pub fn toggle_fold_recursive(
10575        &mut self,
10576        _: &actions::ToggleFoldRecursive,
10577        cx: &mut ViewContext<Self>,
10578    ) {
10579        let selection = self.selections.newest::<Point>(cx);
10580
10581        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10582        let range = if selection.is_empty() {
10583            let point = selection.head().to_display_point(&display_map);
10584            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10585            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10586                .to_point(&display_map);
10587            start..end
10588        } else {
10589            selection.range()
10590        };
10591        if display_map.folds_in_range(range).next().is_some() {
10592            self.unfold_recursive(&Default::default(), cx)
10593        } else {
10594            self.fold_recursive(&Default::default(), cx)
10595        }
10596    }
10597
10598    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10599        let mut fold_ranges = Vec::new();
10600        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10601        let selections = self.selections.all_adjusted(cx);
10602
10603        for selection in selections {
10604            let range = selection.range().sorted();
10605            let buffer_start_row = range.start.row;
10606
10607            if range.start.row != range.end.row {
10608                let mut found = false;
10609                let mut row = range.start.row;
10610                while row <= range.end.row {
10611                    if let Some((foldable_range, fold_text)) =
10612                        { display_map.foldable_range(MultiBufferRow(row)) }
10613                    {
10614                        found = true;
10615                        row = foldable_range.end.row + 1;
10616                        fold_ranges.push((foldable_range, fold_text));
10617                    } else {
10618                        row += 1
10619                    }
10620                }
10621                if found {
10622                    continue;
10623                }
10624            }
10625
10626            for row in (0..=range.start.row).rev() {
10627                if let Some((foldable_range, fold_text)) =
10628                    display_map.foldable_range(MultiBufferRow(row))
10629                {
10630                    if foldable_range.end.row >= buffer_start_row {
10631                        fold_ranges.push((foldable_range, fold_text));
10632                        if row <= range.start.row {
10633                            break;
10634                        }
10635                    }
10636                }
10637            }
10638        }
10639
10640        self.fold_ranges(fold_ranges, true, cx);
10641    }
10642
10643    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10644        let mut fold_ranges = Vec::new();
10645        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10646
10647        for row in 0..display_map.max_buffer_row().0 {
10648            if let Some((foldable_range, fold_text)) =
10649                display_map.foldable_range(MultiBufferRow(row))
10650            {
10651                fold_ranges.push((foldable_range, fold_text));
10652            }
10653        }
10654
10655        self.fold_ranges(fold_ranges, true, cx);
10656    }
10657
10658    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10659        let mut fold_ranges = Vec::new();
10660        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10661        let selections = self.selections.all_adjusted(cx);
10662
10663        for selection in selections {
10664            let range = selection.range().sorted();
10665            let buffer_start_row = range.start.row;
10666
10667            if range.start.row != range.end.row {
10668                let mut found = false;
10669                for row in range.start.row..=range.end.row {
10670                    if let Some((foldable_range, fold_text)) =
10671                        { display_map.foldable_range(MultiBufferRow(row)) }
10672                    {
10673                        found = true;
10674                        fold_ranges.push((foldable_range, fold_text));
10675                    }
10676                }
10677                if found {
10678                    continue;
10679                }
10680            }
10681
10682            for row in (0..=range.start.row).rev() {
10683                if let Some((foldable_range, fold_text)) =
10684                    display_map.foldable_range(MultiBufferRow(row))
10685                {
10686                    if foldable_range.end.row >= buffer_start_row {
10687                        fold_ranges.push((foldable_range, fold_text));
10688                    } else {
10689                        break;
10690                    }
10691                }
10692            }
10693        }
10694
10695        self.fold_ranges(fold_ranges, true, cx);
10696    }
10697
10698    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10699        let buffer_row = fold_at.buffer_row;
10700        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10701
10702        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10703            let autoscroll = self
10704                .selections
10705                .all::<Point>(cx)
10706                .iter()
10707                .any(|selection| fold_range.overlaps(&selection.range()));
10708
10709            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10710        }
10711    }
10712
10713    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10714        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10715        let buffer = &display_map.buffer_snapshot;
10716        let selections = self.selections.all::<Point>(cx);
10717        let ranges = selections
10718            .iter()
10719            .map(|s| {
10720                let range = s.display_range(&display_map).sorted();
10721                let mut start = range.start.to_point(&display_map);
10722                let mut end = range.end.to_point(&display_map);
10723                start.column = 0;
10724                end.column = buffer.line_len(MultiBufferRow(end.row));
10725                start..end
10726            })
10727            .collect::<Vec<_>>();
10728
10729        self.unfold_ranges(ranges, true, true, cx);
10730    }
10731
10732    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10733        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10734        let selections = self.selections.all::<Point>(cx);
10735        let ranges = selections
10736            .iter()
10737            .map(|s| {
10738                let mut range = s.display_range(&display_map).sorted();
10739                *range.start.column_mut() = 0;
10740                *range.end.column_mut() = display_map.line_len(range.end.row());
10741                let start = range.start.to_point(&display_map);
10742                let end = range.end.to_point(&display_map);
10743                start..end
10744            })
10745            .collect::<Vec<_>>();
10746
10747        self.unfold_ranges(ranges, true, true, cx);
10748    }
10749
10750    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10751        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10752
10753        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10754            ..Point::new(
10755                unfold_at.buffer_row.0,
10756                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10757            );
10758
10759        let autoscroll = self
10760            .selections
10761            .all::<Point>(cx)
10762            .iter()
10763            .any(|selection| selection.range().overlaps(&intersection_range));
10764
10765        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10766    }
10767
10768    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10769        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10770        self.unfold_ranges(
10771            [Point::zero()..display_map.max_point().to_point(&display_map)],
10772            true,
10773            true,
10774            cx,
10775        );
10776    }
10777
10778    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10779        let selections = self.selections.all::<Point>(cx);
10780        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10781        let line_mode = self.selections.line_mode;
10782        let ranges = selections.into_iter().map(|s| {
10783            if line_mode {
10784                let start = Point::new(s.start.row, 0);
10785                let end = Point::new(
10786                    s.end.row,
10787                    display_map
10788                        .buffer_snapshot
10789                        .line_len(MultiBufferRow(s.end.row)),
10790                );
10791                (start..end, display_map.fold_placeholder.clone())
10792            } else {
10793                (s.start..s.end, display_map.fold_placeholder.clone())
10794            }
10795        });
10796        self.fold_ranges(ranges, true, cx);
10797    }
10798
10799    pub fn fold_ranges<T: ToOffset + Clone>(
10800        &mut self,
10801        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10802        auto_scroll: bool,
10803        cx: &mut ViewContext<Self>,
10804    ) {
10805        let mut fold_ranges = Vec::new();
10806        let mut buffers_affected = HashMap::default();
10807        let multi_buffer = self.buffer().read(cx);
10808        for (fold_range, fold_text) in ranges {
10809            if let Some((_, buffer, _)) =
10810                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10811            {
10812                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10813            };
10814            fold_ranges.push((fold_range, fold_text));
10815        }
10816
10817        let mut ranges = fold_ranges.into_iter().peekable();
10818        if ranges.peek().is_some() {
10819            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10820
10821            if auto_scroll {
10822                self.request_autoscroll(Autoscroll::fit(), cx);
10823            }
10824
10825            for buffer in buffers_affected.into_values() {
10826                self.sync_expanded_diff_hunks(buffer, cx);
10827            }
10828
10829            cx.notify();
10830
10831            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10832                // Clear diagnostics block when folding a range that contains it.
10833                let snapshot = self.snapshot(cx);
10834                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10835                    drop(snapshot);
10836                    self.active_diagnostics = Some(active_diagnostics);
10837                    self.dismiss_diagnostics(cx);
10838                } else {
10839                    self.active_diagnostics = Some(active_diagnostics);
10840                }
10841            }
10842
10843            self.scrollbar_marker_state.dirty = true;
10844        }
10845    }
10846
10847    pub fn unfold_ranges<T: ToOffset + Clone>(
10848        &mut self,
10849        ranges: impl IntoIterator<Item = Range<T>>,
10850        inclusive: bool,
10851        auto_scroll: bool,
10852        cx: &mut ViewContext<Self>,
10853    ) {
10854        let mut unfold_ranges = Vec::new();
10855        let mut buffers_affected = HashMap::default();
10856        let multi_buffer = self.buffer().read(cx);
10857        for range in ranges {
10858            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10859                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10860            };
10861            unfold_ranges.push(range);
10862        }
10863
10864        let mut ranges = unfold_ranges.into_iter().peekable();
10865        if ranges.peek().is_some() {
10866            self.display_map
10867                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10868            if auto_scroll {
10869                self.request_autoscroll(Autoscroll::fit(), cx);
10870            }
10871
10872            for buffer in buffers_affected.into_values() {
10873                self.sync_expanded_diff_hunks(buffer, cx);
10874            }
10875
10876            cx.notify();
10877            self.scrollbar_marker_state.dirty = true;
10878            self.active_indent_guides_state.dirty = true;
10879        }
10880    }
10881
10882    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10883        self.display_map.read(cx).fold_placeholder.clone()
10884    }
10885
10886    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10887        if hovered != self.gutter_hovered {
10888            self.gutter_hovered = hovered;
10889            cx.notify();
10890        }
10891    }
10892
10893    pub fn insert_blocks(
10894        &mut self,
10895        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10896        autoscroll: Option<Autoscroll>,
10897        cx: &mut ViewContext<Self>,
10898    ) -> Vec<CustomBlockId> {
10899        let blocks = self
10900            .display_map
10901            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10902        if let Some(autoscroll) = autoscroll {
10903            self.request_autoscroll(autoscroll, cx);
10904        }
10905        cx.notify();
10906        blocks
10907    }
10908
10909    pub fn resize_blocks(
10910        &mut self,
10911        heights: HashMap<CustomBlockId, u32>,
10912        autoscroll: Option<Autoscroll>,
10913        cx: &mut ViewContext<Self>,
10914    ) {
10915        self.display_map
10916            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10917        if let Some(autoscroll) = autoscroll {
10918            self.request_autoscroll(autoscroll, cx);
10919        }
10920        cx.notify();
10921    }
10922
10923    pub fn replace_blocks(
10924        &mut self,
10925        renderers: HashMap<CustomBlockId, RenderBlock>,
10926        autoscroll: Option<Autoscroll>,
10927        cx: &mut ViewContext<Self>,
10928    ) {
10929        self.display_map
10930            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10931        if let Some(autoscroll) = autoscroll {
10932            self.request_autoscroll(autoscroll, cx);
10933        }
10934        cx.notify();
10935    }
10936
10937    pub fn remove_blocks(
10938        &mut self,
10939        block_ids: HashSet<CustomBlockId>,
10940        autoscroll: Option<Autoscroll>,
10941        cx: &mut ViewContext<Self>,
10942    ) {
10943        self.display_map.update(cx, |display_map, cx| {
10944            display_map.remove_blocks(block_ids, cx)
10945        });
10946        if let Some(autoscroll) = autoscroll {
10947            self.request_autoscroll(autoscroll, cx);
10948        }
10949        cx.notify();
10950    }
10951
10952    pub fn row_for_block(
10953        &self,
10954        block_id: CustomBlockId,
10955        cx: &mut ViewContext<Self>,
10956    ) -> Option<DisplayRow> {
10957        self.display_map
10958            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10959    }
10960
10961    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10962        self.focused_block = Some(focused_block);
10963    }
10964
10965    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10966        self.focused_block.take()
10967    }
10968
10969    pub fn insert_creases(
10970        &mut self,
10971        creases: impl IntoIterator<Item = Crease>,
10972        cx: &mut ViewContext<Self>,
10973    ) -> Vec<CreaseId> {
10974        self.display_map
10975            .update(cx, |map, cx| map.insert_creases(creases, cx))
10976    }
10977
10978    pub fn remove_creases(
10979        &mut self,
10980        ids: impl IntoIterator<Item = CreaseId>,
10981        cx: &mut ViewContext<Self>,
10982    ) {
10983        self.display_map
10984            .update(cx, |map, cx| map.remove_creases(ids, cx));
10985    }
10986
10987    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10988        self.display_map
10989            .update(cx, |map, cx| map.snapshot(cx))
10990            .longest_row()
10991    }
10992
10993    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10994        self.display_map
10995            .update(cx, |map, cx| map.snapshot(cx))
10996            .max_point()
10997    }
10998
10999    pub fn text(&self, cx: &AppContext) -> String {
11000        self.buffer.read(cx).read(cx).text()
11001    }
11002
11003    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11004        let text = self.text(cx);
11005        let text = text.trim();
11006
11007        if text.is_empty() {
11008            return None;
11009        }
11010
11011        Some(text.to_string())
11012    }
11013
11014    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11015        self.transact(cx, |this, cx| {
11016            this.buffer
11017                .read(cx)
11018                .as_singleton()
11019                .expect("you can only call set_text on editors for singleton buffers")
11020                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11021        });
11022    }
11023
11024    pub fn display_text(&self, cx: &mut AppContext) -> String {
11025        self.display_map
11026            .update(cx, |map, cx| map.snapshot(cx))
11027            .text()
11028    }
11029
11030    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11031        let mut wrap_guides = smallvec::smallvec![];
11032
11033        if self.show_wrap_guides == Some(false) {
11034            return wrap_guides;
11035        }
11036
11037        let settings = self.buffer.read(cx).settings_at(0, cx);
11038        if settings.show_wrap_guides {
11039            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11040                wrap_guides.push((soft_wrap as usize, true));
11041            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11042                wrap_guides.push((soft_wrap as usize, true));
11043            }
11044            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11045        }
11046
11047        wrap_guides
11048    }
11049
11050    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11051        let settings = self.buffer.read(cx).settings_at(0, cx);
11052        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11053        match mode {
11054            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11055                SoftWrap::None
11056            }
11057            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11058            language_settings::SoftWrap::PreferredLineLength => {
11059                SoftWrap::Column(settings.preferred_line_length)
11060            }
11061            language_settings::SoftWrap::Bounded => {
11062                SoftWrap::Bounded(settings.preferred_line_length)
11063            }
11064        }
11065    }
11066
11067    pub fn set_soft_wrap_mode(
11068        &mut self,
11069        mode: language_settings::SoftWrap,
11070        cx: &mut ViewContext<Self>,
11071    ) {
11072        self.soft_wrap_mode_override = Some(mode);
11073        cx.notify();
11074    }
11075
11076    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11077        let rem_size = cx.rem_size();
11078        self.display_map.update(cx, |map, cx| {
11079            map.set_font(
11080                style.text.font(),
11081                style.text.font_size.to_pixels(rem_size),
11082                cx,
11083            )
11084        });
11085        self.style = Some(style);
11086    }
11087
11088    pub fn style(&self) -> Option<&EditorStyle> {
11089        self.style.as_ref()
11090    }
11091
11092    // Called by the element. This method is not designed to be called outside of the editor
11093    // element's layout code because it does not notify when rewrapping is computed synchronously.
11094    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11095        self.display_map
11096            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11097    }
11098
11099    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11100        if self.soft_wrap_mode_override.is_some() {
11101            self.soft_wrap_mode_override.take();
11102        } else {
11103            let soft_wrap = match self.soft_wrap_mode(cx) {
11104                SoftWrap::GitDiff => return,
11105                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11106                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11107                    language_settings::SoftWrap::None
11108                }
11109            };
11110            self.soft_wrap_mode_override = Some(soft_wrap);
11111        }
11112        cx.notify();
11113    }
11114
11115    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11116        let Some(workspace) = self.workspace() else {
11117            return;
11118        };
11119        let fs = workspace.read(cx).app_state().fs.clone();
11120        let current_show = TabBarSettings::get_global(cx).show;
11121        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11122            setting.show = Some(!current_show);
11123        });
11124    }
11125
11126    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11127        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11128            self.buffer
11129                .read(cx)
11130                .settings_at(0, cx)
11131                .indent_guides
11132                .enabled
11133        });
11134        self.show_indent_guides = Some(!currently_enabled);
11135        cx.notify();
11136    }
11137
11138    fn should_show_indent_guides(&self) -> Option<bool> {
11139        self.show_indent_guides
11140    }
11141
11142    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11143        let mut editor_settings = EditorSettings::get_global(cx).clone();
11144        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11145        EditorSettings::override_global(editor_settings, cx);
11146    }
11147
11148    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11149        self.use_relative_line_numbers
11150            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11151    }
11152
11153    pub fn toggle_relative_line_numbers(
11154        &mut self,
11155        _: &ToggleRelativeLineNumbers,
11156        cx: &mut ViewContext<Self>,
11157    ) {
11158        let is_relative = self.should_use_relative_line_numbers(cx);
11159        self.set_relative_line_number(Some(!is_relative), cx)
11160    }
11161
11162    pub fn set_relative_line_number(
11163        &mut self,
11164        is_relative: Option<bool>,
11165        cx: &mut ViewContext<Self>,
11166    ) {
11167        self.use_relative_line_numbers = is_relative;
11168        cx.notify();
11169    }
11170
11171    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11172        self.show_gutter = show_gutter;
11173        cx.notify();
11174    }
11175
11176    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11177        self.show_line_numbers = Some(show_line_numbers);
11178        cx.notify();
11179    }
11180
11181    pub fn set_show_git_diff_gutter(
11182        &mut self,
11183        show_git_diff_gutter: bool,
11184        cx: &mut ViewContext<Self>,
11185    ) {
11186        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11187        cx.notify();
11188    }
11189
11190    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11191        self.show_code_actions = Some(show_code_actions);
11192        cx.notify();
11193    }
11194
11195    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11196        self.show_runnables = Some(show_runnables);
11197        cx.notify();
11198    }
11199
11200    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11201        if self.display_map.read(cx).masked != masked {
11202            self.display_map.update(cx, |map, _| map.masked = masked);
11203        }
11204        cx.notify()
11205    }
11206
11207    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11208        self.show_wrap_guides = Some(show_wrap_guides);
11209        cx.notify();
11210    }
11211
11212    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11213        self.show_indent_guides = Some(show_indent_guides);
11214        cx.notify();
11215    }
11216
11217    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11218        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11219            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11220                if let Some(dir) = file.abs_path(cx).parent() {
11221                    return Some(dir.to_owned());
11222                }
11223            }
11224
11225            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11226                return Some(project_path.path.to_path_buf());
11227            }
11228        }
11229
11230        None
11231    }
11232
11233    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11234        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11235            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11236                cx.reveal_path(&file.abs_path(cx));
11237            }
11238        }
11239    }
11240
11241    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11242        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11243            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11244                if let Some(path) = file.abs_path(cx).to_str() {
11245                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11246                }
11247            }
11248        }
11249    }
11250
11251    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11252        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11253            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11254                if let Some(path) = file.path().to_str() {
11255                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11256                }
11257            }
11258        }
11259    }
11260
11261    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11262        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11263
11264        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11265            self.start_git_blame(true, cx);
11266        }
11267
11268        cx.notify();
11269    }
11270
11271    pub fn toggle_git_blame_inline(
11272        &mut self,
11273        _: &ToggleGitBlameInline,
11274        cx: &mut ViewContext<Self>,
11275    ) {
11276        self.toggle_git_blame_inline_internal(true, cx);
11277        cx.notify();
11278    }
11279
11280    pub fn git_blame_inline_enabled(&self) -> bool {
11281        self.git_blame_inline_enabled
11282    }
11283
11284    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11285        self.show_selection_menu = self
11286            .show_selection_menu
11287            .map(|show_selections_menu| !show_selections_menu)
11288            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11289
11290        cx.notify();
11291    }
11292
11293    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11294        self.show_selection_menu
11295            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11296    }
11297
11298    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11299        if let Some(project) = self.project.as_ref() {
11300            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11301                return;
11302            };
11303
11304            if buffer.read(cx).file().is_none() {
11305                return;
11306            }
11307
11308            let focused = self.focus_handle(cx).contains_focused(cx);
11309
11310            let project = project.clone();
11311            let blame =
11312                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11313            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11314            self.blame = Some(blame);
11315        }
11316    }
11317
11318    fn toggle_git_blame_inline_internal(
11319        &mut self,
11320        user_triggered: bool,
11321        cx: &mut ViewContext<Self>,
11322    ) {
11323        if self.git_blame_inline_enabled {
11324            self.git_blame_inline_enabled = false;
11325            self.show_git_blame_inline = false;
11326            self.show_git_blame_inline_delay_task.take();
11327        } else {
11328            self.git_blame_inline_enabled = true;
11329            self.start_git_blame_inline(user_triggered, cx);
11330        }
11331
11332        cx.notify();
11333    }
11334
11335    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11336        self.start_git_blame(user_triggered, cx);
11337
11338        if ProjectSettings::get_global(cx)
11339            .git
11340            .inline_blame_delay()
11341            .is_some()
11342        {
11343            self.start_inline_blame_timer(cx);
11344        } else {
11345            self.show_git_blame_inline = true
11346        }
11347    }
11348
11349    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11350        self.blame.as_ref()
11351    }
11352
11353    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11354        self.show_git_blame_gutter && self.has_blame_entries(cx)
11355    }
11356
11357    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11358        self.show_git_blame_inline
11359            && self.focus_handle.is_focused(cx)
11360            && !self.newest_selection_head_on_empty_line(cx)
11361            && self.has_blame_entries(cx)
11362    }
11363
11364    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11365        self.blame()
11366            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11367    }
11368
11369    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11370        let cursor_anchor = self.selections.newest_anchor().head();
11371
11372        let snapshot = self.buffer.read(cx).snapshot(cx);
11373        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11374
11375        snapshot.line_len(buffer_row) == 0
11376    }
11377
11378    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11379        let (path, selection, repo) = maybe!({
11380            let project_handle = self.project.as_ref()?.clone();
11381            let project = project_handle.read(cx);
11382
11383            let selection = self.selections.newest::<Point>(cx);
11384            let selection_range = selection.range();
11385
11386            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11387                (buffer, selection_range.start.row..selection_range.end.row)
11388            } else {
11389                let buffer_ranges = self
11390                    .buffer()
11391                    .read(cx)
11392                    .range_to_buffer_ranges(selection_range, cx);
11393
11394                let (buffer, range, _) = if selection.reversed {
11395                    buffer_ranges.first()
11396                } else {
11397                    buffer_ranges.last()
11398                }?;
11399
11400                let snapshot = buffer.read(cx).snapshot();
11401                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11402                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11403                (buffer.clone(), selection)
11404            };
11405
11406            let path = buffer
11407                .read(cx)
11408                .file()?
11409                .as_local()?
11410                .path()
11411                .to_str()?
11412                .to_string();
11413            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11414            Some((path, selection, repo))
11415        })
11416        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11417
11418        const REMOTE_NAME: &str = "origin";
11419        let origin_url = repo
11420            .remote_url(REMOTE_NAME)
11421            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11422        let sha = repo
11423            .head_sha()
11424            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11425
11426        let (provider, remote) =
11427            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11428                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11429
11430        Ok(provider.build_permalink(
11431            remote,
11432            BuildPermalinkParams {
11433                sha: &sha,
11434                path: &path,
11435                selection: Some(selection),
11436            },
11437        ))
11438    }
11439
11440    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11441        let permalink = self.get_permalink_to_line(cx);
11442
11443        match permalink {
11444            Ok(permalink) => {
11445                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11446            }
11447            Err(err) => {
11448                let message = format!("Failed to copy permalink: {err}");
11449
11450                Err::<(), anyhow::Error>(err).log_err();
11451
11452                if let Some(workspace) = self.workspace() {
11453                    workspace.update(cx, |workspace, cx| {
11454                        struct CopyPermalinkToLine;
11455
11456                        workspace.show_toast(
11457                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11458                            cx,
11459                        )
11460                    })
11461                }
11462            }
11463        }
11464    }
11465
11466    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11467        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11468            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11469                if let Some(path) = file.path().to_str() {
11470                    let selection = self.selections.newest::<Point>(cx).start.row + 1;
11471                    cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11472                }
11473            }
11474        }
11475    }
11476
11477    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11478        let permalink = self.get_permalink_to_line(cx);
11479
11480        match permalink {
11481            Ok(permalink) => {
11482                cx.open_url(permalink.as_ref());
11483            }
11484            Err(err) => {
11485                let message = format!("Failed to open permalink: {err}");
11486
11487                Err::<(), anyhow::Error>(err).log_err();
11488
11489                if let Some(workspace) = self.workspace() {
11490                    workspace.update(cx, |workspace, cx| {
11491                        struct OpenPermalinkToLine;
11492
11493                        workspace.show_toast(
11494                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11495                            cx,
11496                        )
11497                    })
11498                }
11499            }
11500        }
11501    }
11502
11503    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11504    /// last highlight added will be used.
11505    ///
11506    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11507    pub fn highlight_rows<T: 'static>(
11508        &mut self,
11509        range: Range<Anchor>,
11510        color: Hsla,
11511        should_autoscroll: bool,
11512        cx: &mut ViewContext<Self>,
11513    ) {
11514        let snapshot = self.buffer().read(cx).snapshot(cx);
11515        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11516        let ix = row_highlights.binary_search_by(|highlight| {
11517            Ordering::Equal
11518                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11519                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11520        });
11521
11522        if let Err(mut ix) = ix {
11523            let index = post_inc(&mut self.highlight_order);
11524
11525            // If this range intersects with the preceding highlight, then merge it with
11526            // the preceding highlight. Otherwise insert a new highlight.
11527            let mut merged = false;
11528            if ix > 0 {
11529                let prev_highlight = &mut row_highlights[ix - 1];
11530                if prev_highlight
11531                    .range
11532                    .end
11533                    .cmp(&range.start, &snapshot)
11534                    .is_ge()
11535                {
11536                    ix -= 1;
11537                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11538                        prev_highlight.range.end = range.end;
11539                    }
11540                    merged = true;
11541                    prev_highlight.index = index;
11542                    prev_highlight.color = color;
11543                    prev_highlight.should_autoscroll = should_autoscroll;
11544                }
11545            }
11546
11547            if !merged {
11548                row_highlights.insert(
11549                    ix,
11550                    RowHighlight {
11551                        range: range.clone(),
11552                        index,
11553                        color,
11554                        should_autoscroll,
11555                    },
11556                );
11557            }
11558
11559            // If any of the following highlights intersect with this one, merge them.
11560            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11561                let highlight = &row_highlights[ix];
11562                if next_highlight
11563                    .range
11564                    .start
11565                    .cmp(&highlight.range.end, &snapshot)
11566                    .is_le()
11567                {
11568                    if next_highlight
11569                        .range
11570                        .end
11571                        .cmp(&highlight.range.end, &snapshot)
11572                        .is_gt()
11573                    {
11574                        row_highlights[ix].range.end = next_highlight.range.end;
11575                    }
11576                    row_highlights.remove(ix + 1);
11577                } else {
11578                    break;
11579                }
11580            }
11581        }
11582    }
11583
11584    /// Remove any highlighted row ranges of the given type that intersect the
11585    /// given ranges.
11586    pub fn remove_highlighted_rows<T: 'static>(
11587        &mut self,
11588        ranges_to_remove: Vec<Range<Anchor>>,
11589        cx: &mut ViewContext<Self>,
11590    ) {
11591        let snapshot = self.buffer().read(cx).snapshot(cx);
11592        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11593        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11594        row_highlights.retain(|highlight| {
11595            while let Some(range_to_remove) = ranges_to_remove.peek() {
11596                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11597                    Ordering::Less | Ordering::Equal => {
11598                        ranges_to_remove.next();
11599                    }
11600                    Ordering::Greater => {
11601                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11602                            Ordering::Less | Ordering::Equal => {
11603                                return false;
11604                            }
11605                            Ordering::Greater => break,
11606                        }
11607                    }
11608                }
11609            }
11610
11611            true
11612        })
11613    }
11614
11615    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11616    pub fn clear_row_highlights<T: 'static>(&mut self) {
11617        self.highlighted_rows.remove(&TypeId::of::<T>());
11618    }
11619
11620    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11621    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11622        self.highlighted_rows
11623            .get(&TypeId::of::<T>())
11624            .map_or(&[] as &[_], |vec| vec.as_slice())
11625            .iter()
11626            .map(|highlight| (highlight.range.clone(), highlight.color))
11627    }
11628
11629    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11630    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11631    /// Allows to ignore certain kinds of highlights.
11632    pub fn highlighted_display_rows(
11633        &mut self,
11634        cx: &mut WindowContext,
11635    ) -> BTreeMap<DisplayRow, Hsla> {
11636        let snapshot = self.snapshot(cx);
11637        let mut used_highlight_orders = HashMap::default();
11638        self.highlighted_rows
11639            .iter()
11640            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11641            .fold(
11642                BTreeMap::<DisplayRow, Hsla>::new(),
11643                |mut unique_rows, highlight| {
11644                    let start = highlight.range.start.to_display_point(&snapshot);
11645                    let end = highlight.range.end.to_display_point(&snapshot);
11646                    let start_row = start.row().0;
11647                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11648                        && end.column() == 0
11649                    {
11650                        end.row().0.saturating_sub(1)
11651                    } else {
11652                        end.row().0
11653                    };
11654                    for row in start_row..=end_row {
11655                        let used_index =
11656                            used_highlight_orders.entry(row).or_insert(highlight.index);
11657                        if highlight.index >= *used_index {
11658                            *used_index = highlight.index;
11659                            unique_rows.insert(DisplayRow(row), highlight.color);
11660                        }
11661                    }
11662                    unique_rows
11663                },
11664            )
11665    }
11666
11667    pub fn highlighted_display_row_for_autoscroll(
11668        &self,
11669        snapshot: &DisplaySnapshot,
11670    ) -> Option<DisplayRow> {
11671        self.highlighted_rows
11672            .values()
11673            .flat_map(|highlighted_rows| highlighted_rows.iter())
11674            .filter_map(|highlight| {
11675                if highlight.should_autoscroll {
11676                    Some(highlight.range.start.to_display_point(snapshot).row())
11677                } else {
11678                    None
11679                }
11680            })
11681            .min()
11682    }
11683
11684    pub fn set_search_within_ranges(
11685        &mut self,
11686        ranges: &[Range<Anchor>],
11687        cx: &mut ViewContext<Self>,
11688    ) {
11689        self.highlight_background::<SearchWithinRange>(
11690            ranges,
11691            |colors| colors.editor_document_highlight_read_background,
11692            cx,
11693        )
11694    }
11695
11696    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11697        self.breadcrumb_header = Some(new_header);
11698    }
11699
11700    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11701        self.clear_background_highlights::<SearchWithinRange>(cx);
11702    }
11703
11704    pub fn highlight_background<T: 'static>(
11705        &mut self,
11706        ranges: &[Range<Anchor>],
11707        color_fetcher: fn(&ThemeColors) -> Hsla,
11708        cx: &mut ViewContext<Self>,
11709    ) {
11710        self.background_highlights
11711            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11712        self.scrollbar_marker_state.dirty = true;
11713        cx.notify();
11714    }
11715
11716    pub fn clear_background_highlights<T: 'static>(
11717        &mut self,
11718        cx: &mut ViewContext<Self>,
11719    ) -> Option<BackgroundHighlight> {
11720        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11721        if !text_highlights.1.is_empty() {
11722            self.scrollbar_marker_state.dirty = true;
11723            cx.notify();
11724        }
11725        Some(text_highlights)
11726    }
11727
11728    pub fn highlight_gutter<T: 'static>(
11729        &mut self,
11730        ranges: &[Range<Anchor>],
11731        color_fetcher: fn(&AppContext) -> Hsla,
11732        cx: &mut ViewContext<Self>,
11733    ) {
11734        self.gutter_highlights
11735            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11736        cx.notify();
11737    }
11738
11739    pub fn clear_gutter_highlights<T: 'static>(
11740        &mut self,
11741        cx: &mut ViewContext<Self>,
11742    ) -> Option<GutterHighlight> {
11743        cx.notify();
11744        self.gutter_highlights.remove(&TypeId::of::<T>())
11745    }
11746
11747    #[cfg(feature = "test-support")]
11748    pub fn all_text_background_highlights(
11749        &mut self,
11750        cx: &mut ViewContext<Self>,
11751    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11752        let snapshot = self.snapshot(cx);
11753        let buffer = &snapshot.buffer_snapshot;
11754        let start = buffer.anchor_before(0);
11755        let end = buffer.anchor_after(buffer.len());
11756        let theme = cx.theme().colors();
11757        self.background_highlights_in_range(start..end, &snapshot, theme)
11758    }
11759
11760    #[cfg(feature = "test-support")]
11761    pub fn search_background_highlights(
11762        &mut self,
11763        cx: &mut ViewContext<Self>,
11764    ) -> Vec<Range<Point>> {
11765        let snapshot = self.buffer().read(cx).snapshot(cx);
11766
11767        let highlights = self
11768            .background_highlights
11769            .get(&TypeId::of::<items::BufferSearchHighlights>());
11770
11771        if let Some((_color, ranges)) = highlights {
11772            ranges
11773                .iter()
11774                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11775                .collect_vec()
11776        } else {
11777            vec![]
11778        }
11779    }
11780
11781    fn document_highlights_for_position<'a>(
11782        &'a self,
11783        position: Anchor,
11784        buffer: &'a MultiBufferSnapshot,
11785    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11786        let read_highlights = self
11787            .background_highlights
11788            .get(&TypeId::of::<DocumentHighlightRead>())
11789            .map(|h| &h.1);
11790        let write_highlights = self
11791            .background_highlights
11792            .get(&TypeId::of::<DocumentHighlightWrite>())
11793            .map(|h| &h.1);
11794        let left_position = position.bias_left(buffer);
11795        let right_position = position.bias_right(buffer);
11796        read_highlights
11797            .into_iter()
11798            .chain(write_highlights)
11799            .flat_map(move |ranges| {
11800                let start_ix = match ranges.binary_search_by(|probe| {
11801                    let cmp = probe.end.cmp(&left_position, buffer);
11802                    if cmp.is_ge() {
11803                        Ordering::Greater
11804                    } else {
11805                        Ordering::Less
11806                    }
11807                }) {
11808                    Ok(i) | Err(i) => i,
11809                };
11810
11811                ranges[start_ix..]
11812                    .iter()
11813                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11814            })
11815    }
11816
11817    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11818        self.background_highlights
11819            .get(&TypeId::of::<T>())
11820            .map_or(false, |(_, highlights)| !highlights.is_empty())
11821    }
11822
11823    pub fn background_highlights_in_range(
11824        &self,
11825        search_range: Range<Anchor>,
11826        display_snapshot: &DisplaySnapshot,
11827        theme: &ThemeColors,
11828    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11829        let mut results = Vec::new();
11830        for (color_fetcher, ranges) in self.background_highlights.values() {
11831            let color = color_fetcher(theme);
11832            let start_ix = match ranges.binary_search_by(|probe| {
11833                let cmp = probe
11834                    .end
11835                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11836                if cmp.is_gt() {
11837                    Ordering::Greater
11838                } else {
11839                    Ordering::Less
11840                }
11841            }) {
11842                Ok(i) | Err(i) => i,
11843            };
11844            for range in &ranges[start_ix..] {
11845                if range
11846                    .start
11847                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11848                    .is_ge()
11849                {
11850                    break;
11851                }
11852
11853                let start = range.start.to_display_point(display_snapshot);
11854                let end = range.end.to_display_point(display_snapshot);
11855                results.push((start..end, color))
11856            }
11857        }
11858        results
11859    }
11860
11861    pub fn background_highlight_row_ranges<T: 'static>(
11862        &self,
11863        search_range: Range<Anchor>,
11864        display_snapshot: &DisplaySnapshot,
11865        count: usize,
11866    ) -> Vec<RangeInclusive<DisplayPoint>> {
11867        let mut results = Vec::new();
11868        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11869            return vec![];
11870        };
11871
11872        let start_ix = match ranges.binary_search_by(|probe| {
11873            let cmp = probe
11874                .end
11875                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11876            if cmp.is_gt() {
11877                Ordering::Greater
11878            } else {
11879                Ordering::Less
11880            }
11881        }) {
11882            Ok(i) | Err(i) => i,
11883        };
11884        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11885            if let (Some(start_display), Some(end_display)) = (start, end) {
11886                results.push(
11887                    start_display.to_display_point(display_snapshot)
11888                        ..=end_display.to_display_point(display_snapshot),
11889                );
11890            }
11891        };
11892        let mut start_row: Option<Point> = None;
11893        let mut end_row: Option<Point> = None;
11894        if ranges.len() > count {
11895            return Vec::new();
11896        }
11897        for range in &ranges[start_ix..] {
11898            if range
11899                .start
11900                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11901                .is_ge()
11902            {
11903                break;
11904            }
11905            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11906            if let Some(current_row) = &end_row {
11907                if end.row == current_row.row {
11908                    continue;
11909                }
11910            }
11911            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11912            if start_row.is_none() {
11913                assert_eq!(end_row, None);
11914                start_row = Some(start);
11915                end_row = Some(end);
11916                continue;
11917            }
11918            if let Some(current_end) = end_row.as_mut() {
11919                if start.row > current_end.row + 1 {
11920                    push_region(start_row, end_row);
11921                    start_row = Some(start);
11922                    end_row = Some(end);
11923                } else {
11924                    // Merge two hunks.
11925                    *current_end = end;
11926                }
11927            } else {
11928                unreachable!();
11929            }
11930        }
11931        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11932        push_region(start_row, end_row);
11933        results
11934    }
11935
11936    pub fn gutter_highlights_in_range(
11937        &self,
11938        search_range: Range<Anchor>,
11939        display_snapshot: &DisplaySnapshot,
11940        cx: &AppContext,
11941    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11942        let mut results = Vec::new();
11943        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11944            let color = color_fetcher(cx);
11945            let start_ix = match ranges.binary_search_by(|probe| {
11946                let cmp = probe
11947                    .end
11948                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11949                if cmp.is_gt() {
11950                    Ordering::Greater
11951                } else {
11952                    Ordering::Less
11953                }
11954            }) {
11955                Ok(i) | Err(i) => i,
11956            };
11957            for range in &ranges[start_ix..] {
11958                if range
11959                    .start
11960                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11961                    .is_ge()
11962                {
11963                    break;
11964                }
11965
11966                let start = range.start.to_display_point(display_snapshot);
11967                let end = range.end.to_display_point(display_snapshot);
11968                results.push((start..end, color))
11969            }
11970        }
11971        results
11972    }
11973
11974    /// Get the text ranges corresponding to the redaction query
11975    pub fn redacted_ranges(
11976        &self,
11977        search_range: Range<Anchor>,
11978        display_snapshot: &DisplaySnapshot,
11979        cx: &WindowContext,
11980    ) -> Vec<Range<DisplayPoint>> {
11981        display_snapshot
11982            .buffer_snapshot
11983            .redacted_ranges(search_range, |file| {
11984                if let Some(file) = file {
11985                    file.is_private()
11986                        && EditorSettings::get(
11987                            Some(SettingsLocation {
11988                                worktree_id: file.worktree_id(cx),
11989                                path: file.path().as_ref(),
11990                            }),
11991                            cx,
11992                        )
11993                        .redact_private_values
11994                } else {
11995                    false
11996                }
11997            })
11998            .map(|range| {
11999                range.start.to_display_point(display_snapshot)
12000                    ..range.end.to_display_point(display_snapshot)
12001            })
12002            .collect()
12003    }
12004
12005    pub fn highlight_text<T: 'static>(
12006        &mut self,
12007        ranges: Vec<Range<Anchor>>,
12008        style: HighlightStyle,
12009        cx: &mut ViewContext<Self>,
12010    ) {
12011        self.display_map.update(cx, |map, _| {
12012            map.highlight_text(TypeId::of::<T>(), ranges, style)
12013        });
12014        cx.notify();
12015    }
12016
12017    pub(crate) fn highlight_inlays<T: 'static>(
12018        &mut self,
12019        highlights: Vec<InlayHighlight>,
12020        style: HighlightStyle,
12021        cx: &mut ViewContext<Self>,
12022    ) {
12023        self.display_map.update(cx, |map, _| {
12024            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12025        });
12026        cx.notify();
12027    }
12028
12029    pub fn text_highlights<'a, T: 'static>(
12030        &'a self,
12031        cx: &'a AppContext,
12032    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12033        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12034    }
12035
12036    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12037        let cleared = self
12038            .display_map
12039            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12040        if cleared {
12041            cx.notify();
12042        }
12043    }
12044
12045    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12046        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12047            && self.focus_handle.is_focused(cx)
12048    }
12049
12050    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12051        self.show_cursor_when_unfocused = is_enabled;
12052        cx.notify();
12053    }
12054
12055    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12056        cx.notify();
12057    }
12058
12059    fn on_buffer_event(
12060        &mut self,
12061        multibuffer: Model<MultiBuffer>,
12062        event: &multi_buffer::Event,
12063        cx: &mut ViewContext<Self>,
12064    ) {
12065        match event {
12066            multi_buffer::Event::Edited {
12067                singleton_buffer_edited,
12068            } => {
12069                self.scrollbar_marker_state.dirty = true;
12070                self.active_indent_guides_state.dirty = true;
12071                self.refresh_active_diagnostics(cx);
12072                self.refresh_code_actions(cx);
12073                if self.has_active_inline_completion(cx) {
12074                    self.update_visible_inline_completion(cx);
12075                }
12076                cx.emit(EditorEvent::BufferEdited);
12077                cx.emit(SearchEvent::MatchesInvalidated);
12078                if *singleton_buffer_edited {
12079                    if let Some(project) = &self.project {
12080                        let project = project.read(cx);
12081                        #[allow(clippy::mutable_key_type)]
12082                        let languages_affected = multibuffer
12083                            .read(cx)
12084                            .all_buffers()
12085                            .into_iter()
12086                            .filter_map(|buffer| {
12087                                let buffer = buffer.read(cx);
12088                                let language = buffer.language()?;
12089                                if project.is_local()
12090                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12091                                {
12092                                    None
12093                                } else {
12094                                    Some(language)
12095                                }
12096                            })
12097                            .cloned()
12098                            .collect::<HashSet<_>>();
12099                        if !languages_affected.is_empty() {
12100                            self.refresh_inlay_hints(
12101                                InlayHintRefreshReason::BufferEdited(languages_affected),
12102                                cx,
12103                            );
12104                        }
12105                    }
12106                }
12107
12108                let Some(project) = &self.project else { return };
12109                let telemetry = project.read(cx).client().telemetry().clone();
12110                refresh_linked_ranges(self, cx);
12111                telemetry.log_edit_event("editor");
12112            }
12113            multi_buffer::Event::ExcerptsAdded {
12114                buffer,
12115                predecessor,
12116                excerpts,
12117            } => {
12118                self.tasks_update_task = Some(self.refresh_runnables(cx));
12119                cx.emit(EditorEvent::ExcerptsAdded {
12120                    buffer: buffer.clone(),
12121                    predecessor: *predecessor,
12122                    excerpts: excerpts.clone(),
12123                });
12124                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12125            }
12126            multi_buffer::Event::ExcerptsRemoved { ids } => {
12127                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12128                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12129            }
12130            multi_buffer::Event::ExcerptsEdited { ids } => {
12131                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12132            }
12133            multi_buffer::Event::ExcerptsExpanded { ids } => {
12134                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12135            }
12136            multi_buffer::Event::Reparsed(buffer_id) => {
12137                self.tasks_update_task = Some(self.refresh_runnables(cx));
12138
12139                cx.emit(EditorEvent::Reparsed(*buffer_id));
12140            }
12141            multi_buffer::Event::LanguageChanged(buffer_id) => {
12142                linked_editing_ranges::refresh_linked_ranges(self, cx);
12143                cx.emit(EditorEvent::Reparsed(*buffer_id));
12144                cx.notify();
12145            }
12146            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12147            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12148            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12149                cx.emit(EditorEvent::TitleChanged)
12150            }
12151            multi_buffer::Event::DiffBaseChanged => {
12152                self.scrollbar_marker_state.dirty = true;
12153                cx.emit(EditorEvent::DiffBaseChanged);
12154                cx.notify();
12155            }
12156            multi_buffer::Event::DiffUpdated { buffer } => {
12157                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12158                cx.notify();
12159            }
12160            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12161            multi_buffer::Event::DiagnosticsUpdated => {
12162                self.refresh_active_diagnostics(cx);
12163                self.scrollbar_marker_state.dirty = true;
12164                cx.notify();
12165            }
12166            _ => {}
12167        };
12168    }
12169
12170    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12171        cx.notify();
12172    }
12173
12174    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12175        self.tasks_update_task = Some(self.refresh_runnables(cx));
12176        self.refresh_inline_completion(true, false, cx);
12177        self.refresh_inlay_hints(
12178            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12179                self.selections.newest_anchor().head(),
12180                &self.buffer.read(cx).snapshot(cx),
12181                cx,
12182            )),
12183            cx,
12184        );
12185
12186        let old_cursor_shape = self.cursor_shape;
12187
12188        {
12189            let editor_settings = EditorSettings::get_global(cx);
12190            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12191            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12192            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12193        }
12194
12195        if old_cursor_shape != self.cursor_shape {
12196            cx.emit(EditorEvent::CursorShapeChanged);
12197        }
12198
12199        let project_settings = ProjectSettings::get_global(cx);
12200        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12201
12202        if self.mode == EditorMode::Full {
12203            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12204            if self.git_blame_inline_enabled != inline_blame_enabled {
12205                self.toggle_git_blame_inline_internal(false, cx);
12206            }
12207        }
12208
12209        cx.notify();
12210    }
12211
12212    pub fn set_searchable(&mut self, searchable: bool) {
12213        self.searchable = searchable;
12214    }
12215
12216    pub fn searchable(&self) -> bool {
12217        self.searchable
12218    }
12219
12220    fn open_proposed_changes_editor(
12221        &mut self,
12222        _: &OpenProposedChangesEditor,
12223        cx: &mut ViewContext<Self>,
12224    ) {
12225        let Some(workspace) = self.workspace() else {
12226            cx.propagate();
12227            return;
12228        };
12229
12230        let buffer = self.buffer.read(cx);
12231        let mut new_selections_by_buffer = HashMap::default();
12232        for selection in self.selections.all::<usize>(cx) {
12233            for (buffer, mut range, _) in
12234                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12235            {
12236                if selection.reversed {
12237                    mem::swap(&mut range.start, &mut range.end);
12238                }
12239                let mut range = range.to_point(buffer.read(cx));
12240                range.start.column = 0;
12241                range.end.column = buffer.read(cx).line_len(range.end.row);
12242                new_selections_by_buffer
12243                    .entry(buffer)
12244                    .or_insert(Vec::new())
12245                    .push(range)
12246            }
12247        }
12248
12249        let proposed_changes_buffers = new_selections_by_buffer
12250            .into_iter()
12251            .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12252            .collect::<Vec<_>>();
12253        let proposed_changes_editor = cx.new_view(|cx| {
12254            ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12255        });
12256
12257        cx.window_context().defer(move |cx| {
12258            workspace.update(cx, |workspace, cx| {
12259                workspace.active_pane().update(cx, |pane, cx| {
12260                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12261                });
12262            });
12263        });
12264    }
12265
12266    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12267        self.open_excerpts_common(true, cx)
12268    }
12269
12270    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12271        self.open_excerpts_common(false, cx)
12272    }
12273
12274    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12275        let buffer = self.buffer.read(cx);
12276        if buffer.is_singleton() {
12277            cx.propagate();
12278            return;
12279        }
12280
12281        let Some(workspace) = self.workspace() else {
12282            cx.propagate();
12283            return;
12284        };
12285
12286        let mut new_selections_by_buffer = HashMap::default();
12287        for selection in self.selections.all::<usize>(cx) {
12288            for (buffer, mut range, _) in
12289                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12290            {
12291                if selection.reversed {
12292                    mem::swap(&mut range.start, &mut range.end);
12293                }
12294                new_selections_by_buffer
12295                    .entry(buffer)
12296                    .or_insert(Vec::new())
12297                    .push(range)
12298            }
12299        }
12300
12301        // We defer the pane interaction because we ourselves are a workspace item
12302        // and activating a new item causes the pane to call a method on us reentrantly,
12303        // which panics if we're on the stack.
12304        cx.window_context().defer(move |cx| {
12305            workspace.update(cx, |workspace, cx| {
12306                let pane = if split {
12307                    workspace.adjacent_pane(cx)
12308                } else {
12309                    workspace.active_pane().clone()
12310                };
12311
12312                for (buffer, ranges) in new_selections_by_buffer {
12313                    let editor =
12314                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12315                    editor.update(cx, |editor, cx| {
12316                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12317                            s.select_ranges(ranges);
12318                        });
12319                    });
12320                }
12321            })
12322        });
12323    }
12324
12325    fn jump(
12326        &mut self,
12327        path: ProjectPath,
12328        position: Point,
12329        anchor: language::Anchor,
12330        offset_from_top: u32,
12331        cx: &mut ViewContext<Self>,
12332    ) {
12333        let workspace = self.workspace();
12334        cx.spawn(|_, mut cx| async move {
12335            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12336            let editor = workspace.update(&mut cx, |workspace, cx| {
12337                // Reset the preview item id before opening the new item
12338                workspace.active_pane().update(cx, |pane, cx| {
12339                    pane.set_preview_item_id(None, cx);
12340                });
12341                workspace.open_path_preview(path, None, true, true, cx)
12342            })?;
12343            let editor = editor
12344                .await?
12345                .downcast::<Editor>()
12346                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12347                .downgrade();
12348            editor.update(&mut cx, |editor, cx| {
12349                let buffer = editor
12350                    .buffer()
12351                    .read(cx)
12352                    .as_singleton()
12353                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12354                let buffer = buffer.read(cx);
12355                let cursor = if buffer.can_resolve(&anchor) {
12356                    language::ToPoint::to_point(&anchor, buffer)
12357                } else {
12358                    buffer.clip_point(position, Bias::Left)
12359                };
12360
12361                let nav_history = editor.nav_history.take();
12362                editor.change_selections(
12363                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12364                    cx,
12365                    |s| {
12366                        s.select_ranges([cursor..cursor]);
12367                    },
12368                );
12369                editor.nav_history = nav_history;
12370
12371                anyhow::Ok(())
12372            })??;
12373
12374            anyhow::Ok(())
12375        })
12376        .detach_and_log_err(cx);
12377    }
12378
12379    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12380        let snapshot = self.buffer.read(cx).read(cx);
12381        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12382        Some(
12383            ranges
12384                .iter()
12385                .map(move |range| {
12386                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12387                })
12388                .collect(),
12389        )
12390    }
12391
12392    fn selection_replacement_ranges(
12393        &self,
12394        range: Range<OffsetUtf16>,
12395        cx: &AppContext,
12396    ) -> Vec<Range<OffsetUtf16>> {
12397        let selections = self.selections.all::<OffsetUtf16>(cx);
12398        let newest_selection = selections
12399            .iter()
12400            .max_by_key(|selection| selection.id)
12401            .unwrap();
12402        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12403        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12404        let snapshot = self.buffer.read(cx).read(cx);
12405        selections
12406            .into_iter()
12407            .map(|mut selection| {
12408                selection.start.0 =
12409                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12410                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12411                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12412                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12413            })
12414            .collect()
12415    }
12416
12417    fn report_editor_event(
12418        &self,
12419        operation: &'static str,
12420        file_extension: Option<String>,
12421        cx: &AppContext,
12422    ) {
12423        if cfg!(any(test, feature = "test-support")) {
12424            return;
12425        }
12426
12427        let Some(project) = &self.project else { return };
12428
12429        // If None, we are in a file without an extension
12430        let file = self
12431            .buffer
12432            .read(cx)
12433            .as_singleton()
12434            .and_then(|b| b.read(cx).file());
12435        let file_extension = file_extension.or(file
12436            .as_ref()
12437            .and_then(|file| Path::new(file.file_name(cx)).extension())
12438            .and_then(|e| e.to_str())
12439            .map(|a| a.to_string()));
12440
12441        let vim_mode = cx
12442            .global::<SettingsStore>()
12443            .raw_user_settings()
12444            .get("vim_mode")
12445            == Some(&serde_json::Value::Bool(true));
12446
12447        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12448            == language::language_settings::InlineCompletionProvider::Copilot;
12449        let copilot_enabled_for_language = self
12450            .buffer
12451            .read(cx)
12452            .settings_at(0, cx)
12453            .show_inline_completions;
12454
12455        let telemetry = project.read(cx).client().telemetry().clone();
12456        telemetry.report_editor_event(
12457            file_extension,
12458            vim_mode,
12459            operation,
12460            copilot_enabled,
12461            copilot_enabled_for_language,
12462        )
12463    }
12464
12465    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12466    /// with each line being an array of {text, highlight} objects.
12467    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12468        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12469            return;
12470        };
12471
12472        #[derive(Serialize)]
12473        struct Chunk<'a> {
12474            text: String,
12475            highlight: Option<&'a str>,
12476        }
12477
12478        let snapshot = buffer.read(cx).snapshot();
12479        let range = self
12480            .selected_text_range(false, cx)
12481            .and_then(|selection| {
12482                if selection.range.is_empty() {
12483                    None
12484                } else {
12485                    Some(selection.range)
12486                }
12487            })
12488            .unwrap_or_else(|| 0..snapshot.len());
12489
12490        let chunks = snapshot.chunks(range, true);
12491        let mut lines = Vec::new();
12492        let mut line: VecDeque<Chunk> = VecDeque::new();
12493
12494        let Some(style) = self.style.as_ref() else {
12495            return;
12496        };
12497
12498        for chunk in chunks {
12499            let highlight = chunk
12500                .syntax_highlight_id
12501                .and_then(|id| id.name(&style.syntax));
12502            let mut chunk_lines = chunk.text.split('\n').peekable();
12503            while let Some(text) = chunk_lines.next() {
12504                let mut merged_with_last_token = false;
12505                if let Some(last_token) = line.back_mut() {
12506                    if last_token.highlight == highlight {
12507                        last_token.text.push_str(text);
12508                        merged_with_last_token = true;
12509                    }
12510                }
12511
12512                if !merged_with_last_token {
12513                    line.push_back(Chunk {
12514                        text: text.into(),
12515                        highlight,
12516                    });
12517                }
12518
12519                if chunk_lines.peek().is_some() {
12520                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12521                        line.pop_front();
12522                    }
12523                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12524                        line.pop_back();
12525                    }
12526
12527                    lines.push(mem::take(&mut line));
12528                }
12529            }
12530        }
12531
12532        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12533            return;
12534        };
12535        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12536    }
12537
12538    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12539        &self.inlay_hint_cache
12540    }
12541
12542    pub fn replay_insert_event(
12543        &mut self,
12544        text: &str,
12545        relative_utf16_range: Option<Range<isize>>,
12546        cx: &mut ViewContext<Self>,
12547    ) {
12548        if !self.input_enabled {
12549            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12550            return;
12551        }
12552        if let Some(relative_utf16_range) = relative_utf16_range {
12553            let selections = self.selections.all::<OffsetUtf16>(cx);
12554            self.change_selections(None, cx, |s| {
12555                let new_ranges = selections.into_iter().map(|range| {
12556                    let start = OffsetUtf16(
12557                        range
12558                            .head()
12559                            .0
12560                            .saturating_add_signed(relative_utf16_range.start),
12561                    );
12562                    let end = OffsetUtf16(
12563                        range
12564                            .head()
12565                            .0
12566                            .saturating_add_signed(relative_utf16_range.end),
12567                    );
12568                    start..end
12569                });
12570                s.select_ranges(new_ranges);
12571            });
12572        }
12573
12574        self.handle_input(text, cx);
12575    }
12576
12577    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12578        let Some(project) = self.project.as_ref() else {
12579            return false;
12580        };
12581        let project = project.read(cx);
12582
12583        let mut supports = false;
12584        self.buffer().read(cx).for_each_buffer(|buffer| {
12585            if !supports {
12586                supports = project
12587                    .language_servers_for_buffer(buffer.read(cx), cx)
12588                    .any(
12589                        |(_, server)| match server.capabilities().inlay_hint_provider {
12590                            Some(lsp::OneOf::Left(enabled)) => enabled,
12591                            Some(lsp::OneOf::Right(_)) => true,
12592                            None => false,
12593                        },
12594                    )
12595            }
12596        });
12597        supports
12598    }
12599
12600    pub fn focus(&self, cx: &mut WindowContext) {
12601        cx.focus(&self.focus_handle)
12602    }
12603
12604    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12605        self.focus_handle.is_focused(cx)
12606    }
12607
12608    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12609        cx.emit(EditorEvent::Focused);
12610
12611        if let Some(descendant) = self
12612            .last_focused_descendant
12613            .take()
12614            .and_then(|descendant| descendant.upgrade())
12615        {
12616            cx.focus(&descendant);
12617        } else {
12618            if let Some(blame) = self.blame.as_ref() {
12619                blame.update(cx, GitBlame::focus)
12620            }
12621
12622            self.blink_manager.update(cx, BlinkManager::enable);
12623            self.show_cursor_names(cx);
12624            self.buffer.update(cx, |buffer, cx| {
12625                buffer.finalize_last_transaction(cx);
12626                if self.leader_peer_id.is_none() {
12627                    buffer.set_active_selections(
12628                        &self.selections.disjoint_anchors(),
12629                        self.selections.line_mode,
12630                        self.cursor_shape,
12631                        cx,
12632                    );
12633                }
12634            });
12635        }
12636    }
12637
12638    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12639        cx.emit(EditorEvent::FocusedIn)
12640    }
12641
12642    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12643        if event.blurred != self.focus_handle {
12644            self.last_focused_descendant = Some(event.blurred);
12645        }
12646    }
12647
12648    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12649        self.blink_manager.update(cx, BlinkManager::disable);
12650        self.buffer
12651            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12652
12653        if let Some(blame) = self.blame.as_ref() {
12654            blame.update(cx, GitBlame::blur)
12655        }
12656        if !self.hover_state.focused(cx) {
12657            hide_hover(self, cx);
12658        }
12659
12660        self.hide_context_menu(cx);
12661        cx.emit(EditorEvent::Blurred);
12662        cx.notify();
12663    }
12664
12665    pub fn register_action<A: Action>(
12666        &mut self,
12667        listener: impl Fn(&A, &mut WindowContext) + 'static,
12668    ) -> Subscription {
12669        let id = self.next_editor_action_id.post_inc();
12670        let listener = Arc::new(listener);
12671        self.editor_actions.borrow_mut().insert(
12672            id,
12673            Box::new(move |cx| {
12674                let cx = cx.window_context();
12675                let listener = listener.clone();
12676                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12677                    let action = action.downcast_ref().unwrap();
12678                    if phase == DispatchPhase::Bubble {
12679                        listener(action, cx)
12680                    }
12681                })
12682            }),
12683        );
12684
12685        let editor_actions = self.editor_actions.clone();
12686        Subscription::new(move || {
12687            editor_actions.borrow_mut().remove(&id);
12688        })
12689    }
12690
12691    pub fn file_header_size(&self) -> u32 {
12692        self.file_header_size
12693    }
12694
12695    pub fn revert(
12696        &mut self,
12697        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12698        cx: &mut ViewContext<Self>,
12699    ) {
12700        self.buffer().update(cx, |multi_buffer, cx| {
12701            for (buffer_id, changes) in revert_changes {
12702                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12703                    buffer.update(cx, |buffer, cx| {
12704                        buffer.edit(
12705                            changes.into_iter().map(|(range, text)| {
12706                                (range, text.to_string().map(Arc::<str>::from))
12707                            }),
12708                            None,
12709                            cx,
12710                        );
12711                    });
12712                }
12713            }
12714        });
12715        self.change_selections(None, cx, |selections| selections.refresh());
12716    }
12717
12718    pub fn to_pixel_point(
12719        &mut self,
12720        source: multi_buffer::Anchor,
12721        editor_snapshot: &EditorSnapshot,
12722        cx: &mut ViewContext<Self>,
12723    ) -> Option<gpui::Point<Pixels>> {
12724        let source_point = source.to_display_point(editor_snapshot);
12725        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12726    }
12727
12728    pub fn display_to_pixel_point(
12729        &mut self,
12730        source: DisplayPoint,
12731        editor_snapshot: &EditorSnapshot,
12732        cx: &mut ViewContext<Self>,
12733    ) -> Option<gpui::Point<Pixels>> {
12734        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12735        let text_layout_details = self.text_layout_details(cx);
12736        let scroll_top = text_layout_details
12737            .scroll_anchor
12738            .scroll_position(editor_snapshot)
12739            .y;
12740
12741        if source.row().as_f32() < scroll_top.floor() {
12742            return None;
12743        }
12744        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12745        let source_y = line_height * (source.row().as_f32() - scroll_top);
12746        Some(gpui::Point::new(source_x, source_y))
12747    }
12748
12749    pub fn has_active_completions_menu(&self) -> bool {
12750        self.context_menu.read().as_ref().map_or(false, |menu| {
12751            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12752        })
12753    }
12754
12755    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12756        self.addons
12757            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12758    }
12759
12760    pub fn unregister_addon<T: Addon>(&mut self) {
12761        self.addons.remove(&std::any::TypeId::of::<T>());
12762    }
12763
12764    pub fn addon<T: Addon>(&self) -> Option<&T> {
12765        let type_id = std::any::TypeId::of::<T>();
12766        self.addons
12767            .get(&type_id)
12768            .and_then(|item| item.to_any().downcast_ref::<T>())
12769    }
12770}
12771
12772fn hunks_for_selections(
12773    multi_buffer_snapshot: &MultiBufferSnapshot,
12774    selections: &[Selection<Anchor>],
12775) -> Vec<MultiBufferDiffHunk> {
12776    let buffer_rows_for_selections = selections.iter().map(|selection| {
12777        let head = selection.head();
12778        let tail = selection.tail();
12779        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12780        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12781        if start > end {
12782            end..start
12783        } else {
12784            start..end
12785        }
12786    });
12787
12788    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12789}
12790
12791pub fn hunks_for_rows(
12792    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12793    multi_buffer_snapshot: &MultiBufferSnapshot,
12794) -> Vec<MultiBufferDiffHunk> {
12795    let mut hunks = Vec::new();
12796    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12797        HashMap::default();
12798    for selected_multi_buffer_rows in rows {
12799        let query_rows =
12800            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12801        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12802            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12803            // when the caret is just above or just below the deleted hunk.
12804            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12805            let related_to_selection = if allow_adjacent {
12806                hunk.row_range.overlaps(&query_rows)
12807                    || hunk.row_range.start == query_rows.end
12808                    || hunk.row_range.end == query_rows.start
12809            } else {
12810                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12811                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12812                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12813                    || selected_multi_buffer_rows.end == hunk.row_range.start
12814            };
12815            if related_to_selection {
12816                if !processed_buffer_rows
12817                    .entry(hunk.buffer_id)
12818                    .or_default()
12819                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12820                {
12821                    continue;
12822                }
12823                hunks.push(hunk);
12824            }
12825        }
12826    }
12827
12828    hunks
12829}
12830
12831pub trait CollaborationHub {
12832    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12833    fn user_participant_indices<'a>(
12834        &self,
12835        cx: &'a AppContext,
12836    ) -> &'a HashMap<u64, ParticipantIndex>;
12837    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12838}
12839
12840impl CollaborationHub for Model<Project> {
12841    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12842        self.read(cx).collaborators()
12843    }
12844
12845    fn user_participant_indices<'a>(
12846        &self,
12847        cx: &'a AppContext,
12848    ) -> &'a HashMap<u64, ParticipantIndex> {
12849        self.read(cx).user_store().read(cx).participant_indices()
12850    }
12851
12852    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12853        let this = self.read(cx);
12854        let user_ids = this.collaborators().values().map(|c| c.user_id);
12855        this.user_store().read_with(cx, |user_store, cx| {
12856            user_store.participant_names(user_ids, cx)
12857        })
12858    }
12859}
12860
12861pub trait CompletionProvider {
12862    fn completions(
12863        &self,
12864        buffer: &Model<Buffer>,
12865        buffer_position: text::Anchor,
12866        trigger: CompletionContext,
12867        cx: &mut ViewContext<Editor>,
12868    ) -> Task<Result<Vec<Completion>>>;
12869
12870    fn resolve_completions(
12871        &self,
12872        buffer: Model<Buffer>,
12873        completion_indices: Vec<usize>,
12874        completions: Arc<RwLock<Box<[Completion]>>>,
12875        cx: &mut ViewContext<Editor>,
12876    ) -> Task<Result<bool>>;
12877
12878    fn apply_additional_edits_for_completion(
12879        &self,
12880        buffer: Model<Buffer>,
12881        completion: Completion,
12882        push_to_history: bool,
12883        cx: &mut ViewContext<Editor>,
12884    ) -> Task<Result<Option<language::Transaction>>>;
12885
12886    fn is_completion_trigger(
12887        &self,
12888        buffer: &Model<Buffer>,
12889        position: language::Anchor,
12890        text: &str,
12891        trigger_in_words: bool,
12892        cx: &mut ViewContext<Editor>,
12893    ) -> bool;
12894
12895    fn sort_completions(&self) -> bool {
12896        true
12897    }
12898}
12899
12900pub trait CodeActionProvider {
12901    fn code_actions(
12902        &self,
12903        buffer: &Model<Buffer>,
12904        range: Range<text::Anchor>,
12905        cx: &mut WindowContext,
12906    ) -> Task<Result<Vec<CodeAction>>>;
12907
12908    fn apply_code_action(
12909        &self,
12910        buffer_handle: Model<Buffer>,
12911        action: CodeAction,
12912        excerpt_id: ExcerptId,
12913        push_to_history: bool,
12914        cx: &mut WindowContext,
12915    ) -> Task<Result<ProjectTransaction>>;
12916}
12917
12918impl CodeActionProvider for Model<Project> {
12919    fn code_actions(
12920        &self,
12921        buffer: &Model<Buffer>,
12922        range: Range<text::Anchor>,
12923        cx: &mut WindowContext,
12924    ) -> Task<Result<Vec<CodeAction>>> {
12925        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12926    }
12927
12928    fn apply_code_action(
12929        &self,
12930        buffer_handle: Model<Buffer>,
12931        action: CodeAction,
12932        _excerpt_id: ExcerptId,
12933        push_to_history: bool,
12934        cx: &mut WindowContext,
12935    ) -> Task<Result<ProjectTransaction>> {
12936        self.update(cx, |project, cx| {
12937            project.apply_code_action(buffer_handle, action, push_to_history, cx)
12938        })
12939    }
12940}
12941
12942fn snippet_completions(
12943    project: &Project,
12944    buffer: &Model<Buffer>,
12945    buffer_position: text::Anchor,
12946    cx: &mut AppContext,
12947) -> Vec<Completion> {
12948    let language = buffer.read(cx).language_at(buffer_position);
12949    let language_name = language.as_ref().map(|language| language.lsp_id());
12950    let snippet_store = project.snippets().read(cx);
12951    let snippets = snippet_store.snippets_for(language_name, cx);
12952
12953    if snippets.is_empty() {
12954        return vec![];
12955    }
12956    let snapshot = buffer.read(cx).text_snapshot();
12957    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12958
12959    let mut lines = chunks.lines();
12960    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12961        return vec![];
12962    };
12963
12964    let scope = language.map(|language| language.default_scope());
12965    let classifier = CharClassifier::new(scope).for_completion(true);
12966    let mut last_word = line_at
12967        .chars()
12968        .rev()
12969        .take_while(|c| classifier.is_word(*c))
12970        .collect::<String>();
12971    last_word = last_word.chars().rev().collect();
12972    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12973    let to_lsp = |point: &text::Anchor| {
12974        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12975        point_to_lsp(end)
12976    };
12977    let lsp_end = to_lsp(&buffer_position);
12978    snippets
12979        .into_iter()
12980        .filter_map(|snippet| {
12981            let matching_prefix = snippet
12982                .prefix
12983                .iter()
12984                .find(|prefix| prefix.starts_with(&last_word))?;
12985            let start = as_offset - last_word.len();
12986            let start = snapshot.anchor_before(start);
12987            let range = start..buffer_position;
12988            let lsp_start = to_lsp(&start);
12989            let lsp_range = lsp::Range {
12990                start: lsp_start,
12991                end: lsp_end,
12992            };
12993            Some(Completion {
12994                old_range: range,
12995                new_text: snippet.body.clone(),
12996                label: CodeLabel {
12997                    text: matching_prefix.clone(),
12998                    runs: vec![],
12999                    filter_range: 0..matching_prefix.len(),
13000                },
13001                server_id: LanguageServerId(usize::MAX),
13002                documentation: snippet.description.clone().map(Documentation::SingleLine),
13003                lsp_completion: lsp::CompletionItem {
13004                    label: snippet.prefix.first().unwrap().clone(),
13005                    kind: Some(CompletionItemKind::SNIPPET),
13006                    label_details: snippet.description.as_ref().map(|description| {
13007                        lsp::CompletionItemLabelDetails {
13008                            detail: Some(description.clone()),
13009                            description: None,
13010                        }
13011                    }),
13012                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13013                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13014                        lsp::InsertReplaceEdit {
13015                            new_text: snippet.body.clone(),
13016                            insert: lsp_range,
13017                            replace: lsp_range,
13018                        },
13019                    )),
13020                    filter_text: Some(snippet.body.clone()),
13021                    sort_text: Some(char::MAX.to_string()),
13022                    ..Default::default()
13023                },
13024                confirm: None,
13025            })
13026        })
13027        .collect()
13028}
13029
13030impl CompletionProvider for Model<Project> {
13031    fn completions(
13032        &self,
13033        buffer: &Model<Buffer>,
13034        buffer_position: text::Anchor,
13035        options: CompletionContext,
13036        cx: &mut ViewContext<Editor>,
13037    ) -> Task<Result<Vec<Completion>>> {
13038        self.update(cx, |project, cx| {
13039            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13040            let project_completions = project.completions(buffer, buffer_position, options, cx);
13041            cx.background_executor().spawn(async move {
13042                let mut completions = project_completions.await?;
13043                //let snippets = snippets.into_iter().;
13044                completions.extend(snippets);
13045                Ok(completions)
13046            })
13047        })
13048    }
13049
13050    fn resolve_completions(
13051        &self,
13052        buffer: Model<Buffer>,
13053        completion_indices: Vec<usize>,
13054        completions: Arc<RwLock<Box<[Completion]>>>,
13055        cx: &mut ViewContext<Editor>,
13056    ) -> Task<Result<bool>> {
13057        self.update(cx, |project, cx| {
13058            project.resolve_completions(buffer, completion_indices, completions, cx)
13059        })
13060    }
13061
13062    fn apply_additional_edits_for_completion(
13063        &self,
13064        buffer: Model<Buffer>,
13065        completion: Completion,
13066        push_to_history: bool,
13067        cx: &mut ViewContext<Editor>,
13068    ) -> Task<Result<Option<language::Transaction>>> {
13069        self.update(cx, |project, cx| {
13070            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13071        })
13072    }
13073
13074    fn is_completion_trigger(
13075        &self,
13076        buffer: &Model<Buffer>,
13077        position: language::Anchor,
13078        text: &str,
13079        trigger_in_words: bool,
13080        cx: &mut ViewContext<Editor>,
13081    ) -> bool {
13082        if !EditorSettings::get_global(cx).show_completions_on_input {
13083            return false;
13084        }
13085
13086        let mut chars = text.chars();
13087        let char = if let Some(char) = chars.next() {
13088            char
13089        } else {
13090            return false;
13091        };
13092        if chars.next().is_some() {
13093            return false;
13094        }
13095
13096        let buffer = buffer.read(cx);
13097        let classifier = buffer
13098            .snapshot()
13099            .char_classifier_at(position)
13100            .for_completion(true);
13101        if trigger_in_words && classifier.is_word(char) {
13102            return true;
13103        }
13104
13105        buffer
13106            .completion_triggers()
13107            .iter()
13108            .any(|string| string == text)
13109    }
13110}
13111
13112fn inlay_hint_settings(
13113    location: Anchor,
13114    snapshot: &MultiBufferSnapshot,
13115    cx: &mut ViewContext<'_, Editor>,
13116) -> InlayHintSettings {
13117    let file = snapshot.file_at(location);
13118    let language = snapshot.language_at(location);
13119    let settings = all_language_settings(file, cx);
13120    settings
13121        .language(language.map(|l| l.name()).as_ref())
13122        .inlay_hints
13123}
13124
13125fn consume_contiguous_rows(
13126    contiguous_row_selections: &mut Vec<Selection<Point>>,
13127    selection: &Selection<Point>,
13128    display_map: &DisplaySnapshot,
13129    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13130) -> (MultiBufferRow, MultiBufferRow) {
13131    contiguous_row_selections.push(selection.clone());
13132    let start_row = MultiBufferRow(selection.start.row);
13133    let mut end_row = ending_row(selection, display_map);
13134
13135    while let Some(next_selection) = selections.peek() {
13136        if next_selection.start.row <= end_row.0 {
13137            end_row = ending_row(next_selection, display_map);
13138            contiguous_row_selections.push(selections.next().unwrap().clone());
13139        } else {
13140            break;
13141        }
13142    }
13143    (start_row, end_row)
13144}
13145
13146fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13147    if next_selection.end.column > 0 || next_selection.is_empty() {
13148        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13149    } else {
13150        MultiBufferRow(next_selection.end.row)
13151    }
13152}
13153
13154impl EditorSnapshot {
13155    pub fn remote_selections_in_range<'a>(
13156        &'a self,
13157        range: &'a Range<Anchor>,
13158        collaboration_hub: &dyn CollaborationHub,
13159        cx: &'a AppContext,
13160    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13161        let participant_names = collaboration_hub.user_names(cx);
13162        let participant_indices = collaboration_hub.user_participant_indices(cx);
13163        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13164        let collaborators_by_replica_id = collaborators_by_peer_id
13165            .iter()
13166            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13167            .collect::<HashMap<_, _>>();
13168        self.buffer_snapshot
13169            .selections_in_range(range, false)
13170            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13171                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13172                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13173                let user_name = participant_names.get(&collaborator.user_id).cloned();
13174                Some(RemoteSelection {
13175                    replica_id,
13176                    selection,
13177                    cursor_shape,
13178                    line_mode,
13179                    participant_index,
13180                    peer_id: collaborator.peer_id,
13181                    user_name,
13182                })
13183            })
13184    }
13185
13186    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13187        self.display_snapshot.buffer_snapshot.language_at(position)
13188    }
13189
13190    pub fn is_focused(&self) -> bool {
13191        self.is_focused
13192    }
13193
13194    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13195        self.placeholder_text.as_ref()
13196    }
13197
13198    pub fn scroll_position(&self) -> gpui::Point<f32> {
13199        self.scroll_anchor.scroll_position(&self.display_snapshot)
13200    }
13201
13202    fn gutter_dimensions(
13203        &self,
13204        font_id: FontId,
13205        font_size: Pixels,
13206        em_width: Pixels,
13207        em_advance: Pixels,
13208        max_line_number_width: Pixels,
13209        cx: &AppContext,
13210    ) -> GutterDimensions {
13211        if !self.show_gutter {
13212            return GutterDimensions::default();
13213        }
13214        let descent = cx.text_system().descent(font_id, font_size);
13215
13216        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13217            matches!(
13218                ProjectSettings::get_global(cx).git.git_gutter,
13219                Some(GitGutterSetting::TrackedFiles)
13220            )
13221        });
13222        let gutter_settings = EditorSettings::get_global(cx).gutter;
13223        let show_line_numbers = self
13224            .show_line_numbers
13225            .unwrap_or(gutter_settings.line_numbers);
13226        let line_gutter_width = if show_line_numbers {
13227            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13228            let min_width_for_number_on_gutter = em_advance * 4.0;
13229            max_line_number_width.max(min_width_for_number_on_gutter)
13230        } else {
13231            0.0.into()
13232        };
13233
13234        let show_code_actions = self
13235            .show_code_actions
13236            .unwrap_or(gutter_settings.code_actions);
13237
13238        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13239
13240        let git_blame_entries_width =
13241            self.git_blame_gutter_max_author_length
13242                .map(|max_author_length| {
13243                    // Length of the author name, but also space for the commit hash,
13244                    // the spacing and the timestamp.
13245                    let max_char_count = max_author_length
13246                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13247                        + 7 // length of commit sha
13248                        + 14 // length of max relative timestamp ("60 minutes ago")
13249                        + 4; // gaps and margins
13250
13251                    em_advance * max_char_count
13252                });
13253
13254        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13255        left_padding += if show_code_actions || show_runnables {
13256            em_width * 3.0
13257        } else if show_git_gutter && show_line_numbers {
13258            em_width * 2.0
13259        } else if show_git_gutter || show_line_numbers {
13260            em_width
13261        } else {
13262            px(0.)
13263        };
13264
13265        let right_padding = if gutter_settings.folds && show_line_numbers {
13266            em_width * 4.0
13267        } else if gutter_settings.folds {
13268            em_width * 3.0
13269        } else if show_line_numbers {
13270            em_width
13271        } else {
13272            px(0.)
13273        };
13274
13275        GutterDimensions {
13276            left_padding,
13277            right_padding,
13278            width: line_gutter_width + left_padding + right_padding,
13279            margin: -descent,
13280            git_blame_entries_width,
13281        }
13282    }
13283
13284    pub fn render_fold_toggle(
13285        &self,
13286        buffer_row: MultiBufferRow,
13287        row_contains_cursor: bool,
13288        editor: View<Editor>,
13289        cx: &mut WindowContext,
13290    ) -> Option<AnyElement> {
13291        let folded = self.is_line_folded(buffer_row);
13292
13293        if let Some(crease) = self
13294            .crease_snapshot
13295            .query_row(buffer_row, &self.buffer_snapshot)
13296        {
13297            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13298                if folded {
13299                    editor.update(cx, |editor, cx| {
13300                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13301                    });
13302                } else {
13303                    editor.update(cx, |editor, cx| {
13304                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13305                    });
13306                }
13307            });
13308
13309            Some((crease.render_toggle)(
13310                buffer_row,
13311                folded,
13312                toggle_callback,
13313                cx,
13314            ))
13315        } else if folded
13316            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13317        {
13318            Some(
13319                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13320                    .selected(folded)
13321                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13322                        if folded {
13323                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13324                        } else {
13325                            this.fold_at(&FoldAt { buffer_row }, cx);
13326                        }
13327                    }))
13328                    .into_any_element(),
13329            )
13330        } else {
13331            None
13332        }
13333    }
13334
13335    pub fn render_crease_trailer(
13336        &self,
13337        buffer_row: MultiBufferRow,
13338        cx: &mut WindowContext,
13339    ) -> Option<AnyElement> {
13340        let folded = self.is_line_folded(buffer_row);
13341        let crease = self
13342            .crease_snapshot
13343            .query_row(buffer_row, &self.buffer_snapshot)?;
13344        Some((crease.render_trailer)(buffer_row, folded, cx))
13345    }
13346}
13347
13348impl Deref for EditorSnapshot {
13349    type Target = DisplaySnapshot;
13350
13351    fn deref(&self) -> &Self::Target {
13352        &self.display_snapshot
13353    }
13354}
13355
13356#[derive(Clone, Debug, PartialEq, Eq)]
13357pub enum EditorEvent {
13358    InputIgnored {
13359        text: Arc<str>,
13360    },
13361    InputHandled {
13362        utf16_range_to_replace: Option<Range<isize>>,
13363        text: Arc<str>,
13364    },
13365    ExcerptsAdded {
13366        buffer: Model<Buffer>,
13367        predecessor: ExcerptId,
13368        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13369    },
13370    ExcerptsRemoved {
13371        ids: Vec<ExcerptId>,
13372    },
13373    ExcerptsEdited {
13374        ids: Vec<ExcerptId>,
13375    },
13376    ExcerptsExpanded {
13377        ids: Vec<ExcerptId>,
13378    },
13379    BufferEdited,
13380    Edited {
13381        transaction_id: clock::Lamport,
13382    },
13383    Reparsed(BufferId),
13384    Focused,
13385    FocusedIn,
13386    Blurred,
13387    DirtyChanged,
13388    Saved,
13389    TitleChanged,
13390    DiffBaseChanged,
13391    SelectionsChanged {
13392        local: bool,
13393    },
13394    ScrollPositionChanged {
13395        local: bool,
13396        autoscroll: bool,
13397    },
13398    Closed,
13399    TransactionUndone {
13400        transaction_id: clock::Lamport,
13401    },
13402    TransactionBegun {
13403        transaction_id: clock::Lamport,
13404    },
13405    CursorShapeChanged,
13406}
13407
13408impl EventEmitter<EditorEvent> for Editor {}
13409
13410impl FocusableView for Editor {
13411    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13412        self.focus_handle.clone()
13413    }
13414}
13415
13416impl Render for Editor {
13417    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13418        let settings = ThemeSettings::get_global(cx);
13419
13420        let text_style = match self.mode {
13421            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13422                color: cx.theme().colors().editor_foreground,
13423                font_family: settings.ui_font.family.clone(),
13424                font_features: settings.ui_font.features.clone(),
13425                font_fallbacks: settings.ui_font.fallbacks.clone(),
13426                font_size: rems(0.875).into(),
13427                font_weight: settings.ui_font.weight,
13428                line_height: relative(settings.buffer_line_height.value()),
13429                ..Default::default()
13430            },
13431            EditorMode::Full => TextStyle {
13432                color: cx.theme().colors().editor_foreground,
13433                font_family: settings.buffer_font.family.clone(),
13434                font_features: settings.buffer_font.features.clone(),
13435                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13436                font_size: settings.buffer_font_size(cx).into(),
13437                font_weight: settings.buffer_font.weight,
13438                line_height: relative(settings.buffer_line_height.value()),
13439                ..Default::default()
13440            },
13441        };
13442
13443        let background = match self.mode {
13444            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13445            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13446            EditorMode::Full => cx.theme().colors().editor_background,
13447        };
13448
13449        EditorElement::new(
13450            cx.view(),
13451            EditorStyle {
13452                background,
13453                local_player: cx.theme().players().local(),
13454                text: text_style,
13455                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13456                syntax: cx.theme().syntax().clone(),
13457                status: cx.theme().status().clone(),
13458                inlay_hints_style: make_inlay_hints_style(cx),
13459                suggestions_style: HighlightStyle {
13460                    color: Some(cx.theme().status().predictive),
13461                    ..HighlightStyle::default()
13462                },
13463                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13464            },
13465        )
13466    }
13467}
13468
13469impl ViewInputHandler for Editor {
13470    fn text_for_range(
13471        &mut self,
13472        range_utf16: Range<usize>,
13473        cx: &mut ViewContext<Self>,
13474    ) -> Option<String> {
13475        Some(
13476            self.buffer
13477                .read(cx)
13478                .read(cx)
13479                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13480                .collect(),
13481        )
13482    }
13483
13484    fn selected_text_range(
13485        &mut self,
13486        ignore_disabled_input: bool,
13487        cx: &mut ViewContext<Self>,
13488    ) -> Option<UTF16Selection> {
13489        // Prevent the IME menu from appearing when holding down an alphabetic key
13490        // while input is disabled.
13491        if !ignore_disabled_input && !self.input_enabled {
13492            return None;
13493        }
13494
13495        let selection = self.selections.newest::<OffsetUtf16>(cx);
13496        let range = selection.range();
13497
13498        Some(UTF16Selection {
13499            range: range.start.0..range.end.0,
13500            reversed: selection.reversed,
13501        })
13502    }
13503
13504    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13505        let snapshot = self.buffer.read(cx).read(cx);
13506        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13507        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13508    }
13509
13510    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13511        self.clear_highlights::<InputComposition>(cx);
13512        self.ime_transaction.take();
13513    }
13514
13515    fn replace_text_in_range(
13516        &mut self,
13517        range_utf16: Option<Range<usize>>,
13518        text: &str,
13519        cx: &mut ViewContext<Self>,
13520    ) {
13521        if !self.input_enabled {
13522            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13523            return;
13524        }
13525
13526        self.transact(cx, |this, cx| {
13527            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13528                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13529                Some(this.selection_replacement_ranges(range_utf16, cx))
13530            } else {
13531                this.marked_text_ranges(cx)
13532            };
13533
13534            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13535                let newest_selection_id = this.selections.newest_anchor().id;
13536                this.selections
13537                    .all::<OffsetUtf16>(cx)
13538                    .iter()
13539                    .zip(ranges_to_replace.iter())
13540                    .find_map(|(selection, range)| {
13541                        if selection.id == newest_selection_id {
13542                            Some(
13543                                (range.start.0 as isize - selection.head().0 as isize)
13544                                    ..(range.end.0 as isize - selection.head().0 as isize),
13545                            )
13546                        } else {
13547                            None
13548                        }
13549                    })
13550            });
13551
13552            cx.emit(EditorEvent::InputHandled {
13553                utf16_range_to_replace: range_to_replace,
13554                text: text.into(),
13555            });
13556
13557            if let Some(new_selected_ranges) = new_selected_ranges {
13558                this.change_selections(None, cx, |selections| {
13559                    selections.select_ranges(new_selected_ranges)
13560                });
13561                this.backspace(&Default::default(), cx);
13562            }
13563
13564            this.handle_input(text, cx);
13565        });
13566
13567        if let Some(transaction) = self.ime_transaction {
13568            self.buffer.update(cx, |buffer, cx| {
13569                buffer.group_until_transaction(transaction, cx);
13570            });
13571        }
13572
13573        self.unmark_text(cx);
13574    }
13575
13576    fn replace_and_mark_text_in_range(
13577        &mut self,
13578        range_utf16: Option<Range<usize>>,
13579        text: &str,
13580        new_selected_range_utf16: Option<Range<usize>>,
13581        cx: &mut ViewContext<Self>,
13582    ) {
13583        if !self.input_enabled {
13584            return;
13585        }
13586
13587        let transaction = self.transact(cx, |this, cx| {
13588            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13589                let snapshot = this.buffer.read(cx).read(cx);
13590                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13591                    for marked_range in &mut marked_ranges {
13592                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13593                        marked_range.start.0 += relative_range_utf16.start;
13594                        marked_range.start =
13595                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13596                        marked_range.end =
13597                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13598                    }
13599                }
13600                Some(marked_ranges)
13601            } else if let Some(range_utf16) = range_utf16 {
13602                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13603                Some(this.selection_replacement_ranges(range_utf16, cx))
13604            } else {
13605                None
13606            };
13607
13608            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13609                let newest_selection_id = this.selections.newest_anchor().id;
13610                this.selections
13611                    .all::<OffsetUtf16>(cx)
13612                    .iter()
13613                    .zip(ranges_to_replace.iter())
13614                    .find_map(|(selection, range)| {
13615                        if selection.id == newest_selection_id {
13616                            Some(
13617                                (range.start.0 as isize - selection.head().0 as isize)
13618                                    ..(range.end.0 as isize - selection.head().0 as isize),
13619                            )
13620                        } else {
13621                            None
13622                        }
13623                    })
13624            });
13625
13626            cx.emit(EditorEvent::InputHandled {
13627                utf16_range_to_replace: range_to_replace,
13628                text: text.into(),
13629            });
13630
13631            if let Some(ranges) = ranges_to_replace {
13632                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13633            }
13634
13635            let marked_ranges = {
13636                let snapshot = this.buffer.read(cx).read(cx);
13637                this.selections
13638                    .disjoint_anchors()
13639                    .iter()
13640                    .map(|selection| {
13641                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13642                    })
13643                    .collect::<Vec<_>>()
13644            };
13645
13646            if text.is_empty() {
13647                this.unmark_text(cx);
13648            } else {
13649                this.highlight_text::<InputComposition>(
13650                    marked_ranges.clone(),
13651                    HighlightStyle {
13652                        underline: Some(UnderlineStyle {
13653                            thickness: px(1.),
13654                            color: None,
13655                            wavy: false,
13656                        }),
13657                        ..Default::default()
13658                    },
13659                    cx,
13660                );
13661            }
13662
13663            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13664            let use_autoclose = this.use_autoclose;
13665            let use_auto_surround = this.use_auto_surround;
13666            this.set_use_autoclose(false);
13667            this.set_use_auto_surround(false);
13668            this.handle_input(text, cx);
13669            this.set_use_autoclose(use_autoclose);
13670            this.set_use_auto_surround(use_auto_surround);
13671
13672            if let Some(new_selected_range) = new_selected_range_utf16 {
13673                let snapshot = this.buffer.read(cx).read(cx);
13674                let new_selected_ranges = marked_ranges
13675                    .into_iter()
13676                    .map(|marked_range| {
13677                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13678                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13679                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13680                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13681                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13682                    })
13683                    .collect::<Vec<_>>();
13684
13685                drop(snapshot);
13686                this.change_selections(None, cx, |selections| {
13687                    selections.select_ranges(new_selected_ranges)
13688                });
13689            }
13690        });
13691
13692        self.ime_transaction = self.ime_transaction.or(transaction);
13693        if let Some(transaction) = self.ime_transaction {
13694            self.buffer.update(cx, |buffer, cx| {
13695                buffer.group_until_transaction(transaction, cx);
13696            });
13697        }
13698
13699        if self.text_highlights::<InputComposition>(cx).is_none() {
13700            self.ime_transaction.take();
13701        }
13702    }
13703
13704    fn bounds_for_range(
13705        &mut self,
13706        range_utf16: Range<usize>,
13707        element_bounds: gpui::Bounds<Pixels>,
13708        cx: &mut ViewContext<Self>,
13709    ) -> Option<gpui::Bounds<Pixels>> {
13710        let text_layout_details = self.text_layout_details(cx);
13711        let style = &text_layout_details.editor_style;
13712        let font_id = cx.text_system().resolve_font(&style.text.font());
13713        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13714        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13715
13716        let em_width = cx
13717            .text_system()
13718            .typographic_bounds(font_id, font_size, 'm')
13719            .unwrap()
13720            .size
13721            .width;
13722
13723        let snapshot = self.snapshot(cx);
13724        let scroll_position = snapshot.scroll_position();
13725        let scroll_left = scroll_position.x * em_width;
13726
13727        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13728        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13729            + self.gutter_dimensions.width;
13730        let y = line_height * (start.row().as_f32() - scroll_position.y);
13731
13732        Some(Bounds {
13733            origin: element_bounds.origin + point(x, y),
13734            size: size(em_width, line_height),
13735        })
13736    }
13737}
13738
13739trait SelectionExt {
13740    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13741    fn spanned_rows(
13742        &self,
13743        include_end_if_at_line_start: bool,
13744        map: &DisplaySnapshot,
13745    ) -> Range<MultiBufferRow>;
13746}
13747
13748impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13749    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13750        let start = self
13751            .start
13752            .to_point(&map.buffer_snapshot)
13753            .to_display_point(map);
13754        let end = self
13755            .end
13756            .to_point(&map.buffer_snapshot)
13757            .to_display_point(map);
13758        if self.reversed {
13759            end..start
13760        } else {
13761            start..end
13762        }
13763    }
13764
13765    fn spanned_rows(
13766        &self,
13767        include_end_if_at_line_start: bool,
13768        map: &DisplaySnapshot,
13769    ) -> Range<MultiBufferRow> {
13770        let start = self.start.to_point(&map.buffer_snapshot);
13771        let mut end = self.end.to_point(&map.buffer_snapshot);
13772        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13773            end.row -= 1;
13774        }
13775
13776        let buffer_start = map.prev_line_boundary(start).0;
13777        let buffer_end = map.next_line_boundary(end).0;
13778        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13779    }
13780}
13781
13782impl<T: InvalidationRegion> InvalidationStack<T> {
13783    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13784    where
13785        S: Clone + ToOffset,
13786    {
13787        while let Some(region) = self.last() {
13788            let all_selections_inside_invalidation_ranges =
13789                if selections.len() == region.ranges().len() {
13790                    selections
13791                        .iter()
13792                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13793                        .all(|(selection, invalidation_range)| {
13794                            let head = selection.head().to_offset(buffer);
13795                            invalidation_range.start <= head && invalidation_range.end >= head
13796                        })
13797                } else {
13798                    false
13799                };
13800
13801            if all_selections_inside_invalidation_ranges {
13802                break;
13803            } else {
13804                self.pop();
13805            }
13806        }
13807    }
13808}
13809
13810impl<T> Default for InvalidationStack<T> {
13811    fn default() -> Self {
13812        Self(Default::default())
13813    }
13814}
13815
13816impl<T> Deref for InvalidationStack<T> {
13817    type Target = Vec<T>;
13818
13819    fn deref(&self) -> &Self::Target {
13820        &self.0
13821    }
13822}
13823
13824impl<T> DerefMut for InvalidationStack<T> {
13825    fn deref_mut(&mut self) -> &mut Self::Target {
13826        &mut self.0
13827    }
13828}
13829
13830impl InvalidationRegion for SnippetState {
13831    fn ranges(&self) -> &[Range<Anchor>] {
13832        &self.ranges[self.active_index]
13833    }
13834}
13835
13836pub fn diagnostic_block_renderer(
13837    diagnostic: Diagnostic,
13838    max_message_rows: Option<u8>,
13839    allow_closing: bool,
13840    _is_valid: bool,
13841) -> RenderBlock {
13842    let (text_without_backticks, code_ranges) =
13843        highlight_diagnostic_message(&diagnostic, max_message_rows);
13844
13845    Box::new(move |cx: &mut BlockContext| {
13846        let group_id: SharedString = cx.block_id.to_string().into();
13847
13848        let mut text_style = cx.text_style().clone();
13849        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13850        let theme_settings = ThemeSettings::get_global(cx);
13851        text_style.font_family = theme_settings.buffer_font.family.clone();
13852        text_style.font_style = theme_settings.buffer_font.style;
13853        text_style.font_features = theme_settings.buffer_font.features.clone();
13854        text_style.font_weight = theme_settings.buffer_font.weight;
13855
13856        let multi_line_diagnostic = diagnostic.message.contains('\n');
13857
13858        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13859            if multi_line_diagnostic {
13860                v_flex()
13861            } else {
13862                h_flex()
13863            }
13864            .when(allow_closing, |div| {
13865                div.children(diagnostic.is_primary.then(|| {
13866                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13867                        .icon_color(Color::Muted)
13868                        .size(ButtonSize::Compact)
13869                        .style(ButtonStyle::Transparent)
13870                        .visible_on_hover(group_id.clone())
13871                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13872                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13873                }))
13874            })
13875            .child(
13876                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13877                    .icon_color(Color::Muted)
13878                    .size(ButtonSize::Compact)
13879                    .style(ButtonStyle::Transparent)
13880                    .visible_on_hover(group_id.clone())
13881                    .on_click({
13882                        let message = diagnostic.message.clone();
13883                        move |_click, cx| {
13884                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13885                        }
13886                    })
13887                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13888            )
13889        };
13890
13891        let icon_size = buttons(&diagnostic, cx.block_id)
13892            .into_any_element()
13893            .layout_as_root(AvailableSpace::min_size(), cx);
13894
13895        h_flex()
13896            .id(cx.block_id)
13897            .group(group_id.clone())
13898            .relative()
13899            .size_full()
13900            .pl(cx.gutter_dimensions.width)
13901            .w(cx.max_width + cx.gutter_dimensions.width)
13902            .child(
13903                div()
13904                    .flex()
13905                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13906                    .flex_shrink(),
13907            )
13908            .child(buttons(&diagnostic, cx.block_id))
13909            .child(div().flex().flex_shrink_0().child(
13910                StyledText::new(text_without_backticks.clone()).with_highlights(
13911                    &text_style,
13912                    code_ranges.iter().map(|range| {
13913                        (
13914                            range.clone(),
13915                            HighlightStyle {
13916                                font_weight: Some(FontWeight::BOLD),
13917                                ..Default::default()
13918                            },
13919                        )
13920                    }),
13921                ),
13922            ))
13923            .into_any_element()
13924    })
13925}
13926
13927pub fn highlight_diagnostic_message(
13928    diagnostic: &Diagnostic,
13929    mut max_message_rows: Option<u8>,
13930) -> (SharedString, Vec<Range<usize>>) {
13931    let mut text_without_backticks = String::new();
13932    let mut code_ranges = Vec::new();
13933
13934    if let Some(source) = &diagnostic.source {
13935        text_without_backticks.push_str(source);
13936        code_ranges.push(0..source.len());
13937        text_without_backticks.push_str(": ");
13938    }
13939
13940    let mut prev_offset = 0;
13941    let mut in_code_block = false;
13942    let has_row_limit = max_message_rows.is_some();
13943    let mut newline_indices = diagnostic
13944        .message
13945        .match_indices('\n')
13946        .filter(|_| has_row_limit)
13947        .map(|(ix, _)| ix)
13948        .fuse()
13949        .peekable();
13950
13951    for (quote_ix, _) in diagnostic
13952        .message
13953        .match_indices('`')
13954        .chain([(diagnostic.message.len(), "")])
13955    {
13956        let mut first_newline_ix = None;
13957        let mut last_newline_ix = None;
13958        while let Some(newline_ix) = newline_indices.peek() {
13959            if *newline_ix < quote_ix {
13960                if first_newline_ix.is_none() {
13961                    first_newline_ix = Some(*newline_ix);
13962                }
13963                last_newline_ix = Some(*newline_ix);
13964
13965                if let Some(rows_left) = &mut max_message_rows {
13966                    if *rows_left == 0 {
13967                        break;
13968                    } else {
13969                        *rows_left -= 1;
13970                    }
13971                }
13972                let _ = newline_indices.next();
13973            } else {
13974                break;
13975            }
13976        }
13977        let prev_len = text_without_backticks.len();
13978        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13979        text_without_backticks.push_str(new_text);
13980        if in_code_block {
13981            code_ranges.push(prev_len..text_without_backticks.len());
13982        }
13983        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13984        in_code_block = !in_code_block;
13985        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13986            text_without_backticks.push_str("...");
13987            break;
13988        }
13989    }
13990
13991    (text_without_backticks.into(), code_ranges)
13992}
13993
13994fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13995    match severity {
13996        DiagnosticSeverity::ERROR => colors.error,
13997        DiagnosticSeverity::WARNING => colors.warning,
13998        DiagnosticSeverity::INFORMATION => colors.info,
13999        DiagnosticSeverity::HINT => colors.info,
14000        _ => colors.ignored,
14001    }
14002}
14003
14004pub fn styled_runs_for_code_label<'a>(
14005    label: &'a CodeLabel,
14006    syntax_theme: &'a theme::SyntaxTheme,
14007) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14008    let fade_out = HighlightStyle {
14009        fade_out: Some(0.35),
14010        ..Default::default()
14011    };
14012
14013    let mut prev_end = label.filter_range.end;
14014    label
14015        .runs
14016        .iter()
14017        .enumerate()
14018        .flat_map(move |(ix, (range, highlight_id))| {
14019            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14020                style
14021            } else {
14022                return Default::default();
14023            };
14024            let mut muted_style = style;
14025            muted_style.highlight(fade_out);
14026
14027            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14028            if range.start >= label.filter_range.end {
14029                if range.start > prev_end {
14030                    runs.push((prev_end..range.start, fade_out));
14031                }
14032                runs.push((range.clone(), muted_style));
14033            } else if range.end <= label.filter_range.end {
14034                runs.push((range.clone(), style));
14035            } else {
14036                runs.push((range.start..label.filter_range.end, style));
14037                runs.push((label.filter_range.end..range.end, muted_style));
14038            }
14039            prev_end = cmp::max(prev_end, range.end);
14040
14041            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14042                runs.push((prev_end..label.text.len(), fade_out));
14043            }
14044
14045            runs
14046        })
14047}
14048
14049pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14050    let mut prev_index = 0;
14051    let mut prev_codepoint: Option<char> = None;
14052    text.char_indices()
14053        .chain([(text.len(), '\0')])
14054        .filter_map(move |(index, codepoint)| {
14055            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14056            let is_boundary = index == text.len()
14057                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14058                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14059            if is_boundary {
14060                let chunk = &text[prev_index..index];
14061                prev_index = index;
14062                Some(chunk)
14063            } else {
14064                None
14065            }
14066        })
14067}
14068
14069pub trait RangeToAnchorExt: Sized {
14070    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14071
14072    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14073        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14074        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14075    }
14076}
14077
14078impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14079    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14080        let start_offset = self.start.to_offset(snapshot);
14081        let end_offset = self.end.to_offset(snapshot);
14082        if start_offset == end_offset {
14083            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14084        } else {
14085            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14086        }
14087    }
14088}
14089
14090pub trait RowExt {
14091    fn as_f32(&self) -> f32;
14092
14093    fn next_row(&self) -> Self;
14094
14095    fn previous_row(&self) -> Self;
14096
14097    fn minus(&self, other: Self) -> u32;
14098}
14099
14100impl RowExt for DisplayRow {
14101    fn as_f32(&self) -> f32 {
14102        self.0 as f32
14103    }
14104
14105    fn next_row(&self) -> Self {
14106        Self(self.0 + 1)
14107    }
14108
14109    fn previous_row(&self) -> Self {
14110        Self(self.0.saturating_sub(1))
14111    }
14112
14113    fn minus(&self, other: Self) -> u32 {
14114        self.0 - other.0
14115    }
14116}
14117
14118impl RowExt for MultiBufferRow {
14119    fn as_f32(&self) -> f32 {
14120        self.0 as f32
14121    }
14122
14123    fn next_row(&self) -> Self {
14124        Self(self.0 + 1)
14125    }
14126
14127    fn previous_row(&self) -> Self {
14128        Self(self.0.saturating_sub(1))
14129    }
14130
14131    fn minus(&self, other: Self) -> u32 {
14132        self.0 - other.0
14133    }
14134}
14135
14136trait RowRangeExt {
14137    type Row;
14138
14139    fn len(&self) -> usize;
14140
14141    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14142}
14143
14144impl RowRangeExt for Range<MultiBufferRow> {
14145    type Row = MultiBufferRow;
14146
14147    fn len(&self) -> usize {
14148        (self.end.0 - self.start.0) as usize
14149    }
14150
14151    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14152        (self.start.0..self.end.0).map(MultiBufferRow)
14153    }
14154}
14155
14156impl RowRangeExt for Range<DisplayRow> {
14157    type Row = DisplayRow;
14158
14159    fn len(&self) -> usize {
14160        (self.end.0 - self.start.0) as usize
14161    }
14162
14163    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14164        (self.start.0..self.end.0).map(DisplayRow)
14165    }
14166}
14167
14168fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14169    if hunk.diff_base_byte_range.is_empty() {
14170        DiffHunkStatus::Added
14171    } else if hunk.row_range.is_empty() {
14172        DiffHunkStatus::Removed
14173    } else {
14174        DiffHunkStatus::Modified
14175    }
14176}
14177
14178/// If select range has more than one line, we
14179/// just point the cursor to range.start.
14180fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14181    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14182        range
14183    } else {
14184        range.start..range.start
14185    }
14186}